diff --git a/scintilla/License.txt b/scintilla/License.txt new file mode 100644 index 00000000..8d286121 --- /dev/null +++ b/scintilla/License.txt @@ -0,0 +1,20 @@ +License for Scintilla and SciTE + +Copyright 1998-2003 by Neil Hodgson + +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation. + +NEIL HODGSON DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS, IN NO EVENT SHALL NEIL HODGSON BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE +OR PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/scintilla/README b/scintilla/README new file mode 100644 index 00000000..9775d703 --- /dev/null +++ b/scintilla/README @@ -0,0 +1,69 @@ +README for building of Scintilla and SciTE + +Scintilla can be built by itself. +To build SciTE, Scintilla must first be built. + + +*** GTK+/Linux version *** + +You must first have GTK+ 1.2 or later and GCC (3.1 or better) installed. +GTK+ 1.0x will not work and when it did it was very slow. +Other C++ compilers may work but may require tweaking the make file. + +To build Scintilla, use the makefile located in the scintilla/gtk directory + cd scintilla/gtk + make + cd ../.. + +To build and install SciTE, use the makefile located in the scite/gtk directory + cd scite/gtk + make + make install + +This installs SciTE into $prefix/bin. The value of $prefix is determined from +the location of Gnome if it is installed. This is usually /usr if installed +with Linux or /usr/local if built from source. If Gnome is not installed +/usr/bin is used as the prefix. The prefix can be overridden on the command +line like "make prefix=/opt" but the same value should be used for both make +and make install as this location is compiled into the executable. The global +properties file is installed at $prefix/share/scite/SciTEGlobal.properties. +The language specific properties files are also installed into this directory. + +To build Scintilla for GTK+ 1 rather than the default GTK+ 2, define GTK1 on +the make command line: + make GTK1=1 + +To remove SciTE + make uninstall + +To clean the object files which may be needed to change $prefix + make clean + +The current make file only supports static linking between SciTE and Scintilla. + + +*** Windows version *** + +A C++ compiler is required. Visual Studio .NET 2003 is the development system +used for most development although Mingw32 3.1 and Borland C++ are also +supported. +For older versions of Borland make such as version 5.02, add the -l option. + +To build Scintilla, make in the scintilla/win32 directory + cd scintilla\win32 +GCC: mingw32-make +VS .NET: nmake -f scintilla.mak +VC++ 6: nmake -f scintilla_vc6.mak +Borland: make -fscintilla.mak + cd ..\.. + +To build SciTE, use the makefiles located in the scite/win32 directory + cd scite\win32 +GCC: mingw32-make +VS .NET: nmake -f scite.mak +Borland: make -fscite.mak + +An executable SciTE will now be in scite\bin. + +The Visual C++ 6.0 project (.dsp) files are no longer supported but are left +in the download for people that are prepared to update them. diff --git a/scintilla/bin/empty.txt b/scintilla/bin/empty.txt new file mode 100644 index 00000000..66183855 --- /dev/null +++ b/scintilla/bin/empty.txt @@ -0,0 +1 @@ +This empty files ensures that the directory is created. \ No newline at end of file diff --git a/scintilla/delbin.bat b/scintilla/delbin.bat new file mode 100644 index 00000000..8d29322f --- /dev/null +++ b/scintilla/delbin.bat @@ -0,0 +1 @@ +del /S /Q *.a *.aps *.bsc *.dll *.dsw *.exe *.idb *.ilc *.ild *.ilf *.ilk *.ils *.lib *.map *.ncb *.obj *.o *.opt *.pdb *.plg *.res *.sbr *.tds *.exp >NUL: diff --git a/scintilla/delcvs.bat b/scintilla/delcvs.bat new file mode 100644 index 00000000..d3ed21ce --- /dev/null +++ b/scintilla/delcvs.bat @@ -0,0 +1 @@ +del /S /Q .cvsignore diff --git a/scintilla/doc/Design.html b/scintilla/doc/Design.html new file mode 100644 index 00000000..d426cb36 --- /dev/null +++ b/scintilla/doc/Design.html @@ -0,0 +1,249 @@ + + + + + + + + + Scintilla and SciTE + + + + + + + + +
+ Scintilla icon + + Scintilla + Component Design +
+

+ Top level structure +

+

+ Scintilla consists of three major layers of C++ code +

+ +

+ The primary purpose of this structure is to separate the platform dependent code from the + platform independent core code. This makes it easier to port Scintilla to a new platform and + ensures that most readers of the code do not have to deal with platform details. To minimise + portability problems and avoid code bloat, a conservative subset of C++ is used in Scintilla + with no exception handling, run time type information or use of the standard C++ + library and with limited use of templates. +

+

+ The currently supported platforms, Windows, GTK+/Linux and wxWindows are fairly similar in + many ways. + Each has windows, menus and bitmaps. These features generally work in similar ways so each + has a way to move a window or draw a red line. Sometimes one platform requires a sequence of + calls rather than a single call. At other times, the differences are more profound. Reading + the Windows clipboard occurs synchronously but reading the GTK+ clipboard requires a request + call that will be asynchronously answered with a message containing the clipboard data. + The wxWindows platform is available from the wxWindows site +

+
+

+ Portability Library +

+

+ This is a fairly small and thin layer over the platform's native capabilities. +

+

+ The portability library is defined in Platform.h and is implemented once for each platform. + PlatWin.cxx defines the Windows variants of the methods and PlatGTK.cxx the GTK+ variants. +

+

+ Several of the classes here hold platform specific object identifiers and act as proxies to + these platform objects. Most client code can thus manipulate the platform objects without + caring which is the current platform. Sometimes client code needs access to the underlying + object identifiers and this is provided by the GetID method. The underlying types of the + platform specific identifiers are typedefed to common names to allow them to be transferred + around in client code where needed. +

+

+ Point, PRectangle +

+

+ These are simple classes provided to hold the commonly used geometric primitives. A + PRectangle follows the Mac / Windows convention of not including its bottom and right sides + instead of including all its sides as is normal in GTK+. It is not called Rectangle as this may be + the name of a macro on Windows. +

+

+ Colour, ColourPair, Palette +

+

+ Colour holds a platform specific colour identifier - COLORREF for Windows and GdkColor for + GTK+. The red, green and blue components that make up the colour are limited to the 8 bits of + precision available on Windows. ColourPairs are used because not all possible colours are + always available. Using an 8 bit colour mode, which is a common setting for both Windows and + GTK+, only 256 colours are possible on the display. Thus when an application asks for a dull + red, say #400000, it may only be allocated an already available colour such as #800000 or + #330000. With 16 or 2 colour modes even less choice is available and the application will + have to use the limited set of already available colours. +

+ A Palette object holds a set of colour pairs and can make the appropriate calls to ask to + allocate these colours and to see what the platform has decided will be allowed. +

+ Font +

+

+ Font holds a platform specific font identifier - HFONT for Windows, GdkFont* for GTK+. It + does not own the identifier and so will not delete the platform font object in its + destructor. Client code should call Destroy at appropriate times. +

+

+ Surface +

+

+ Surface is an abstraction over each platform's concept of somewhere that graphical drawing + operations can be done. It may wrap an already created drawing place such as a window or be + used to create a bitmap that can be drawn into and later copied onto another surface. On + Windows it wraps a HDC and possibly a HBITMAP. On GTK+ it wraps a GdkDrawable* and possibly a + GdkPixmap*. Other platform specific objects are created (and correctly destroyed) whenever + required to perform drawing actions. +

+

+ Drawing operations provided include drawing filled and unfilled polygons, lines, rectangles, + ellipses and text. The height and width of text as well as other details can be measured. + Operations can be clipped to a rectangle. Most of the calls are stateless with all parameters + being passed at each call. The exception to this is line drawing which is performed by + calling MoveTo and then LineTo. +

+

+ Window +

+

+ Window acts as a proxy to a platform window allowing operations such as showing, moving, + redrawing, and destroying to be performed. It contains a platform specific window identifier + - HWND for Windows, GtkWidget* for GTK+. +

+

+ ListBox +

+

+ ListBox is a subclass of Window and acts as a proxy to a platform listbox adding methods for + operations such as adding, retrieving, and selecting items. +

+

+ Menu +

+

+ Menu is a small helper class for constructing popup menus. It contains the platform specific + menu identifier - HMENU for Windows, GtkItemFactory* for GTK+. Most of the work in + constructing menus requires access to platform events and so is done in the Platform Events + and API layer. +

+

+ Platform +

+

+ The Platform class is used to access the facilities of the platform. System wide parameters + such as double click speed and chrome colour are available from Platform. Utility functions + such as DebugPrintf are also available from Platform. +

+

+ Core Code +

+

+ The bulk of Scintilla's code is platform independent. This is made up of the CellBuffer, + ContractionState, Document, Editor, Indicator, LineMarker, Style, ViewStyle, KeyMap, + ScintillaBase, CallTip, + and AutoComplete primary classes. +

+

+ CellBuffer +

+

+ A CellBuffer holds text and styling information, the undo stack, the assignment of line + markers to lines, and the fold structure. +

+

+ A cell contains a character byte and its associated style byte. The current state of the + cell buffer is the sequence of cells that make up the text and a sequence of line information + containing the starting position of each line and any markers assigned to each line. +

+

+ The undo stack holds a sequence of actions on the cell buffer. Each action is one of a text + insertion, a text deletion or an undo start action. The start actions are used to group + sequences of text insertions and deletions together so they can be undone together. To + perform an undo operation, each insertion or deletion is undone in reverse sequence. + Similarly, redo reapplies each action to the buffer in sequence. Whenever a character is + inserted in the buffer either directly through a call such as InsertString or through undo or + redo, its styling byte is initially set to zero. Client code is responsible for styling each + character whenever convenient. Styling information is not stored in undo actions. +

+

+ Document +

+

+ A document contains a CellBuffer and deals with some higher level abstractions such as + words, DBCS character sequences and line end character sequences. It is responsible for + managing the styling process and for notifying other objects when changes occur to the + document. +

+

+ Editor +

+

+ The Editor object is central to Scintilla. It is responsible for displaying a document and + responding to user actions and requests from the container. It uses ContractionState, Indicator, + LineMarker, Style, and ViewStyle objects to display the document and a KeyMap class to + map key presses to functions. + The visibility of each line is kept in the ContractionState which is also responsible for mapping + from display lines to documents lines and vice versa. +

+

+ There may be multiple Editor objects attached to one Document object. Changes to a + document are broadcast to the editors through the DocWatcher mechanism. +

+

+ ScintillaBase +

+

+ ScintillaBase is a subclass of Editor and adds extra windowing features including display of + calltips, autocompletion lists and context menus. These features use CallTip and AutoComplete + objects. This class is optional so a lightweight implementation of Scintilla may bypass it if + the added functionality is not required. +

+

+ Platform Events and API +

+

+ Each platform uses different mechanisms for receiving events. On Windows, events are + received through messages and COM. On GTK+, callback functions are used. +

+

+ For each platform, a class is derived from ScintillaBase (and thus from Editor). This is + ScintillaWin on Windows and ScintillaGTK on GTK+. These classes are responsible for + connecting to the platforms event mechanism and also to implement some virtual methods in + Editor and ScintillaBase which are different on the platforms. For example, this layer has to + support this difference between the synchronous Windows clipboard and the asynchronous GTK+ + clipboard. +

+

+ The external API is defined in this layer as each platform has different preferred styles of + API - messages on Windows and function calls on GTK+. This also allows multiple APIs to be + defined on a platform. The currently available API on GTK+ is similar to the Windows API and + does not follow platform conventions well. A second API could be implemented here that did + follow platform conventions. +

+ + + diff --git a/scintilla/doc/Icons.html b/scintilla/doc/Icons.html new file mode 100644 index 00000000..0d8b8bf5 --- /dev/null +++ b/scintilla/doc/Icons.html @@ -0,0 +1,56 @@ + + + + + + + + + Scintilla icons + + + + + + + + +
+ Scintilla icon + + Scintilla + and SciTE +
+

+ Icons +

+

+ These images may be used under the same license as Scintilla. +

+

+ Drawn by Iago Rubio, Philippe Lhoste, and Neil Hodgson. +

+

+ zip format (70K) +

+ + + + + + + + + + + + + + + + + +
For autocompletion listsFor margin markers
12x1216x1624x2432x32
+ + diff --git a/scintilla/doc/Lexer.txt b/scintilla/doc/Lexer.txt new file mode 100644 index 00000000..5f118e73 --- /dev/null +++ b/scintilla/doc/Lexer.txt @@ -0,0 +1,226 @@ +How to write a scintilla lexer + +A lexer for a particular language determines how a specified range of +text shall be colored. Writing a lexer is relatively straightforward +because the lexer need only color given text. The harder job of +determining how much text actually needs to be colored is handled by +Scintilla itself, that is, the lexer's caller. + + +Parameters + +The lexer for language LLL has the following prototype: + + static void ColouriseLLLDoc ( + unsigned int startPos, int length, + int initStyle, + WordList *keywordlists[], + Accessor &styler); + +The styler parameter is an Accessor object. The lexer must use this +object to access the text to be colored. The lexer gets the character +at position i using styler.SafeGetCharAt(i); + +The startPos and length parameters indicate the range of text to be +recolored; the lexer must determine the proper color for all characters +in positions startPos through startPos+length. + +The initStyle parameter indicates the initial state, that is, the state +at the character before startPos. States also indicate the coloring to +be used for a particular range of text. + +Note: the character at StartPos is assumed to start a line, so if a +newline terminates the initStyle state the lexer should enter its +default state (or whatever state should follow initStyle). + +The keywordlists parameter specifies the keywords that the lexer must +recognize. A WordList class object contains methods that make simplify +the recognition of keywords. Present lexers use a helper function +called classifyWordLLL to recognize keywords. These functions show how +to use the keywordlists parameter to recognize keywords. This +documentation will not discuss keywords further. + + +The lexer code + +The task of a lexer can be summarized briefly: for each range r of +characters that are to be colored the same, the lexer should call + + styler.ColourTo(i, state) + +where i is the position of the last character of the range r. The lexer +should set the state variable to the coloring state of the character at +position i and continue until the entire text has been colored. + +Note 1: the styler (Accessor) object remembers the i parameter in the +previous calls to styler.ColourTo, so the single i parameter suffices to +indicate a range of characters. + +Note 2: As a side effect of calling styler.ColourTo(i,state), the +coloring states of all characters in the range are remembered so that +Scintilla may set the initStyle parameter correctly on future calls to +the +lexer. + + +Lexer organization + +There are at least two ways to organize the code of each lexer. Present +lexers use what might be called a "character-based" approach: the outer +loop iterates over characters, like this: + + lengthDoc = startPos + length ; + for (unsigned int i = startPos; i < lengthDoc; i++) { + chNext = styler.SafeGetCharAt(i + 1); + << handle special cases >> + switch(state) { + // Handlers examine only ch and chNext. + // Handlers call styler.ColorTo(i,state) if the state changes. + case state_1: << handle ch in state 1 >> + case state_2: << handle ch in state 2 >> + ... + case state_n: << handle ch in state n >> + } + chPrev = ch; + } + styler.ColourTo(lengthDoc - 1, state); + + +An alternative would be to use a "state-based" approach. The outer loop +would iterate over states, like this: + + lengthDoc = startPos+lenth ; + for ( unsigned int i = startPos ;; ) { + char ch = styler.SafeGetCharAt(i); + int new_state = 0 ; + switch ( state ) { + // scanners set new_state if they set the next state. + case state_1: << scan to the end of state 1 >> break ; + case state_2: << scan to the end of state 2 >> break ; + case default_state: + << scan to the next non-default state and set new_state >> + } + styler.ColourTo(i, state); + if ( i >= lengthDoc ) break ; + if ( ! new_state ) { + ch = styler.SafeGetCharAt(i); + << set state based on ch in the default state >> + } + } + styler.ColourTo(lengthDoc - 1, state); + +This approach might seem to be more natural. State scanners are simpler +than character scanners because less needs to be done. For example, +there is no need to test for the start of a C string inside the scanner +for a C comment. Also this way makes it natural to define routines that +could be used by more than one scanner; for example, a scanToEndOfLine +routine. + +However, the special cases handled in the main loop in the +character-based approach would have to be handled by each state scanner, +so both approaches have advantages. These special cases are discussed +below. + +Special case: Lead characters + +Lead bytes are part of DBCS processing for languages such as Japanese +using an encoding such as Shift-JIS. In these encodings, extended +(16-bit) characters are encoded as a lead byte followed by a trail byte. + +Lead bytes are rarely of any lexical significance, normally only being +allowed within strings and comments. In such contexts, lexers should +ignore ch if styler.IsLeadByte(ch) returns TRUE. + +Note: UTF-8 is simpler than Shift-JIS, so no special handling is +applied for it. All UTF-8 extended characters are >= 128 and none are +lexically significant in programming languages which, so far, use only +characters in ASCII for operators, comment markers, etc. + + +Special case: Folding + +Folding may be performed in the lexer function. It is better to use a +separate folder function as that avoids some troublesome interaction +between styling and folding. The folder function will be run after the +lexer function if folding is enabled. The rest of this section explains +how to perform folding within the lexer function. + +During initialization, lexers that support folding set + + bool fold = styler.GetPropertyInt("fold"); + +If folding is enabled in the editor, fold will be TRUE and the lexer +should call: + + styler.SetLevel(line, level); + +at the end of each line and just before exiting. + +The line parameter is simply the count of the number of newlines seen. +It's initial value is styler.GetLine(startPos) and it is incremented +(after calling styler.SetLevel) whenever a newline is seen. + +The level parameter is the desired indentation level in the low 12 bits, +along with flag bits in the upper four bits. The indentation level +depends on the language. For C++, it is incremented when the lexer sees +a '{' and decremented when the lexer sees a '}' (outside of strings and +comments, of course). + +The following flag bits, defined in Scintilla.h, may be set or cleared +in the flags parameter. The SC_FOLDLEVELWHITEFLAG flag is set if the +lexer considers that the line contains nothing but whitespace. The +SC_FOLDLEVELHEADERFLAG flag indicates that the line is a fold point. +This normally means that the next line has a greater level than present +line. However, the lexer may have some other basis for determining a +fold point. For example, a lexer might create a header line for the +first line of a function definition rather than the last. + +The SC_FOLDLEVELNUMBERMASK mask denotes the level number in the low 12 +bits of the level param. This mask may be used to isolate either flags +or level numbers. + +For example, the C++ lexer contains the following code when a newline is +seen: + + if (fold) { + int lev = levelPrev; + + // Set the "all whitespace" bit if the line is blank. + if (visChars == 0) + lev |= SC_FOLDLEVELWHITEFLAG; + + // Set the "header" bit if needed. + if ((levelCurrent > levelPrev) && (visChars > 0)) + lev |= SC_FOLDLEVELHEADERFLAG; + styler.SetLevel(lineCurrent, lev); + + // reinitialize the folding vars describing the present line. + lineCurrent++; + visChars = 0; // Number of non-whitespace characters on the line. + levelPrev = levelCurrent; + } + +The following code appears in the C++ lexer just before exit: + + // Fill in the real level of the next line, keeping the current flags + // as they will be filled in later. + if (fold) { + // Mask off the level number, leaving only the previous flags. + int flagsNext = styler.LevelAt(lineCurrent); + flagsNext &= ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, levelPrev | flagsNext); + } + + +Don't worry about performance + +The writer of a lexer may safely ignore performance considerations: the +cost of redrawing the screen is several orders of magnitude greater than +the cost of function calls, etc. Moreover, Scintilla performs all the +important optimizations; Scintilla ensures that a lexer will be called +only to recolor text that actually needs to be recolored. Finally, it +is not necessary to avoid extra calls to styler.ColourTo: the sytler +object buffers calls to ColourTo to avoid multiple updates of the +screen. + +Page contributed by Edward K. Ream \ No newline at end of file diff --git a/scintilla/doc/SciBreak.jpg b/scintilla/doc/SciBreak.jpg new file mode 100644 index 00000000..b63b09f9 Binary files /dev/null and b/scintilla/doc/SciBreak.jpg differ diff --git a/scintilla/doc/SciCoding.html b/scintilla/doc/SciCoding.html new file mode 100644 index 00000000..c7d072b8 --- /dev/null +++ b/scintilla/doc/SciCoding.html @@ -0,0 +1,251 @@ + + + + + + + + Scintilla and SciTE Code Style Preferences + + + + + + + + + +
+ Scintilla icon + + Scintilla + and SciTE +
+

+ Code Style +

+

+ Introduction +

+

+ The source code of Scintilla and SciTE follow my preferences. + Some of these decisions are arbitrary and based on my sense of aesthetics + but its good to have all the code look the same even if its not exactly how + everyone would prefer. +

+

+ Code that does not follow these conventions will be accepted, but will be modified + as time goes by to fit the conventions. Scintilla code follows the conventions more + closely than SciTE except for lexers which are relatively independent modules. + Lexers that are maintained by others are left as they are submitted except that + warnings will be fixed so the whole project can compile cleanly. +

+

+ The AStyle formatting + program with a '-tapO' argument formats code in much the right way although + there are a few bugs in AStyle. The scite/scripts/Fixer.py script will run AStyle + over a C++ source file and fix up some of those bugs. +

+

+ Language features +

+

+ Design goals for Scintilla and SciTE include portability to currently available C++ + compilers on diverse platforms with high performance and low resource usage. + Scintilla has stricter portability requirements to SciTE as it may be ported to + low capability platforms such as Windows CE or PalmOS but it is less likely + SciTE will be. +

+

+ To achieve portability, only a subset of C++ features are used. Exceptions are + not available on some platforms such as Windows CE so exceptions are not used + and thus the standard C++ library can not be used. + Template support differs between compilers so is not used in Scintilla but there + are some simple uses in SciTE. + Run-time type information adds to memory use so is turned off. + Name spaces are not used. +

+

+ The goto statement is not used because of bad memories from my first job + maintaining FORTRAN programs. The union feature is not used as it can lead to + non-type-safe value access. +

+

+ Casting +

+

+ Do not use old C style casts like (char *)s. Instead use the most strict form of C++ + cast possible like const_cast<char *>(s). Use static_cast and const_cast + where possible rather than reinterpret_cast. Because the code is compiled with + run-time type information turned off, dynamic_cast will not work. +

+

+ The benefit to using the new style casts is that they explicitly detail what evil is + occurring and act as signals that something potentially unsafe is being done. +

+

+ Code that treats const seriously is easier to reason about both for humans + and compilers, so use const parameters and avoid const_cast. +

+

+ Warnings +

+

+ To help ensure code is well written and portable, it is compiled with almost all + warnings turned on. This sometimes results in warnings about code that is + completely good (false positives) but changing the code to avoid the warnings + is generally fast and has little impact on readability. +

+

+ Initialise all variables and minimise the scope of variables. If a variable is defined + just before its use then it can't be misused by code before that point. + Use loop declarations that are compatible with both the C++ standard and currently + available compilers. +

+

+ Allocation +

+

+ As exceptions are not used, memory exhaustion can occur. + This should be checked for and handled but there is quite a lot of Scintilla and + SciTE code that doesn't yet. + Fixed length buffers are often used as these are simple and avoid the need to + worry about memory exhaustion but then require that buffer lengths are + respected. +

+

+ The C++ new and delete operators are preferred over C's malloc and free + as new and delete are type safe. +

+

+ Bracketing +

+

+ Start brackets, '{', should be located on the line of the control structure they + start and end brackets, '}', should be at the indented start of a line. When there is + an else clause, this occurs on the same line as the '}'. + This format uses less lines than alternatives, allowing more code to be seen on screen. + Fully bracketed control + structures are preferred because this makes it more likely that modifications will + be correct and it allows Scintilla's folder to work. No braces on returned + expressions as return is a keyword, not a function call. +

+bool fn(int a) {
+        
if (a) {
+                
s();
+                
t();
+        
} else {
+                
u();
+        
}
+        
return !a;
+
}
+

+ Spacing +

+

+ Spaces on both sides of '=' and comparison operators and no attempt to line up '='. + No space before or after '(', when used in calls, but a space after every ','. + No spaces between tokens in short expressions but may be present in + longer expressions. Space before '{'. No space before ';'. + No space after '*' when used to mean pointer and no space after '[' or ']'. + One space between keywords and '('. +

+void StoreConditionally(int c, const char *s) {
+        
if (c && (baseSegment == trustSegment["html"])) {
+                
baseSegment = s+1;
+                
Store(s, baseSegment, "html");
+        
}
+
} +

+ Names +

+

+ Identifiers use mixed case and no underscores. + Class, function and method names start with an uppercase letter and use + further upper case letters to distinguish words. Variables start with a lower + case letter and use upper case letters to distinguish words. + Loop counters and similar variables can have simple names like 'i'. + Function calls should be differentiated from method calls with an initial '::' + global scope modifier. +

+class StorageZone {
+
public:
+        
void Store(const char *s) {
+                
Media *mediaStore = ::GetBaseMedia(zoneDefault);
+                
for (int i=mediaStore->cursor; mediaStore[i], i++) {
+                        
mediaStore->Persist(s[i]);
+                
}
+        
}
+
}; + + diff --git a/scintilla/doc/SciRest.jpg b/scintilla/doc/SciRest.jpg new file mode 100644 index 00000000..4b052239 Binary files /dev/null and b/scintilla/doc/SciRest.jpg differ diff --git a/scintilla/doc/SciTEIco.png b/scintilla/doc/SciTEIco.png new file mode 100644 index 00000000..d0cc869b Binary files /dev/null and b/scintilla/doc/SciTEIco.png differ diff --git a/scintilla/doc/SciWord.jpg b/scintilla/doc/SciWord.jpg new file mode 100644 index 00000000..60e70e89 Binary files /dev/null and b/scintilla/doc/SciWord.jpg differ diff --git a/scintilla/doc/ScintillaDoc.html b/scintilla/doc/ScintillaDoc.html new file mode 100644 index 00000000..002d2bd9 --- /dev/null +++ b/scintilla/doc/ScintillaDoc.html @@ -0,0 +1,5595 @@ + + + + + + + + + + Scintilla and SciTE + + + + + + + + + + + +
Scintilla iconScintilla
+ +

Scintilla Documentation

+ +

Last edited 20/June/2007 NH

+ +

There is an overview of the internal design of + Scintilla.
+ Some notes on using Scintilla.
+ How to use the Scintilla Edit Control on Windows.
+ A simple sample using Scintilla from + C++ on Windows.
+ A simple sample using Scintilla from + Visual Basic.
+ Bait is a tiny sample using Scintilla + on GTK+.
+ A detailed description of how to write a lexer, including a + discussion of folding.
+ + How to implement a lexer in the container.
+ + How to implement folding.
+ The coding style used in Scintilla and SciTE is + worth following if you want to contribute code to Scintilla but is not compulsory.

+ +

Introduction

+ +

The Windows version of Scintilla is a Windows Control. As such, its primary programming + interface is through Windows messages. Early versions of Scintilla emulated much of the API + defined by the standard Windows Edit and RichEdit controls but those APIs are now deprecated in + favour of Scintilla's own, more consistent API. In addition to messages performing the actions + of a normal Edit control, Scintilla allows control of syntax styling, folding, markers, autocompletion + and call tips.

+ +

The GTK+ version also uses messages in a similar way to the Windows version. This is + different to normal GTK+ practice but made it easier to implement rapidly.

+ +

This documentation describes the individual messages and notifications used by Scintilla. It + does not describe how to link them together to form a useful editor. For now, the best way to + work out how to develop using Scintilla is to see how SciTE uses it. SciTE exercises most of + Scintilla's facilities.

+ +

In the descriptions that follow, the messages are described as function calls with zero, one + or two arguments. These two arguments are the standard wParam and + lParam familiar to Windows programmers. These parameters are integers that + are large enough to hold pointers, and the return value is also an integer large enough to contain a + pointer. + Although the commands only use the + arguments described, because all messages have two arguments whether Scintilla uses them or + not, it is strongly recommended that any unused arguments are set to 0. This allows future + enhancement of messages without the risk of breaking existing code. Common argument types + are:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
boolArguments expect the values 0 for false and 1 for + true.
intArguments are 32-bit signed integers.
const char *Arguments point at text that is being passed to Scintilla but not modified. The text + may be zero terminated or another argument may specify the character count, the + description will make this clear.
char *Arguments point at text buffers that Scintilla will fill with text. In some cases, + another argument will tell Scintilla the buffer size. In others, you must make sure that + the buffer is big enough to hold the requested text. If a NULL pointer (0) is passed + then, for SCI_* calls, the length that should be allocated is returned.
colourColours are set using the RGB format (Red, Green, Blue). The intensity of each colour + is set in the range 0 to 255. If you have three such intensities, they are combined as: + red | (green << 8) | (blue << 16). If you set all intensities to 255, the + colour is white. If you set all intensities to 0, the colour is black. When you set a + colour, you are making a request. What you will get depends on the capabilities of the + system and the current screen mode.
alphaTranslucency is set using an alpha value. + Alpha ranges from 0 (SC_ALPHA_TRANSPARENT) which is completely transparent to + 255 (SC_ALPHA_OPAQUE) which is opaque. The value 256 (SC_ALPHA_NOALPHA) + is opaque and uses code that is not alpha-aware and may be faster. Not all platforms support + translucency and only some Scintilla features implement translucency. + The default alpha value for most features is SC_ALPHA_NOALPHA.
<unused>This is an unused argument. Setting it to 0 will ensure compatibility with future + enhancements.
+ +

Contents

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
o Text retrieval and + modificationo Searching and replacingo Overtype
o Cut, copy and pasteo Error handlingo Undo and Redo
o Selection and informationo Scrolling and automatic + scrollingo White space
o Cursoro Mouse captureo Line endings
o Stylingo Style definitiono Caret, selection, and hotspot styles
o Marginso Other settingso Brace highlighting
o Tabs and Indentation + Guideso Markerso Indicators
o Autocompletiono User listso Call tips
o Keyboard commandso Key bindingso Popup edit menu
o Macro recordingo Printingo Direct access
o Multiple viewso Foldingo Line wrapping
o Zoomingo Long lineso Lexer
o Notificationso GTK+o Deprecated messages
o Edit messages never + supported by Scintillao Building Scintilla
+ +

Messages with names of the form SCI_SETxxxxx often have a companion + SCI_GETxxxxx. To save tedious repetition, if the SCI_GETxxxxx message + returns the value set by the SCI_SETxxxxx message, the SET routine is + described and the GET routine is left to your imagination.

+ +

Text retrieval and modification

+ +

Each character in a Scintilla document is followed by an associated byte of styling + information. The combination of a character byte and a style byte is called a cell. Style bytes + are interpreted an index into an array of styles. + Style bytes may be split into an index and a set of indicator bits + but this use is discouraged and indicators should now use + SCI_INDICATORFILLRANGE + and related calls. + The default split is with the index in the low 5 bits and 3 high bits as indicators. This allows 32 fundamental styles, which is enough for most + languages, and three independent indicators so that, for example, syntax errors, deprecated + names and bad indentation could all be displayed at once. The number of bits used for styles + can be altered with SCI_SETSTYLEBITS up to a maximum of 7 bits. + The remaining bits can be used for indicators.

+ +

Positions within the Scintilla document refer to a character or the gap before that + character. The first character in a document is 0, the second 1 and so on. If a document + contains nLen characters, the last character is numbered nLen-1. + The caret exists between character positions and can be located from before the first character (0) + to after the last character (nLen).

+ +

There are places where the caret can not go where two character bytes make up one character. + This occurs when a DBCS character from a language like Japanese is included in the document or + when line ends are marked with the CP/M standard of a carriage return followed by a line feed. + The INVALID_POSITION constant (-1) represents an invalid position within the + document.

+ +

All lines of text in Scintilla are the same height, and this height is calculated from the + largest font in any current style. This restriction is for performance; if lines differed in + height then calculations involving positioning of text would require the text to be styled + first.

+ SCI_GETTEXT(int length, char *text)
+ SCI_SETTEXT(<unused>, const char *text)
+ SCI_SETSAVEPOINT
+ SCI_GETLINE(int line, char *text)
+ SCI_REPLACESEL(<unused>, const char + *text)
+ SCI_SETREADONLY(bool readOnly)
+ SCI_GETREADONLY
+ SCI_GETTEXTRANGE(<unused>, TextRange + *tr)
+ SCI_ALLOCATE(int bytes, <unused>)
+ SCI_ADDTEXT(int length, const char *s)
+ SCI_ADDSTYLEDTEXT(int length, cell *s)
+ SCI_APPENDTEXT(int length, const char *s)
+ SCI_INSERTTEXT(int pos, const char *text)
+ SCI_CLEARALL
+ SCI_CLEARDOCUMENTSTYLE
+ SCI_GETCHARAT(int position)
+ SCI_GETSTYLEAT(int position)
+ SCI_GETSTYLEDTEXT(<unused>, TextRange + *tr)
+ SCI_SETSTYLEBITS(int bits)
+ SCI_GETSTYLEBITS
+ SCI_TARGETASUTF8(<unused>, char *s)
+ SCI_ENCODEDFROMUTF8(const char *utf8, char *encoded)
+ SCI_SETLENGTHFORENCODE(int bytes)
+
+ +

SCI_GETTEXT(int length, char *text)
+ This returns length-1 characters of text from the start of the document plus one + terminating 0 character. To collect all the text in a document, use SCI_GETLENGTH + to get the number of characters in the document (nLen), allocate a character + buffer of length nLen+1 bytes, then call SCI_GETTEXT(nLen+1, char + *text). If the text argument is 0 then the length that should be allocated to store the + entire document is returned. + If you then save the text, you should use SCI_SETSAVEPOINT to mark + the text as unmodified.

+ +

See also: SCI_GETSELTEXT, SCI_GETCURLINE, SCI_GETLINE, SCI_GETSTYLEDTEXT, SCI_GETTEXTRANGE

+ +

SCI_SETTEXT(<unused>, const char *text)
+ This replaces all the text in the document with the zero terminated text string you pass + in.

+ +

SCI_SETSAVEPOINT
+ This message tells Scintilla that the current state of the document is unmodified. This is + usually done when the file is saved or loaded, hence the name "save point". As Scintilla + performs undo and redo operations, it notifies the container that it has entered or left the + save point with SCN_SAVEPOINTREACHED and SCN_SAVEPOINTLEFT notification messages, allowing the container to know if the file + should be considered dirty or not.

+ +

See also: SCI_EMPTYUNDOBUFFER, SCI_GETMODIFY

+ +

SCI_GETLINE(int line, char *text)
+ This fills the buffer defined by text with the contents of the nominated line (lines start at + 0). The buffer is not terminated by a 0 character. It is up to you to make sure that the buffer + is long enough for the text, use SCI_LINELENGTH(int line). The returned value is the + number of characters copied to the buffer. The returned text includes any end of line + characters. If you ask for a line number outside the range of lines in the document, 0 + characters are copied. If the text argument is 0 then the length that should be allocated + to store the entire line is returned.

+ +

See also: SCI_GETCURLINE, SCI_GETSELTEXT, SCI_GETTEXTRANGE, SCI_GETSTYLEDTEXT, SCI_GETTEXT

+ +

SCI_REPLACESEL(<unused>, const char *text)
+ The currently selected text between the anchor + and the current position is replaced by the 0 terminated text string. If the anchor and + current position are the same, the text is inserted at the caret position. The caret is + positioned after the inserted text and the caret is scrolled into view.

+ +

SCI_SETREADONLY(bool readOnly)
+ SCI_GETREADONLY
+ These messages set and get the read-only flag for the document. If you mark a document as read + only, attempts to modify the text cause the SCN_MODIFYATTEMPTRO notification.

+ +

SCI_GETTEXTRANGE(<unused>, TextRange *tr)
+ This collects the text between the positions cpMin and cpMax and + copies it to lpstrText (see struct TextRange in + Scintilla.h). If cpMax is -1, text is returned to the end of the + document. The text is 0 terminated, so you must supply a buffer that is at least 1 character + longer than the number of characters you wish to read. The return value is the length of the + returned text not including the terminating 0.

+ +

See also: SCI_GETSELTEXT, SCI_GETLINE, SCI_GETCURLINE, SCI_GETSTYLEDTEXT, SCI_GETTEXT

+ +

SCI_GETSTYLEDTEXT(<unused>, TextRange *tr)
+ This collects styled text into a buffer using two bytes for each cell, with the character at + the lower address of each pair and the style byte at the upper address. Characters between the + positions cpMin and cpMax are copied to lpstrText (see + struct TextRange in Scintilla.h). Two 0 bytes are added to the end of + the text, so the buffer that lpstrText points at must be at least + 2*(cpMax-cpMin)+2 bytes long. No check is made for sensible values of + cpMin or cpMax. Positions outside the document return character codes + and style bytes of 0.

+ +

See also: SCI_GETSELTEXT, SCI_GETLINE, SCI_GETCURLINE, SCI_GETTEXTRANGE, SCI_GETTEXT

+ +

SCI_ALLOCATE(int bytes, <unused>)
+ Allocate a document buffer large enough to store a given number of bytes. + The document will not be made smaller than its current contents.

+ +

SCI_ADDTEXT(int length, const char *s)
+ This inserts the first length characters from the string s + at the current position. This will include any 0's in the string that you might have expected + to stop the insert operation. The current position is set at the end of the inserted text, + but it is not scrolled into view.

+ +

SCI_ADDSTYLEDTEXT(int length, cell *s)
+ This behaves just like SCI_ADDTEXT, but inserts styled text.

+ +

SCI_APPENDTEXT(int length, const char *s)
+ This adds the first length characters from the string s to the end + of the document. This will include any 0's in the string that you might have expected to stop + the operation. The current selection is not changed and the new text is not scrolled into + view.

+ +

SCI_INSERTTEXT(int pos, const char *text)
+ This inserts the zero terminated text string at position pos or at + the current position if pos is -1. If the current position is after the insertion point + then it is moved along with its surrounding text but no scrolling is performed.

+ +

SCI_CLEARALL
+ Unless the document is read-only, this deletes all the text.

+ +

SCI_CLEARDOCUMENTSTYLE
+ When wanting to completely restyle the document, for example after choosing a lexer, the + SCI_CLEARDOCUMENTSTYLE can be used to clear all styling information and reset the + folding state.

+ +

SCI_GETCHARAT(int pos)
+ This returns the character at pos in the document or 0 if pos is + negative or past the end of the document.

+ +

SCI_GETSTYLEAT(int pos)
+ This returns the style at pos in the document, or 0 if pos is + negative or past the end of the document.

+ +

SCI_SETSTYLEBITS(int bits)
+ SCI_GETSTYLEBITS
+ This pair of routines sets and reads back the number of bits in each cell to use for styling, + to a maximum of 7 style bits. The remaining bits can be used as indicators. The standard + setting is SCI_SETSTYLEBITS(5). + The number of styling bits needed by the current lexer can be found with + SCI_GETSTYLEBITSNEEDED.

+ +

TextRange and CharacterRange
+ These structures are defined to be exactly the same shape as the Win32 TEXTRANGE + and CHARRANGE, so that older code that treats Scintilla as a RichEdit will + work.

+
+struct CharacterRange {
+    long cpMin;
+    long cpMax;
+};
+
+struct TextRange {
+    struct CharacterRange chrg;
+    char *lpstrText;
+};
+
+ +

GTK+-specific: Access to encoded text

+ +

SCI_TARGETASUTF8(<unused>, char *s)
+ This method retrieves the value of the target encoded as UTF-8 which is the default + encoding of GTK+ so is useful for retrieving text for use in other parts of the user interface, + such as find and replace dialogs. The length of the encoded text in bytes is returned. +

+ +

SCI_ENCODEDFROMUTF8(const char *utf8, char *encoded)
+ SCI_SETLENGTHFORENCODE(int bytes)
+ SCI_ENCODEDFROMUTF8 converts a UTF-8 string into the document's + encoding which is useful for taking the results of a find dialog, for example, and receiving + a string of bytes that can be searched for in the document. Since the text can contain nul bytes, + the SCI_SETLENGTHFORENCODE method can be used to set the + length that will be converted. If set to -1, the length is determined by finding a nul byte. + The length of the converted string is returned. +

+ + +

Searching

+

+ There are methods to search for text and for regular expressions. The regular expression support + is limited and should only be used for simple cases and initial development. +

+ SCI_FINDTEXT(int flags, TextToFind + *ttf)
+ SCI_SEARCHANCHOR
+ SCI_SEARCHNEXT(int searchFlags, const char + *text)
+ SCI_SEARCHPREV(int searchFlags, const char + *text)
+ Search and replace using the + target
+
+ +

searchFlags
+ Several of the search routines use flag options, which include a simple regular expression + search. Combine the flag options by adding them:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SCFIND_MATCHCASEA match only occurs with text that matches the case of the search string.
SCFIND_WHOLEWORDA match only occurs if the characters before and after are not word characters.
SCFIND_WORDSTARTA match only occurs if the character before is not a word character.
SCFIND_REGEXPThe search string should be interpreted as a regular expression.
SCFIND_POSIXTreat regular expression in a more POSIX compatible manner + by interpreting bare ( and ) for tagged sections rather than \( and \).
+ +

If SCFIND_REGEXP is not included in the searchFlags, you can + search backwards to find the previous occurrence of a search string by setting the end of the + search range before the start. If SCFIND_REGEXP is included, searches are always + from a lower position to a higher position, even if the search range is backwards.

+ +

In a regular expression, special characters interpreted are:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
.Matches any character
\(This marks the start of a region for tagging a match.
\)This marks the end of a tagged region.
\nWhere n is 1 through 9 refers to the first through ninth tagged region + when replacing. For example, if the search string was Fred\([1-9]\)XXX and + the replace string was Sam\1YYY, when applied to Fred2XXX this + would generate Sam2YYY.
\<This matches the start of a word using Scintilla's definitions of words.
\>This matches the end of a word using Scintilla's definition of words.
\xThis allows you to use a character x that would otherwise have a special meaning. For + example, \[ would be interpreted as [ and not as the start of a character set.
[...]This indicates a set of characters, for example, [abc] means any of the characters a, + b or c. You can also use ranges, for example [a-z] for any lower case character.
[^...]The complement of the characters in the set. For example, [^A-Za-z] means any + character except an alphabetic character.
^This matches the start of a line (unless used inside a set, see above).
$This matches the end of a line.
*This matches 0 or more times. For example, Sa*m matches Sm, + Sam, Saam, Saaam and so on.
+This matches 1 or more times. For example, Sa+m matches + Sam, Saam, Saaam and so on.
+ +

SCI_FINDTEXT(int searchFlags, TextToFind *ttf)
+ This message searches for text in the document. It does not use or move the current selection. + The searchFlags argument controls the + search type, which includes regular expression searches.

+ +

The TextToFind structure is defined in Scintilla.h; set + chrg.cpMin and chrg.cpMax with the range of positions in the document + to search. If SCFIND_REGEXP is not included in the flags, you can search backwards by + setting chrg.cpMax less than chrg.cpMin. If SCFIND_REGEXP + is included, the search is always forwards (even if chrg.cpMax is less than chrg.cpMin). + Set the lpstrText member of TextToFind to point at a zero terminated + text string holding the search pattern. If your language makes the use of TextToFind + difficult, you should consider using SCI_SEARCHINTARGET instead.

+ +

The return value is -1 if the search fails or the position of the start of the found text if + it succeeds. The chrgText.cpMin and chrgText.cpMax members of + TextToFind are filled in with the start and end positions of the found text.

+ +

See also: SCI_SEARCHINTARGET

+ +

TextToFind
+ This structure is defined to have exactly the same shape as the Win32 structure + FINDTEXTEX for old code that treated Scintilla as a RichEdit control.

+
+struct TextToFind {
+    struct CharacterRange chrg;     // range to search
+    char *lpstrText;                // the search pattern (zero terminated)
+    struct CharacterRange chrgText; // returned as position of matching text
+};
+
+ +

SCI_SEARCHANCHOR
+ SCI_SEARCHNEXT(int searchFlags, const char *text)
+ SCI_SEARCHPREV(int searchFlags, const char *text)
+ These messages provide relocatable search support. This allows multiple incremental + interactive searches to be macro recorded while still setting the selection to found text so + the find/select operation is self-contained. These three messages send SCN_MACRORECORD notifications if macro recording is enabled.

+ +

SCI_SEARCHANCHOR sets the search start point used by + SCI_SEARCHNEXT and SCI_SEARCHPREV to the start of the current + selection, that is, the end of the selection that is nearer to the start of the document. You + should always call this before calling either of SCI_SEARCHNEXT or + SCI_SEARCHPREV.

+ +

SCI_SEARCHNEXT and SCI_SEARCHPREV search for the next and previous + occurrence of the zero terminated search string pointed at by text. The search is modified by + the searchFlags. If you request a regular + expression, SCI_SEARCHPREV finds the first occurrence of the search string in the + document, not the previous one before the anchor point.

+ +

The return value is -1 if nothing is found, otherwise the return value is the start position + of the matching text. The selection is updated to show the matched text, but is not scrolled + into view.

+ +

See also: SCI_SEARCHINTARGET, + SCI_FINDTEXT

+ +

Search and replace using the target

+ +

Using SCI_REPLACESEL, + modifications cause scrolling and other visible changes, which may take some time and cause + unwanted display updates. If performing many changes, such as a replace all command, the target + can be used instead. First, set the target, ie. the range to be replaced. Then call + SCI_REPLACETARGET or SCI_REPLACETARGETRE.

+ +

Searching can be performed within the target range with SCI_SEARCHINTARGET, + which uses a counted string to allow searching for null characters. It returns the length of + range or -1 for failure, in which case the target is not moved. The flags used by + SCI_SEARCHINTARGET such as SCFIND_MATCHCASE, + SCFIND_WHOLEWORD, SCFIND_WORDSTART, and SCFIND_REGEXP + can be set with SCI_SETSEARCHFLAGS. SCI_SEARCHINTARGET may be simpler + for some clients to use than SCI_FINDTEXT, as that requires using a pointer to a + structure.

+ SCI_SETTARGETSTART(int pos)
+ SCI_GETTARGETSTART
+ SCI_SETTARGETEND(int pos)
+ SCI_GETTARGETEND
+ SCI_TARGETFROMSELECTION
+ SCI_SETSEARCHFLAGS(int searchFlags)
+ SCI_GETSEARCHFLAGS
+ SCI_SEARCHINTARGET(int length, const char + *text)
+ SCI_REPLACETARGET(int length, const char + *text)
+ SCI_REPLACETARGETRE(int length, const char + *text)
+
+ +

SCI_SETTARGETSTART(int pos)
+ SCI_GETTARGETSTART
+ SCI_SETTARGETEND(int pos)
+ SCI_GETTARGETEND
+ These functions set and return the start and end of the target. When searching in non-regular + expression mode, you can set start greater than end to find the last matching text in the + target rather than the first matching text. The target is also set by a successful + SCI_SEARCHINTARGET.

+ +

SCI_TARGETFROMSELECTION
+ Set the target start and end to the start and end positions of the selection.

+ +

SCI_SETSEARCHFLAGS(int searchFlags)
+ SCI_GETSEARCHFLAGS
+ These get and set the searchFlags used by + SCI_SEARCHINTARGET. There are several option flags including a simple regular + expression search.

+ +

SCI_SEARCHINTARGET(int length, const char *text)
+ This searches for the first occurrence of a text string in the target defined by + SCI_SETTARGETSTART and SCI_SETTARGETEND. The text string is not zero + terminated; the size is set by length. The search is modified by the search flags + set by SCI_SETSEARCHFLAGS. If the search succeeds, the target is set to the found + text and the return value is the position of the start of the matching text. If the search + fails, the result is -1.

+ +

SCI_REPLACETARGET(int length, const char *text)
+ If length is -1, text is a zero terminated string, otherwise + length sets the number of character to replace the target with. + After replacement, the target range refers to the replacement text. + The return value + is the length of the replacement string.
+ Note that the recommended way to delete text in the document is to set the target to the text to be removed, + and to perform a replace target with an empty string.

+ +

SCI_REPLACETARGETRE(int length, const char *text)
+ This replaces the target using regular expressions. If length is -1, + text is a zero terminated string, otherwise length is the number of + characters to use. The replacement string is formed from the text string with any sequences of + \1 through \9 replaced by tagged matches from the most recent regular + expression search. + After replacement, the target range refers to the replacement text. + The return value is the length of the replacement string.

+ +

See also: SCI_FINDTEXT

+ +

Overtype

+ +

SCI_SETOVERTYPE(bool overType)
+ SCI_GETOVERTYPE
+ When overtype is enabled, each typed character replaces the character to the right of the text + caret. When overtype is disabled, characters are inserted at the caret. + SCI_GETOVERTYPE returns TRUE (1) if overtyping is active, otherwise + FALSE (0) will be returned. Use SCI_SETOVERTYPE to set the overtype + mode.

+ +

Cut, copy and paste

+ + SCI_CUT
+ SCI_COPY
+ SCI_PASTE
+ SCI_CLEAR
+ SCI_CANPASTE
+ SCI_COPYRANGE(int start, int end)
+ SCI_COPYTEXT(int length, + const char *text)
+ SCI_COPYALLOWLINE
+ SCI_SETPASTECONVERTENDINGS(bool convert)
+ SCI_GETPASTECONVERTENDINGS
+
+ +

SCI_CUT
+ SCI_COPY
+ SCI_PASTE
+ SCI_CLEAR
+ SCI_CANPASTE
+ SCI_COPYALLOWLINE
+ These commands perform the standard tasks of cutting and copying data to the clipboard, + pasting from the clipboard into the document, and clearing the document. + SCI_CANPASTE returns non-zero if the document isn't read-only and if the selection + doesn't contain protected text. If you need a "can copy" or "can cut", use + SCI_GETSELECTIONSTART()-SCI_GETSELECTIONEND(), which will be non-zero if you can + copy or cut to the clipboard.

+ +

GTK+ does not really support SCI_CANPASTE and always returns TRUE + unless the document is read-only.

+ +

On X, the clipboard is asynchronous and may require several messages between + the destination and source applications. Data from SCI_PASTE will not arrive in the + document immediately.

+ +

SCI_COPYALLOWLINE works the same as SCI_COPY except that if the + selection is empty then the current line is copied. On Windows, an extra "MSDEVLineSelect" marker + is added to the clipboard which is then used in SCI_PASTE to paste + the whole line before the current line.

+ + SCI_COPYRANGE(int start, int end)
+ SCI_COPYTEXT(int length, const char *text)
+

SCI_COPYRANGE copies a range of text from the document to + the system clipboard and SCI_COPYTEXT copies a supplied piece of + text to the system clipboard.

+ +

SCI_SETPASTECONVERTENDINGS(bool convert)
+ SCI_GETPASTECONVERTENDINGS
+ If this property is set then when text is pasted any line ends are converted to match the document's + end of line mode as set with + SCI_SETEOLMODE. + Currently only changeable on Windows. On GTK+ pasted text is always converted.

+ +

Error handling

+ +

SCI_SETSTATUS(int status)
+ SCI_GETSTATUS
+ If an error occurs, Scintilla may set an internal error number that can be retrieved with + SCI_GETSTATUS. Not currently used but will be in the future. To clear the error + status call SCI_SETSTATUS(0).

+ +

Undo and Redo

+ +

Scintilla has multiple level undo and redo. It will continue to collect undoable actions + until memory runs out. Scintilla saves actions that change the document. Scintilla does not + save caret and selection movements, view scrolling and the like. Sequences of typing or + deleting are compressed into single transactions to make it easier to undo and redo at a sensible + level of detail. Sequences of actions can be combined into transactions that are undone as a unit. + These sequences occur between SCI_BEGINUNDOACTION and + SCI_ENDUNDOACTION messages. These transactions can be nested and only the top-level + sequences are undone as units.

+ SCI_UNDO
+ SCI_CANUNDO
+ SCI_EMPTYUNDOBUFFER
+ SCI_REDO
+ SCI_CANREDO
+ SCI_SETUNDOCOLLECTION(bool + collectUndo)
+ SCI_GETUNDOCOLLECTION
+ SCI_BEGINUNDOACTION
+ SCI_ENDUNDOACTION
+
+ +

SCI_UNDO
+ SCI_CANUNDO
+ SCI_UNDO undoes one action, or if the undo buffer has reached a + SCI_ENDUNDOACTION point, all the actions back to the corresponding + SCI_BEGINUNDOACTION.

+ +

SCI_CANUNDO returns 0 if there is nothing to undo, and 1 if there is. You would + typically use the result of this message to enable/disable the Edit menu Undo command.

+ +

SCI_REDO
+ SCI_CANREDO
+ SCI_REDO undoes the effect of the last SCI_UNDO operation.

+ +

SCI_CANREDO returns 0 if there is no action to redo and 1 if there are undo + actions to redo. You could typically use the result of this message to enable/disable the Edit + menu Redo command.

+ +

SCI_EMPTYUNDOBUFFER
+ This command tells Scintilla to forget any saved undo or redo history. It also sets the save + point to the start of the undo buffer, so the document will appear to be unmodified. This does + not cause the SCN_SAVEPOINTREACHED notification to be sent to the + container.

+ +

See also: SCI_SETSAVEPOINT

+ +

SCI_SETUNDOCOLLECTION(bool collectUndo)
+ SCI_GETUNDOCOLLECTION
+ You can control whether Scintilla collects undo information with + SCI_SETUNDOCOLLECTION. Pass in true (1) to collect information and + false (0) to stop collecting. If you stop collection, you should also use + SCI_EMPTYUNDOBUFFER to avoid the undo buffer being unsynchronized with the data in + the buffer.

+ +

You might wish to turn off saving undo information if you use the Scintilla to store text + generated by a program (a Log view) or in a display window where text is often deleted and + regenerated.

+ +

SCI_BEGINUNDOACTION
+ SCI_ENDUNDOACTION
+ Send these two messages to Scintilla to mark the beginning and end of a set of operations that + you want to undo all as one operation but that you have to generate as several operations. + Alternatively, you can use these to mark a set of operations that you do not want to have + combined with the preceding or following operations if they are undone.

+ +

Selection and information

+ +

Scintilla maintains a selection that stretches between two points, the anchor and the + current position. If the anchor and the current position are the same, there is no selected + text. Positions in the document range from 0 (before the first character), to the document size + (after the last character). If you use messages, there is nothing to stop you setting a + position that is in the middle of a CRLF pair, or in the middle of a 2 byte character. However, + keyboard commands will not move the caret into such positions.

+ SCI_GETTEXTLENGTH
+ SCI_GETLENGTH
+ SCI_GETLINECOUNT
+ SCI_GETFIRSTVISIBLELINE
+ SCI_LINESONSCREEN
+ SCI_GETMODIFY
+ SCI_SETSEL(int anchorPos, int currentPos)
+ SCI_GOTOPOS(int position)
+ SCI_GOTOLINE(int line)
+ SCI_SETCURRENTPOS(int position)
+ SCI_GETCURRENTPOS
+ SCI_SETANCHOR(int position)
+ SCI_GETANCHOR
+ SCI_SETSELECTIONSTART(int position)
+ SCI_GETSELECTIONSTART
+ SCI_SETSELECTIONEND(int position)
+ SCI_GETSELECTIONEND
+ SCI_SELECTALL
+ SCI_LINEFROMPOSITION(int position)
+ SCI_POSITIONFROMLINE(int line)
+ SCI_GETLINEENDPOSITION(int line)
+ SCI_LINELENGTH(int line)
+ SCI_GETCOLUMN(int position)
+ SCI_FINDCOLUMN(int line, int column)
+ SCI_POSITIONFROMPOINT(int x, int y)
+ SCI_POSITIONFROMPOINTCLOSE(int x, int + y)
+ SCI_POINTXFROMPOSITION(<unused>, int + position)
+ SCI_POINTYFROMPOSITION(<unused>, int + position)
+ SCI_HIDESELECTION(bool hide)
+ SCI_GETSELTEXT(<unused>, char *text)
+ SCI_GETCURLINE(int textLen, char *text)
+ SCI_SELECTIONISRECTANGLE
+ SCI_SETSELECTIONMODE(int mode)
+ SCI_GETSELECTIONMODE
+ SCI_GETLINESELSTARTPOSITION(int line)
+ SCI_GETLINESELENDPOSITION(int line)
+ SCI_MOVECARETINSIDEVIEW
+ SCI_WORDENDPOSITION(int position, bool + onlyWordCharacters)
+ SCI_WORDSTARTPOSITION(int position, bool + onlyWordCharacters)
+ SCI_POSITIONBEFORE(int position)
+ SCI_POSITIONAFTER(int position)
+ SCI_TEXTWIDTH(int styleNumber, const char *text)
+ SCI_TEXTHEIGHT(int line)
+ SCI_CHOOSECARETX
+
+ +

SCI_GETTEXTLENGTH
+ SCI_GETLENGTH
+ Both these messages return the length of the document in characters.

+ +

SCI_GETLINECOUNT
+ This returns the number of lines in the document. An empty document contains 1 line. A + document holding only an end of line sequence has 2 lines.

+ +

SCI_GETFIRSTVISIBLELINE
+ This returns the line number of the first visible line in the Scintilla view. The first line + in the document is numbered 0. The value is a visible line rather than a document line.

+ +

SCI_LINESONSCREEN
+ This returns the number of complete lines visible on the screen. With a constant line height, + this is the vertical space available divided by the line separation. Unless you arrange to size + your window to an integral number of lines, there may be a partial line visible at the bottom + of the view.

+ +

SCI_GETMODIFY
+ This returns non-zero if the document is modified and 0 if it is unmodified. The modified + status of a document is determined by the undo position relative to the save point. The save + point is set by SCI_SETSAVEPOINT, + usually when you have saved data to a file.

+ +

If you need to be notified when the document becomes modified, Scintilla notifies the + container that it has entered or left the save point with the SCN_SAVEPOINTREACHED and SCN_SAVEPOINTLEFT notification messages.

+ +

SCI_SETSEL(int anchorPos, int currentPos)
+ This message sets both the anchor and the current position. If currentPos is + negative, it means the end of the document. If anchorPos is negative, it means + remove any selection (i.e. set the anchor to the same position as currentPos). The + caret is scrolled into view after this operation.

+ +

SCI_GOTOPOS(int pos)
+ This removes any selection, sets the caret at pos and scrolls the view to make + the caret visible, if necessary. It is equivalent to + SCI_SETSEL(pos, pos). The anchor position is set the same as the current + position.

+ +

SCI_GOTOLINE(int line)
+ This removes any selection and sets the caret at the start of line number line + and scrolls the view (if needed) to make it visible. The anchor position is set the same as the + current position. If line is outside the lines in the document (first line is 0), + the line set is the first or last.

+ +

SCI_SETCURRENTPOS(int pos)
+ This sets the current position and creates a selection between the anchor and the current + position. The caret is not scrolled into view.

+ +

See also: SCI_SCROLLCARET

+ +

SCI_GETCURRENTPOS
+ This returns the current position.

+ +

SCI_SETANCHOR(int pos)
+ This sets the anchor position and creates a selection between the anchor position and the + current position. The caret is not scrolled into view.

+ +

See also: SCI_SCROLLCARET

+ +

SCI_GETANCHOR
+ This returns the current anchor position.

+ +

SCI_SETSELECTIONSTART(int pos)
+ SCI_SETSELECTIONEND(int pos)
+ These set the selection based on the assumption that the anchor position is less than the + current position. They do not make the caret visible. The table shows the positions of the + anchor and the current position after using these messages.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ anchorcurrent
SCI_SETSELECTIONSTARTposMax(pos, current)
SCI_SETSELECTIONENDMin(anchor, pos)pos
+ +

See also: SCI_SCROLLCARET

+ +

SCI_GETSELECTIONSTART
+ SCI_GETSELECTIONEND
+ These return the start and end of the selection without regard to which end is the current + position and which is the anchor. SCI_GETSELECTIONSTART returns the smaller of the + current position or the anchor position. SCI_GETSELECTIONEND returns the larger of + the two values.

+ +

SCI_SELECTALL
+ This selects all the text in the document. The current position is not scrolled into view.

+ +

SCI_LINEFROMPOSITION(int pos)
+ This message returns the line that contains the position pos in the document. The + return value is 0 if pos <= 0. The return value is the last line if + pos is beyond the end of the document.

+ +

SCI_POSITIONFROMLINE(int line)
+ This returns the document position that corresponds with the start of the line. If + line is negative, the position of the line holding the start of the selection is + returned. If line is greater than the lines in the document, the return value is + -1. If line is equal to the number of lines in the document (i.e. 1 line past the + last line), the return value is the end of the document.

+ +

SCI_GETLINEENDPOSITION(int line)
+ This returns the position at the end of the line, before any line end characters. If line + is the last line in the document (which does not have any end of line characters), the result is the size of the + document. If line is negative or line >= SCI_GETLINECOUNT(), the result is undefined.

+ +

SCI_LINELENGTH(int line)
+ This returns the length of the line, including any line end characters. If line + is negative or beyond the last line in the document, the result is 0. If you want the length of + the line not including any end of line characters, use SCI_GETLINEENDPOSITION(line) - SCI_POSITIONFROMLINE(line).

+ SCI_GETSELTEXT(<unused>, char *text)
+ This copies the currently selected text and a terminating 0 byte to the text + buffer. The buffer must be at least + SCI_GETSELECTIONEND()-SCI_GETSELECTIONSTART()+1 bytes long.
+ If the text argument is 0 then the length that should be allocated + to store the entire selection is returned.
+ +

See also: SCI_GETCURLINE, SCI_GETLINE, SCI_GETTEXT, SCI_GETSTYLEDTEXT, SCI_GETTEXTRANGE

+ +

SCI_GETCURLINE(int textLen, char *text)
+ This retrieves the text of the line containing the caret and returns the position within the + line of the caret. Pass in char* text pointing at a buffer large enough to hold + the text you wish to retrieve and a terminating 0 character. + Set textLen to the + length of the buffer which must be at least 1 to hold the terminating 0 character. + If the text argument is 0 then the length that should be allocated + to store the entire current line is returned.

+ +

See also: SCI_GETSELTEXT, SCI_GETLINE, SCI_GETTEXT, SCI_GETSTYLEDTEXT, SCI_GETTEXTRANGE

+ +

SCI_SELECTIONISRECTANGLE
+ This returns 1 if the current selection is in rectangle mode, 0 if not.

+ +

SCI_SETSELECTIONMODE(int mode)
+ SCI_GETSELECTIONMODE
+ The two functions set and get the selection mode, which can be + stream (SC_SEL_STREAM=0) or + rectangular (SC_SEL_RECTANGLE=1) + or by lines (SC_SEL_LINES=2). + When set in these modes, regular caret moves will extend or reduce the selection, + until the mode is cancelled by a call with same value or with SCI_CANCEL. + The get function returns the current mode even if the selection was made by mouse + or with regular extended moves.

+ +

SCI_GETLINESELSTARTPOSITION(int line)
+ SCI_GETLINESELENDPOSITION(int line)
+ Retrieve the position of the start and end of the selection at the given line with + INVALID_POSITION returned if no selection on this line.

+ +

SCI_MOVECARETINSIDEVIEW
+ If the caret is off the top or bottom of the view, it is moved to the nearest line that is + visible to its current position. Any selection is lost.

+ +

SCI_WORDENDPOSITION(int position, bool + onlyWordCharacters)
+ SCI_WORDSTARTPOSITION(int position, bool + onlyWordCharacters)
+ These messages return the start and end of words using the same definition of words as used + internally within Scintilla. You can set your own list of characters that count as words with + SCI_SETWORDCHARS. The position + sets the start or the search, which is forwards when searching for the end and backwards when + searching for the start.

+ +

Set onlyWordCharacters to true (1) to stop searching at the first + non-word character in the search direction. If onlyWordCharacters is + false (0), the first character in the search direction sets the type of the search + as word or non-word and the search stops at the first non-matching character. Searches are also + terminated by the start or end of the document.

+ +

If "w" represents word characters and "." represents non-word characters and "|" represents + the position and true or false is the state of + onlyWordCharacters:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Initial stateend, trueend, falsestart, truestart, false
..ww..|..ww....ww..|..ww....ww....|ww....ww..|..ww....ww|....ww..
....ww|ww........wwww|........wwww|........|wwww........|wwww....
..ww|....ww....ww|....ww....ww....|ww....|ww....ww....|ww....ww..
..ww....|ww....ww....ww|....ww....ww|....ww....|ww....ww|....ww..
+ +

SCI_POSITIONBEFORE(int position)
+ SCI_POSITIONAFTER(int position)
+ These messages return the position before and after another position + in the document taking into account the current code page. The minimum + position returned is 0 and the maximum is the last position in the document. + If called with a position within a multi byte character will return the position + of the start/end of that character.

+ +

SCI_TEXTWIDTH(int styleNumber, const char *text)
+ This returns the pixel width of a string drawn in the given styleNumber which can + be used, for example, to decide how wide to make the line number margin in order to display a + given number of numerals.

+ +

SCI_TEXTHEIGHT(int line)
+ This returns the height in pixels of a particular line. Currently all lines are the same + height.

+ +

SCI_GETCOLUMN(int pos)
+ This message returns the column number of a position pos within the document + taking the width of tabs into account. This returns the column number of the last tab on the + line before pos, plus the number of characters between the last tab and + pos. If there are no tab characters on the line, the return value is the number of + characters up to the position on the line. In both cases, double byte characters count as a + single character. This is probably only useful with monospaced fonts.

+ +

SCI_FINDCOLUMN(int line, int column)
+ This message returns the position of a column on a line + taking the width of tabs into account. It treats a multi-byte character as a single column. + Column numbers, like lines start at 0.

+ +

SCI_POSITIONFROMPOINT(int x, int y)
+ SCI_POSITIONFROMPOINTCLOSE(int x, int y)
+ SCI_POSITIONFROMPOINT finds the closest character position to a point and + SCI_POSITIONFROMPOINTCLOSE is similar but returns -1 if the point is outside the + window or not close to any characters.

+ +

SCI_POINTXFROMPOSITION(<unused>, int pos)
+ SCI_POINTYFROMPOSITION(<unused>, int pos)
+ These messages return the x and y display pixel location of text at position pos + in the document.

+ +

SCI_HIDESELECTION(bool hide)
+ The normal state is to make the selection visible by drawing it as set by SCI_SETSELFORE and SCI_SETSELBACK. However, if you hide the selection, it + is drawn as normal text.

+ +

SCI_CHOOSECARETX
+ Scintilla remembers the x value of the last position horizontally moved to explicitly by the + user and this value is then used when moving vertically such as by using the up and down keys. + This message sets the current x position of the caret as the remembered value.

+ +

Scrolling and automatic scrolling

+ SCI_LINESCROLL(int column, int line)
+ SCI_SCROLLCARET
+ SCI_SETXCARETPOLICY(int caretPolicy, int + caretSlop)
+ SCI_SETYCARETPOLICY(int caretPolicy, int + caretSlop)
+ SCI_SETVISIBLEPOLICY(int caretPolicy, int + caretSlop)
+ SCI_SETHSCROLLBAR(bool visible)
+ SCI_GETHSCROLLBAR
+ SCI_SETVSCROLLBAR(bool visible)
+ SCI_GETVSCROLLBAR
+ SCI_GETXOFFSET
+ SCI_SETXOFFSET(int xOffset)
+ SCI_SETSCROLLWIDTH(int pixelWidth)
+ SCI_GETSCROLLWIDTH
+ SCI_SETSCROLLWIDTHTRACKING(bool tracking)
+ SCI_GETSCROLLWIDTHTRACKING
+ SCI_SETENDATLASTLINE(bool + endAtLastLine)
+ SCI_GETENDATLASTLINE
+
+ +

SCI_LINESCROLL(int column, int line)
+ This will attempt to scroll the display by the number of columns and lines that you specify. + Positive line values increase the line number at the top of the screen (i.e. they move the text + upwards as far as the user is concerned), Negative line values do the reverse.

+ +

The column measure is the width of a space in the default style. Positive values increase + the column at the left edge of the view (i.e. they move the text leftwards as far as the user + is concerned). Negative values do the reverse.

+ +

See also: SCI_SETXOFFSET

+ +

SCI_SCROLLCARET
+ If the current position (this is the caret if there is no selection) is not visible, the view + is scrolled to make it visible according to the current caret policy.

+ +

SCI_SETXCARETPOLICY(int caretPolicy, int caretSlop)
+ SCI_SETYCARETPOLICY(int caretPolicy, int caretSlop)
+ These set the caret policy. The value of caretPolicy is a combination of + CARET_SLOP, CARET_STRICT, CARET_JUMPS and + CARET_EVEN.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CARET_SLOPIf set, we can define a slop value: caretSlop. This value defines an + unwanted zone (UZ) where the caret is... unwanted. This zone is defined as a number of + pixels near the vertical margins, and as a number of lines near the horizontal margins. + By keeping the caret away from the edges, it is seen within its context. This makes it + likely that the identifier that the caret is on can be completely seen, and that the + current line is seen with some of the lines following it, which are often dependent on + that line.
CARET_STRICTIf set, the policy set by CARET_SLOP is enforced... strictly. The caret + is centred on the display if caretSlop is not set, and cannot go in the UZ + if caretSlop is set.
CARET_JUMPSIf set, the display is moved more energetically so the caret can move in the same + direction longer before the policy is applied again. '3UZ' notation is used to indicate + three time the size of the UZ as a distance to the margin.
CARET_EVENIf not set, instead of having symmetrical UZs, the left and bottom UZs are extended + up to right and top UZs respectively. This way, we favour the displaying of useful + information: the beginning of lines, where most code reside, and the lines after the + caret, for example, the body of a function.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
slopstrictjumpsevenCaret can go to the marginOn reaching limit (going out of visibility
+ or going into the UZ) display is...
0000Yesmoved to put caret on top/on right
0001Yesmoved by one position
0010Yesmoved to put caret on top/on right
0011Yescentred on the caret
01-0Caret is always on top/on right of display-
01-1No, caret is always centred-
1000Yesmoved to put caret out of the asymmetrical UZ
1001Yesmoved to put caret out of the UZ
1010Yesmoved to put caret at 3UZ of the top or right margin
1011Yesmoved to put caret at 3UZ of the margin
11-0Caret is always at UZ of top/right margin-
1101No, kept out of UZmoved by one position
1110No, kept out of UZmoved to put caret at 3UZ of the margin
+ +

SCI_SETVISIBLEPOLICY(int caretPolicy, int caretSlop)
+ This determines how the vertical positioning is determined when SCI_ENSUREVISIBLEENFORCEPOLICY is + called. It takes VISIBLE_SLOP and VISIBLE_STRICT flags for the policy + parameter. It is similar in operation to SCI_SETYCARETPOLICY(int caretPolicy, int + caretSlop).

+ +

SCI_SETHSCROLLBAR(bool visible)
+ SCI_GETHSCROLLBAR
+ The horizontal scroll bar is only displayed if it is needed for the assumed width. + If you never wish to see it, call + SCI_SETHSCROLLBAR(0). Use SCI_SETHSCROLLBAR(1) to enable it again. + SCI_GETHSCROLLBAR returns the current state. The default state is to display it + when needed. + See also: SCI_SETSCROLLWIDTH.

+ +

SCI_SETVSCROLLBAR(bool visible)
+ SCI_GETVSCROLLBAR
+ By default, the vertical scroll bar is always displayed when required. You can choose to hide + or show it with SCI_SETVSCROLLBAR and get the current state with + SCI_GETVSCROLLBAR.

+ +

SCI_SETXOFFSET(int xOffset)
+ SCI_GETXOFFSET
+ The xOffset is the horizontal scroll position in pixels of the start of the text + view. A value of 0 is the normal position with the first text column visible at the left of the + view.

+ +

See also: SCI_LINESCROLL

+ +

SCI_SETSCROLLWIDTH(int pixelWidth)
+ SCI_GETSCROLLWIDTH
+ For performance, Scintilla does not measure the display width of the document to determine + the properties of the horizontal scroll bar. Instead, an assumed width is used. + These messages set and get the document width in pixels assumed by Scintilla. + The default value is 2000. + To ensure the width of the currently visible lines can be scrolled use + SCI_SETSCROLLWIDTHTRACKING

+ +

SCI_SETSCROLLWIDTHTRACKING(bool tracking)
+ SCI_GETSCROLLWIDTHTRACKING
+ If scroll width tracking is enabled then the scroll width is adjusted to ensure that all of the lines currently + displayed can be completely scrolled. This mode never adjusts the scroll width to be narrower.

+ +

SCI_SETENDATLASTLINE(bool endAtLastLine)
+ SCI_GETENDATLASTLINE
+ SCI_SETENDATLASTLINE sets the scroll range so that maximum scroll position has + the last line at the bottom of the view (default). Setting this to false allows + scrolling one page below the last line.

+ +

White space

+ SCI_SETVIEWWS(int wsMode)
+ SCI_GETVIEWWS
+ SCI_SETWHITESPACEFORE(bool + useWhitespaceForeColour, int colour)
+ SCI_SETWHITESPACEBACK(bool + useWhitespaceBackColour, int colour)
+
+ +

SCI_SETVIEWWS(int wsMode)
+ SCI_GETVIEWWS
+ White space can be made visible which may useful for languages in which white space is + significant, such as Python. Space characters appear as small centred dots and tab characters + as light arrows pointing to the right. There are also ways to control the display of end of line characters. The two messages set and get the + white space display mode. The wsMode argument can be one of:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
SCWS_INVISIBLE0The normal display mode with white space displayed as an empty background + colour.
SCWS_VISIBLEALWAYS1White space characters are drawn as dots and arrows,
SCWS_VISIBLEAFTERINDENT2White space used for indentation is displayed normally but after the first visible + character, it is shown as dots and arrows.
+ +

The effect of using any other wsMode value is undefined.

+ +

SCI_SETWHITESPACEFORE<(bool useWhitespaceForeColour, int colour)
+ SCI_SETWHITESPACEBACK(bool useWhitespaceBackColour, int colour)
+ By default, the colour of visible white space is determined by the lexer in use. The + foreground and/or background colour of all visible white space can be set globally, overriding + the lexer's colours with SCI_SETWHITESPACEFORE and + SCI_SETWHITESPACEBACK.

+ +

Cursor

+ +

SCI_SETCURSOR(int curType)
+ SCI_GETCURSOR
+ The cursor is normally chosen in a context sensitive way, so it will be different over the + margin than when over the text. When performing a slow action, you may wish to change to a wait + cursor. You set the cursor type with SCI_SETCURSOR. The curType + argument can be:

+ + + + + + + + + + + + + + + + + + + +
SC_CURSORNORMAL-1The normal cursor is displayed.
SC_CURSORWAIT 4The wait cursor is displayed when the mouse is over or owned by the Scintilla + window.
+ +

Cursor values 1 through 7 have defined cursors, but only SC_CURSORWAIT is + usefully controllable. Other values of curType cause a pointer to be displayed. + The SCI_GETCURSOR message returns the last cursor type you set, or + SC_CURSORNORMAL (-1) if you have not set a cursor type.

+ +

Mouse capture

+ +

SCI_SETMOUSEDOWNCAPTURES(bool captures)
+ SCI_GETMOUSEDOWNCAPTURES
+ When the mouse is pressed inside Scintilla, it is captured so future mouse movement events are + sent to Scintilla. This behavior may be turned off with + SCI_SETMOUSEDOWNCAPTURES(0).

+ +

Line endings

+ +

Scintilla can interpret any of the three major line end conventions, Macintosh (\r), Unix + (\n) and CP/M / DOS / Windows (\r\n). When the user presses the Enter key, one of these line + end strings is inserted into the buffer. The default is \r\n in Windows and \n in Unix, but + this can be changed with the SCI_SETEOLMODE message. You can also convert the + entire document to one of these line endings with SCI_CONVERTEOLS. Finally, you + can choose to display the line endings with SCI_SETVIEWEOL.

+ SCI_SETEOLMODE(int eolMode)
+ SCI_GETEOLMODE
+ SCI_CONVERTEOLS(int eolMode)
+ SCI_SETVIEWEOL(bool visible)
+ SCI_GETVIEWEOL
+
+ +

SCI_SETEOLMODE(int eolMode)
+ SCI_GETEOLMODE
+ SCI_SETEOLMODE sets the characters that are added into the document when the user + presses the Enter key. You can set eolMode to one of SC_EOL_CRLF (0), + SC_EOL_CR (1), or SC_EOL_LF (2). The SCI_GETEOLMODE + message retrieves the current state.

+ +

SCI_CONVERTEOLS(int eolMode)
+ This message changes all the end of line characters in the document to match + eolMode. Valid values are: SC_EOL_CRLF (0), SC_EOL_CR + (1), or SC_EOL_LF (2).

+ +

SCI_SETVIEWEOL(bool visible)
+ SCI_GETVIEWEOL
+ Normally, the end of line characters are hidden, but SCI_SETVIEWEOL allows you to + display (or hide) them by setting visible true (or + false). The visible rendering of the end of line characters is similar to + (CR), (LF), or (CR)(LF). SCI_GETVIEWEOL + returns the current state.

+ +

Styling

+ +

The styling messages allow you to assign styles to text. The standard Scintilla settings + divide the 8 style bits available for each character into 5 bits (0 to 4 = styles 0 to 31) that set a style and three bits (5 to 7) that + define indicators. You can change the balance between + styles and indicators with SCI_SETSTYLEBITS. If your styling needs can be met by + one of the standard lexers, or if you can write your own, then a lexer is probably the easiest + way to style your document. If you choose to use the container to do the styling you can use + the SCI_SETLEXER command to select + SCLEX_CONTAINER, in which case the container is sent a SCN_STYLENEEDED notification each time text needs styling for display. As another + alternative, you might use idle time to style the document. Even if you use a lexer, you might + use the styling commands to mark errors detected by a compiler. The following commands can be + used.

+ SCI_GETENDSTYLED
+ SCI_STARTSTYLING(int position, int mask)
+ SCI_SETSTYLING(int length, int style)
+ SCI_SETSTYLINGEX(int length, const char + *styles)
+ SCI_SETLINESTATE(int line, int value)
+ SCI_GETLINESTATE(int line)
+ SCI_GETMAXLINESTATE
+
+ +

SCI_GETENDSTYLED
+ Scintilla keeps a record of the last character that is likely to be styled correctly. This is + moved forwards when characters after it are styled and moved backwards if changes are made to + the text of the document before it. Before drawing text, this position is checked to see if any + styling is needed and, if so, a SCN_STYLENEEDED notification message is sent to the + container. The container can send SCI_GETENDSTYLED to work out where it needs to + start styling. Scintilla will always ask to style whole lines.

+ +

SCI_STARTSTYLING(int pos, int mask)
+ This prepares for styling by setting the styling position pos to start at and a + mask indicating which bits of the style bytes can be set. The mask allows styling + to occur over several passes, with, for example, basic styling done on an initial pass to + ensure that the text of the code is seen quickly and correctly, and then a second slower pass, + detecting syntax errors and using indicators to show where these are. For example, with the + standard settings of 5 style bits and 3 indicator bits, you would use a mask value + of 31 (0x1f) if you were setting text styles and did not want to change the indicators. After + SCI_STARTSTYLING, send multiple SCI_SETSTYLING messages for each + lexical entity to style.

+ +

SCI_SETSTYLING(int length, int style)
+ This message sets the style of length characters starting at the styling position + and then increases the styling position by length, ready for the next call. If + sCell is the style byte, the operation is:
+ if ((sCell & mask) != style) sCell = (sCell & ~mask) | (style & + mask);
+

+ +

SCI_SETSTYLINGEX(int length, const char *styles)
+ As an alternative to SCI_SETSTYLING, which applies the same style to each byte, + you can use this message which specifies the styles for each of length bytes from + the styling position and then increases the styling position by length, ready for + the next call. The length styling bytes pointed at by styles should + not contain any bits not set in mask.

+ +

SCI_SETLINESTATE(int line, int value)
+ SCI_GETLINESTATE(int line)
+ As well as the 8 bits of lexical state stored for each character there is also an integer + stored for each line. This can be used for longer lived parse states such as what the current + scripting language is in an ASP page. Use SCI_SETLINESTATE to set the integer + value and SCI_GETLINESTATE to get the value. + Changing the value produces a SC_MOD_CHANGELINESTATE notification. +

+ +

SCI_GETMAXLINESTATE
+ This returns the last line that has any line state.

+ +

Style definition

+ +

While the style setting messages mentioned above change the style numbers associated with + text, these messages define how those style numbers are interpreted visually. There are 128 + lexer styles that can be set, numbered 0 to STYLEMAX (127). Unless you use SCI_SETSTYLEBITS to change the number + of style bits, styles 0 to 31 are used to set the text attributes. There are also some + predefined numbered styles starting at 32, The following STYLE_* constants are + defined.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
STYLE_DEFAULT32This style defines the attributes that all styles receive when the + SCI_STYLECLEARALL message is used.
STYLE_LINENUMBER33This style sets the attributes of the text used to display line numbers in a line + number margin. The background colour set for this style also sets the background colour + for all margins that do not have any folding mask bits set. That is, any margin for which + mask & SC_MASK_FOLDERS is 0. See SCI_SETMARGINMASKN for more about masks.
STYLE_BRACELIGHT34This style sets the attributes used when highlighting braces with the SCI_BRACEHIGHLIGHT message and + when highlighting the corresponding indentation with SCI_SETHIGHLIGHTGUIDE.
STYLE_BRACEBAD35This style sets the display attributes used when marking an unmatched brace with the + SCI_BRACEBADLIGHT + message.
STYLE_CONTROLCHAR36This style sets the font used when drawing control characters. + Only the font, size, bold, italics, and character set attributes are used and not + the colour attributes. See + also: SCI_SETCONTROLCHARSYMBOL.
STYLE_INDENTGUIDE37This style sets the foreground and background colours used when drawing the + indentation guides.
STYLE_CALLTIP38 Call tips normally use the font attributes defined by STYLE_DEFAULT. + Use of SCI_CALLTIPUSESTYLE + causes call tips to use this style instead. Only the font face name, font size, + foreground and background colours and character set attributes are used.
STYLE_LASTPREDEFINED39To make it easier for client code to discover the range of styles that are + predefined, this is set to the style number of the last predefined style. This is + currently set to 39 and the last style with an identifier is 38, which reserves space + for one future predefined style.
STYLE_MAX127This is not a style but is the number of the maximum style that can be set. Styles + between STYLE_LASTPREDEFINED and STYLE_MAX would be appropriate + if you used SCI_SETSTYLEBITS + to set more than 5 style bits.
+ +

For each style you can set the font name, size and use of bold, italic and underline, + foreground and background colour and the character set. You can also choose to hide text with a + given style, display all characters as upper or lower case and fill from the last character on + a line to the end of the line (for embedded languages). There is also an experimental attribute + to make text read-only.

+ +

It is entirely up to you how you use styles. If you want to use syntax colouring you might + use style 0 for white space, style 1 for numbers, style 2 for keywords, style 3 for strings, + style 4 for preprocessor, style 5 for operators, and so on.

+ SCI_STYLERESETDEFAULT
+ SCI_STYLECLEARALL
+ SCI_STYLESETFONT(int styleNumber, char + *fontName)
+ SCI_STYLEGETFONT(int styleNumber, char *fontName)
+ SCI_STYLESETSIZE(int styleNumber, int + sizeInPoints)
+ SCI_STYLEGETSIZE(int styleNumber)
+ SCI_STYLESETBOLD(int styleNumber, bool + bold)
+ SCI_STYLEGETBOLD(int styleNumber)
+ SCI_STYLESETITALIC(int styleNumber, bool + italic)
+ SCI_STYLEGETITALIC(int styleNumber)
+ SCI_STYLESETUNDERLINE(int styleNumber, bool + underline)
+ SCI_STYLEGETUNDERLINE(int styleNumber)
+ SCI_STYLESETFORE(int styleNumber, int + colour)
+ SCI_STYLEGETFORE(int styleNumber)
+ SCI_STYLESETBACK(int styleNumber, int + colour)
+ SCI_STYLESETBACK(int styleNumber)
+ SCI_STYLESETEOLFILLED(int styleNumber, bool + eolFilled)
+ SCI_STYLEGETEOLFILLED(int styleNumber)
+ SCI_STYLESETCHARACTERSET(int styleNumber, + int charSet)
+ SCI_STYLEGETCHARACTERSET(int styleNumber)
+ SCI_STYLESETCASE(int styleNumber, int + caseMode)
+ SCI_STYLEGETCASE(int styleNumber)
+ SCI_STYLESETVISIBLE(int styleNumber, bool + visible)
+ SCI_STYLEGETVISIBLE(int styleNumber)
+ SCI_STYLESETCHANGEABLE(int styleNumber, bool + changeable)
+ SCI_STYLEGETCHANGEABLE(int styleNumber)
+ SCI_STYLESETHOTSPOT(int styleNumber, bool + hotspot)
+ SCI_STYLEGETHOTSPOT(int styleNumber)
+
+ +

SCI_STYLERESETDEFAULT
+ This message resets STYLE_DEFAULT to its state when Scintilla was + initialised.

+ +

SCI_STYLECLEARALL
+ This message sets all styles to have the same attributes as STYLE_DEFAULT. If you + are setting up Scintilla for syntax colouring, it is likely that the lexical styles you set + will be very similar. One way to set the styles is to:
+ 1. Set STYLE_DEFAULT to the common features of all styles.
+ 2. Use SCI_STYLECLEARALL to copy this to all styles.
+ 3. Set the style attributes that make your lexical styles different.

+ +

SCI_STYLESETFONT(int styleNumber, const char *fontName)
+ SCI_STYLEGETFONT(int styleNumber, char *fontName)
+ SCI_STYLESETSIZE(int styleNumber, int sizeInPoints)
+ SCI_STYLEGETSIZE(int styleNumber)
+ SCI_STYLESETBOLD(int styleNumber, bool bold)
+ SCI_STYLEGETBOLD(int styleNumber)
+ SCI_STYLESETITALIC(int styleNumber, bool italic)
+ SCI_STYLEGETITALIC(int styleNumber)
+ These messages (plus SCI_STYLESETCHARACTERSET) set the font + attributes that are used to match the fonts you request to those available. The + fontName is a zero terminated string holding the name of a font. Under Windows, + only the first 32 characters of the name are used and the name is not case sensitive. For + internal caching, Scintilla tracks fonts by name and does care about the casing of font names, + so please be consistent. On GTK+ 2.x, either GDK or Pango can be used to display text. + Pango antialiases text, works well with Unicode and is better supported in recent versions of GTK+ + but GDK is faster. + Prepend a '!' character to the font name to use Pango.

+ +

SCI_STYLESETUNDERLINE(int styleNumber, bool + underline)
+ SCI_STYLEGETUNDERLINE(int styleNumber)
+ You can set a style to be underlined. The underline is drawn in the foreground colour. All + characters with a style that includes the underline attribute are underlined, even if they are + white space.

+ +

SCI_STYLESETFORE(int styleNumber, int colour)
+ SCI_STYLEGETFORE(int styleNumber)
+ SCI_STYLESETBACK(int styleNumber, int colour)
+ SCI_STYLEGETBACK(int styleNumber)
+ Text is drawn in the foreground colour. The space in each character cell that is not occupied + by the character is drawn in the background colour.

+ +

SCI_STYLESETEOLFILLED(int styleNumber, bool + eolFilled)
+ SCI_STYLEGETEOLFILLED(int styleNumber)
+ If the last character in the line has a style with this attribute set, the remainder of the + line up to the right edge of the window is filled with the background colour set for the last + character. This is useful when a document contains embedded sections in another language such + as HTML pages with embedded JavaScript. By setting eolFilled to true + and a consistent background colour (different from the background colour set for the HTML + styles) to all JavaScript styles then JavaScript sections will be easily distinguished from + HTML.

+ +

SCI_STYLESETCHARACTERSET(int styleNumber, int + charSet)
+ SCI_STYLEGETCHARACTERSET(int styleNumber)
+ You can set a style to use a different character set than the default. The places where such + characters sets are likely to be useful are comments and literal strings. For example, + SCI_STYLESETCHARACTERSET(SCE_C_STRING, SC_CHARSET_RUSSIAN) would ensure that + strings in Russian would display correctly in C and C++ (SCE_C_STRING is the style + number used by the C and C++ lexer to display literal strings; it has the value 6). This + feature works differently on Windows and GTK+.

+ +

The character sets supported on Windows are:
+ SC_CHARSET_ANSI, SC_CHARSET_ARABIC, SC_CHARSET_BALTIC, + SC_CHARSET_CHINESEBIG5, SC_CHARSET_DEFAULT, + SC_CHARSET_EASTEUROPE, SC_CHARSET_GB2312, + SC_CHARSET_GREEK, SC_CHARSET_HANGUL, SC_CHARSET_HEBREW, + SC_CHARSET_JOHAB, SC_CHARSET_MAC, SC_CHARSET_OEM, + SC_CHARSET_RUSSIAN (code page 1251), + SC_CHARSET_SHIFTJIS, SC_CHARSET_SYMBOL, SC_CHARSET_THAI, + SC_CHARSET_TURKISH, and SC_CHARSET_VIETNAMESE.

+ +

The character sets supported on GTK+ are:
+ SC_CHARSET_ANSI, SC_CHARSET_CYRILLIC (code page 1251), + SC_CHARSET_EASTEUROPE, + SC_CHARSET_GB2312, SC_CHARSET_HANGUL, + SC_CHARSET_RUSSIAN (KOI8-R), SC_CHARSET_SHIFTJIS, and + SC_CHARSET_8859_15.

+ +

SCI_STYLESETCASE(int styleNumber, int caseMode)
+ SCI_STYLEGETCASE(int styleNumber)
+ The value of caseMode determines how text is displayed. You can set upper case + (SC_CASE_UPPER, 1) or lower case (SC_CASE_LOWER, 2) or display + normally (SC_CASE_MIXED, 0). This does not change the stored text, only how it is + displayed.

+ +

SCI_STYLESETVISIBLE(int styleNumber, bool visible)
+ SCI_STYLEGETVISIBLE(int styleNumber)
+ Text is normally visible. However, you can completely hide it by giving it a style with the + visible set to 0. This could be used to hide embedded formatting instructions or + hypertext keywords in HTML or XML.

+ +

SCI_STYLESETCHANGEABLE(int styleNumber, bool + changeable)
+ SCI_STYLEGETCHANGEABLE(int styleNumber)
+ This is an experimental and incompletely implemented style attribute. The default setting is + changeable set true but when set false it makes text + read-only. Currently it only stops the caret from being within not-changeable text and does not + yet stop deleting a range that contains not-changeable text.

+ +

SCI_STYLESETHOTSPOT(int styleNumber, bool + hotspot)
+ SCI_STYLEGETHOTSPOT(int styleNumber)
+ This style is used to mark ranges of text that can detect mouse clicks. + The cursor changes to a hand over hotspots, and the foreground, and background colours + may change and an underline appear to indicate that these areas are sensitive to clicking. + This may be used to allow hyperlinks to other documents.

+ +

Caret, selection, and hotspot styles

+ +

The selection is shown by changing the foreground and/or background colours. If one of these + is not set then that attribute is not changed for the selection. The default is to show the + selection by changing the background to light gray and leaving the foreground the same as when + it was not selected. When there is no selection, the current insertion point is marked by the + text caret. This is a vertical line that is normally blinking on and off to attract the users + attention.

+ SCI_SETSELFORE(bool useSelectionForeColour, + int colour)
+ SCI_SETSELBACK(bool useSelectionBackColour, + int colour)
+ SCI_SETSELALPHA(int alpha)
+ SCI_GETSELALPHA
+ SCI_SETSELEOLFILLED(bool filled)
+ SCI_GETSELEOLFILLED
+ SCI_SETCARETFORE(int colour)
+ SCI_GETCARETFORE
+ SCI_SETCARETLINEVISIBLE(bool + show)
+ SCI_GETCARETLINEVISIBLE
+ SCI_SETCARETLINEBACK(int colour)
+ SCI_GETCARETLINEBACK
+ SCI_SETCARETLINEBACKALPHA(int alpha)
+ SCI_GETCARETLINEBACKALPHA
+ SCI_SETCARETPERIOD(int milliseconds)
+ SCI_GETCARETPERIOD
+ SCI_SETCARETSTYLE(int style)
+ SCI_GETCARETSTYLE
+ SCI_SETCARETWIDTH(int pixels)
+ SCI_GETCARETWIDTH
+ SCI_SETHOTSPOTACTIVEFORE(bool useSetting, + int colour)
+ SCI_GETHOTSPOTACTIVEFORE
+ SCI_SETHOTSPOTACTIVEBACK(bool useSetting, + int colour)
+ SCI_GETHOTSPOTACTIVEBACK
+ SCI_SETHOTSPOTACTIVEUNDERLINE(bool underline)
+ SCI_GETHOTSPOTACTIVEUNDERLINE
+ SCI_SETHOTSPOTSINGLELINE(bool singleLine)
+ SCI_GETHOTSPOTSINGLELINE
+ SCI_SETCONTROLCHARSYMBOL(int + symbol)
+ SCI_GETCONTROLCHARSYMBOL
+ SCI_SETCARETSTICKY(bool useCaretStickyBehaviour)
+ SCI_GETCARETSTICKY
+ SCI_TOGGLECARETSTICKY
+
+ +

SCI_SETSELFORE(bool useSelectionForeColour, int colour)
+ SCI_SETSELBACK(bool useSelectionBackColour, int colour)
+ You can choose to override the default selection colouring with these two messages. The colour + you provide is used if you set useSelection*Colour to true. If it is + set to false, the default styled colouring is used and the colour + argument has no effect.

+

SCI_SETSELALPHA(int alpha)
+ SCI_GETSELALPHA
+ The selection can be drawn translucently in the selection background colour by + setting an alpha value.

+ +

SCI_SETSELEOLFILLED(bool filled)
+ SCI_GETSELEOLFILLED
+ The selection can be drawn up to the right hand border by setting this property.

+ +

SCI_SETCARETFORE(int colour)
+ SCI_GETCARETFORE
+ The colour of the caret can be set with SCI_SETCARETFORE and retrieved with + SCI_CETCARETFORE.

+ +

SCI_SETCARETLINEVISIBLE(bool show)
+ SCI_GETCARETLINEVISIBLE
+ SCI_SETCARETLINEBACK(int colour)
+ SCI_GETCARETLINEBACK
+ SCI_SETCARETLINEBACKALPHA(int alpha)
+ SCI_GETCARETLINEBACKALPHA
+ You can choose to make the background colour of the line containing the caret different with + these messages. To do this, set the desired background colour with + SCI_SETCARETLINEBACK, then use SCI_SETCARETLINEVISIBLE(true) to + enable the effect. You can cancel the effect with SCI_SETCARETLINEVISIBLE(false). + The two SCI_GETCARET* functions return the state and the colour. This form of + background colouring has highest priority when a line has markers that would otherwise change + the background colour. + The caret line may also be drawn translucently which allows other background colours to show + through. This is done by setting the alpha (translucency) value by calling + SCI_SETCARETLINEBACKALPHA. When the alpha is not SC_ALPHA_NOALPHA, + the caret line is drawn after all other features so will affect the colour of all other features. +

+ +

SCI_SETCARETPERIOD(int milliseconds)
+ SCI_GETCARETPERIOD
+ The rate at which the caret blinks can be set with SCI_SETCARETPERIOD which + determines the time in milliseconds that the caret is visible or invisible before changing + state. Setting the period to 0 stops the caret blinking. The default value is 500 milliseconds. + SCI_GETCARETPERIOD returns the current setting.

+ +

SCI_SETCARETSTYLE(int style)
+ SCI_GETCARETSTYLE
+ The style of the caret can be set with SCI_SETCARETSTYLE to be a line caret + (CARETSTYLE_LINE=1), a block caret (CARETSTYLE_BLOCK=2) or to not draw at all + (CARETSTYLE_INVISIBLE=0). The default value is the line caret (CARETSTYLE_LINE=1). + You can determine the current caret style setting using SCI_GETCARETSTYLE.

+ +

The block character draws most combining and multibyte character sequences successfully, + though some fonts like Thai Fonts (and possibly others) can sometimes appear strange when + the cursor is positioned at these characters, which may result in only drawing a part of the + cursor character sequence. This is most notable on Windows platforms.

+ +

SCI_SETCARETWIDTH(int pixels)
+ SCI_GETCARETWIDTH
+ The width of the line caret can be set with SCI_SETCARETWIDTH to a value of + 0, 1, 2 or 3 pixels. The default width is 1 pixel. You can read back the current width with + SCI_GETCARETWIDTH. A width of 0 makes the caret invisible (added at version + 1.50), similar to setting the caret style to CARETSTYLE_INVISIBLE (though not interchangable). + This setting only affects the width of the cursor when the cursor style is set to line caret + mode, it does not affect the width for a block caret.

+ +

SCI_SETHOTSPOTACTIVEFORE(bool useHotSpotForeColour, int colour)
+ SCI_GETHOTSPOTACTIVEFORE
+ SCI_SETHOTSPOTACTIVEBACK(bool useHotSpotBackColour, int colour)
+ SCI_GETHOTSPOTACTIVEBACK
+ SCI_SETHOTSPOTACTIVEUNDERLINE(bool underline)
+ SCI_GETHOTSPOTACTIVEUNDERLINE
+ SCI_SETHOTSPOTSINGLELINE(bool singleLine)
+ SCI_GETHOTSPOTSINGLELINE
+ While the cursor hovers over text in a style with the hotspot attribute set, + the default colouring can be modified and an underline drawn with these settings. + Single line mode stops a hotspot from wrapping onto next line.

+ +

SCI_SETCONTROLCHARSYMBOL(int symbol)
+ SCI_GETCONTROLCHARSYMBOL
+ By default, Scintilla displays control characters (characters with codes less than 32) in a + rounded rectangle as ASCII mnemonics: "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", + "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI", "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", + "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US". These mnemonics come from the + early days of signaling, though some are still used (LF = Line Feed, BS = Back Space, CR = + Carriage Return, for example).

+ +

You can choose to replace these mnemonics by a nominated symbol with an ASCII code in the + range 32 to 255. If you set a symbol value less than 32, all control characters are displayed + as mnemonics. The symbol you set is rendered in the font of the style set for the character. + You can read back the current symbol with the SCI_GETCONTROLCHARSYMBOL message. + The default symbol value is 0.

+ +

SCI_SETCARETSTICKY(bool useCaretStickyBehaviour)
+ SCI_GETCARETSTICKY
+ SCI_TOGGLECARETSTICKY
+ These messages set, get or toggle the caretSticky flag which controls when the last position + of the caret on the line is saved. When set to true, the position is not saved when you type + a character, a tab, paste the clipboard content or press backspace.

+ +

Margins

+ +

There may be up to five margins to the left of the text display, plus a gap either side of + the text. Each margin can be set to display either symbols or line numbers with SCI_SETMARGINTYPEN. The markers + that can be displayed in each margin are set with SCI_SETMARGINMASKN. Any markers not associated with + a visible margin will be displayed as changes in background colour in the text. A width in + pixels can be set for each margin. Margins with a zero width are ignored completely. You can + choose if a mouse click in a margin sends a SCN_MARGINCLICK notification to the container or + selects a line of text.

+ +

The margins are numbered 0 to 4. Using a margin number outside the valid range has no + effect. By default, margin 0 is set to display line numbers, but is given a width of 0, so it + is hidden. Margin 1 is set to display non-folding symbols and is given a width of 16 pixels, so + it is visible. Margin 2 is set to display the folding symbols, but is given a width of 0, so it + is hidden. Of course, you can set the margins to be whatever you wish.

+ SCI_SETMARGINTYPEN(int margin, int + type)
+ SCI_GETMARGINTYPEN(int margin)
+ SCI_SETMARGINWIDTHN(int margin, int + pixelWidth)
+ SCI_GETMARGINWIDTHN(int margin)
+ SCI_SETMARGINMASKN(int margin, int + mask)
+ SCI_GETMARGINMASKN(int margin)
+ SCI_SETMARGINSENSITIVEN(int margin, bool + sensitive)
+ SCI_GETMARGINSENSITIVEN(int + margin)
+ SCI_SETMARGINLEFT(<unused>, int + pixels)
+ SCI_GETMARGINLEFT
+ SCI_SETMARGINRIGHT(<unused>, int + pixels)
+ SCI_GETMARGINRIGHT
+ SCI_SETFOLDMARGINCOLOUR(bool useSetting, int colour)
+ SCI_SETFOLDMARGINHICOLOUR(bool useSetting, int colour)
+
+ +

SCI_SETMARGINTYPEN(int margin, int iType)
+ SCI_GETMARGINTYPEN(int margin)
+ These two routines set and get the type of a margin. The margin argument should be 0, 1, 2, 3 or 4. + You can use the predefined constants SC_MARGIN_SYMBOL (0) and + SC_MARGIN_NUMBER (1) to set a margin as either a line number or a symbol margin. + By convention, margin 0 is used for line numbers and the next two are used for symbols. You can + also use the constants SC_MARGIN_BACK (2) and SC_MARGIN_FORE (3) for + symbol margins that set their background colour to match the STYLE_DEFAULT background and + foreground colours.

+ +

SCI_SETMARGINWIDTHN(int margin, int pixelWidth)
+ SCI_GETMARGINWIDTHN(int margin)
+ These routines set and get the width of a margin in pixels. A margin with zero width is + invisible. By default, Scintilla sets margin 1 for symbols with a width of 16 pixels, so this + is a reasonable guess if you are not sure what would be appropriate. Line number margins widths + should take into account the number of lines in the document and the line number style. You + could use something like SCI_TEXTWIDTH(STYLE_LINENUMBER, "_99999") to get a + suitable width.

+ +

SCI_SETMARGINMASKN(int margin, int mask)
+ SCI_GETMARGINMASKN(int margin)
+ The mask is a 32-bit value. Each bit corresponds to one of 32 logical symbols that can be + displayed in a margin that is enabled for symbols. There is a useful constant, + SC_MASK_FOLDERS (0xFE000000 or -33554432), that is a mask for the 7 logical + symbols used to denote folding. You can assign a wide range of symbols and colours to each of + the 32 logical symbols, see Markers for more information. If (mask + & SC_MASK_FOLDERS)==0, the margin background colour is controlled by style 33 (STYLE_LINENUMBER).

+ +

You add logical markers to a line with SCI_MARKERADD. If a line has an associated marker that + does not appear in the mask of any margin with a non-zero width, the marker changes the + background colour of the line. For example, suppose you decide to use logical marker 10 to mark + lines with a syntax error and you want to show such lines by changing the background colour. + The mask for this marker is 1 shifted left 10 times (1<<10) which is 0x400. If you make + sure that no symbol margin includes 0x400 in its mask, any line with the marker gets the + background colour changed.

+ +

To set a non-folding margin 1 use SCI_SETMARGINMASKN(1, ~SC_MASK_FOLDERS); to + set a folding margin 2 use SCI_SETMARGINMASKN(2, SC_MASK_FOLDERS). This is the + default set by Scintilla. ~SC_MASK_FOLDERS is 0x1FFFFFF in hexadecimal or 33554431 + decimal. Of course, you may need to display all 32 symbols in a margin, in which case use + SCI_SETMARGINMASKN(margin, -1).

+ +

SCI_SETMARGINSENSITIVEN(int margin, bool + sensitive)
+ SCI_GETMARGINSENSITIVEN(int margin)
+ Each of the five margins can be set sensitive or insensitive to mouse clicks. A click in a + sensitive margin sends a SCN_MARGINCLICK notification to the container. Margins that are not sensitive act as + selection margins which make it easy to select ranges of lines. By default, all margins are + insensitive.

+ +

SCI_SETMARGINLEFT(<unused>, int pixels)
+ SCI_GETMARGINLEFT
+ SCI_SETMARGINRIGHT(<unused>, int pixels)
+ SCI_GETMARGINRIGHT
+ These messages set and get the width of the blank margin on both sides of the text in pixels. + The default is to one pixel on each side.

+ +

SCI_SETFOLDMARGINCOLOUR(bool useSetting, int colour)
+ SCI_SETFOLDMARGINHICOLOUR(bool useSetting, int colour)
+ These messages allow changing the colour of the fold margin and fold margin highlight. + On Windows the fold margin colour defaults to ::GetSysColor(COLOR_3DFACE) and the fold margin highlight + colour to ::GetSysColor(COLOR_3DHIGHLIGHT).

+ +

Other settings

+ SCI_SETUSEPALETTE(bool + allowPaletteUse)
+ SCI_GETUSEPALETTE
+ SCI_SETBUFFEREDDRAW(bool isBuffered)
+ SCI_GETBUFFEREDDRAW
+ SCI_SETTWOPHASEDRAW(bool twoPhase)
+ SCI_GETTWOPHASEDRAW
+ SCI_SETCODEPAGE(int codePage)
+ SCI_GETCODEPAGE
+ SCI_SETWORDCHARS(<unused>, const char + *chars)
+ SCI_SETWHITESPACECHARS(<unused>, const char + *chars)
+ SCI_SETCHARSDEFAULT
+ SCI_GRABFOCUS
+ SCI_SETFOCUS(bool focus)
+ SCI_GETFOCUS
+
+ +

SCI_SETUSEPALETTE(bool allowPaletteUse)
+ SCI_GETUSEPALETTE
+ On 8 bit displays, which can only display a maximum of 256 colours, the graphics environment + mediates between the colour needs of applications through the use of palettes. On GTK+, + Scintilla always uses a palette.

+ +

On Windows, there are some problems with visual flashing when switching between applications + with palettes and it is also necessary for the application containing the Scintilla control to + forward some messages to Scintilla for its palette code to work. Because of this, by default, + the palette is not used and the application must tell Scintilla to use one. If Scintilla is not + using a palette, it will only display in those colours already available, which are often the + 20 Windows system colours.

+ +

To see an example of how to enable palette support in Scintilla, search the text of SciTE + for WM_PALETTECHANGED, WM_QUERYNEWPALETTE and + SCI_SETUSEPALETTE. The Windows messages to forward are:
+ WM_SYSCOLORCHANGE, WM_PALETTECHANGED, + WM_QUERYNEWPALETTE (should return TRUE).

+ +

To forward a message (WM_XXXX, WPARAM, LPARAM) to Scintilla, you can use + SendMessage(hScintilla, WM_XXXX, WPARAM, LPARAM) where hScintilla is + the handle to the Scintilla window you created as your editor.

+ +

While we are on the subject of forwarding messages in Windows, the top level window should + forward any WM_SETTINGCHANGE messages to Scintilla (this is currently used to + collect changes to mouse settings, but could be used for other user interface items in the + future).

+ +

SCI_SETBUFFEREDDRAW(bool isBuffered)
+ SCI_GETBUFFEREDDRAW
+ These messages turn buffered drawing on or off and report the buffered drawing state. Buffered + drawing draws each line into a bitmap rather than directly to the screen and then copies the + bitmap to the screen. This avoids flickering although it does take longer. The default is for + drawing to be buffered.

+ +

SCI_SETTWOPHASEDRAW(bool twoPhase)
+ SCI_GETTWOPHASEDRAW
+ Two phase drawing is a better but slower way of drawing text. + In single phase drawing each run of characters in one style is drawn along with its background. + If a character overhangs the end of a run, such as in "V_" where the + "V" is in a different style from the "_", then this can cause the right hand + side of the "V" to be overdrawn by the background of the "_" which + cuts it off. Two phase drawing + fixes this by drawing all the backgrounds first and then drawing the text in + transparent mode. Two phase drawing may flicker more than single phase + unless buffered drawing is on. The default is for drawing to be two phase.

+ +

SCI_SETCODEPAGE(int codePage)
+ SCI_GETCODEPAGE
+ Scintilla has some support for Japanese, Chinese and Korean DBCS. Use this message with + codePage set to the code page number to set Scintilla to use code page information + to ensure double byte characters are treated as one character rather than two. This also stops + the caret from moving between the two bytes in a double byte character. + Do not use this message to choose between different single byte character sets: it doesn't do that. + Call with + codePage set to zero to disable DBCS support. The default is + SCI_SETCODEPAGE(0).

+ +

Code page SC_CP_UTF8 (65001) sets Scintilla into Unicode mode with the document + treated as a sequence of characters expressed in UTF-8. The text is converted to the platform's + normal Unicode encoding before being drawn by the OS and thus can display Hebrew, Arabic, + Cyrillic, and Han characters. Languages which can use two characters stacked vertically in one + horizontal space, such as Thai, will mostly work but there are some issues where the characters + are drawn separately leading to visual glitches. Bi-directional text is not supported. Characters outside the + Basic Multilingual Plane are unlikely to work.

+ +

On Windows, code page can be set to 932 (Japanese Shift-JIS), 936 (Simplified Chinese GBK), + 949 (Korean Unified Hangul Code), 950 (Traditional Chinese Big5), or 1361 (Korean Johab) + although these may require installation of language specific support.

+ +

On GTK+, code page SC_CP_DBCS (1) sets Scintilla into + multi byte character mode as is required for Japanese language processing with + the EUC encoding.

+ +

For GTK+ 1.x, the locale should be set to a Unicode locale with a call similar to + setlocale(LC_CTYPE, "en_US.UTF-8"). Fonts with an "iso10646" registry + should be used in a font set. Font sets are a comma separated list of partial font + specifications where each partial font specification can be in the form: + foundry-fontface-charsetregistry-encoding or + fontface-charsetregistry-encoding or foundry-fontface or + fontface. An example is "misc-fixed-iso10646-1,*". + On GTK+ 2.x, Pango fonts should be used rather than font sets.

+ +

Setting codePage to a non-zero value that is not SC_CP_UTF8 is + operating system dependent.

+ +

SCI_SETWORDCHARS(<unused>, const char *chars)
+ Scintilla has several functions that operate on words, which are defined to be contiguous + sequences of characters from a particular set of characters. This message defines which + characters are members of that set. The character sets are set to default values before processing this + function. + For example, if you don't allow '_' in your set of characters + use:
+ SCI_SETWORDCHARS(0, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");

+ +

SCI_SETWHITESPACECHARS(<unused>, const char *chars)
+ Similar to SCI_SETWORDCHARS, this message allows the user to define which chars Scintilla considers + as whitespace. Setting the whitespace chars allows the user to fine-tune Scintilla's behaviour doing + such things as moving the cursor to the start or end of a word; for example, by defining punctuation chars + as whitespace, they will be skipped over when the user presses ctrl+left or ctrl+right. + This function should be called after SCI_SETWORDCHARS as it will + reset the whitespace characters to the default set.

+

SCI_SETCHARSDEFAULT
+ Use the default sets of word and whitespace characters. This sets whitespace to space, tab and other + characters with codes less than 0x20, with word characters set to alphanumeric and '_'. +

+ + +

SCI_GRABFOCUS
+ SCI_SETFOCUS(bool focus)
+ SCI_GETFOCUS
+ Scintilla can be told to grab the focus with this message. This is needed more on GTK+ where + focus handling is more complicated than on Windows.

+ +

The internal focus flag can be set with SCI_SETFOCUS. This is used by clients + that have complex focus requirements such as having their own window that gets the real focus + but with the need to indicate that Scintilla has the logical focus.

+ +

Brace highlighting

+ SCI_BRACEHIGHLIGHT(int pos1, int + pos2)
+ SCI_BRACEBADLIGHT(int pos1)
+ SCI_BRACEMATCH(int position, int + maxReStyle)
+
+ +

SCI_BRACEHIGHLIGHT(int pos1, int pos2)
+ Up to two characters can be highlighted in a 'brace highlighting style', which is defined as + style number STYLE_BRACELIGHT (34). + If you have enabled indent guides, you may also wish to highlight the indent that corresponds + with the brace. You can locate the column with SCI_GETCOLUMN and highlight the indent with SCI_SETHIGHLIGHTGUIDE.

+ +

SCI_BRACEBADLIGHT(int pos1)
+ If there is no matching brace then the brace + badlighting style, style BRACE_BADLIGHT (35), can be used to show the brace + that is unmatched. Using a position of INVALID_POSITION (-1) removes the + highlight.

+ +

SCI_BRACEMATCH(int pos, int maxReStyle)
+ The SCI_BRACEMATCH message finds a corresponding matching brace given + pos, the position of one brace. The brace characters handled are '(', ')', '[', + ']', '{', '}', '<', and '>'. The search is forwards from an opening brace and backwards + from a closing brace. If the character at position is not a brace character, or a matching + brace cannot be found, the return value is -1. Otherwise, the return value is the position of + the matching brace.

+ +

A match only occurs if the style of the matching brace is the same as the starting brace or + the matching brace is beyond the end of styling. Nested braces are handled correctly. The + maxReStyle parameter must currently be 0 - it may be used in the future to limit + the length of brace searches.

+ +

Tabs and Indentation Guides

+ +

Indentation (the white space at the start of a line) is often used by programmers to clarify + program structure and in some languages, for example Python, it may be part of the language + syntax. Tabs are normally used in editors to insert a tab character or to pad text with spaces + up to the next tab.

+ +

Scintilla can be set to treat tab and backspace in the white space at the start of a line in + a special way: inserting a tab indents the line to the next indent position rather than just + inserting a tab at the current character position and backspace unindents the line rather than + deleting a character. Scintilla can also display indentation guides (vertical lines) to help + you to generate code.

+ SCI_SETTABWIDTH(int widthInChars)
+ SCI_GETTABWIDTH
+ SCI_SETUSETABS(bool useTabs)
+ SCI_GETUSETABS
+ SCI_SETINDENT(int widthInChars)
+ SCI_GETINDENT
+ SCI_SETTABINDENTS(bool tabIndents)
+ SCI_GETTABINDENTS
+ SCI_SETBACKSPACEUNINDENTS(bool + bsUnIndents)
+ SCI_GETBACKSPACEUNINDENTS
+ SCI_SETLINEINDENTATION(int line, int + indentation)
+ SCI_GETLINEINDENTATION(int line)
+ SCI_GETLINEINDENTPOSITION(int + line)
+ SCI_SETINDENTATIONGUIDES(bool + view)
+ SCI_GETINDENTATIONGUIDES
+ SCI_SETHIGHLIGHTGUIDE(int column)
+ SCI_GETHIGHLIGHTGUIDE
+
+ +

SCI_SETTABWIDTH(int widthInChars)
+ SCI_GETTABWIDTH
+ SCI_SETTABWIDTH sets the size of a tab as a multiple of the size of a space + character in STYLE_DEFAULT. The default tab width is 8 characters. There are no + limits on tab sizes, but values less than 1 or large values may have undesirable effects.

+ +

SCI_SETUSETABS(bool useTabs)
+ SCI_GETUSETABS
+ SCI_SETUSETABS determines whether indentation should be created out of a mixture + of tabs and spaces or be based purely on spaces. Set useTabs to false + (0) to create all tabs and indents out of spaces. The default is true. You can use + SCI_GETCOLUMN to get the column of a + position taking the width of a tab into account.

+ SCI_SETINDENT(int widthInChars)
+ SCI_GETINDENT
+ SCI_SETINDENT sets the size of indentation in terms of the width of a space in STYLE_DEFAULT. If you set a width of + 0, the indent size is the same as the tab size. There are no limits on indent sizes, but values + less than 0 or large values may have undesirable effects.
+
+ + +

SCI_SETTABINDENTS(bool tabIndents)
+ SCI_GETTABINDENTS
+ SCI_SETBACKSPACEUNINDENTS(bool bsUnIndents)
+ SCI_GETBACKSPACEUNINDENTS
+

+ +

Inside indentation white space, the tab and backspace keys can be made to indent and + unindent rather than insert a tab character or delete a character with the + SCI_SETTABINDENTS and SCI_SETBACKSPACEUNINDENTS functions.

+ +

SCI_SETLINEINDENTATION(int line, int indentation)
+ SCI_GETLINEINDENTATION(int line)
+ The amount of indentation on a line can be discovered and set with + SCI_GETLINEINDENTATION and SCI_SETLINEINDENTATION. The indentation is + measured in character columns, which correspond to the width of space characters.

+ +

SCI_GETLINEINDENTPOSITION(int line)
+ This returns the position at the end of indentation of a line.

+ +

SCI_SETINDENTATIONGUIDES(int indentView)
+ SCI_GETINDENTATIONGUIDES
+ Indentation guides are dotted vertical lines that appear within indentation white space every + indent size columns. They make it easy to see which constructs line up especially when they + extend over multiple pages. Style STYLE_INDENTGUIDE (37) is used to specify the + foreground and background colour of the indentation guides.

+ +

There are 4 indentation guide views. + SC_IV_NONE turns the feature off but the other 3 states determine how far the guides appear on + empty lines. + + + + + + + + + + + + + + + + + + + + + + +
SC_IV_NONENo indentation guides are shown.
SC_IV_REALIndentation guides are shown inside real indentation white space.
SC_IV_LOOKFORWARDIndentation guides are shown beyond the actual indentation up to the level of the + next non-empty line. + If the previous non-empty line was a fold header then indentation guides are shown for + one more level of indent than that line. This setting is good for Python.
SC_IV_LOOKBOTHIndentation guides are shown beyond the actual indentation up to the level of the + next non-empty line or previous non-empty line whichever is the greater. + This setting is good for most languages.
+

+ +

SCI_SETHIGHLIGHTGUIDE(int column)
+ SCI_GETHIGHLIGHTGUIDE
+ When brace highlighting occurs, the indentation guide corresponding to the braces may be + highlighted with the brace highlighting style, STYLE_BRACELIGHT (34). Set column to 0 to + cancel this highlight.

+ +

Markers

+ +

There are 32 markers, numbered 0 to 31, and you can assign any combination of them to each + line in the document. Markers appear in the selection + margin to the left of the text. If the selection margin is set to zero width, the + background colour of the whole line is changed instead. Marker numbers 25 to 31 are used by + Scintilla in folding margins, and have symbolic names of the form SC_MARKNUM_*, + for example SC_MARKNUM_FOLDEROPEN.

+ +

Marker numbers 0 to 24 have no pre-defined function; you can use them to mark syntax errors + or the current point of execution, break points, or whatever you need marking. If you do not + need folding, you can use all 32 for any purpose you wish.

+ +

Each marker number has a symbol associated with it. You can also set the foreground and + background colour for each marker number, so you can use the same symbol more than once with + different colouring for different uses. Scintilla has a set of symbols you can assign + (SC_MARK_*) or you can use characters. By default, all 32 markers are set to + SC_MARK_CIRCLE with a black foreground and a white background.

+ +

The markers are drawn in the order of their numbers, so higher numbered markers appear on + top of lower numbered ones. Markers try to move with their text by tracking where the start of + their line moves. When a line is deleted, its markers are combined, by an OR + operation, with the markers of the previous line.

+ SCI_MARKERDEFINE(int markerNumber, int + markerSymbols)
+ SCI_MARKERDEFINEPIXMAP(int markerNumber, + const char *xpm)
+ SCI_MARKERSETFORE(int markerNumber, int + colour)
+ SCI_MARKERSETBACK(int markerNumber, int + colour)
+ SCI_MARKERSETALPHA(int markerNumber, int + alpha)
+ SCI_MARKERADD(int line, int markerNumber)
+ SCI_MARKERADDSET(int line, int markerMask)
+ SCI_MARKERDELETE(int line, int + markerNumber)
+ SCI_MARKERDELETEALL(int markerNumber)
+ SCI_MARKERGET(int line)
+ SCI_MARKERNEXT(int lineStart, int + markerMask)
+ SCI_MARKERPREVIOUS(int lineStart, int + markerMask)
+ SCI_MARKERLINEFROMHANDLE(int + handle)
+ SCI_MARKERDELETEHANDLE(int handle)
+
+ +

SCI_MARKERDEFINE(int markerNumber, int markerSymbols)
+ This message associates a marker number in the range 0 to 31 with one of the marker symbols or + an ASCII character. The general-purpose marker symbols currently available are:
+ SC_MARK_CIRCLE, SC_MARK_ROUNDRECT, SC_MARK_ARROW, + SC_MARK_SMALLRECT, SC_MARK_SHORTARROW, SC_MARK_EMPTY, + SC_MARK_ARROWDOWN, SC_MARK_MINUS, SC_MARK_PLUS, + SC_MARK_ARROWS, SC_MARK_DOTDOTDOT, SC_MARK_EMPTY, + SC_MARK_BACKGROUND, SC_MARK_LEFTRECT + and SC_MARK_FULLRECT.

+ +

The SC_MARK_BACKGROUND marker changes the background colour of the line only. + The SC_MARK_FULLRECT symbol mirrors this, changing only the margin background colour. + The SC_MARK_EMPTY symbol is invisible, allowing client code to track the movement + of lines. You would also use it if you changed the folding style and wanted one or more of the + SC_FOLDERNUM_* markers to have no associated symbol.

+ +

There are also marker symbols designed for use in the folding margin in a flattened tree + style.
+ SC_MARK_BOXMINUS, SC_MARK_BOXMINUSCONNECTED, + SC_MARK_BOXPLUS, SC_MARK_BOXPLUSCONNECTED, + SC_MARK_CIRCLEMINUS, SC_MARK_CIRCLEMINUSCONNECTED, + SC_MARK_CIRCLEPLUS, SC_MARK_CIRCLEPLUSCONNECTED, + SC_MARK_LCORNER, SC_MARK_LCORNERCURVE, SC_MARK_TCORNER, + SC_MARK_TCORNERCURVE, and SC_MARK_VLINE.

+ Characters can be used as markers by adding the ASCII value of the character to + SC_MARK_CHARACTER (10000). For example, to use 'A' (ASCII code 65) as marker + number 1 use:
+ SCI_MARKERDEFINE(1, SC_MARK_CHARACTER+65).
+ +

The marker numbers SC_MARKNUM_FOLDER and SC_MARKNUM_FOLDEROPEN are + used for showing that a fold is present and open or closed. Any symbols may be assigned for + this purpose although the (SC_MARK_PLUS, SC_MARK_MINUS) pair or the + (SC_MARK_ARROW, SC_MARK_ARROWDOWN) pair are good choices. As well as + these two, more assignments are needed for the flattened tree style: + SC_MARKNUM_FOLDEREND, SC_MARKNUM_FOLDERMIDTAIL, + SC_MARKNUM_FOLDEROPENMID, SC_MARKNUM_FOLDERSUB, and + SC_MARKNUM_FOLDERTAIL. The bits used for folding are specified by + SC_MASK_FOLDERS, which is commonly used as an argument to + SCI_SETMARGINMASKN when defining a margin to be used for folding.

+ +

This table shows which SC_MARK_* symbols should be assigned to which + SC_MARKNUM_* marker numbers to obtain four folding styles: Arrow (mimics + Macintosh), plus/minus shows folded lines as '+' and opened folds as '-', Circle tree, Box + tree.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SC_MARKNUM_*ArrowPlus/minusCircle treeBox tree
FOLDEROPENARROWDOWNMINUSCIRCLEMINUSBOXMINUS
FOLDERARROWPLUSCIRCLEPLUSBOXPLUS
FOLDERSUBEMPTYEMPTYVLINEVLINE
FOLDERTAILEMPTYEMPTYLCORNERCURVELCORNER
FOLDERENDEMPTYEMPTYCIRCLEPLUSCONNECTEDBOXPLUSCONNECTED
FOLDEROPENMIDEMPTYEMPTYCIRCLEMINUSCONNECTEDBOXMINUSCONNECTED
FOLDERMIDTAILEMPTYEMPTYTCORNERCURVETCORNER
+ +

SCI_MARKERDEFINEPIXMAP(int markerNumber, const char + *xpm)
+ Markers can be set to pixmaps with this message. The XPM format is used for the pixmap and it + is limited to pixmaps that use one character per pixel with no named colours. + The transparent colour may be named 'None'. + The data should be null terminated. + Pixmaps use the SC_MARK_PIXMAP marker symbol. You can find the full description of + the XPM format here.

+ +

SCI_MARKERSETFORE(int markerNumber, int colour)
+ SCI_MARKERSETBACK(int markerNumber, int colour)
+ These two messages set the foreground and background colour of a marker number.

+

SCI_MARKERSETALPHA(int markerNumber, int alpha)
+ When markers are drawn in the content area, either because there is no margin for them or + they are of SC_MARK_BACKGROUND type, they may be drawn translucently by + setting an alpha value.

+ +

SCI_MARKERADD(int line, int markerNumber)
+ This message adds marker number markerNumber to a line. The message returns -1 if + this fails (illegal line number, out of memory) or it returns a marker handle number that + identifies the added marker. You can use this returned handle with SCI_MARKERLINEFROMHANDLE to find where a + marker is after moving or combining lines and with SCI_MARKERDELETEHANDLE to delete the marker + based on its handle. The message does not check the value of markerNumber, nor does it + check if the line already contains the marker.

+ +

SCI_MARKERADDSET(int line, int markerMask)
+ This message can add one or more markers to a line with a single call, specified in the same "one-bit-per-marker" 32-bit integer format returned by + SCI_MARKERGET + (and used by the mask-based marker search functions + SCI_MARKERNEXT and + SCI_MARKERPREVIOUS). + As with + SCI_MARKERADD, no check is made + to see if any of the markers are already present on the targeted line.

+ +

SCI_MARKERDELETE(int line, int markerNumber)
+ This searches the given line number for the given marker number and deletes it if it is + present. If you added the same marker more than once to the line, this will delete one copy + each time it is used. If you pass in a marker number of -1, all markers are deleted from the + line.

+ +

SCI_MARKERDELETEALL(int markerNumber)
+ This removes markers of the given number from all lines. If markerNumber is -1, it deletes all + markers from all lines.

+ +

SCI_MARKERGET(int line)
+ This returns a 32-bit integer that indicates which markers were present on the line. Bit 0 is + set if marker 0 is present, bit 1 for marker 1 and so on.

+ +

SCI_MARKERNEXT(int lineStart, int markerMask)
+ SCI_MARKERPREVIOUS(int lineStart, int markerMask)
+ These messages search efficiently for lines that include a given set of markers. The search + starts at line number lineStart and continues forwards to the end of the file + (SCI_MARKERNEXT) or backwards to the start of the file + (SCI_MARKERPREVIOUS). The markerMask argument should have one bit set + for each marker you wish to find. Set bit 0 to find marker 0, bit 1 for marker 1 and so on. The + message returns the line number of the first line that contains one of the markers in + markerMask or -1 if no marker is found.

+ +

SCI_MARKERLINEFROMHANDLE(int markerHandle)
+ The markerHandle argument is an identifier for a marker returned by SCI_MARKERADD. This function searches + the document for the marker with this handle and returns the line number that contains it or -1 + if it is not found.

+ +

SCI_MARKERDELETEHANDLE(int markerHandle)
+ The markerHandle argument is an identifier for a marker returned by SCI_MARKERADD. This function searches + the document for the marker with this handle and deletes the marker if it is found.

+ +

Indicators

+ +

Indicators are used to display additional information over the top of styling. + They can be used to show, for example, syntax errors, deprecated names and bad indentation + by drawing underlines under text or boxes around text. Originally, Scintilla stored indicator information in + the style bytes but this has proved limiting, so now up to 32 separately stored indicators may be used. + While style byte indicators currently still work, they will soon be removed so all the bits in each style + byte can be used for lexical states.

+ +

Indicators may be displayed as simple underlines, squiggly underlines, a + line of small 'T' shapes, a line of diagonal hatching, a strike-out or a rectangle around the text.

+ +

The SCI_INDIC* messages allow you to get and set the visual appearance of the + indicators. They all use an indicatorNumber argument in the range 0 to INDIC_MAX(31) + to set the indicator to style. To prevent interference the set of indicators is divided up into a range for use + by lexers (0..7) and a range for use by containers + (8=INDIC_CONTAINER .. 31=INDIC_MAX).

+ + SCI_INDICSETSTYLE(int indicatorNumber, int + indicatorStyle)
+ SCI_INDICGETSTYLE(int indicatorNumber)
+ SCI_INDICSETFORE(int indicatorNumber, int + colour)
+ SCI_INDICGETFORE(int indicatorNumber)
+
+ +

SCI_INDICSETSTYLE(int indicatorNumber, int + indicatorStyle)
+ SCI_INDICGETSTYLE(int indicatorNumber)
+ These two messages set and get the style for a particular indicator. The indicator styles + currently available are:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SymbolValueVisual effect
INDIC_PLAIN0Underlined with a single, straight line.
INDIC_SQUIGGLE1A squiggly underline.
INDIC_TT2A line of small T shapes.
INDIC_DIAGONAL3Diagonal hatching.
INDIC_STRIKE4Strike out.
INDIC_HIDDEN5An indicator with no visual effect.
INDIC_BOX6A rectangle around the text.
INDIC_ROUNDBOX7A rectangle with rounded corners around the text using translucent drawing with the + interior more transparent than the border.
+ +

The default indicator styles are equivalent to:
+ SCI_INDICSETSTYLE(0, INDIC_SQUIGGLE);
+ SCI_INDICSETSTYLE(1, INDIC_TT);
+ SCI_INDICSETSTYLE(2, INDIC_PLAIN);

+ +

SCI_INDICSETFORE(int indicatorNumber, int colour)
+ SCI_INDICGETFORE(int indicatorNumber)
+ These two messages set and get the colour used to draw an indicator. The default indicator + colours are equivalent to:
+ SCI_INDICSETFORE(0, 0x007f00); (dark green)
+ SCI_INDICSETFORE(1, 0xff0000); (light blue)
+ SCI_INDICSETFORE(2, 0x0000ff); (light red)

+ +

SCI_INDICSETUNDER(int indicatorNumber, bool under)
+ SCI_INDICGETUNDER(int indicatorNumber)
+ These two messages set and get whether an indicator is drawn under text or over(default). + Drawing under text works only for modern indicators when two phase drawing + is enabled.

+ +

Modern Indicators

+ +

Modern indicators are stored in a format similar to run length encoding which is efficient in both + speed and storage for sparse information.

+

An indicator may store different values for each range but currently all values are drawn the same. + In the future, it may be possible to draw different values in different styles.

+

+ SCI_SETINDICATORCURRENT(int indicator)
+ SCI_GETINDICATORCURRENT
+ These two messages set and get the indicator that will be affected by calls to + SCI_INDICATORFILLRANGE and + SCI_INDICATORCLEARRANGE. +

+ +

+ SCI_SETINDICATORVALUE(int value)
+ SCI_GETINDICATORVALUE
+ These two messages set and get the value that will be set by calls to + SCI_INDICATORFILLRANGE. +

+ +

+ SCI_INDICATORFILLRANGE(int position, int fillLength)
+ SCI_INDICATORCLEARRANGE(int position, int clearLength)
+ These two messages fill or clear a range for the current indicator. + SCI_INDICATORFILLRANGE fills with the + the current value. +

+ +

+ SCI_INDICATORALLONFOR(int position)
+ Retrieve a bitmap value representing which indicators are non-zero at a position. +

+ +

+ SCI_INDICATORVALUEAT(int indicator, int position)
+ Retrieve the value of a particular indicator at a position. +

+ +

+ SCI_INDICATORSTART(int indicator, int position)
+ SCI_INDICATOREND(int indicator, int position)
+ Find the start or end of a range with one value from a position within the range. + Can be used to iterate through the document to discover all the indicator positions. +

+ +

Style Byte Indicators (deprecated)

+

By default, Scintilla organizes the style byte associated with each text byte as 5 bits of + style information (for 32 styles) and 3 bits of indicator information for 3 independent + indicators so that, for example, syntax errors, deprecated names and bad indentation could all + be displayed at once.

+ +

The indicators are set using SCI_STARTSTYLING with a INDICS_MASK mask + and SCI_SETSTYLING with the values + INDIC0_MASK, INDIC1_MASK and INDIC2_MASK.

+ +

If you are using indicators in a buffer that has a lexer active + (see SCI_SETLEXER), + you must save lexing state information before setting any indicators and restore it afterwards. + Use SCI_GETENDSTYLED + to retrieve the current "styled to" position and + SCI_STARTSTYLING + to reset the styling position and mask (0x1f in the default layout of 5 style bits and 3 indicator bits) + when you are done.

+ +

The number of bits used for styles can be altered with SCI_SETSTYLEBITS from 0 to 7 bits. The remaining bits + can be used for indicators, so there can be from 1 to 8 indicators. However, the + INDIC*_MASK constants defined in Scintilla.h all assume 5 bits of + styling information and 3 indicators. If you use a different arrangement, you must define your + own constants.

+ + +

Autocompletion

+ +

Autocompletion displays a list box showing likely identifiers based upon the user's typing. + The user chooses the currently selected item by pressing the tab character or another character + that is a member of the fillup character set defined with SCI_AUTOCSETFILLUPS. + Autocompletion is triggered by your application. For example, in C if you detect that the user + has just typed fred. you could look up fred, and if it has a known + list of members, you could offer them in an autocompletion list. Alternatively, you could + monitor the user's typing and offer a list of likely items once their typing has narrowed down + the choice to a reasonable list. As yet another alternative, you could define a key code to + activate the list.

+ +

When the user makes a selection from the list the container is sent a SCN_AUTOCSELECTION notification message. On return from the notification Scintilla will insert + the selected text unless the autocompletion list has been cancelled, for example by the container sending + SCI_AUTOCCANCEL.

+ +

To make use of autocompletion you must monitor each character added to the document. See + SciTEBase::CharAdded() in SciTEBase.cxx for an example of autocompletion.

+ SCI_AUTOCSHOW(int lenEntered, const char + *list)
+ SCI_AUTOCCANCEL
+ SCI_AUTOCACTIVE
+ SCI_AUTOCPOSSTART
+ SCI_AUTOCCOMPLETE
+ SCI_AUTOCSTOPS(<unused>, const char + *chars)
+ SCI_AUTOCSETSEPARATOR(char + separator)
+ SCI_AUTOCGETSEPARATOR
+ SCI_AUTOCSELECT(<unused>, const char + *select)
+ SCI_AUTOCGETCURRENT
+ SCI_AUTOCSETCANCELATSTART(bool + cancel)
+ SCI_AUTOCGETCANCELATSTART
+ SCI_AUTOCSETFILLUPS(<unused>, const char + *chars)
+ SCI_AUTOCSETCHOOSESINGLE(bool + chooseSingle)
+ SCI_AUTOCGETCHOOSESINGLE
+ SCI_AUTOCSETIGNORECASE(bool + ignoreCase)
+ SCI_AUTOCGETIGNORECASE
+ SCI_AUTOCSETAUTOHIDE(bool autoHide)
+ SCI_AUTOCGETAUTOHIDE
+ SCI_AUTOCSETDROPRESTOFWORD(bool + dropRestOfWord)
+ SCI_AUTOCGETDROPRESTOFWORD
+ SCI_REGISTERIMAGE
+ SCI_CLEARREGISTEREDIMAGES
+ SCI_AUTOCSETTYPESEPARATOR(char separatorCharacter)
+ SCI_AUTOCGETTYPESEPARATOR
+ SCI_AUTOCSETMAXHEIGHT(int rowCount)
+ SCI_AUTOCGETMAXHEIGHT
+ SCI_AUTOCSETMAXWIDTH(int characterCount)
+ SCI_AUTOCGETMAXWIDTH
+
+ +

SCI_AUTOCSHOW(int lenEntered, const char *list)
+ This message causes a list to be displayed. lenEntered is the number of + characters of the word already entered and list is the list of words separated by + separator characters. The initial separator character is a space but this can be set or got + with SCI_AUTOCSETSEPARATOR + and SCI_AUTOCGETSEPARATOR.

+ +

The list of words should be in sorted order. If set to ignore case mode with SCI_AUTOCSETIGNORECASE, then + strings are matched after being converted to upper case. One result of this is that the list + should be sorted with the punctuation characters '[', '\', ']', '^', '_', and '`' sorted after + letters.

+ +

SCI_AUTOCCANCEL
+ This message cancels any displayed autocompletion list. When in autocompletion mode, the list + should disappear when the user types a character that can not be part of the autocompletion, + such as '.', '(' or '[' when typing an identifier. A set of characters that will cancel + autocompletion can be specified with SCI_AUTOCSTOPS.

+ +

SCI_AUTOCACTIVE
+ This message returns non-zero if there is an active autocompletion list and zero if there is + not.

+ +

SCI_AUTOCPOSSTART
+ This returns the value of the current position when SCI_AUTOCSHOW started display + of the list.

+ +

SCI_AUTOCCOMPLETE
+ This message triggers autocompletion. This has the same effect as the tab key.

+ +

SCI_AUTOCSTOPS(<unused>, const char *chars)
+ The chars argument is a string containing a list of characters that will + automatically cancel the autocompletion list. When you start the editor, this list is + empty.

+ +

SCI_AUTOCSETSEPARATOR(char separator)
+ SCI_AUTOCGETSEPARATOR
+ These two messages set and get the separator character used to separate words in the + SCI_AUTOCSHOW list. The default is the space character.

+ +

SCI_AUTOCSELECT(<unused>, const char *select)
+ SCI_AUTOCGETCURRENT
+ This message selects an item in the autocompletion list. It searches the list of words for the + first that matches select. By default, comparisons are case sensitive, but you can + change this with SCI_AUTOCSETIGNORECASE. The match is character + by character for the length of the select string. That is, if select is "Fred" it + will match "Frederick" if this is the first item in the list that begins with "Fred". If an + item is found, it is selected. If the item is not found, the autocompletion list closes if + auto-hide is true (see SCI_AUTOCSETAUTOHIDE).
+ The current selection can be retrieved with SCI_AUTOCGETCURRENT +

+ +

SCI_AUTOCSETCANCELATSTART(bool cancel)
+ SCI_AUTOCGETCANCELATSTART
+ The default behavior is for the list to be cancelled if the caret moves before the location it + was at when the list was displayed. By calling this message with a false argument, + the list is not cancelled until the caret moves before the first character of the word being + completed.

+ +

SCI_AUTOCSETFILLUPS(<unused>, const char *chars)
+ If a fillup character is typed with an autocompletion list active, the currently selected item + in the list is added into the document, then the fillup character is added. Common fillup + characters are '(', '[' and '.' but others are possible depending on the language. By default, + no fillup characters are set.

+ +

SCI_AUTOCSETCHOOSESINGLE(bool chooseSingle)
+ SCI_AUTOCGETCHOOSESINGLE
+ If you use SCI_AUTOCSETCHOOSESINGLE(1) and a list has only one item, it is + automatically added and no list is displayed. The default is to display the list even if there + is only a single item.

+ +

SCI_AUTOCSETIGNORECASE(bool ignoreCase)
+ SCI_AUTOCGETIGNORECASE
+ By default, matching of characters to list members is case sensitive. These messages let you + set and get case sensitivity.

+ +

SCI_AUTOCSETAUTOHIDE(bool autoHide)
+ SCI_AUTOCGETAUTOHIDE
+ By default, the list is cancelled if there are no viable matches (the user has typed + characters that no longer match a list entry). If you want to keep displaying the original + list, set autoHide to false. This also effects SCI_AUTOCSELECT.

+ +

SCI_AUTOCSETDROPRESTOFWORD(bool dropRestOfWord)
+ SCI_AUTOCGETDROPRESTOFWORD
+ When an item is selected, any word characters following the caret are first erased if + dropRestOfWord is set true. The default is false.

+ +

+ SCI_REGISTERIMAGE(int type, const char *xpmData)
+ SCI_CLEARREGISTEREDIMAGES
+ SCI_AUTOCSETTYPESEPARATOR(char separatorCharacter)
+ SCI_AUTOCGETTYPESEPARATOR
+ + Autocompletion list items may display an image as well as text. Each image is first registered with an integer + type. Then this integer is included in the text of the list separated by a '?' from the text. For example, + "fclose?2 fopen" displays image 2 before the string "fclose" and no image before "fopen". + The images are in XPM format as is described for + SCI_MARKERDEFINEPIXMAP + The set of registered images can be cleared with SCI_CLEARREGISTEREDIMAGES and the '?' separator changed + with SCI_AUTOCSETTYPESEPARATOR. +

+ +

+ SCI_AUTOCSETMAXHEIGHT(int rowCount)
+ SCI_AUTOCGETMAXHEIGHT
+ + Get or set the maximum number of rows that will be visible in an autocompletion list. If there are more rows in the list, then a vertical + scrollbar is shown. The default is 5. +

+ +

+ SCI_AUTOCSETMAXWIDTH(int characterCount)
+ SCI_AUTOCGETMAXWIDTH
+ + Get or set the maximum width of an autocompletion list expressed as the number of characters in the longest item that will be totally visible. + If zero (the default) then the list's width is calculated to fit the item with the most characters. Any items that cannot be fully displayed within + the available width are indicated by the presence of ellipsis. +

+ +

User lists

+ +

User lists use the same internal mechanisms as autocompletion lists, and all the calls + listed for autocompletion work on them; you cannot display a user list at the same time as an + autocompletion list is active. They differ in the following respects:

+ +

o The SCI_AUTOCSETCHOOSESINGLE message has no + effect.
+ o When the user makes a selection you are sent a SCN_USERLISTSELECTION notification message rather than SCN_AUTOCSELECTION.

+ +

BEWARE: if you have set fillup characters or stop characters, these will still be active + with the user list, and may result in items being selected or the user list cancelled due to + the user typing into the editor.

+ +

SCI_USERLISTSHOW(int listType, const char *list)
+ The listType parameter is returned to the container as the wParam + field of the SCNotification + structure. It must be greater than 0 as this is how Scintilla tells the difference between an + autocompletion list and a user list. If you have different types of list, for example a list of + buffers and a list of macros, you can use listType to tell which one has returned + a selection.

+ +

Call tips

+ +

Call tips are small windows displaying the arguments to a function and are displayed after + the user has typed the name of the function. They normally display characters using the font + facename, size and character set defined by + STYLE_DEFAULT. You can choose to + use STYLE_CALLTIP to define the + facename, size, foreground and background colours and character set with + SCI_CALLTIPUSESTYLE. + This also enables support for Tab characters. + + There is some interaction between call tips and autocompletion lists in that showing a + call tip cancels any active autocompletion list, and vice versa.

+ +

Call tips can highlight part of the text within them. You could use this to highlight the + current argument to a function by counting the number of commas (or whatever separator your + language uses). See SciTEBase::CharAdded() in SciTEBase.cxx for an + example of call tip use.

+ +

The mouse may be clicked on call tips and this causes a + SCN_CALLTIPCLICK + notification to be sent to the container. Small up an down arrows may be displayed within + a call tip by, respectively, including the characters '\001', or '\002'. This is useful + for showing that there are overloaded variants of one function name and that the user can + click on the arrows to cycle through the overloads.

+ +

Alternatively, call tips can be displayed when you leave the mouse pointer for a while over + a word in response to the SCN_DWELLSTART notification and cancelled in response to SCN_DWELLEND. This method could be used in a debugger to give + the value of a variable, or during editing to give information about the word under the + pointer.

+ SCI_CALLTIPSHOW(int posStart, const char + *definition)
+ SCI_CALLTIPCANCEL
+ SCI_CALLTIPACTIVE
+ SCI_CALLTIPPOSSTART
+ SCI_CALLTIPSETHLT(int highlightStart, int + highlightEnd)
+ SCI_CALLTIPSETBACK(int colour)
+ SCI_CALLTIPSETFORE(int colour)
+ SCI_CALLTIPSETFOREHLT(int colour)
+ SCI_CALLTIPUSESTYLE(int tabsize)
+
+ +

SCI_CALLTIPSHOW(int posStart, const char *definition)
+ This message starts the process by displaying the call tip window. If a call tip is already + active, this has no effect.
+ posStart is the position in the document at which to align the call tip. The call + tip text is aligned to start 1 line below this character unless you have included up and/or + down arrows in the call tip text in which case the tip is aligned to the right-hand edge of + the rightmost arrow. The assumption is that you will start the text with something like + "\001 1 of 3 \002".
+ definition is the call tip text. This can contain multiple lines separated by + '\n' (Line Feed, ASCII code 10) characters. Do not include '\r' (Carriage Return, ASCII + code 13), as this will most likely print as an empty box. '\t' (Tab, ASCII code 9) is + supported if you set a tabsize with + SCI_CALLTIPUSESTYLE.

+ +

SCI_CALLTIPCANCEL
+ This message cancels any displayed call tip. Scintilla will also cancel call tips for you if + you use any keyboard commands that are not compatible with editing the argument list of a + function.

+ +

SCI_CALLTIPACTIVE
+ This returns 1 if a call tip is active and 0 if it is not active.

+ +

SCI_CALLTIPPOSSTART
+ This message returns the value of the current position when SCI_CALLTIPSHOW + started to display the tip.

+ +

SCI_CALLTIPSETHLT(int hlStart, int hlEnd)
+ This sets the region of the call tips text to display in a highlighted style. + hlStart is the zero-based index into the string of the first character to + highlight and hlEnd is the index of the first character after the highlight. + hlEnd must be greater than hlStart; hlEnd-hlStart is the + number of characters to highlight. Highlights can extend over line ends if this is + required.

+ +

Unhighlighted text is drawn in a mid gray. Selected text is drawn in a dark blue. The + background is white. These can be changed with + SCI_CALLTIPSETBACK, + SCI_CALLTIPSETFORE, and + SCI_CALLTIPSETFOREHLT. +

+ +

SCI_CALLTIPSETBACK(int colour)
+ The background colour of call tips can be set with this message; the default colour is white. + It is not a good idea to set a dark colour as the background as the default colour for normal + calltip text is mid gray and the defaultcolour for highlighted text is dark blue. This also + sets the background colour of STYLE_CALLTIP.

+ +

SCI_CALLTIPSETFORE(int colour)
+ The colour of call tip text can be set with this message; the default colour is mid gray. + This also sets the foreground colour of STYLE_CALLTIP.

+ +

SCI_CALLTIPSETFOREHLT(int colour)
+ The colour of highlighted call tip text can be set with this message; the default colour + is dark blue.

+ +

SCI_CALLTIPUSESTYLE(int tabsize)
+ This message changes the style used for call tips from STYLE_DEFAULT to + STYLE_CALLTIP and sets a tab size in screen pixels. If tabsize is + less than 1, Tab characters are not treated specially. Once this call has been used, the + call tip foreground and background colours are also taken from the style.

+ + +

Keyboard commands

+ +

To allow the container application to perform any of the actions available to the user with + keyboard, all the keyboard actions are messages. They do not take any parameters. These + commands are also used when redefining the key bindings with the SCI_ASSIGNCMDKEY message.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SCI_LINEDOWNSCI_LINEDOWNEXTENDSCI_LINEDOWNRECTEXTENDSCI_LINESCROLLDOWN
SCI_LINEUPSCI_LINEUPEXTENDSCI_LINEUPRECTEXTENDSCI_LINESCROLLUP
SCI_PARADOWNSCI_PARADOWNEXTENDSCI_PARAUPSCI_PARAUPEXTEND
SCI_CHARLEFTSCI_CHARLEFTEXTENDSCI_CHARLEFTRECTEXTEND
SCI_CHARRIGHTSCI_CHARRIGHTEXTENDSCI_CHARRIGHTRECTEXTEND
SCI_WORDLEFTSCI_WORDLEFTEXTENDSCI_WORDRIGHTSCI_WORDRIGHTEXTEND
SCI_WORDLEFTENDSCI_WORDLEFTENDEXTENDSCI_WORDRIGHTENDSCI_WORDRIGHTENDEXTEND
SCI_WORDPARTLEFTSCI_WORDPARTLEFTEXTENDSCI_WORDPARTRIGHTSCI_WORDPARTRIGHTEXTEND
SCI_HOMESCI_HOMEEXTEND[SCI_HOMERECTEXTEND]
SCI_HOMEDISPLAYSCI_HOMEDISPLAYEXTENDSCI_HOMEWRAPSCI_HOMEWRAPEXTEND
SCI_VCHOMESCI_VCHOMEEXTENDSCI_VCHOMERECTEXTEND
SCI_VCHOMEWRAPSCI_VCHOMEWRAPEXTEND
SCI_LINEENDSCI_LINEENDEXTENDSCI_LINEENDRECTEXTEND
SCI_LINEENDDISPLAYSCI_LINEENDDISPLAYEXTENDSCI_LINEENDWRAPSCI_LINEENDWRAPEXTEND
SCI_DOCUMENTSTARTSCI_DOCUMENTSTARTEXTENDSCI_DOCUMENTENDSCI_DOCUMENTENDEXTEND
SCI_PAGEUPSCI_PAGEUPEXTENDSCI_PAGEUPRECTEXTEND
SCI_PAGEDOWNSCI_PAGEDOWNEXTENDSCI_PAGEDOWNRECTEXTEND
SCI_STUTTEREDPAGEUPSCI_STUTTEREDPAGEUPEXTEND
SCI_STUTTEREDPAGEDOWNSCI_STUTTEREDPAGEDOWNEXTEND
SCI_DELETEBACKSCI_DELETEBACKNOTLINE
SCI_DELWORDLEFTSCI_DELWORDRIGHTSCI_DELWORDRIGHTEND
SCI_DELLINELEFTSCI_DELLINERIGHTSCI_LINEDELETE
SCI_LINECUTSCI_LINECOPYSCI_LINETRANSPOSESCI_LINEDUPLICATE
SCI_LOWERCASESCI_UPPERCASESCI_CANCELSCI_EDITTOGGLEOVERTYPE
SCI_NEWLINESCI_FORMFEEDSCI_TABSCI_BACKTAB
SCI_SELECTIONDUPLICATE
+ +

The SCI_*EXTEND messages extend the selection.

+ +

The SCI_*RECTEXTEND messages extend the rectangular selection + (and convert regular selection to rectangular one, if any).

+ +

The SCI_WORDPART* commands are used to move between word segments marked by + capitalisation (aCamelCaseIdentifier) or underscores (an_under_bar_ident).

+ +

The SCI_HOME* commands move the caret to the start of the line, while the + SCI_VCHOME*commands move the caret to the first non-blank character of the line + (ie. just after the indentation) unless it is already there; in this case, it acts as SCI_HOME*.

+ +

The SCI_[HOME|LINEEND]DISPLAY* commands are used when in line wrap mode to + allow movement to the start or end of display lines as opposed to the normal + SCI_[HOME|LINEEND] commands which move to the start or end of document lines.

+ +

The SCI_[[VC]HOME|LINEEND]WRAP* commands are like their namesakes + SCI_[[VC]HOME|LINEEND]* except they behave differently when word-wrap is enabled: + They go first to the start / end of the display line, like SCI_[HOME|LINEEND]DISPLAY*, + but if the cursor is already at the point, it goes on to the start or end of the document line, + as appropriate for SCI_[[VC]HOME|LINEEND]*. +

+ +

Key bindings

+ +

There is a default binding of keys to commands that is defined in the Scintilla source in + the file KeyMap.cxx by the constant KeyMap::MapDefault[]. This table + maps key definitions to SCI_* messages with no parameters (mostly the keyboard commands discussed above, but any Scintilla + command that has no arguments can be mapped). You can change the mapping to suit your own + requirements.

+ SCI_ASSIGNCMDKEY(int keyDefinition, int + sciCommand)
+ SCI_CLEARCMDKEY(int keyDefinition)
+ SCI_CLEARALLCMDKEYS
+ SCI_NULL
+
+ +

keyDefinition
+ A key definition contains the key code in the low 16-bits and the key modifiers in the high + 16-bits. To combine keyCode and keyMod set:
+
+ keyDefinition = keyCode + (keyMod << 16)

+ +

The key code is a visible or control character or a key from the SCK_* + enumeration, which contains:
+ SCK_ADD, SCK_BACK, SCK_DELETE, SCK_DIVIDE, + SCK_DOWN, SCK_END, SCK_ESCAPE, SCK_HOME, + SCK_INSERT, SCK_LEFT, SCK_MENU, SCK_NEXT (Page Down), + SCK_PRIOR (Page Up), SCK_RETURN, SCK_RIGHT, + SCK_RWIN, + SCK_SUBTRACT, SCK_TAB, SCK_UP, and + SCK_WIN.

+ +

The modifiers are a combination of zero or more of SCMOD_ALT, + SCMOD_CTRL, and SCMOD_SHIFT. If you are building a table, you might + want to use SCMOD_NORM, which has the value 0, to mean no modifiers.

+ +

SCI_ASSIGNCMDKEY(int keyDefinition, int sciCommand)
+ This assigns the given key definition to a Scintilla command identified by + sciCommand. sciCommand can be any SCI_* command that has + no arguments.

+ +

SCI_CLEARCMDKEY(int keyDefinition)
+ This makes the given key definition do nothing by assigning the action SCI_NULL + to it.

+ +

SCI_CLEARALLCMDKEYS
+ This command removes all keyboard command mapping by setting an empty mapping table.

+ +

SCI_NULL
+ The SCI_NULL does nothing and is the value assigned to keys that perform no + action. SCI_NULL ensures that keys do not propagate to the parent window as that may + cause focus to move. If you want the standard platform behaviour use the constant 0 instead.

+ +

Popup edit menu

+ +

SCI_USEPOPUP(bool bEnablePopup)
+ Clicking the wrong button on the mouse pops up a short default editing menu. This may be + turned off with SCI_USEPOPUP(0). If you turn it off, context menu commands (in + Windows, WM_CONTEXTMENU) will not be handled by Scintilla, so the parent of the + Scintilla window will have the opportunity to handle the message.

+ +

Macro recording

+ +

Start and stop macro recording mode. In macro recording mode, actions are reported to the + container through SCN_MACRORECORD + notifications. It is then up to the container to + record these actions for future replay.

+ +

SCI_STARTRECORD
+ SCI_STOPRECORD
+ These two messages turn macro recording on and off.

+ +

Printing

+ +

On Windows SCI_FORMATRANGE can be used to draw the text onto a display context + which can include a printer display context. Printed output shows text styling as on the + screen, but it hides all margins except a line number margin. All special marker effects are + removed and the selection and caret are hidden.

+ SCI_FORMATRANGE(bool bDraw, RangeToFormat + *pfr)
+ SCI_SETPRINTMAGNIFICATION(int + magnification)
+ SCI_GETPRINTMAGNIFICATION
+ SCI_SETPRINTCOLOURMODE(int mode)
+ SCI_GETPRINTCOLOURMODE
+ SCI_SETPRINTWRAPMODE
+ SCI_GETPRINTWRAPMODE
+
+ +

SCI_FORMATRANGE(bool bDraw, RangeToFormat *pfr)
+ This call allows Windows users to render a range of text into a device context. If you use + this for printing, you will probably want to arrange a page header and footer; Scintilla does + not do this for you. See SciTEWin::Print() in SciTEWinDlg.cxx for an + example. Each use of this message renders a range of text into a rectangular area and returns + the position in the document of the next character to print.

+ +

bDraw controls if any output is done. Set this to false if you are paginating + (for example, if you use this with MFC you will need to paginate in + OnBeginPrinting() before you output each page.

+
+struct RangeToFormat {
+    SurfaceID hdc;        // The HDC (device context) we print to
+    SurfaceID hdcTarget;  // The HDC we use for measuring (may be same as hdc)
+    PRectangle rc;        // Rectangle in which to print
+    PRectangle rcPage;    // Physically printable page size
+    CharacterRange chrg;  // Range of characters to print
+};
+
+ +

hdc and hdcTarget should both be set to the device context handle + of the output device (usually a printer). If you print to a metafile these will not be the same + as Windows metafiles (unlike extended metafiles) do not implement the full API for returning + information. In this case, set hdcTarget to the screen DC.
+ rcPage is the rectangle {0, 0, maxX, maxY} where maxX+1 + and maxY+1 are the number of physically printable pixels in x and y.
+ rc is the rectangle to render the text in (which will, of course, fit within the + rectangle defined by rcPage).
+ chrg.cpMin and chrg.cpMax define the start position and maximum + position of characters to output. All of each line within this character range is drawn.

+ +

When printing, the most tedious part is always working out what the margins should be to + allow for the non-printable area of the paper and printing a header and footer. If you look at + the printing code in SciTE, you will find that most of it is taken up with this. The loop that + causes Scintilla to render text is quite simple if you strip out all the margin, non-printable + area, header and footer code.

+ +

SCI_SETPRINTMAGNIFICATION(int magnification)
+ SCI_GETPRINTMAGNIFICATION
+ SCI_GETPRINTMAGNIFICATION lets you to print at a different size than the screen + font. magnification is the number of points to add to the size of each screen + font. A value of -3 or -4 gives reasonably small print. You can get this value with + SCI_GETPRINTMAGNIFICATION.

+ +

SCI_SETPRINTCOLOURMODE(int mode)
+ SCI_GETPRINTCOLOURMODE
+ These two messages set and get the method used to render coloured text on a printer that is + probably using white paper. It is especially important to consider the treatment of colour if + you use a dark or black screen background. Printing white on black uses up toner and ink very + many times faster than the other way around. You can set the mode to one of:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SymbolValuePurpose
SC_PRINT_NORMAL0Print using the current screen colours. This is the default.
SC_PRINT_INVERTLIGHT1If you use a dark screen background this saves ink by inverting the light value of + all colours and printing on a white background.
SC_PRINT_BLACKONWHITE2Print all text as black on a white background.
SC_PRINT_COLOURONWHITE3Everything prints in its own colour on a white background.
SC_PRINT_COLOURONWHITEDEFAULTBG4Everything prints in its own colour on a white background except that line numbers + use their own background colour.
+ +

SCI_SETPRINTWRAPMODE(int wrapMode)
+ SCI_GETPRINTWRAPMODE
+ These two functions get and set the printer wrap mode. wrapMode can be + set to SC_WRAP_NONE (0), SC_WRAP_WORD (1) or + SC_WRAP_CHAR (2). The default is + SC_WRAP_WORD, which wraps printed output so that all characters fit + into the print rectangle. If you set SC_WRAP_NONE, each line of text + generates one line of output and the line is truncated if it is too long to fit + into the print area.
+ SC_WRAP_WORD tries to wrap only between words as indicated by + white space or style changes although if a word is longer than a line, it will be wrapped before + the line end. SC_WRAP_CHAR is preferred to + SC_WRAP_WORD for Asian languages where there is no white space + between words.

+ +

Direct access

+ SCI_GETDIRECTFUNCTION
+ SCI_GETDIRECTPOINTER
+
+ +

On Windows, the message-passing scheme used to communicate between the container and + Scintilla is mediated by the operating system SendMessage function and can lead to + bad performance when calling intensively. To avoid this overhead, Scintilla provides messages + that allow you to call the Scintilla message function directly. The code to do this in C/C++ is + of the form:

+
+#include "Scintilla.h"
+SciFnDirect pSciMsg = (SciFnDirect)SendMessage(hSciWnd, SCI_GETDIRECTFUNCTION, 0, 0);
+sptr_t pSciWndData = (sptr_t)SendMessage(hSciWnd, SCI_GETDIRECTPOINTER, 0, 0);
+
+// now a wrapper to call Scintilla directly
+sptr_t CallScintilla(unsigned int iMessage, uptr_t wParam, sptr_t lParam){
+    return pSciMsg(pSciWndData, iMessage, wParam, lParam);
+}
+
+ +

SciFnDirect, sptr_t and uptr_t are declared in + Scintilla.h. hSciWnd is the window handle returned when you created + the Scintilla window.

+ +

While faster, this direct calling will cause problems if performed from a different thread + to the native thread of the Scintilla window in which case SendMessage(hSciWnd, SCI_*, + wParam, lParam) should be used to synchronize with the window's thread.

+ +

This feature also works on GTK+ but has no significant impact on speed.

+ +

From version 1.47 on Windows, Scintilla exports a function called + Scintilla_DirectFunction that can be used the same as the function returned by + SCI_GETDIRECTFUNCTION. This saves you the call to + SCI_GETDIRECTFUNCTION and the need to call Scintilla indirectly via the function + pointer.

+ +

SCI_GETDIRECTFUNCTION
+ This message returns the address of the function to call to handle Scintilla messages without + the overhead of passing through the Windows messaging system. You need only call this once, + regardless of the number of Scintilla windows you create.

+ +

SCI_GETDIRECTPOINTER
+ This returns a pointer to data that identifies which Scintilla window is in use. You must call + this once for each Scintilla window you create. When you call the direct function, you must + pass in the direct pointer associated with the target window.

+ +

Multiple views

+ +

A Scintilla window and the document that it displays are separate entities. When you create + a new window, you also create a new, empty document. Each document has a reference count that + is initially set to 1. The document also has a list of the Scintilla windows that are linked to + it so when any window changes the document, all other windows in which it appears are notified + to cause them to update. The system is arranged in this way so that you can work with many + documents in a single Scintilla window and so you can display a single document in multiple + windows (for use with splitter windows).

+ +

Although these messages use document *pDoc, to ensure compatibility with future + releases of Scintilla you should treat pDoc as an opaque void*. That + is, you can use and store the pointer as described in this section but you should not + dereference it.

+ SCI_GETDOCPOINTER
+ SCI_SETDOCPOINTER(<unused>, document + *pDoc)
+ SCI_CREATEDOCUMENT
+ SCI_ADDREFDOCUMENT(<unused>, document + *pDoc)
+ SCI_RELEASEDOCUMENT(<unused>, document + *pDoc)
+
+ +

SCI_GETDOCPOINTER
+ This returns a pointer to the document currently in use by the window. It has no other + effect.

+ +

SCI_SETDOCPOINTER(<unused>, document *pDoc)
+ This message does the following:
+ 1. It removes the current window from the list held by the current document.
+ 2. It reduces the reference count of the current document by 1.
+ 3. If the reference count reaches 0, the document is deleted.
+ 4. pDoc is set as the new document for the window.
+ 5. If pDoc was 0, a new, empty document is created and attached to the + window.
+ 6. If pDoc was not 0, its reference count is increased by 1.

+ +

SCI_CREATEDOCUMENT
+ This message creates a new, empty document and returns a pointer to it. This document is not + selected into the editor and starts with a reference count of 1. This means that you have + ownership of it and must either reduce its reference count by 1 after using + SCI_SETDOCPOINTER so that the Scintilla window owns it or you must make sure that + you reduce the reference count by 1 with SCI_RELEASEDOCUMENT before you close the + application to avoid memory leaks.

+ +

SCI_ADDREFDOCUMENT(<unused>, document *pDoc)
+ This increases the reference count of a document by 1. If you want to replace the current + document in the Scintilla window and take ownership of the current document, for example if you + are editing many documents in one window, do the following:
+ 1. Use SCI_GETDOCPOINTER to get a pointer to the document, + pDoc.
+ 2. Use SCI_ADDREFDOCUMENT(0, pDoc) to increment the reference count.
+ 3. Use SCI_SETDOCPOINTER(0, pNewDoc) to set a different document or + SCI_SETDOCPOINTER(0, 0) to set a new, empty document.

+ +

SCI_RELEASEDOCUMENT(<unused>, document *pDoc)
+ This message reduces the reference count of the document identified by pDoc. pDoc + must be the result of SCI_GETDOCPOINTER or SCI_CREATEDOCUMENT and + must point at a document that still exists. If you call this on a document with a reference + count of 1 that is still attached to a Scintilla window, bad things will happen. To keep the + world spinning in its orbit you must balance each call to SCI_CREATEDOCUMENT or + SCI_ADDREFDOCUMENT with a call to SCI_RELEASEDOCUMENT.

+ +

Folding

+ +

The fundamental operation in folding is making lines invisible or visible. Line visibility + is a property of the view rather than the document so each view may be displaying a different + set of lines. From the point of view of the user, lines are hidden and displayed using fold + points. Generally, the fold points of a document are based on the hierarchical structure of the + document contents. In Python, the hierarchy is determined by indentation and in C++ by brace + characters. This hierarchy can be represented within a Scintilla document object by attaching a + numeric "fold level" to each line. The fold level is most easily set by a lexer, but you can + also set it with messages.

+ +

It is up to your code to set the connection between user actions and folding and unfolding. + The best way to see how this is done is to search the SciTE source code for the messages used + in this section of the documentation and see how they are used. You will also need to use + markers and a folding margin to complete your folding implementation. + The "fold" property should be set to "1" with + SCI_SETPROPERTY("fold", "1") to enable folding.

+ SCI_VISIBLEFROMDOCLINE(int + docLine)
+ SCI_DOCLINEFROMVISIBLE(int + displayLine)
+ SCI_SHOWLINES(int lineStart, int lineEnd)
+ SCI_HIDELINES(int lineStart, int lineEnd)
+ SCI_GETLINEVISIBLE(int line)
+ SCI_SETFOLDLEVEL(int line, int level)
+ SCI_GETFOLDLEVEL(int line)
+ SCI_SETFOLDFLAGS(int flags)
+ SCI_GETLASTCHILD(int line, int level)
+ SCI_GETFOLDPARENT(int line)
+ SCI_SETFOLDEXPANDED(int line, bool + expanded)
+ SCI_GETFOLDEXPANDED(int line)
+ SCI_TOGGLEFOLD(int line)
+ SCI_ENSUREVISIBLE(int line)
+ SCI_ENSUREVISIBLEENFORCEPOLICY(int + line)
+
+ +

SCI_VISIBLEFROMDOCLINE(int docLine)
+ When some lines are folded, then a particular line in the document may be displayed at a + different position to its document position. If no lines are folded, this message returns + docLine. Otherwise, this returns the display line (counting the very first visible + line as 0). The display line of an invisible line is the same as the previous visible line. The + display line number of the first line in the document is 0. If there is folding and + docLine is outside the range of lines in the document, the return value is -1. + Lines can occupy more than one display line if they wrap.

+ +

SCI_DOCLINEFROMVISIBLE(int displayLine)
+ When some lines are hidden, then a particular line in the document may be displayed at a + different position to its document position. This message returns the document line number that + corresponds to a display line (counting the display line of the first line in the document as + 0). If displayLine is less than or equal to 0, the result is 0. If + displayLine is greater than or equal to the number of displayed lines, the result + is the number of lines in the document.

+ +

SCI_SHOWLINES(int lineStart, int lineEnd)
+ SCI_HIDELINES(int lineStart, int lineEnd)
+ SCI_GETLINEVISIBLE(int line)
+ The first two messages mark a range of lines as visible or invisible and then redraw the + display. The third message reports on the visible state of a line and returns 1 if it is + visible and 0 if it is not visible. These messages have no effect on fold levels or fold + flags.

+ +

SCI_SETFOLDLEVEL(int line, int level)
+ SCI_GETFOLDLEVEL(int line)
+ These two messages set and get a 32-bit value that contains the fold level of a line and some + flags associated with folding. The fold level is a number in the range 0 to + SC_FOLDLEVELNUMBERMASK (4095). However, the initial fold level is set to + SC_FOLDLEVELBASE (1024) to allow unsigned arithmetic on folding levels. There are + two addition flag bits. SC_FOLDLEVELWHITEFLAG indicates that the line is blank and + allows it to be treated slightly different then its level may indicate. For example, blank + lines should generally not be fold points and will be considered part of the preceding section even though + they may have a lesser fold level. + SC_FOLDLEVELHEADERFLAG indicates that + the line is a header (fold point).

+ +

Use SCI_GETFOLDLEVEL(line) & SC_FOLDLEVELNUMBERMASK to get the fold level + of a line. Likewise, use SCI_GETFOLDLEVEL(line) & SC_FOLDLEVEL*FLAG to get the + state of the flags. To set the fold level you must or in the associated flags. For instance, to + set the level to thisLevel and mark a line as being a fold point use: + SCI_SETFOLDLEVEL(line, thisLevel | SC_FOLDLEVELHEADERFLAG).

+ If you use a lexer, you should not need to use SCI_SETFOLDLEVEL as this is far + better handled by the lexer. You will need to use SCI_GETFOLDLEVEL to decide how + to handle user folding requests. If you do change the fold levels, the folding margin will + update to match your changes. + +

SCI_SETFOLDFLAGS(int flags)
+ In addition to showing markers in the folding margin, you can indicate folds to the user by + drawing lines in the text area. The lines are drawn in the foreground colour set for STYLE_DEFAULT. Bits set in + flags determine where folding lines are drawn:
+

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueEffect
1Experimental - draw boxes if expanded
2Draw above if expanded
4Draw above if not expanded
8Draw below if expanded
16Draw below if not expanded
64display hexadecimal fold levels in line margin to aid debugging of + folding. This feature needs to be redesigned to be sensible.
+ +

This message causes the display to redraw.

+ +

SCI_GETLASTCHILD(int startLine, int level)
+ This message searches for the next line after startLine, that has a folding level + that is less than or equal to level and then returns the previous line number. If + you set level to -1, level is set to the folding level of line + startLine. If from is a fold point, SCI_GETLASTCHILD(from, + -1) returns the last line that would be in made visible or hidden by toggling the fold + state.

+ +

SCI_GETFOLDPARENT(int startLine)
+ This message returns the line number of the first line before startLine that is + marked as a fold point with SC_FOLDLEVELHEADERFLAG and has a fold level less than + the startLine. If no line is found, or if the header flags and fold levels are + inconsistent, the return value is -1.

+ +

SCI_TOGGLEFOLD(int line)
+ Each fold point may be either expanded, displaying all its child lines, or contracted, hiding + all the child lines. This message toggles the folding state of the given line as long as it has + the SC_FOLDLEVELHEADERFLAG set. This message takes care of folding or expanding + all the lines that depend on the line. The display updates after this message.

+ +

SCI_SETFOLDEXPANDED(int line, bool expanded)
+ SCI_GETFOLDEXPANDED(int line)
+ These messages set and get the expanded state of a single line. The set message has no effect + on the visible state of the line or any lines that depend on it. It does change the markers in + the folding margin. If you ask for the expansion state of a line that is outside the document, + the result is false (0).

+ +

If you just want to toggle the fold state of one line and handle all the lines that are + dependent on it, it is much easier to use SCI_TOGGLEFOLD. You would use the + SCI_SETFOLDEXPANDED message to process many folds without updating the display + until you had finished. See SciTEBase::FoldAll() and + SciTEBase::Expand() for examples of the use of these messages.

+ +

SCI_ENSUREVISIBLE(int line)
+ SCI_ENSUREVISIBLEENFORCEPOLICY(int line)
+ A line may be hidden because more than one of its parent lines is contracted. Both these + message travels up the fold hierarchy, expanding any contracted folds until they reach the top + level. The line will then be visible. If you use SCI_ENSUREVISIBLEENFORCEPOLICY, + the vertical caret policy set by SCI_SETVISIBLEPOLICY is then applied.

+ +

Line wrapping

+ + SCI_SETWRAPMODE(int wrapMode)
+ SCI_GETWRAPMODE
+ SCI_SETWRAPVISUALFLAGS(int wrapVisualFlags)
+ SCI_GETWRAPVISUALFLAGS
+ SCI_SETWRAPSTARTINDENT(int indent)
+ SCI_GETWRAPSTARTINDENT
+ SCI_SETLAYOUTCACHE(int cacheMode)
+ SCI_GETLAYOUTCACHE
+ SCI_SETPOSITIONCACHE(int size)
+ SCI_GETPOSITIONCACHE
+ SCI_LINESSPLIT(int pixelWidth)
+ SCI_LINESJOIN
+ SCI_WRAPCOUNT(int docLine)
+
+ +

By default, Scintilla does not wrap lines of text. If you enable line wrapping, lines wider + than the window width are continued on the following lines. Lines are broken after space or tab + characters or between runs of different styles. If this is not possible because a word in one + style is wider than the window then the break occurs after the last character that completely + fits on the line. The horizontal scroll bar does not appear when wrap mode is on.

+ +

For wrapped lines Scintilla can draw visual flags (little arrows) at end of a a subline of a + wrapped line and at begin of the next subline. These can be enabled individually, but if Scintilla + draws the visual flag at begin of the next subline this subline will be indented by one char. + Independent from drawing a visual flag at the begin the subline can have an indention.

+ +

Much of the time used by Scintilla is spent on laying out and drawing text. The same text + layout calculations may be performed many times even when the data used in these calculations + does not change. To avoid these unnecessary calculations in some circumstances, the line layout + cache can store the results of the calculations. The cache is invalidated whenever the + underlying data, such as the contents or styling of the document changes. Caching the layout of + the whole document has the most effect, making dynamic line wrap as much as 20 times faster but + this requires 7 times the memory required by the document contents plus around 80 bytes per + line.

+ +

Wrapping is not performed immediately there is a change but is delayed until the display + is redrawn. This delay improves peformance by allowing a set of changes to be performed + and then wrapped and displayed once. Because of this, some operations may not occur as + expected. If a file is read and the scroll position moved to a particular line in the text, + such as occurs when a container tries to restore a previous editing session, then + the scroll position will have been determined before wrapping so an unexpected range + of text will be displayed. To scroll to the position correctly, delay the scroll until the + wrapping has been performed by waiting for an initial + SCN_PAINTED notification.

+ +

SCI_SETWRAPMODE(int wrapMode)
+ SCI_GETWRAPMODE
+ Set wrapMode to SC_WRAP_WORD (1) to enable wrapping + on word boundaries, SC_WRAP_CHAR (2) to enable wrapping + between any characters, and to SC_WRAP_NONE (0) to disable line + wrapping. SC_WRAP_CHAR is preferred to + SC_WRAP_WORD for Asian languages where there is no white space + between words.

+ + +

SCI_SETWRAPVISUALFLAGS(int wrapVisualFlags)
+ SCI_GETWRAPVISUALFLAGS
+ You can enable the drawing of visual flags to indicate a line is wrapped. Bits set in + wrapVisualFlags determine which visual flags are drawn. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SymbolValueEffect
SC_WRAPVISUALFLAG_NONE0No visual flags
SC_WRAPVISUALFLAG_END1Visual flag at end of subline of a wrapped line.
SC_WRAPVISUALFLAG_START2Visual flag at begin of subline of a wrapped line.
+ Subline is indented by at least 1 to make room for the flag.
+
+ +

SCI_SETWRAPVISUALFLAGSLOCATION(int wrapVisualFlagsLocation)
+ SCI_GETWRAPVISUALFLAGSLOCATION
+ You can set wether the visual flags to indicate a line is wrapped are drawn near the border or near the text. + Bits set in wrapVisualFlagsLocation set the location to near the text for the corresponding visual flag. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SymbolValueEffect
SC_WRAPVISUALFLAGLOC_DEFAULT0Visual flags drawn near border
SC_WRAPVISUALFLAGLOC_END_BY_TEXT1Visual flag at end of subline drawn near text
SC_WRAPVISUALFLAGLOC_START_BY_TEXT2Visual flag at begin of subline drawn near text
+ +
+ +

SCI_SETWRAPSTARTINDENT(int indent)
+ SCI_GETWRAPSTARTINDENT
+ SCI_SETWRAPSTARTINDENT sets the size of indentation of sublines for + wrapped lines in terms of the width of a space in + STYLE_DEFAULT. + There are no limits on indent sizes, but values less than 0 or large values may have + undesirable effects.
+ The indention of sublines is independent of visual flags, but if + SC_WRAPVISUALFLAG_START is set an indent of at least 1 is used. +

+ +

SCI_SETLAYOUTCACHE(int cacheMode)
+ SCI_GETLAYOUTCACHE
+ You can set cacheMode to one of the symbols in the table:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SymbolValueLayout cached for these lines
SC_CACHE_NONE0No lines are cached.
SC_CACHE_CARET1The line containing the text caret. This is the default.
SC_CACHE_PAGE2Visible lines plus the line containing the caret.
SC_CACHE_DOCUMENT3All lines in the document.
+
+ +

SCI_SETPOSITIONCACHE(int size)
+ SCI_GETPOSITIONCACHE
+ The position cache stores position information for short runs of text + so that their layout can be determined more quickly if the run recurs. + The size in entries of this cache can be set with SCI_SETPOSITIONCACHE.

+ +

SCI_LINESSPLIT(int pixelWidth)
+ Split a range of lines indicated by the target into lines that are at most pixelWidth wide. + Splitting occurs on word boundaries wherever possible in a similar manner to line wrapping. + When pixelWidth is 0 then the width of the window is used. +

+ +

SCI_LINESJOIN
+ Join a range of lines indicated by the target into one line by + removing line end characters. + Where this would lead to no space between words, an extra space is inserted. +

+ +

SCI_WRAPCOUNT(int docLine)
+ Document lines can occupy more than one display line if they wrap and this + returns the number of display lines needed to wrap a document line.

+ +

Zooming

+ +

Scintilla incorporates a "zoom factor" that lets you make all the text in the document + larger or smaller in steps of one point. The displayed point size never goes below 2, whatever + zoom factor you set. You can set zoom factors in the range -10 to +20 points.

+ SCI_ZOOMIN
+ SCI_ZOOMOUT
+ SCI_SETZOOM(int zoomInPoints)
+ SCI_GETZOOM
+
+ +

SCI_ZOOMIN
+ SCI_ZOOMOUT
+ SCI_ZOOMIN increases the zoom factor by one point if the current zoom factor is + less than 20 points. SCI_ZOOMOUT decreases the zoom factor by one point if the + current zoom factor is greater than -10 points.

+ +

SCI_SETZOOM(int zoomInPoints)
+ SCI_GETZOOM
+ These messages let you set and get the zoom factor directly. There is no limit set on the + factors you can set, so limiting yourself to -10 to +20 to match the incremental zoom functions + is a good idea.

+ +

Long lines

+ +

You can choose to mark lines that exceed a given length by drawing a vertical line or by + colouring the background of characters that exceed the set length.

+ SCI_SETEDGEMODE(int mode)
+ SCI_GETEDGEMODE
+ SCI_SETEDGECOLUMN(int column)
+ SCI_GETEDGECOLUMN
+ SCI_SETEDGECOLOUR(int colour)
+ SCI_GETEDGECOLOUR
+
+ +

SCI_SETEDGEMODE(int edgeMode)
+ SCI_GETEDGEMODE
+ These two messages set and get the mode used to display long lines. You can set one of the + values in the table:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SymbolValueLong line display mode
EDGE_NONE0Long lines are not marked. This is the default state.
EDGE_LINE1A vertical line is drawn at the column number set by SCI_SETEDGECOLUMN. + This works well for monospaced fonts. The line is drawn at a position based on the width + of a space character in STYLE_DEFAULT, so it may not work very well if + your styles use proportional fonts or if your style have varied font sizes or you use a + mixture of bold, italic and normal text. .
EDGE_BACKGROUND2The background colour of characters after the column limit is changed to the colour + set by SCI_SETEDGECOLOUR. This is recommended for proportional fonts.
+
+
+ + +

SCI_SETEDGECOLUMN(int column)
+ SCI_GETEDGECOLUMN
+ These messages set and get the column number at which to display the long line marker. When + drawing lines, the column sets a position in units of the width of a space character in + STYLE_DEFAULT. When setting the background colour, the column is a character count + (allowing for tabs) into the line.

+ +

SCI_SETEDGECOLOUR(int colour)
+ SCI_GETEDGECOLOUR
+ These messages set and get the colour of the marker used to show that a line has exceeded the + length set by SCI_SETEDGECOLUMN.

+ +

Lexer

+ +

If you define the symbol SCI_LEXER when building Scintilla, (this is sometimes + called the SciLexer version of Scintilla), lexing support for a wide range programming + languages is included and the messages in this section are supported. If you want to set + styling and fold points for an unsupported language you can either do this in the container or + better still, write your own lexer following the pattern of one of the existing ones.

+ +

Scintilla also supports external lexers. These are DLLs (on Windows) or .so modules (on GTK+/Linux) that export four + functions: GetLexerCount, GetLexerName, Lex and + Fold. See externalLexer.cxx for more.

+ SCI_SETLEXER(int lexer)
+ SCI_GETLEXER
+ SCI_SETLEXERLANGUAGE(<unused>, char + *name)
+ SCI_LOADLEXERLIBRARY(<unused>, char + *path)
+ SCI_COLOURISE(int start, int end)
+ SCI_SETPROPERTY(const char *key, const char *value)
+ SCI_GETPROPERTY(const char *key, char *value)
+ SCI_GETPROPERTYEXPANDED(const char *key, char *value)
+ SCI_GETPROPERTYINT(const char *key, int default)
+ SCI_SETKEYWORDS(int keyWordSet, const char + *keyWordList)
+ SCI_GETSTYLEBITSNEEDED +
+
+ +

SCI_SETLEXER(int lexer)
+ SCI_GETLEXER
+ You can select the lexer to use with an integer code from the SCLEX_* enumeration + in Scintilla.h. There are two codes in this sequence that do not use lexers: + SCLEX_NULL to select no lexing action and SCLEX_CONTAINER which sends + the SCN_STYLENEEDED notification to + the container whenever a range of text needs to be styled. You cannot use the + SCLEX_AUTOMATIC value; this identifies additional external lexers that Scintilla + assigns unused lexer numbers to.

+ +

SCI_SETLEXERLANGUAGE(<unused>, const char *name)
+ This message lets you select a lexer by name, and is the only method if you are using an + external lexer or if you have written a lexer module for a language of your own and do not wish + to assign it an explicit lexer number. To select an existing lexer, set name to + match the (case sensitive) name given to the module, for example "ada" or "python", not "Ada" + or "Python". To locate the name for the built-in lexers, open the relevant + Lex*.cxx file and search for LexerModule. The third argument in the + LexerModule constructor is the name to use.

+ +

To test if your lexer assignment worked, use SCI_GETLEXER before and after setting the new lexer to + see if the lexer number changed.

+ +

SCI_LOADLEXERLIBRARY(<unused>, const char *path)
+ Load a lexer implemented in a shared library. This is a .so file on GTK+/Linux or a .DLL file on Windows. +

+ +

SCI_COLOURISE(int startPos, int endPos)
+ This requests the current lexer or the container (if the lexer is set to + SCLEX_CONTAINER) to style the document between startPos and + endPos. If endPos is -1, the document is styled from + startPos to the end. If the "fold" property is set to + "1" and your lexer or container supports folding, fold levels are also set. This + message causes a redraw.

+ +

SCI_SETPROPERTY(const char *key, const char *value)
+ You can communicate settings to lexers with keyword:value string pairs. There is no limit to + the number of keyword pairs you can set, other than available memory. key is a + case sensitive keyword, value is a string that is associated with the keyword. If + there is already a value string associated with the keyword, it is replaced. If you pass a zero + length string, the message does nothing. Both key and value are used + without modification; extra spaces at the beginning or end of key are + significant.

+ +

The value string can refer to other keywords. For example, + SCI_SETPROPERTY("foldTimes10", "$(fold)0") stores the string + "$(fold)0", but when this is accessed, the $(fold) is replaced by the + value of the "fold" keyword (or by nothing if this keyword does not exist).

+ +

Currently the "fold" property is defined for most of the lexers to set the fold structure if + set to "1". SCLEX_PYTHON understands "tab.timmy.whinge.level" as a + setting that determines how to indicate bad indentation. Most keywords have values that are + interpreted as integers. Search the lexer sources for GetPropertyInt to see how + properties are used.

+ +

SCI_GETPROPERTY(const char *key, char *value)
+ Lookup a keyword:value pair using the specified key; if found, copy the value to the user-supplied + buffer and return the length (not including the terminating 0). If not found, copy an empty string + to the buffer and return 0.

+ +

Note that "keyword replacement" as described in + SCI_SETPROPERTY will not be performed.

+ +

If the value argument is 0 then the length that should be allocated to store the value is returned; + again, the terminating 0 is not included.

+ +

SCI_GETPROPERTYEXPANDED(const char *key, char *value)
+ Lookup a keyword:value pair using the specified key; if found, copy the value to the user-supplied + buffer and return the length (not including the terminating 0). If not found, copy an empty string + to the buffer and return 0.

+ +

Note that "keyword replacement" as described in + SCI_SETPROPERTY will be performed.

+ +

If the value argument is 0 then the length that should be allocated to store the value (including any indicated keyword replacement) + is returned; again, the terminating 0 is not included.

+ +

SCI_GETPROPERTYINT(const char *key, int default)
+ Lookup a keyword:value pair using the specified key; if found, interpret the value as an integer and return it. + If not found (or the value is an empty string) then return the supplied default. If the keyword:value pair is found but is not + a number, then return 0.

+ +

Note that "keyword replacement" as described in + SCI_SETPROPERTY will be performed before any numeric interpretation.

+ +

SCI_SETKEYWORDS(int keyWordSet, const char *keyWordList)
+ You can set up to 9 lists of keywords for use by the current lexer. This was increased from 6 + at revision 1.50. keyWordSet can be 0 to 8 (actually 0 to KEYWORDSET_MAX) + and selects which keyword list to replace. keyWordList is a list of keywords + separated by spaces, tabs, "\n" or "\r" or any combination of these. + It is expected that the keywords will be composed of standard ASCII printing characters, + but there is nothing to stop you using any non-separator character codes from 1 to 255 + (except common sense).

+ +

How these keywords are used is entirely up to the lexer. Some languages, such as HTML may + contain embedded languages, VBScript and JavaScript are common for HTML. For HTML, key word set + 0 is for HTML, 1 is for JavaScript and 2 is for VBScript, 3 is for Python, 4 is for PHP and 5 + is for SGML and DTD keywords. Review the lexer code to see examples of keyword list. A fully + conforming lexer sets the fourth argument of the LexerModule constructor to be a + list of strings that describe the uses of the keyword lists.

+ +

Alternatively, you might use set 0 for general keywords, set 1 for keywords that cause + indentation and set 2 for keywords that cause unindentation. Yet again, you might have a simple + lexer that colours keywords and you could change languages by changing the keywords in set 0. + There is nothing to stop you building your own keyword lists into the lexer, but this means + that the lexer must be rebuilt if more keywords are added.

+ +

SCI_GETSTYLEBITSNEEDED
+ Retrieve the number of bits the current lexer needs for styling. This should normally be the argument + to SCI_SETSTYLEBITS. +

+ +

Notifications

+ +

Notifications are sent (fired) from the Scintilla control to its container when an event has + occurred that may interest the container. Notifications are sent using the + WM_NOTIFY message on Windows and the "notify" signal on GTK+. The container is + passed a SCNotification structure containing information about the event.

+
+struct NotifyHeader {   // This matches the Win32 NMHDR structure
+    void *hwndFrom;     // environment specific window handle/pointer
+    uptr_t idFrom;	// CtrlID of the window issuing the notification
+    unsigned int code;  // The SCN_* notification code
+};
+
+struct SCNotification {
+    struct NotifyHeader nmhdr;
+    int position;
+    // SCN_STYLENEEDED, SCN_DOUBLECLICK, SCN_MODIFIED, SCN_DWELLSTART,
+    // SCN_DWELLEND, SCN_CALLTIPCLICK,
+    // SCN_HOTSPOTCLICK, SCN_HOTSPOTDOUBLECLICK
+    int ch;             // SCN_CHARADDED, SCN_KEY
+    int modifiers;      // SCN_KEY, SCN_DOUBLECLICK, SCN_HOTSPOTCLICK, SCN_HOTSPOTDOUBLECLICK
+    int modificationType; // SCN_MODIFIED
+    const char *text;   // SCN_MODIFIED, SCN_USERLISTSELECTION, SCN_AUTOCSELECTION
+    int length;         // SCN_MODIFIED
+    int linesAdded;     // SCN_MODIFIED
+    int message;        // SCN_MACRORECORD
+    uptr_t wParam;      // SCN_MACRORECORD
+    sptr_t lParam;      // SCN_MACRORECORD
+    int line;           // SCN_MODIFIED, SCN_DOUBLECLICK
+    int foldLevelNow;   // SCN_MODIFIED
+    int foldLevelPrev;  // SCN_MODIFIED
+    int margin;         // SCN_MARGINCLICK
+    int listType;       // SCN_USERLISTSELECTION, SCN_AUTOCSELECTION
+    int x;              // SCN_DWELLSTART, SCN_DWELLEND
+    int y;              // SCN_DWELLSTART, SCN_DWELLEND
+};
+
+ +

The notification messages that your container can choose to handle and the messages + associated with them are:

+ SCN_STYLENEEDED
+ SCN_CHARADDED
+ SCN_SAVEPOINTREACHED
+ SCN_SAVEPOINTLEFT
+ SCN_MODIFYATTEMPTRO
+ SCN_KEY
+ SCN_DOUBLECLICK
+ SCN_UPDATEUI
+ SCN_MODIFIED
+ SCN_MACRORECORD
+ SCN_MARGINCLICK
+ SCN_NEEDSHOWN
+ SCN_PAINTED
+ SCN_USERLISTSELECTION
+ SCN_URIDROPPED
+ SCN_DWELLSTART
+ SCN_DWELLEND
+ SCN_ZOOM
+ SCN_HOTSPOTCLICK
+ SCN_HOTSPOTDOUBLECLICK
+ SCN_INDICATORCLICK
+ SCN_INDICATORRELEASE
+ SCN_CALLTIPCLICK
+ SCN_AUTOCSELECTION
+
+ +

The following SCI_* messages are associated with these notifications:

+ SCI_SETMODEVENTMASK(int + eventMask)
+ SCI_GETMODEVENTMASK
+ SCI_SETMOUSEDWELLTIME
+ SCI_GETMOUSEDWELLTIME
+
+ +

The following additional notifications are sent using the WM_COMMAND message on + Windows and the "Command" signal on GTK+. This emulates the Windows Edit control. Only the lower + 16 bits of the control's ID is passed in these notifications.

+ SCEN_CHANGE
+ SCEN_SETFOCUS
+ SCEN_KILLFOCUS
+
+ +

SCN_STYLENEEDED
+ If you used SCI_SETLEXER(SCLEX_CONTAINER) to make the container act as the + lexer, you will receive this notification when Scintilla is about to display or print text that + requires styling. You are required to style the text from the line that contains the position + returned by SCI_GETENDSTYLED up to + the position passed in SCNotification.position. Symbolically, you need code of the + form:

+
+    startPos = SCI_GETENDSTYLED()
+    lineNumber = SCI_LINEFROMPOSITION(startPos);
+    startPos = SCI_POSITIONFROMLINE(lineNumber);
+    MyStyleRoutine(startPos, SCNotification.position);
+
+ +

SCN_CHARADDED
+ This is sent when the user types an ordinary text character (as opposed to a command + character) that is entered into the text. The container can use this to decide to display a call tip or an auto + completion list. The character is in SCNotification.ch. + This notification is sent before the character has been styled so processing that depends on + styling should instead be performed in the SCN_UPDATEUI notification.

+ +

SCN_SAVEPOINTREACHED
+ SCN_SAVEPOINTLEFT
+ Sent to the container when the save point is entered or left, allowing the container to + display a "document dirty" indicator and change its menus.
+ See also: SCI_SETSAVEPOINT, SCI_GETMODIFY

+ +

SCN_MODIFYATTEMPTRO
+ When in read-only mode, this notification is sent to the container if the user tries to change + the text. This can be used to check the document out of a version control system. You can set + the read-only state of a document with SCI_SETREADONLY.

+ +

SCN_KEY
+ Reports all keys pressed but not consumed by Scintilla. Used on GTK+ because of + some problems with keyboard focus and is not sent by the Windows version. SCNotification.ch holds the key code and + SCNotification.modifiers holds the modifiers. This notification is sent if the + modifiers include SCMOD_ALT or SCMOD_CTRL and the key code is less + than 256.

+ +

SCN_DOUBLECLICK
+ The mouse button was double clicked in editor. The position field is set to the text position of the + double click and the line field is set to the line of the double click.

+ +

SCN_UPDATEUI
+ Either the text or styling of the document has changed or the selection range has changed. Now + would be a good time to update any container UI elements that depend on document or view state. + This was previously called SCN_CHECKBRACE because a common use is to check whether the + caret is next to a brace and set highlights on this brace and its corresponding matching brace. + This also replaces SCN_POSCHANGED, + which is now deprecated.

+ +

SCN_MODIFIED
+ This notification is sent when the text or styling of the document changes or is about to + change. You can set a mask for the notifications that are sent to the container with SCI_SETMODEVENTMASK. The + notification structure contains information about what changed, how the change occurred and + whether this changed the number of lines in the document. No modifications may be performed + while in a SCN_MODIFIED event. The SCNotification fields used + are:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldUsage
modificationTypeA set of flags that identify the change(s) made. See the next + table.
positionStart position of a text or styling change. Set to 0 if not used.
lengthLength of the change in cells or characters when the text or styling + changes. Set to 0 if not used.
linesAddedNumber of added lines. If negative, the number of deleted lines. Set to + 0 if not used or no lines added or deleted.
textValid for text changes, not for style changes. If we are collecting undo + information this holds a pointer to the text that is handed to the Undo system, otherwise + it is zero. For user performed SC_MOD_BEFOREDELETE the text field is 0 and + for user performed SC_MOD_BEFOREINSERT the text field points to an array of cells, + not bytes and the length is the number of cells.
lineThe line number at which a fold level or marker change occurred. This is + 0 if unused and may be -1 if more than one line changed.
foldLevelNowThe new fold level applied to the line or 0 if this field is + unused.
foldLevelPrevThe previous folding level of the line or 0 if this field is + unused.
+ +

The SCNotification.modificationType field has bits set to tell you what has + been done. The SC_MOD_* bits correspond to actions. The + SC_PERFORMED_* bits tell you if the action was done by the user, or the result of + Undo or Redo of a previous action.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SymbolValueMeaningSCNotification fields
SC_MOD_INSERTTEXT0x01Text has been inserted into the document.position, length, text, linesAdded
SC_MOD_DELETETEXT0x02Text has been removed from the document.position, length, text, linesAdded
SC_MOD_CHANGESTYLE0x04A style change has occurred.position, length
SC_MOD_CHANGEFOLD0x08A folding change has occurred.line, foldLevelNow, foldLevelPrev
SC_PERFORMED_USER0x10Information: the operation was done by the user.None
SC_PERFORMED_UNDO0x20Information: this was the result of an Undo.None
SC_PERFORMED_REDO0x40Information: this was the result of a Redo.None
SC_MULTISTEPUNDOREDO0x80This is part of a multi-step Undo or Redo transaction.None
SC_LASTSTEPINUNDOREDO0x100This is the final step in an Undo or Redo transaction.None
SC_MOD_CHANGEMARKER0x200One or more markers has changed in a line.line
SC_MOD_BEFOREINSERT0x400Text is about to be inserted into the document.position, if performed by user then text in cells, length in cells
SC_MOD_BEFOREDELETE0x800Text is about to be deleted from the document.position, length
SC_MOD_CHANGEINDICATOR0x4000An indicator has been added or removed from a range of text.position, length
SC_MOD_CHANGELINESTATE0x8000A line state has changed because SCI_SETLINESTATE + was called.line
SC_MULTILINEUNDOREDO0x1000This is part of an Undo or Redo with multi-line changes.None
SC_STARTACTION0x2000This is set on a SC_PERFORMED_USER action when it is the + first or only step in an undo transaction. This can be used to integrate the Scintilla + undo stack with an undo stack in the container application by adding a Scintilla + action to the container's stack for the currently opened container transaction or + to open a new container transaction if there is no open container transaction. + None
SC_MODEVENTMASKALL0x1fffThis is a mask for all valid flags. This is the default mask state set by SCI_SETMODEVENTMASK.None
+ +

SCEN_CHANGE
+ SCEN_CHANGE (768) is fired when the text (not the style) of the document changes. + This notification is sent using the WM_COMMAND message on Windows and the + "Command" signal on GTK+ as this is the behavior of the standard Edit control + (SCEN_CHANGE has the same value as the Windows Edit control + EN_CHANGE). No other information is sent. If you need more detailed information + use SCN_MODIFIED. You can filter the + types of changes you are notified about with SCI_SETMODEVENTMASK.

+ +

SCI_SETMODEVENTMASK(int eventMask)
+ SCI_GETMODEVENTMASK
+ These messages set and get an event mask that determines which document change events are + notified to the container with SCN_MODIFIED and SCEN_CHANGE. For example, a container may decide to see + only notifications about changes to text and not styling changes by calling + SCI_SETMODEVENTMASK(SC_MOD_INSERTTEXT|SC_MOD_DELETETEXT).

+ +

The possible notification types are the same as the modificationType bit flags + used by SCN_MODIFIED: SC_MOD_INSERTTEXT, + SC_MOD_DELETETEXT, SC_MOD_CHANGESTYLE, + SC_MOD_CHANGEFOLD, SC_PERFORMED_USER, SC_PERFORMED_UNDO, + SC_PERFORMED_REDO, SC_MULTISTEPUNDOREDO, + SC_LASTSTEPINUNDOREDO, SC_MOD_CHANGEMARKER, + SC_MOD_BEFOREINSERT, SC_MOD_BEFOREDELETE, + SC_MULTILINEUNDOREDO, and SC_MODEVENTMASKALL.

+ +

SCEN_SETFOCUS
+ SCEN_KILLFOCUS
+ SCEN_SETFOCUS (512) is fired when Scintilla receives focus and + SCEN_KILLFOCUS (256) when it loses focus. These notifications are sent using the + WM_COMMAND message on Windows and the "Command" signal on GTK+ as this is the + behavior of the standard Edit control. Unfortunately, these codes do not match the Windows Edit + notification codes EN_SETFOCUS (256) and EN_KILLFOCUS (512). It is + now too late to change the Scintilla codes as clients depend on the current values.

+ +

SCN_MACRORECORD
+ The SCI_STARTRECORD and SCI_STOPRECORD messages enable and + disable macro recording. When enabled, each time a recordable change occurs, the + SCN_MACRORECORD notification is sent to the container. It is up to the container + to record the action. To see the complete list of SCI_* messages that are + recordable, search the Scintilla source Editor.cxx for + Editor::NotifyMacroRecord. The fields of SCNotification set in this + notification are:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldUsage
messageThe SCI_* message that caused the notification.
wParamThe value of wParam in the SCI_* message.
lParamThe value of lParam in the SCI_* message.
+ +

SCN_MARGINCLICK
+ This notification tells the container that the mouse was clicked inside a margin that was marked as sensitive (see SCI_SETMARGINSENSITIVEN). This can be used to + perform folding or to place breakpoints. The following SCNotification fields are + used:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldUsage
modifiersThe appropriate combination of SCI_SHIFT, + SCI_CTRL and SCI_ALT to indicate the keys that were held down + at the time of the margin click.
positionThe position of the start of the line in the document that corresponds + to the margin click.
marginThe margin number that was clicked.
+ +

SCN_NEEDSHOWN
+ Scintilla has determined that a range of lines that is currently invisible should be made + visible. An example of where this may be needed is if the end of line of a contracted fold + point is deleted. This message is sent to the container in case it wants to make the line + visible in some unusual way such as making the whole document visible. Most containers will + just ensure each line in the range is visible by calling SCI_ENSUREVISIBLE. The position and + length fields of SCNotification indicate the range of the document + that should be made visible. The container code will be similar to the following code + skeleton:

+
+firstLine = SCI_LINEFROMPOSITION(scn.position)
+lastLine = SCI_LINEFROMPOSITION(scn.position+scn.length-1)
+for line = lineStart to lineEnd do SCI_ENSUREVISIBLE(line) next
+
+ +

SCN_PAINTED
+ Painting has just been done. Useful when you want to update some other widgets based on a + change in Scintilla, but want to have the paint occur first to appear more responsive. There is + no other information in SCNotification.

+ +

SCN_USERLISTSELECTION
+ The user has selected an item in a user list. The + SCNotification fields used are:

+ + + + + + + + + + + + + + + + + + + + + + + +
FieldUsage
wParamThis is set to the listType parameter from the SCI_USERLISTSHOW message that + initiated the list.
textThe text of the selection.
+
+
+ + +

SCN_URIDROPPED
+ Only on the GTK+ version. Indicates that the user has dragged a URI such as a file name or Web + address onto Scintilla. The container could interpret this as a request to open the file. The + text field of SCNotification points at the URI text.

+ +

SCN_DWELLSTART
+ SCN_DWELLEND
+ SCN_DWELLSTART is generated when the user keeps the mouse in one position for the + dwell period (see SCI_SETMOUSEDWELLTIME). SCN_DWELLEND is + generated after a SCN_DWELLSTART and the mouse is moved or other activity such as + key press indicates the dwell is over. Both notifications set the same fields in + SCNotification:

+ + + + + + + + + + + + + + + + + + + + + + + +
FieldUsage
positionThis is the nearest position in the document to the position where the + mouse pointer was lingering.
x, yWhere the pointer lingered. The position field is set to + SCI_POSITIONFROMPOINTCLOSE(x, y).
+
+
+ +

SCI_SETMOUSEDWELLTIME
+ SCI_GETMOUSEDWELLTIME
+ These two messages set and get the time the mouse must sit still, in milliseconds, to generate + a SCN_DWELLSTART notification. If + set to SC_TIME_FOREVER, the default, no dwell events are generated.

+ +

SCN_ZOOM
+ This notification is generated when the user zooms the display using the keyboard or the + SCI_SETZOOM method is called. This + notification can be used to recalculate positions, such as the width of the line number margin + to maintain sizes in terms of characters rather than pixels. SCNotification has no + additional information.

+ +

+ SCN_HOTSPOTCLICK
+ SCN_HOTSPOTDOUBLECLICK
+ These notifications are generated when the user clicks or double clicks on + text that is in a style with the hotspot attribute set. + This notification can be used to link to variable definitions or web pages. + The position field is set the text position of the click or + double click and the modifiers field set to the key modifiers + held down in a similar manner to SCN_KEY.

+ +

+ SCN_INDICATORCLICK
+ SCN_INDICATORRELEASE
+ These notifications are generated when the user clicks or releases the mouse on + text that has an indicator. + The position field is set the text position of the click or + double click and the modifiers field set to the key modifiers + held down in a similar manner to SCN_KEY.

+ +

SCN_CALLTIPCLICK
+ This notification is generated when the user clicks on a calltip. + This notification can be used to display the next function prototype when a + function name is overloaded with different arguments. + The position field is set to 1 if the click is in an up arrow, + 2 if in a down arrow, and 0 if elsewhere.

+ +

SCN_AUTOCSELECTION
+ The user has selected an item in an autocompletion list. The + notification is sent before the selection is inserted. Automatic insertion can be cancelled by sending a + SCI_AUTOCCANCEL message + before returning from the notification. The SCNotification fields used are:

+ + + + + + + + + + + + + + + + + + + + + + +
FieldUsage
lParamThe start position of the word being completed.
textThe text of the selection.
+ +

GTK+

+

On GTK+, the following functions create a Scintilla widget, communicate with it and allow + resources to be released after all Scintilla widgets hace been destroyed.

+ GtkWidget *scintilla_new()
+ void scintilla_set_id(ScintillaObject *sci, uptr_t id)
+ sptr_t scintilla_send_message(ScintillaObject *sci,unsigned int iMessage, uptr_t wParam, sptr_t lParam)
+ void scintilla_release_resources()
+
+ +

GtkWidget *scintilla_new()
+ Create a new Scintilla widget. The returned pointer can be added to a container and displayed in the same way as other + widgets.

+ +

void scintilla_set_id(ScintillaObject *sci, uptr_t id)
+ Set the control ID which will be used in the idFrom field of the NotifyHeader structure of all + notifications for this instance. When an application creates multiple Scintilla widgets, this allows + the source of each notification to be found. The value should be small, preferrably less than 16 bits, + rather than a pointer as some of the functions will only transmit 16 or 32 bits.

+ +

sptr_t scintilla_send_message(ScintillaObject *sci,unsigned int iMessage, uptr_t wParam, sptr_t lParam)
+ The main entry point allows sending any of the messages described in this document.

+ +

void scintilla_release_resources()
+ Call this to free any remaining resources after all the Scintilla widgets have been destroyed.

+ +

Deprecated messages and notifications

+ +

The following messages are currently supported to emulate existing Windows controls, but + they will be removed in future versions of Scintilla. If you use these messages you should + replace them with the Scintilla equivalent.

+
+WM_GETTEXT(int length, char *text)
+WM_SETTEXT(<unused>, const char *text)
+EM_GETLINE(int line, char *text)
+EM_REPLACESEL(<unused>, const char *text)
+EM_SETREADONLY
+EM_GETTEXTRANGE(<unused>, TEXTRANGE *tr)
+WM_CUT
+WM_COPY
+WM_PASTE
+WM_CLEAR
+WM_UNDO
+EM_CANUNDO
+EM_EMPTYUNDOBUFFER
+WM_GETTEXTLENGTH
+EM_GETFIRSTVISIBLELINE
+EM_GETLINECOUNT
+EM_GETMODIFY
+EM_SETMODIFY(bool isModified)
+EM_GETRECT(RECT *rect)
+EM_GETSEL(int *start, int *end)
+EM_EXGETSEL(<unused>, CHARRANGE *cr)
+EM_SETSEL(int start, int end)
+EM_EXSETSEL(<unused>, CHARRANGE *cr)
+EM_GETSELTEXT(<unused>, char *text)
+EM_LINEFROMCHAR(int position)
+EM_EXLINEFROMCHAR(int position)
+EM_LINEINDEX(int line)
+EM_LINELENGTH(int position)
+EM_SCROLL(int line)
+EM_LINESCROLL(int column, int line)
+EM_SCROLLCARET()
+EM_CANPASTE
+EM_CHARFROMPOS(<unused>, POINT *location)
+EM_POSFROMCHAR(int position, POINT *location)
+EM_SELECTIONTYPE
+EM_HIDESELECTION(bool hide)
+EM_FINDTEXT(int flags, FINDTEXTEX *ft)
+EM_FINDTEXTEX(int flags, FINDTEXTEX *ft)
+EM_GETMARGINS
+EM_SETMARGINS(EC_LEFTMARGIN or EC_RIGHTMARGIN or EC_USEFONTINFO, int val)
+EM_FORMATRANGE
+
+ +

The following are features that are only included if you define + INCLUDE_DEPRECATED_FEATURES in Scintilla.h. To ensure future + compatibility you should change them as indicated.

+ +

SCN_POSCHANGED() Deprecated
+ Fired when the user moves the cursor to a different position in the text. Use SCN_UPDATEUI instead.

+ +

SCN_CHECKBRACE Deprecated
+ Either the text or styling of the document has changed or the selection range has changed. + This is replaced by SCN_UPDATEUI. You + can also use SCN_MODIFIED for more + detailed information on text and styling changes,

+ +

Edit messages never supported by Scintilla

+
+EM_GETWORDBREAKPROC EM_GETWORDBREAKPROCEX
+EM_SETWORDBREAKPROC EM_SETWORDBREAKPROCEX
+EM_GETWORDWRAPMODE EM_SETWORDWRAPMODE
+EM_LIMITTEXT EM_EXLIMITTEXT
+EM_SETRECT EM_SETRECTNP
+EM_FMTLINES
+EM_GETHANDLE EM_SETHANDLE
+EM_GETPASSWORDCHAR EM_SETPASSWORDCHAR
+EM_SETTABSTOPS
+EM_FINDWORDBREAK
+EM_GETCHARFORMAT EM_SETCHARFORMAT
+EM_GETOLEINTERFACE EM_SETOLEINTERFACE
+EM_SETOLECALLBACK
+EM_GETPARAFORMAT EM_SETPARAFORMAT
+EM_PASTESPECIAL
+EM_REQUESTRESIZE
+EM_GETBKGNDCOLOR EM_SETBKGNDCOLOR
+EM_STREAMIN EM_STREAMOUT
+EM_GETIMECOLOR EM_SETIMECOLOR
+EM_GETIMEOPTIONS EM_SETIMEOPTIONS
+EM_GETOPTIONS EM_SETOPTIONS
+EM_GETPUNCTUATION EM_SETPUNCTUATION
+EM_GETTHUMB
+EM_GETEVENTMASK
+EM_SETEVENTMASK
+EM_DISPLAYBAND
+EM_SETTARGETDEVICE
+
+ +

Scintilla tries to be a superset of the standard windows Edit and RichEdit controls wherever + that makes sense. As it is not intended for use in a word processor, some edit messages can not + be sensibly handled. Unsupported messages have no effect.

+ +

Building Scintilla

+ +

To build Scintilla or SciTE, see the README file present in both the Scintilla and SciTE + directories. For Windows, GCC 3.2, Borland C++ or Microsoft Visual Studio .NET can be used + for building. There is a make file for building Scintilla but not SciTE with Visual C++ 6 at + scintilla/win32/scintilla_vc6.mak. For GTK+, GCC 3.1 should be used. GTK+ 1.2x and 2.0x are + supported. The version of GTK+ installed should be detected automatically. + When both GTK+ 1 and GTK+ 2 are present, building for GTK+ 1.x requires defining GTK1 + on the command line.

+ +

Static linking

+ +

On Windows, Scintilla is normally used as a dynamic library as a .DLL file. If you want to + link Scintilla directly into your application .EXE or .DLL file, then the + STATIC_BUILD preprocessor symbol should be defined and + Scintilla_RegisterClasses called. STATIC_BUILD prevents compiling the + DllMain function which will conflict with any DllMain defined in your + code. Scintilla_RegisterClasses takes the HINSTANCE of your + application and ensures that the "Scintilla" window class is registered. To make sure that the + right pointing arrow cursor used in the margin is displayed by Scintilla add the + scintilla/win32/Margin.cur file to your application's resources with the ID + IDC_MARGIN which is defined in scintilla/win32/platfromRes.h as + 400.

+ +

Ensuring lexers are linked into Scintilla

+ +

Depending on the compiler and linker used, the lexers may be stripped out. This is most + often caused when building a static library. To ensure the lexers are linked in, the + Scintilla_LinkLexers() function may be called.

+ +

Changing set of lexers

+ +

To change the set of lexers in Scintilla, add and remove lexer source files + (Lex*.cxx) from the scintilla/src directory and run the + src/LexGen.py script from the src directory to update the make files + and KeyWords.cxx. LexGen.py requires Python 2.1 or later. If you do + not have access to Python, you can hand edit KeyWords.cxx in a simple-minded way, + following the patterns of other lexers. The important thing is to include + LINK_LEXER(lmMyLexer); to correspond with the LexerModule + lmMyLexer(...); in your lexer source code.

+ + + + diff --git a/scintilla/doc/ScintillaDownload.html b/scintilla/doc/ScintillaDownload.html new file mode 100644 index 00000000..74d3dd9f --- /dev/null +++ b/scintilla/doc/ScintillaDownload.html @@ -0,0 +1,70 @@ + + + + + + + + + Download Scintilla + + + + + + + + +
+ Scintilla icon + + Download + Scintilla +
+ + + + +
+ + Windows   + + GTK+/Linux   + +
+

+ Download. +

+

+ The license for using Scintilla or SciTE is similar to that of Python + containing very few restrictions. +

+

+ Release 1.75 +

+

+ Source Code +

+ The source code package contains all of the source code for Scintilla but no binary + executable code and is available in + + Instructions for building on both Windows and Linux are included in the readme file. +

+ Windows Executable Code +

+ There is no download available containing only the Scintilla DLL. + However, it is included in the SciTE + executable full download as SciLexer.DLL. +

+ SciTE is a good demonstration of Scintilla. +

+

+ Previous versions can be downloaded from the history + page. +

+ + diff --git a/scintilla/doc/ScintillaHistory.html b/scintilla/doc/ScintillaHistory.html new file mode 100644 index 00000000..148ef4be --- /dev/null +++ b/scintilla/doc/ScintillaHistory.html @@ -0,0 +1,5834 @@ + + + + + + + + + Scintilla and SciTE + + + + + + + + + +
+ Scintilla icon + + Scintilla + and SciTE +
+

+ History of Scintilla and SciTE +

+

+ Contributors +

+

+ Thanks to all the people that have contributed patches, bug reports and suggestions. +

+

+ Source code and documentation have been contributed by +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Atsuo IshimotoMark HammondFrancois Le CoguiecDale Nagata
Ralf ReinhardtPhilippe LhosteAndrew McKinlayStephan R. A. Deibel
Hans EckardtVassili BourdoMaksim LinRobin Dunn
John EhresmanSteffen GoeldnerDeepak S.Yann Gaillard
Aubin PaulJason DiamondAhmad BaitalmalPaul Winwood
Maxim BaranovRagnar HøjlandChristian ObrechtAndreas Neukoetter
Adam GatesSteve LhommeFerdinand PrantlJan Dries
Markus GritschTahir KaracaAhmad ZawawiLaurent le Tynevez
Walter BraeuAshley CambrellGarrett SerackHolger Schmidt
ActiveStateJames LarcombeAlexey YutkinJan Hercek
Richard PeclEdward K. ReamValery KondakoffSmári McCarthy
Clemens WyssSimon SteeleSerge A. BaranovXavier Nodet
Willy DevauxDavid ClainBrendon YensonVamsi Potluru
Praveen AmbekarAlan KnowlesKengo JinnoValentin Valchev
Marcos E. WurziusMartin AldersonRobert GustavssonJosé Fonseca
Holger KiemesFrancis IrvingScott KirkwoodBrian Quinlan
UbiMichael R. DuerigDeepak TDon Paul Beletsky
Gerhard KalabOlivier DagenaisJosh WingstromBruce Dodson
Sergey KoshcheyevChuan-jian ShenShane CaraveoAlexander Scripnik
Ryan ChristiansonMartin SteffensenJakub VránaThe Black Horus
Bernd KreussThomas LauerMike LansdaalYukihiro Nakai
Jochen TuchtGreg SmithSteve SchoettlerMauritius Thinnes
Darren SchroederPedro GuerreiroDan PetittBiswapesh Chattopadhyay
Kein-Hong ManPatrizio BekerleNigel HathawayHrishikesh Desai
Sergey PuljajevMathias RauenAngelo MandatoDenis Sureau
Kaspar SchiessChristoph HöslerJoão Paulo F FariasRon Schofield
Stefan WosnikMarius GheorgheNaba KumarSean O'Dell
Stefanos TogoulidisHans HagenJim CapeRoland Walter
Brian MosherNicholas NemtsevRoy WoodPeter-Henry Mander
Robert BoucherChristoph DalitzApril WhiteS. Umar
Trent MickFilip YaghobAvi YegudinVivi Orunitia
Manfred BeckerDimitris KeletsekisYuigaDavide Scola
Jason BoggsReinhold NiesnerJos van der ZandePescuma
Pavol BosikJohannes SchmidBlair McGlashanMikael Hultgren
Florian BalmerHadar RazHerr PfarrerBen Key
Gene BarryNiki SpahievCarsten SperberPhil Reid
Iago RubioRégis VaquetteMassimo CoràElias Pschernig
Chris JonesJosiah ReynoldsRobert Roessler rftp.comSteve Donovan
Jan Martin PettersenSergey PhilippovBorujoaMichael Owens
Franck MarciaMassimo Maria GhisalbertiFrank WunderlichJosepmaria Roca
Tobias EngvallSuzumizaki KimitakaMichael CartmellPascal Hurni
AndreRandy ButlerGeorg RitterMichael Goffioul
Ben HarperAdam StrzeleckiKamen StanevSteve Menard
Oliver YeohEric PromislowJoseph GalbraithJeffrey Ren
Armel AsselinJim PatteeFriedrich VedderSebastian Pipping
Andre ArpinStanislav MaslovskiMartin StoneFabien Proriol
mimirNicola CivranSnowMitchell Foral
Pieter HoltzhausenWaldemar AugustynJason HaslamSebastian Steinlechner
Chris RickardRob McMullenStefan SchwendelerCristian Adam
Nicolas ChachereauIstvan SzollosiXie RenhuiEnrico Tröger
Todd WhitemanYuval PapishinstantonSergio Lucato
VladVRODmitry MaslovchupakabraJuan Carlos Arevalo Baeza
Nick TreleavenStephen StaggJean-Paul IribarrenTim Gerundt
Sam HarwellBoris
+

+ Images used in GTK+ version +

+ +

+ Release 1.75 +

+ +

+ Release 1.74 +

+ +

+ Release 1.73 +

+ +

+ Release 1.72 +

+ +

+ Release 1.71 +

+ +

+ Release 1.70 +

+ +

+ Release 1.69 +

+ +

+ Release 1.68 +

+ +

+ Release 1.67 +

+ +

+ Release 1.66 +

+ +

+ Release 1.65 +

+ +

+ Release 1.64 +

+ +

+ Release 1.63 +

+ +

+ Release 1.62 +

+ +

+ Release 1.61 +

+ +

+ Release 1.60 +

+ +

+ Release 1.59 +

+ +

+ Release 1.58 +

+ +

+ Release 1.57 +

+ +

+ Release 1.56 +

+ +

+ Release 1.55 +

+ +

+ Release 1.54 +

+ +

+ Release 1.53 +

+ +

+ Release 1.52 +

+ +

+ Release 1.51 +

+ +

+ Release 1.50 +

+ +

+ Release 1.49 +

+ +

+ Release 1.48 +

+ +

+ Release 1.47 +

+ +

+ Release 1.46 +

+ +

+ Release 1.45 +

+ +

+ Release 1.44 +

+ +

+ Release 1.43 +

+ +

+ Release 1.42 +

+ +

+ Release 1.41 +

+ +

+ Release 1.40 +

+ +

+ Release 1.39 +

+ +

+ Release 1.38 +

+ +

+ Release 1.37 +

+ +

+ Release 1.36 +

+ +

+ Release 1.35 +

+ +

+ Release 1.34 +

+ +

+ Release 1.33 +

+ +

+ Release 1.32 +

+ +

+ Release 1.31 +

+ +

+ Release 1.30 +

+ +

+ Release 1.28 +

+ +

+ Release 1.27 +

+ +

+ Release 1.26 +

+ +

+ Release 1.25 +

+ +

+ Release 1.24 +

+ +

+ Release 1.23 +

+ +

+ Release 1.22 +

+ +

+ Release 1.21 +

+ +

+ Release 1.2 +

+ +

+ Release 1.15 +

+ +

+ Release 1.14 +

+ +

+ Release 1.13 +

+ +

+ Release 1.12 +

+ +

+ Release 1.11 +

+ +

+ Release 1.1 +

+ +

+ Release 1.02 +

+ +

+ Release 1.01 +

+ +

+ Release 1.0 +

+ +

+ Beta release 0.93 +

+ +

+ Beta release 0.92 +

+ +

+ Beta release 0.91 +

+ +

+ Beta release 0.90 +

+ +

+ Beta release 0.82 +

+ +

+ Beta release 0.81 +

+ +

+ Beta release 0.80 +

+ +

+ Beta releases of SciTE were called Tide +

+ + + + diff --git a/scintilla/doc/ScintillaRelated.html b/scintilla/doc/ScintillaRelated.html new file mode 100644 index 00000000..05cadf0c --- /dev/null +++ b/scintilla/doc/ScintillaRelated.html @@ -0,0 +1,503 @@ + + + + + + + + + Scintilla and SciTE Related Sites + + + + + + + + +
+ Scintilla icon + + Scintilla + and SciTE +
+

+ Related Sites +

+

+ Ports and Bindings of Scintilla +

+

+ Editawy + is an ActiveX Control wrapper that support all Scintilla functions and additional high level functions. +

+

+ Jintilla + is a JNI wrapper that allows Scintilla to be used in Java with + both SWT and AWT. +

+

+ Delphi Scintilla Interface Components + is a FREE collection of components that makes it easy to use the + Scintilla source code editing control from within Delphi and C++ Builder. +

+

+ wxStEdit + is a library and sample program that provides extra features over wxStyledTextControl. +

+

+ CScintillaCtrl, CScintillaView & CScintillaDoc + are freeware MFC classes to encapsulate Scintilla. +

+

+ ScintillaNet + is an encapsulation of Scintilla for use within the .NET framework. +

+

+ QScintilla + is a port of Scintilla to the Qt platform. It has a similar license to Qt: GPL for use in + free software and commercial for use in close-source applications. +

+

+ + GWindows is a Win32 RAD GUI Framework for Ada 95 that + includes a binding of Scintilla. +

+

+ + DolphinScintilla is a DolphinSmalltalk wrapper for Scintilla. +

+

+ ScintillaVB + is an ActiveX control written in VB that encapsulates Scintilla. +

+

+ FXScintilla + is a port of Scintilla to the FOX platform. FXRuby includes Ruby + bindings for FXScintilla. +

+

+ Delphi wrapper for + Scintilla which is also usable from Borland C++ Builder. +

+

+ The wxStyledTextCtrl editor component in the + wxWindows cross platform toolkit is based on Scintilla.
+ A Python binding for wxStyledTextCtrl is part of wxPython. +

+

+ gtkscintilla + is an alternative GTK class implementation for scintilla. + This implementation acts more like a Gtk+ object, with many methods rather + than just scintilla_send_message() and is available as a shared library. + This implementation works with GTK 1.x. +

+

+ gtkscintilla2 + is an alternative GTK class implementation for scintilla + similar to the above, but for GTK 2.x. +

+

+ pyscintilla + is the original Python binding for Scintilla's default GTK + 1.x class. Includes some additional support, such as native printing on + Windows. The binding is hand-written rather than auto-generated from the + Scintilla.iface file. +

+

+ pygtkscintilla + is a Python binding for gtk1.x scintilla that uses + gtkscintilla instead of the default GTK class. +

+

+ pyscintilla2 + is a Python binding for GTK 2.x scintilla that uses + gtkscintilla2. +

+

+ ScintillaCtrl + is an unmaintained ActiveX control wrapper for Scintilla. +

+

+ Projects using Scintilla +

+

+ UniversalIndentGUI + is a cross platform GUI for several code formatters, beautifiers and indenters + like GreatCode, AStyle (Artistic Styler), GNU Indent, BCPP and so on. +

+

+ TrackBack + watches and backs up every change made in your source code. +

+

+ ReportBuilder Primary + is designed to reduce the time to compose detailed and professional primary school reports. +

+

+ Visual Classworks + Visual class modeling and coding in C++ via 'live' + UML style class diagrams. +

+

+ Javelin + Visual Class modeling and coding in Java via 'live' UML style + class diagrams. +

+

+ The ExtendScript Toolkit + is a development and debugging tool for JavaScript + scripts included with Adobe CS3 Suites. +

+

+ TortoiseSVN + is a Windows GUI client for the Subversion source control software. +

+

+ Geany + is a small and fast GTK2 based IDE, which has only a few dependencies from other packages. +

+

+ ECMerge + is a commercial graphical and batch diff / merge tool for Windows, Linux and Solaris + (aiming to target all major platforms). +

+

+ PyPE + is an editor written in Python with the wxPython GUI toolkit. +

+

+ Sciboo + is an editor based on ScintillaNET. +

+

+ The Scite Config Tool + is a graphical user interface for changing SciTE properties files. +

+

+ Scintilla Lister + is a plugin for Total Commander allowing viewing all documents with syntax highlighting + inside Total Commander. +

+

+ ChSciTE + is a free IDE for C/C++ interpreter Ch. It runs cross platform. + Ch is for cross-platform scripting, shell + programming, 2D/3D plotting, numerical computing, and embedded + scripting. +

+

+ + Code::Blocks is an open source, cross platform free C++ IDE. +

+

+ + Notepad++ is a free source code editor under Windows. +

+

+ + Gubed is a cross platform program to debug PHP scripts. +

+

+ + LSW DotNet-Lab is a development environment for the .NET platform. +

+

+ + GLIntercept is an OpenGL function call interceptor that uses SciTE as a + run-time shader editor. +

+

+ + Xin is an open-source XML editor for Windows. +

+

+ + wyoEditor is "A nice editor with a well designed and consistent look and feel". +

+

+ + Notepad2 is "Yet another Notepad replacement". +

+

+ + PyCrash Viewer can examine crash dumps of Python programs. +

+

+ + MPT series Wire Analyzers use Scintilla and SciTE. +

+

+ MyGeneration + is a .NET based code generator. +

+

+ CSSED + is a tiny GTK2 CSS editor. +

+

+ DIDE + is a free IDE for the D language on Windows. +

+

+ + IdePS + is a free Integrated Development Environment for PostScript +

+

+ + CUTE + is a user-friendly source code editor easily extended using Python. +

+

+ + Venis IX, + the Visual Environment for NSIS (Nullsoft Scriptable Install System). +

+

+ + MinGW Developer Studio + is a simple C/C++ IDE for the MinGW compiler on Windows. +

+

+ Eric3 + is a Python IDE written using PyQt and QScintilla. +

+

+ TemplateTamer + is a tool for development of template based PHP web pages. +

+

+ SciTE|Flash + is a free Scintilla-based ActionScript editor for Windows. +

+

+ CPPIDE + is part of some commercial high-school oriented programming course software. +

+

+ Instant Source + is a commercial tool for looking at the HTML on web sites. +

+

+ RAD.On++ + is a free C++ Rapid Application Developer for Win32. +

+

+ wxBasic is an open source + Basic interpreter that uses the wxWindows toolkit. A small IDE is under construction. +

+

+ FreeRIDE will be a + cross-platform IDE for the Ruby programming language. +

+

+ Visual MinGW is an + IDE for the MinGW compiler system.This runs on Windows with gcc. +

+

+ The Wing IDE is a + complete integrated development environment for the Python programming + language. + Available on Intel based Linux and Windows and on MacOS X through XDarwin. +

+

+ LuaIDE + is an IDE for Lua on Windows. +

+

+ Sphere + is 2D RPG engine with a development environment. +

+

+ Practical Ruby + is an IDE for Ruby on Windows. +

+

+ GNUe + is a suite of tools and applications for solving the needs of the enterprise. +

+

+ SilverCity + is a lexing package that can provide lexical analysis for over 20 programming + and markup languages. +

+

+ HAP Python Remote Debugger + is a Python debugger that can run on one Windows machine debugging a Python program running + on either the same or another machine. +

+

+ pyeditor and wxEditor + are scriptable editors implemented in Python. pyeditor is based on GTK+ and + the pyscintilla wrapper. wxEditor is based on wxWindows, wxPython and + wxStyledTextControl. +

+

+ PyCrust is an interactive + Python shell based on wxPython. +

+

+ Black Adder is a + Qt based development environment for Python and Ruby. +

+

+ Komodo + is a cross-platform multi-language development environment built + as an application of Mozilla. +

+

+ titmouse + is a Lua editor/debugger for Windows. It is available as both a component + and an application. +

+

+ Filerx + is a project manager for SciTE on Windows. + Open source and includes an implementation of SciTE's Director interface so + will be of interest to others wanting to control SciTE. +

+

+ Anjuta + is an open source C/C++ IDE for Linux/GNOME. +

+

+ A version of SciTE for Win32 enhanced + with a tab control to allow easy movement between buffers. + Go to the "Goodies" area on this site. +

+

+ + Suneido is an integrated application platform currently available for Win32 that includes an + object-oriented language, client-server database, and user interface and reporting frameworks. +

+

+ + BitLeaf is a new GNOME based development environment. + Currently at an early stage of development. +

+

+ + Agast is an authoring system for adventure games which includes + a customised version of SciTE. +

+

+ Boa Constructor is a RAD GUI + Building IDE for the wxWindows cross platform platform. Written using wxPython with the + wxStyledTextCtrl used as its editor. +

+

+ PythonWin, a Win32 IDE for Python, uses + Scintilla for both its editing and interactive windows. +

+

+ Editing Components +

+

+ GtkSourceView + is a text widget that extends the standard GTK+ 2.x text widget and improves it + by implementing syntax highlighting and other features typical of a source editor. +

+

+ AEditor + is a free source code editing component implemented in Ruby. +

+

+ SyntaxEditor + is a commercial native .Net source code editing component. +

+

+ jEdit is a good Open Source syntax colouring + editor written in and for Java. +

+

+ GTK+, the GIMP Toolkit, contains a rich text editing + widget.
+ Gedit is an editor for GTK+/GNOME.
+ +

+

+ CodeGuru has source code for several Win32 MFC based + editors. +

+ SynEdit is a Win32 edit control written + in Delphi. +

+ SourceView is a commercial editing + component for Win32. +

+

+ CodeMax is another commercial component for Win32. +

+

+ Documents +

+

+ The Craft of Text Editing + describes how EMACS works, Craig A. Finseth +

+

+ Data Structures in a Bit-Mapped Text + Editor, Wilfred J. Hanson, Byte January 1987 +

+

+ Text Editors: Algorithms and Architectures, Ray Valdés, Dr. Dobbs Journal + April 1993 +

+

+ Macintosh User Interface Guidelines and TextEdit chapters of Inside Macintosh +

+

+ Development Tools +

+

+ Scintilla and SciTE were developed using the + Mingw version of GCC. +

+

+ AStyle is a source code formatter for C++ and + Java code. SciTE has an Indent command defined for .cxx files that uses AStyle. +

+

+ WinMerge is an interactive diff / merge + for Windows. I prefer code submissions in the form of source files rather than diffs and then run + WinMerge over the files to work out how to merge. +

+

+ Python is my favourite programming language. Scintilla + was started after I tried to improve the editor built into PythonWin, but was frustrated by the limitations of + the Windows Richedit control which PythonWin used. +

+

+ regex is a public domain + implementation of regular expression pattern matching used in Scintilla. +

+ +

+ + Inspirational coding soundscapes by David Bridie. +

+

+ Get away from hacking without any of that tedious standing up bother: Virtually There ;). +

+ + + + diff --git a/scintilla/doc/ScintillaToDo.html b/scintilla/doc/ScintillaToDo.html new file mode 100644 index 00000000..a8098006 --- /dev/null +++ b/scintilla/doc/ScintillaToDo.html @@ -0,0 +1,178 @@ + + + + + + + + + Scintilla and SciTE To Do + + + + + + + + +
+ Scintilla icon + + Scintilla + and SciTE +
+

+ Bugs and To Do List +

+

+ Feedback +

+

+ Issues can be reported on the Bug Tracker + and features requested on the Feature Request Tracker. +

+

+ Scintilla Bugs +

+

+ At the end of italics style runs characters can be chopped off. An example + is using Verdana 12 point italics for strings makes an ending double quote + half visible and an ending single quote invisible. This is hard to solve + completely, may be better to avoid these situations by, for example, + choosing a font like Times New Roman for strings. There is a specific kluge + for the end of line which adds some room for italics but this does not + work elsewhere. +

+

+ Dragging over bold text in some fonts will ripple because of the difference in + size between drawing all of a string at once and drawing it in parts. +

+

+ Automatic scrolling when text dragged near edge of window. +

+

+ GTK+ Version Bugs +

+

+ Scintilla To Do +

+

+ Folding for languages that don't have it yet and good folding for languages + that inherited poor folding from another languages folding code. +

+

+ Simple pattern based styling. +

+

+ Different height lines based upon tallest text on the line rather than on the tallest style + possible. +

+

+ Composition of lexing for mixed languages (such as ASP+ over COBOL) by + combining lexers. +

+

+ Printing support on GTK+. Maybe Postscript output or use Gnome? +

+

+ Stream folding which could be used to fold up the contents of HTML elements. +

+

+ Persisting view state such as current folding into a stream or blob so it is easy + to restore. +

+

+ Move line up and move line down keys or move selected lines up / down. +

+

+ Printing of highlight lines and folding margin. +

+

+ Flow diagrams inside editor similar to + + GRASP. +

+

+ A VCL component wrapper around Scintilla so it can be used with Delphi or + Borland C++ Builder. + There is some work + on this available. +

+

+ Port to MacOS X. +

+

+ More lexers for other languages. +

+

+ Automatically calculated range for horizontal scrolling. +

+

+ Virtual space at the end of lines so the caret can be moved beyond the end + of lines with the cursor keys. May also make rectangular operations easier + to perform. +

+

+ SciTE To Do +

+

+ Good regular expression support through a plugin. +

+

+ Allow tools to transform the selection, performing an operation like + indentation or sorting. +

+

+ Allow file name based selection on all properties rather than just a chosen few. +

+

+ Opening from and saving to FTP servers. +

+

+ Setting to fold away comments upon opening. +

+

+ User defined fold ranges. +

+

+ Silent mode that does not display any message boxes. +

+

+ Features I am unlikely to do +

+

+ These are features I don't like or don't think are important enough to work on. + Implementations are welcome from others though. +

+

+ Automatically saving modified menu shortcuts on exit. +

+

+ Mouse wheel panning (press the mouse wheel and then move the mouse) on + Windows. +

+

+ Adding options to the save dialog to save in a particular encoding or with a + chosen line ending. +

+

+ Directions +

+

+ The main point of this development is Scintilla, and this is where most effort will + go. SciTE will get new features, but only when they make my life easier - I am + not intending to make it grow up to be a huge full-function IDE like Visual + Cafe. The lines I've currently decided not to step over in SciTE are any sort of + project facility and any configuration dialogs. SciTE for Windows now has a + Director interface for communicating with a separate project manager + application. +

+

+ If you are interested in contributing code, do not feel any need to make it cross + platform. + Just code it for your platform and I'll either reimplement for the other platform or + ensure that there is no effect on the other platform. +

+ + diff --git a/scintilla/doc/ScintillaUsage.html b/scintilla/doc/ScintillaUsage.html new file mode 100644 index 00000000..c19cbc55 --- /dev/null +++ b/scintilla/doc/ScintillaUsage.html @@ -0,0 +1,375 @@ + + + + + + + + + Scintilla Usage Notes + + + + + + + + + +
+ Scintilla icon + + Scintilla + Usage Notes +
+

+ Implementing Auto-Indent +

+

+ The key idea is to use the SCN_CHARADDED notification to add indentation after a newline. +

+

+ The lParam on the notification is a pointer to a SCNotification structure whose ch member + specifies the character added. If a newline was added, the previous line can be retrieved and + the same indentation can be added to the new line. +

+

+ Here is the relevant portion of code from SciTE: (SciTE.cxx SciTEWindow::CharAdded) +

+ if  (ch  ==  '\r'  ||  ch  ==  '\n')  {
+     
char  + linebuf[1000];
+     
int  + curLine  =  GetCurrentLineNumber();
+     
int  + lineLength  + =  SendEditor(SCI_LINELENGTH,  curLine);
+     
+ //Platform::DebugPrintf("[CR] %d len = %d\n", curLine, lineLength);
+     
if  (curLine  >  0  &&  + lineLength  + <=  2)  {
+     
int  + prevLineLength  + =  SendEditor(SCI_LINELENGTH,  curLine  -  1);
+     
if  (prevLineLength  <  sizeof(linebuf))  {
+         
WORD  buflen  =  sizeof(linebuf);
+         
memcpy(linebuf,  &buflen,  sizeof(buflen));
+         
+ SendEditor(EM_GETLINE,  curLine  -  1,
+                    
+ reinterpret_cast<LPARAM>(static_cast<char  *>(linebuf)));
+         
linebuf[prevLineLength]  =  '\0';
+         
for  (int  pos  =  0;  linebuf[pos];  pos++)  {
+             
if  (linebuf[pos]  !=  ' '  &&  + linebuf[pos]  !=  '\t')
+                 
+ linebuf[pos]  =  '\0';
+         
}
+         
+ SendEditor(EM_REPLACESEL,  0,  + reinterpret_cast<LPARAM>(static_cast<char  *>(linebuf)));
+     
}
+
}
+ +

+ Of course, fancier handling could be implemented. For example, if the previous line was the + start of a control construct, the next line could be automatically indented one tab further. + (Assuming that is your indenting style.) +

+

+ Implementing Syntax Styling +

+

+ Syntax styling is handled by the SCN_STYLENEEDED notification. Scintilla keeps track of the + end of the styled text - this is retrieved with SCI_GETENDSTYLED. In response to the + SCN_STYLENEEDED notification, you should apply styles to the text from ENDSTYLED to the + position specified by the notification. +

+

+ Here is the relevant portion of code from SciTE: (SciTE.cxx) +

+ void  + SciTEWindow::Notify(SCNotification  *notification)  {
+     
switch  + (notification->nmhdr.code)  {
+     
case  + SCN_STYLENEEDED:  {
+             
if  (notification->nmhdr.idFrom  ==  IDM_SRCWIN)  {
+                 
+ int  + endStyled  =  SendEditor(SCI_GETENDSTYLED);
+                 
+ int  + lineEndStyled  =  SendEditor(EM_LINEFROMCHAR,  + endStyled);
+                 
+ endStyled  + =  SendEditor(EM_LINEINDEX,  lineEndStyled);
+                 
+ Colourise(endStyled,  notification->position);
+ +

+ Colourize(start, end) retrieves the specified range of text and then calls ColourizeDoc in + keywords.cxx. It starts the process by calling: +

+     SendMessage(hwnd,  SCI_STARTSTYLING,  + startPos,  31);
+ +

+ and then for each token of the text, calling: +

+     SendMessage(hwnd,  SCI_SETSTYLING,  length,  style);
+ +

+ where style is a number from 0 to 31 whose appearance has been defined using the + SCI_STYLESET... messages. +

+

+ Implementing Calltips +

+

+ Again, the SCN_CHARADDED notification is used to catch when an opening parenthesis is added. + The preceding word can then be retrieved from the current line: +

+     char  linebuf[1000];
+
    int  current  =  SendEditor(SCI_GETCURLINE,  sizeof(linebuf),
+         
+ reinterpret_cast<LPARAM>(static_cast<char  *>(linebuf)));
+
    int  pos  =  SendEditor(SCI_GETCURRENTPOS);
+
+
    int  startword  =  current  -  1;
+
    while  + (startword  + >  0  &&  + isalpha(linebuf[startword  -  1]))
+         
+ startword--;
+
    linebuf[current  -  1]  =  '\0';
+
    char*  word  =  linebuf  +  startword;
+ +

+ Then if a calltip is available it can be displayed. The calltip appears immediately below + the position specified. The calltip can be multiple lines separated by newlines (\n). +

+     pos  =  SendMessage(hwnd,  SCI_GETCURRENTPOS,  0,  0);
+
    SendMessageText(hwnd,  SCI_CALLTIPSHOW,  pos  -  wordLen  -  1,  calltip);
+ +

+ The calltip can be removed when a closing parenthesis is entered: +

+     if  (SendMessage(hwnd,  SCI_CALLTIPACTIVE,  + 0,  0))
+         
+ SendMessage(hwnd,  + SCI_CALLTIPCANCEL,  0,  + 0);
+ +

+ Obviously, it is up the application to look after supplying the appropriate calltip text. +

+

+ SciTE goes one step further, counting the commas between arguments and highlighting the + corresponding part of the calltip. This code is in ContinueCallTip. +

+

+ Page contributed by Andrew McKinlay. +

+ + + diff --git a/scintilla/doc/Steps.html b/scintilla/doc/Steps.html new file mode 100644 index 00000000..765268da --- /dev/null +++ b/scintilla/doc/Steps.html @@ -0,0 +1,142 @@ + +How to use the Scintilla Edit Control in windows? +

How to use the Scintilla Edit Control in windows?

+

+ This should be a little step by step explanation how to use Scintilla in the windows environment. +

+

+

How to create Scintilla Edit Control?

+

+ First of all, load the Scintilla DLL with something like: +

+
+
+	hmod = LoadLibrary("SciLexer.DLL");
+		if (hmod==NULL)
+		{
+			MessageBox(hwndParent,
+			"The Scintilla DLL could not be loaded.",
+			"Error loading Scintilla",
+			MB_OK | MB_ICONERROR);
+		}
+		
+

+ If the DLL was loaded successfully, then the DLL has registered (yes, by itself) a new + window class. The new class called "Scintilla" is the new scintilla edit control. +

+

+ Now you can use this new control just like any other windows control. +

+
+
+	hwndScintilla = CreateWindowEx(0,
+		"Scintilla","", WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_CLIPCHILDREN,
+		10,10,500,400,hwndParent,(HMENU)GuiID, hInstance,NULL);
+		
+

+ Note the new window class name: "Scintilla". By reaching this point you actually included + a Scintilla Edit Control to your windows program. +

+

+

How to control the Scintilla Edit Control?

+

+ You can control Scintilla by sending commands to the Edit Control. + There a 2 ways of doing this. A simple and fast way. +

+

The simple way to control Scintilla

+

+ The simple way is just like with any other windows control. You can send messages to the + Scintilla Edit Control and receive notifications from the control. (Note that the notifications + are sent to the parent window of the Scintilla Edit Control.) +

+

+ The Scintilla Edit Control knows a special message for each command. + To send commands to the Scintilla Edit Control you can use the SendMessage function. +

+
+
+	SendMessage(hwndScintilla,sci_command,wparam,lparam);
+			
+

+ like: +

+
+
+	SendMessage(hwndScintilla,SCI_CREATEDOCUMENT, 0, 0);
+			
+

+ Some of the commands will return a value and unused parameters should be set to NULL. +

+

+

The fast way to control Scintilla

+

+ The fast way of controlling the Scintilla Edit Control is to call message handling function by yourself. + You can retrieve a pointer to the message handling function of the Scintilla Edit Control and + call it directly to execute a command. This way is much more faster than the SendMessage() way. +

+

+ 1st you have to use the SCI_GETDIRECTFUNCTION and SCI_GETDIRECTPOINTER commands to + retrieve the pointer to the function and a pointer which must be the first parameter when calling the retrieved + function pointer. + You have to do this with the SendMessage way :) +

+

+ The whole thing has to look like this: +

+
+
+	int (*fn)(void*,int,int,int);
+	void * ptr;
+	int canundo;
+
+	fn = (int (__cdecl *)(void *,int,int,int))SendMessage(
+		hwndScintilla,SCI_GETDIRECTFUNCTION,0,0);
+	ptr = (void *)SendMessage(hwndScintilla,SCI_GETDIRECTPOINTER,0,0);
+
+	canundo = fn(ptr,SCI_CANUNDO,0,0);
+			
+

+ with "fn" as the function pointer to the message handling function of the Scintilla Control + and "ptr" as the pointer that must be used as 1st parameter. + The next parameters are the Scintilla Command with its two (optional) parameters. +

+ +

+

How will I receive notifications?

+

+ Whenever an event occurs where Scintilla wants to inform you about something, the Scintilla Edit Control + will send notification to the parent window. This is done by a WM_NOTITY message. + When receiving that message, you have to look in the xxx struct for the actual message. +

+

+ So in Scintillas parent window message handling function you have to include some code like this: +

+
+	NMHDR *lpnmhdr;
+
+	[...]
+
+	case WM_NOTIFY:
+		lpnmhdr = (LPNMHDR) lParam;
+
+		if(lpnmhdr->hwndFrom==hwndScintilla)
+		{
+			switch(lpnmhdr->code)
+			{
+				case SCN_CHARADDED:
+					/* Hey, Scintilla just told me that a new */
+					/* character was added to the Edit Control.*/
+					/* Now i do something cool with that char. */
+				break;
+			}
+		}
+	break;
+			
+

+

+ +

+ Page contributed by Holger Schmidt. +

+ + diff --git a/scintilla/doc/index.html b/scintilla/doc/index.html new file mode 100644 index 00000000..8f08d09f --- /dev/null +++ b/scintilla/doc/index.html @@ -0,0 +1,200 @@ + + + + + + + + + + + + + + Scintilla and SciTE + + + + + + + + + + +
+ Scintilla + + A free source code editing component for Win32 and + GTK+ + + Release version 1.75
+ Site last modified November 22 2007
+
+   +
+ + + + +
+   +
+ + + + + + + + + + + + + + + + + + + +
+ Version 1.75 displays invalid UTF-8 bytes as hexadecimal and + can show indentation guides on completely empty lines. +
+ Version 1.74 runs natively on OS X. + Indicators are separated from the style buffer so there can be more indicators. + Wide lines are faster. +
+ Version 1.73 allows style changes to be made during text modification events. +
+ Version 1.72 is more efficient at handling per-line information. +
+ Version 1.71 has some internationalisation fixes. +
+ Version 1.70 allows, on GTK+, approximate character set conversions + for pasting and uses internationalised input at all times. +
+ + + + +
+ + + Documentation   + Bugs   + + + History   Related   +
+

+ Scintilla is a free source code editing component. + It comes with complete source code and a license that + permits use in any free project or commercial product. +

+

+ As well as features found in standard text editing components, Scintilla includes features + especially useful when editing and debugging source code. + These include support for syntax styling, error indicators, code completion and call tips. + The selection margin can contain markers like those used in debuggers to indicate + breakpoints and the current line. Styling choices are more open than with many editors, + allowing the use of proportional fonts, bold and italics, multiple foreground and background + colours and multiple fonts. +

+

+ The SinkWorld project + investigates possible future directions for Scintilla to make it more flexible, robust, perform + better and run on the .NET and Java virtual machines. +

+

+ SciTE is a SCIntilla based Text Editor. Originally built to + demonstrate Scintilla, it has grown to be a generally useful editor with facilities for + building and running programs. It is best used for jobs with simple configurations - I use it + for building test and demonstration programs as well as SciTE and Scintilla, themselves. +

+

+ Development of Scintilla started as an effort to improve the text editor in PythonWin. After + being frustrated by problems in the Richedit control used by PythonWin, it looked like the + best way forward was to write a new edit control. The biggest problem with Richedit and other + similar controls is that they treat styling changes as important persistent changes to the + document so they are saved into the undo stack and set the document's dirty flag. For source + code, styling should not be persisted as it can be mechanically recreated. +

+

+ Scintilla and SciTE are currently available for Intel Win32 and Linux compatible operating + systems with GTK+. They have been run on Windows 95, NT 4.0, Windows 2000, and on Red Hat + Linux 8 and 9 with GTK+ 1.2 and 2.0. Here is a screenshot of + SciTE.
+

+

+ You can download Scintilla. +

+

+ The source code can be downloaded via CVS at the Source Forge + Scintilla project page. +

+

+ Related sites. +

+

+ Bugs and To Do list. +

+

+ History and contribution credits. +

+

+ Icons that can be used with Scintilla. +

+

+ The scintilla-interest mailing list has moved from lyra.org to Google Groups. + Questions and comments about Scintilla should be directed to the + scintilla-interest + mailing list, + which is for discussion of Scintilla and related projects, their bugs and future features. + This is a low traffic list, averaging less than 50 messages per week. + To avoid spam, only list members can write to the list. + New versions of Scintilla are announced on scintilla-interest and may also be received by SourceForge + members by clicking on the Monitor column icon for "scintilla" on + the downloads page. + Messages sent to my personal email address that could have been sent to the list + may receive no response. +
+

+ + + + + diff --git a/scintilla/gtk/Converter.h b/scintilla/gtk/Converter.h new file mode 100644 index 00000000..aeb5e159 --- /dev/null +++ b/scintilla/gtk/Converter.h @@ -0,0 +1,87 @@ +// Scintilla source code edit control +// Converter.h - Encapsulation of iconv +// Copyright 2004 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#if GTK_MAJOR_VERSION >= 2 + typedef GIConv ConverterHandle; +#else + typedef iconv_t ConverterHandle; +#endif +const ConverterHandle iconvhBad = (ConverterHandle)(-1); +// Since various versions of iconv can not agree on whether the src argument +// is char ** or const char ** provide a templatised adaptor. +template +size_t iconv_adaptor(size_t(*f_iconv)(ConverterHandle, T, size_t *, char **, size_t *), + ConverterHandle cd, char** src, size_t *srcleft, + char **dst, size_t *dstleft) { + return f_iconv(cd, (T)src, srcleft, dst, dstleft); +} +/** + * Encapsulate iconv safely and avoid iconv_adaptor complexity in client code. + */ +class Converter { + ConverterHandle iconvh; + void OpenHandle(const char *fullDestination, const char *charSetSource) { +#if GTK_MAJOR_VERSION >= 2 + iconvh = g_iconv_open(fullDestination, charSetSource); +#else + iconvh = iconv_open(fullDestination, charSetSource); +#endif + } + bool Succeeded() const { + return iconvh != iconvhBad; + } +public: + Converter() { + iconvh = iconvhBad; + } + Converter(const char *charSetDestination, const char *charSetSource, bool transliterations) { + iconvh = iconvhBad; + Open(charSetDestination, charSetSource, transliterations); + } + ~Converter() { + Close(); + } + operator bool() const { + return Succeeded(); + } + void Open(const char *charSetDestination, const char *charSetSource, bool transliterations=true) { + Close(); + if (*charSetSource) { + // Try allowing approximate transliterations + if (transliterations) { + char fullDest[200]; + strcpy(fullDest, charSetDestination); + strcat(fullDest, "//TRANSLIT"); + OpenHandle(fullDest, charSetSource); + } + if (!Succeeded()) { + // Transliterations failed so try basic name + OpenHandle(charSetDestination, charSetSource); + } + } + } + void Close() { + if (Succeeded()) { +#if GTK_MAJOR_VERSION >= 2 + g_iconv_close(iconvh); +#else + iconv_close(iconvh); +#endif + iconvh = iconvhBad; + } + } + size_t Convert(char** src, size_t *srcleft, char **dst, size_t *dstleft) const { + if (!Succeeded()) { + return (size_t)(-1); + } else { +#if GTK_MAJOR_VERSION >= 2 + return iconv_adaptor(g_iconv, iconvh, src, srcleft, dst, dstleft); +#else + return iconv_adaptor(iconv, iconvh, src, srcleft, dst, dstleft); +#endif + } + } +}; diff --git a/scintilla/gtk/PlatGTK.cxx b/scintilla/gtk/PlatGTK.cxx new file mode 100644 index 00000000..d459a337 --- /dev/null +++ b/scintilla/gtk/PlatGTK.cxx @@ -0,0 +1,2755 @@ +// Scintilla source code edit control +// PlatGTK.cxx - implementation of platform facilities on GTK+/Linux +// Copyright 1998-2004 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "Scintilla.h" +#include "ScintillaWidget.h" +#include "UniConversion.h" +#include "XPM.h" + +/* GLIB must be compiled with thread support, otherwise we + will bail on trying to use locks, and that could lead to + problems for someone. `glib-config --libs gthread` needs + to be used to get the glib libraries for linking, otherwise + g_thread_init will fail */ +#define USE_LOCK defined(G_THREADS_ENABLED) && !defined(G_THREADS_IMPL_NONE) +/* Use fast way of getting char data on win32 to work around problems + with gdk_string_extents. */ +#define FAST_WAY + +#if GTK_MAJOR_VERSION >= 2 +#define USE_PANGO 1 +#include "Converter.h" +#endif + +#ifdef _MSC_VER +// Ignore unreferenced local functions in GTK+ headers +#pragma warning(disable: 4505) +#endif + +enum encodingType { singleByte, UTF8, dbcs}; + +struct LOGFONT { + int size; + bool bold; + bool italic; + int characterSet; + char faceName[300]; +}; + +#if USE_LOCK +static GMutex *fontMutex = NULL; + +static void InitializeGLIBThreads() { + if (!g_thread_supported()) { + g_thread_init(NULL); + } +} +#endif + +static void FontMutexAllocate() { +#if USE_LOCK + if (!fontMutex) { + InitializeGLIBThreads(); + fontMutex = g_mutex_new(); + } +#endif +} + +static void FontMutexFree() { +#if USE_LOCK + if (fontMutex) { + g_mutex_free(fontMutex); + fontMutex = NULL; + } +#endif +} + +static void FontMutexLock() { +#if USE_LOCK + g_mutex_lock(fontMutex); +#endif +} + +static void FontMutexUnlock() { +#if USE_LOCK + if (fontMutex) { + g_mutex_unlock(fontMutex); + } +#endif +} + +// On GTK+ 1.x holds a GdkFont* but on GTK+ 2.x can hold a GdkFont* or a +// PangoFontDescription*. +class FontHandle { + int width[128]; + encodingType et; +public: + int ascent; + GdkFont *pfont; +#ifdef USE_PANGO + PangoFontDescription *pfd; + int characterSet; +#endif + FontHandle(GdkFont *pfont_) { + et = singleByte; + ascent = 0; + pfont = pfont_; +#ifdef USE_PANGO + pfd = 0; + characterSet = -1; +#endif + ResetWidths(et); + } +#ifdef USE_PANGO + FontHandle(PangoFontDescription *pfd_, int characterSet_) { + et = singleByte; + ascent = 0; + pfont = 0; + pfd = pfd_; + characterSet = characterSet_; + ResetWidths(et); + } +#endif + ~FontHandle() { + if (pfont) + gdk_font_unref(pfont); + pfont = 0; +#ifdef USE_PANGO + if (pfd) + pango_font_description_free(pfd); + pfd = 0; +#endif + } + void ResetWidths(encodingType et_) { + et = et_; + for (int i=0; i<=127; i++) { + width[i] = 0; + } + } + int CharWidth(unsigned char ch, encodingType et_) { + int w = 0; + FontMutexLock(); + if ((ch <= 127) && (et == et_)) { + w = width[ch]; + } + FontMutexUnlock(); + return w; + } + void SetCharWidth(unsigned char ch, int w, encodingType et_) { + if (ch <= 127) { + FontMutexLock(); + if (et != et_) { + ResetWidths(et_); + } + width[ch] = w; + FontMutexUnlock(); + } + } +}; + +// X has a 16 bit coordinate space, so stop drawing here to avoid wrapping +static const int maxCoordinate = 32000; + +static FontHandle *PFont(Font &f) { + return reinterpret_cast(f.GetID()); +} + +static GtkWidget *PWidget(WindowID id) { + return reinterpret_cast(id); +} + +static GtkWidget *PWidget(Window &w) { + return PWidget(w.GetID()); +} + +Point Point::FromLong(long lpoint) { + return Point( + Platform::LowShortFromLong(lpoint), + Platform::HighShortFromLong(lpoint)); +} + +Palette::Palette() { + used = 0; + allowRealization = false; + allocatedPalette = 0; + allocatedLen = 0; + size = 100; + entries = new ColourPair[size]; +} + +Palette::~Palette() { + Release(); + delete []entries; + entries = 0; +} + +void Palette::Release() { + used = 0; + delete [](reinterpret_cast(allocatedPalette)); + allocatedPalette = 0; + allocatedLen = 0; + delete []entries; + size = 100; + entries = new ColourPair[size]; +} + +// This method either adds a colour to the list of wanted colours (want==true) +// or retrieves the allocated colour back to the ColourPair. +// This is one method to make it easier to keep the code for wanting and retrieving in sync. +void Palette::WantFind(ColourPair &cp, bool want) { + if (want) { + for (int i=0; i < used; i++) { + if (entries[i].desired == cp.desired) + return; + } + + if (used >= size) { + int sizeNew = size * 2; + ColourPair *entriesNew = new ColourPair[sizeNew]; + for (int j=0; j(allocatedPalette), + allocatedLen); + delete [](reinterpret_cast(allocatedPalette)); + allocatedPalette = 0; + allocatedLen = 0; + } + GdkColor *paletteNew = new GdkColor[used]; + allocatedPalette = paletteNew; + gboolean *successPalette = new gboolean[used]; + if (paletteNew) { + allocatedLen = used; + int iPal = 0; + for (iPal = 0; iPal < used; iPal++) { + paletteNew[iPal].red = entries[iPal].desired.GetRed() * (65535 / 255); + paletteNew[iPal].green = entries[iPal].desired.GetGreen() * (65535 / 255); + paletteNew[iPal].blue = entries[iPal].desired.GetBlue() * (65535 / 255); + paletteNew[iPal].pixel = entries[iPal].desired.AsLong(); + } + gdk_colormap_alloc_colors(gtk_widget_get_colormap(PWidget(w)), + paletteNew, allocatedLen, FALSE, TRUE, + successPalette); + for (iPal = 0; iPal < used; iPal++) { + entries[iPal].allocated.Set(paletteNew[iPal].pixel); + } + } + delete []successPalette; +} + +static const char *CharacterSetName(int characterSet) { + switch (characterSet) { + case SC_CHARSET_ANSI: + return "iso8859-*"; + case SC_CHARSET_DEFAULT: + return "iso8859-*"; + case SC_CHARSET_BALTIC: + return "iso8859-13"; + case SC_CHARSET_CHINESEBIG5: + return "*-*"; + case SC_CHARSET_EASTEUROPE: + return "*-2"; + case SC_CHARSET_GB2312: + return "gb2312.1980-*"; + case SC_CHARSET_GREEK: + return "*-7"; + case SC_CHARSET_HANGUL: + return "ksc5601.1987-*"; + case SC_CHARSET_MAC: + return "*-*"; + case SC_CHARSET_OEM: + return "*-*"; + case SC_CHARSET_RUSSIAN: + return "*-r"; + case SC_CHARSET_CYRILLIC: + return "*-cp1251"; + case SC_CHARSET_SHIFTJIS: + return "jisx0208.1983-*"; + case SC_CHARSET_SYMBOL: + return "*-*"; + case SC_CHARSET_TURKISH: + return "*-9"; + case SC_CHARSET_JOHAB: + return "*-*"; + case SC_CHARSET_HEBREW: + return "*-8"; + case SC_CHARSET_ARABIC: + return "*-6"; + case SC_CHARSET_VIETNAMESE: + return "*-*"; + case SC_CHARSET_THAI: + return "iso8859-11"; + case SC_CHARSET_8859_15: + return "iso8859-15"; + default: + return "*-*"; + } +} + +static bool IsDBCSCharacterSet(int characterSet) { + switch (characterSet) { + case SC_CHARSET_GB2312: + case SC_CHARSET_HANGUL: + case SC_CHARSET_SHIFTJIS: + case SC_CHARSET_CHINESEBIG5: + return true; + default: + return false; + } +} + +static void GenerateFontSpecStrings(const char *fontName, int characterSet, + char *foundary, int foundary_len, + char *faceName, int faceName_len, + char *charset, int charset_len) { + // supported font strings include: + // foundary-fontface-isoxxx-x + // fontface-isoxxx-x + // foundary-fontface + // fontface + if (strchr(fontName, '-')) { + char tmp[300]; + char *d1 = NULL, *d2 = NULL, *d3 = NULL; + strncpy(tmp, fontName, sizeof(tmp) - 1); + d1 = strchr(tmp, '-'); + // we know the first dash exists + d2 = strchr(d1 + 1, '-'); + if (d2) + d3 = strchr(d2 + 1, '-'); + if (d3) { + // foundary-fontface-isoxxx-x + *d2 = '\0'; + foundary[0] = '-'; + foundary[1] = '\0'; + strncpy(faceName, tmp, foundary_len - 1); + strncpy(charset, d2 + 1, charset_len - 1); + } else if (d2) { + // fontface-isoxxx-x + *d1 = '\0'; + strcpy(foundary, "-*-"); + strncpy(faceName, tmp, faceName_len - 1); + strncpy(charset, d1 + 1, charset_len - 1); + } else { + // foundary-fontface + foundary[0] = '-'; + foundary[1] = '\0'; + strncpy(faceName, tmp, faceName_len - 1); + strncpy(charset, CharacterSetName(characterSet), charset_len - 1); + } + } else { + strncpy(foundary, "-*-", foundary_len); + strncpy(faceName, fontName, faceName_len - 1); + strncpy(charset, CharacterSetName(characterSet), charset_len - 1); + } +} + +static void SetLogFont(LOGFONT &lf, const char *faceName, int characterSet, int size, bool bold, bool italic) { + memset(&lf, 0, sizeof(lf)); + lf.size = size; + lf.bold = bold; + lf.italic = italic; + lf.characterSet = characterSet; + strncpy(lf.faceName, faceName, sizeof(lf.faceName) - 1); +} + +/** + * Create a hash from the parameters for a font to allow easy checking for identity. + * If one font is the same as another, its hash will be the same, but if the hash is the + * same then they may still be different. + */ +static int HashFont(const char *faceName, int characterSet, int size, bool bold, bool italic) { + return + size ^ + (characterSet << 10) ^ + (bold ? 0x10000000 : 0) ^ + (italic ? 0x20000000 : 0) ^ + faceName[0]; +} + +class FontCached : Font { + FontCached *next; + int usage; + LOGFONT lf; + int hash; + FontCached(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_); + ~FontCached() {} + bool SameAs(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_); + virtual void Release(); + static FontID CreateNewFont(const char *fontName, int characterSet, + int size, bool bold, bool italic); + static FontCached *first; +public: + static FontID FindOrCreate(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_); + static void ReleaseId(FontID id_); +}; + +FontCached *FontCached::first = 0; + +FontCached::FontCached(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_) : +next(0), usage(0), hash(0) { + ::SetLogFont(lf, faceName_, characterSet_, size_, bold_, italic_); + hash = HashFont(faceName_, characterSet_, size_, bold_, italic_); + id = CreateNewFont(faceName_, characterSet_, size_, bold_, italic_); + usage = 1; +} + +bool FontCached::SameAs(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_) { + return + lf.size == size_ && + lf.bold == bold_ && + lf.italic == italic_ && + lf.characterSet == characterSet_ && + 0 == strcmp(lf.faceName, faceName_); +} + +void FontCached::Release() { + if (id) + delete PFont(*this); + id = 0; +} + +FontID FontCached::FindOrCreate(const char *faceName_, int characterSet_, int size_, bool bold_, bool italic_) { + FontID ret = 0; + FontMutexLock(); + int hashFind = HashFont(faceName_, characterSet_, size_, bold_, italic_); + for (FontCached *cur = first; cur; cur = cur->next) { + if ((cur->hash == hashFind) && + cur->SameAs(faceName_, characterSet_, size_, bold_, italic_)) { + cur->usage++; + ret = cur->id; + } + } + if (ret == 0) { + FontCached *fc = new FontCached(faceName_, characterSet_, size_, bold_, italic_); + if (fc) { + fc->next = first; + first = fc; + ret = fc->id; + } + } + FontMutexUnlock(); + return ret; +} + +void FontCached::ReleaseId(FontID id_) { + FontMutexLock(); + FontCached **pcur = &first; + for (FontCached *cur = first; cur; cur = cur->next) { + if (cur->id == id_) { + cur->usage--; + if (cur->usage == 0) { + *pcur = cur->next; + cur->Release(); + cur->next = 0; + delete cur; + } + break; + } + pcur = &cur->next; + } + FontMutexUnlock(); +} + +static GdkFont *LoadFontOrSet(const char *fontspec, int characterSet) { + if (IsDBCSCharacterSet(characterSet)) { + return gdk_fontset_load(fontspec); + } else { + return gdk_font_load(fontspec); + } +} + +FontID FontCached::CreateNewFont(const char *fontName, int characterSet, + int size, bool bold, bool italic) { + char fontset[1024]; + char fontspec[300]; + char foundary[50]; + char faceName[100]; + char charset[50]; + fontset[0] = '\0'; + fontspec[0] = '\0'; + foundary[0] = '\0'; + faceName[0] = '\0'; + charset[0] = '\0'; + +#ifdef USE_PANGO + if (fontName[0] == '!') { + PangoFontDescription *pfd = pango_font_description_new(); + if (pfd) { + pango_font_description_set_family(pfd, fontName+1); + pango_font_description_set_size(pfd, size * PANGO_SCALE); + pango_font_description_set_weight(pfd, bold ? PANGO_WEIGHT_BOLD : PANGO_WEIGHT_NORMAL); + pango_font_description_set_style(pfd, italic ? PANGO_STYLE_ITALIC : PANGO_STYLE_NORMAL); + return new FontHandle(pfd, characterSet); + } + } +#endif + + GdkFont *newid = 0; + // If name of the font begins with a '-', assume, that it is + // a full fontspec. + if (fontName[0] == '-') { + if (strchr(fontName, ',') || IsDBCSCharacterSet(characterSet)) { + newid = gdk_fontset_load(fontName); + } else { + newid = gdk_font_load(fontName); + } + if (!newid) { + // Font not available so substitute a reasonable code font + // iso8859 appears to only allow western characters. + newid = LoadFontOrSet("-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-*", + characterSet); + } + return new FontHandle(newid); + } + + // it's not a full fontspec, build one. + + // This supports creating a FONT_SET + // in a method that allows us to also set size, slant and + // weight for the fontset. The expected input is multiple + // partial fontspecs seperated by comma + // eg. adobe-courier-iso10646-1,*-courier-iso10646-1,*-*-*-* + if (strchr(fontName, ',')) { + // build a fontspec and use gdk_fontset_load + int remaining = sizeof(fontset); + char fontNameCopy[1024]; + strncpy(fontNameCopy, fontName, sizeof(fontNameCopy) - 1); + char *fn = fontNameCopy; + char *fp = strchr(fn, ','); + for (;;) { + const char *spec = "%s%s%s%s-*-*-*-%0d-*-*-*-*-%s"; + if (fontset[0] != '\0') { + // if this is not the first font in the list, + // append a comma seperator + spec = ",%s%s%s%s-*-*-*-%0d-*-*-*-*-%s"; + } + + if (fp) + *fp = '\0'; // nullify the comma + GenerateFontSpecStrings(fn, characterSet, + foundary, sizeof(foundary), + faceName, sizeof(faceName), + charset, sizeof(charset)); + + g_snprintf(fontspec, + sizeof(fontspec) - 1, + spec, + foundary, faceName, + bold ? "-bold" : "-medium", + italic ? "-i" : "-r", + size * 10, + charset); + + // if this is the first font in the list, and + // we are doing italic, add an oblique font + // to the list + if (italic && fontset[0] == '\0') { + strncat(fontset, fontspec, remaining - 1); + remaining -= strlen(fontset); + + g_snprintf(fontspec, + sizeof(fontspec) - 1, + ",%s%s%s-o-*-*-*-%0d-*-*-*-*-%s", + foundary, faceName, + bold ? "-bold" : "-medium", + size * 10, + charset); + } + + strncat(fontset, fontspec, remaining - 1); + remaining -= strlen(fontset); + + if (!fp) + break; + + fn = fp + 1; + fp = strchr(fn, ','); + } + + newid = gdk_fontset_load(fontset); + if (newid) + return new FontHandle(newid); + + // if fontset load failed, fall through, we'll use + // the last font entry and continue to try and + // get something that matches + } + + // single fontspec support + + GenerateFontSpecStrings(fontName, characterSet, + foundary, sizeof(foundary), + faceName, sizeof(faceName), + charset, sizeof(charset)); + + g_snprintf(fontspec, + sizeof(fontspec) - 1, + "%s%s%s%s-*-*-*-%0d-*-*-*-*-%s", + foundary, faceName, + bold ? "-bold" : "-medium", + italic ? "-i" : "-r", + size * 10, + charset); + newid = LoadFontOrSet(fontspec, characterSet); + if (!newid) { + // some fonts have oblique, not italic + g_snprintf(fontspec, + sizeof(fontspec) - 1, + "%s%s%s%s-*-*-*-%0d-*-*-*-*-%s", + foundary, faceName, + bold ? "-bold" : "-medium", + italic ? "-o" : "-r", + size * 10, + charset); + newid = LoadFontOrSet(fontspec, characterSet); + } + if (!newid) { + g_snprintf(fontspec, + sizeof(fontspec) - 1, + "-*-*-*-*-*-*-*-%0d-*-*-*-*-%s", + size * 10, + charset); + newid = gdk_font_load(fontspec); + } + if (!newid) { + // Font not available so substitute a reasonable code font + // iso8859 appears to only allow western characters. + newid = LoadFontOrSet("-*-*-*-*-*-*-*-*-*-*-*-*-iso8859-*", + characterSet); + } + return new FontHandle(newid); +} + +Font::Font() : id(0) {} + +Font::~Font() {} + +void Font::Create(const char *faceName, int characterSet, int size, + bool bold, bool italic, bool) { + Release(); + id = FontCached::FindOrCreate(faceName, characterSet, size, bold, italic); +} + +void Font::Release() { + if (id) + FontCached::ReleaseId(id); + id = 0; +} + +class SurfaceImpl : public Surface { + encodingType et; + GdkDrawable *drawable; + GdkGC *gc; + GdkPixmap *ppixmap; + int x; + int y; + bool inited; + bool createdGC; +#ifdef USE_PANGO + PangoContext *pcontext; + PangoLayout *layout; + Converter conv; + int characterSet; + void SetConverter(int characterSet_); +#endif +public: + SurfaceImpl(); + virtual ~SurfaceImpl(); + + void Init(WindowID wid); + void Init(SurfaceID sid, WindowID wid); + void InitPixMap(int width, int height, Surface *surface_, WindowID wid); + + void Release(); + bool Initialised(); + void PenColour(ColourAllocated fore); + int LogPixelsY(); + int DeviceHeightFont(int points); + void MoveTo(int x_, int y_); + void LineTo(int x_, int y_); + void Polygon(Point *pts, int npts, ColourAllocated fore, ColourAllocated back); + void RectangleDraw(PRectangle rc, ColourAllocated fore, ColourAllocated back); + void FillRectangle(PRectangle rc, ColourAllocated back); + void FillRectangle(PRectangle rc, Surface &surfacePattern); + void RoundedRectangle(PRectangle rc, ColourAllocated fore, ColourAllocated back); + void AlphaRectangle(PRectangle rc, int cornerSize, ColourAllocated fill, int alphaFill, + ColourAllocated outline, int alphaOutline, int flags); + void Ellipse(PRectangle rc, ColourAllocated fore, ColourAllocated back); + void Copy(PRectangle rc, Point from, Surface &surfaceSource); + + void DrawTextBase(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore); + void DrawTextNoClip(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back); + void DrawTextClipped(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back); + void DrawTextTransparent(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore); + void MeasureWidths(Font &font_, const char *s, int len, int *positions); + int WidthText(Font &font_, const char *s, int len); + int WidthChar(Font &font_, char ch); + int Ascent(Font &font_); + int Descent(Font &font_); + int InternalLeading(Font &font_); + int ExternalLeading(Font &font_); + int Height(Font &font_); + int AverageCharWidth(Font &font_); + + int SetPalette(Palette *pal, bool inBackGround); + void SetClip(PRectangle rc); + void FlushCachedState(); + + void SetUnicodeMode(bool unicodeMode_); + void SetDBCSMode(int codePage); +}; + +const char *CharacterSetID(int characterSet) { + switch (characterSet) { + case SC_CHARSET_ANSI: + return ""; + case SC_CHARSET_DEFAULT: + return "ISO-8859-1"; + case SC_CHARSET_BALTIC: + return "ISO-8859-13"; + case SC_CHARSET_CHINESEBIG5: + return "BIG-5"; + case SC_CHARSET_EASTEUROPE: + return "ISO-8859-2"; + case SC_CHARSET_GB2312: + return "GB2312"; + case SC_CHARSET_GREEK: + return "ISO-8859-7"; + case SC_CHARSET_HANGUL: + return ""; + case SC_CHARSET_MAC: + return "MACINTOSH"; + case SC_CHARSET_OEM: + return "ASCII"; + case SC_CHARSET_RUSSIAN: + return "KOI8-R"; + case SC_CHARSET_CYRILLIC: + return "CP1251"; + case SC_CHARSET_SHIFTJIS: + return "SHIFT-JIS"; + case SC_CHARSET_SYMBOL: + return ""; + case SC_CHARSET_TURKISH: + return "ISO-8859-9"; + case SC_CHARSET_JOHAB: + return "JOHAB"; + case SC_CHARSET_HEBREW: + return "ISO-8859-8"; + case SC_CHARSET_ARABIC: + return "ISO-8859-6"; + case SC_CHARSET_VIETNAMESE: + return ""; + case SC_CHARSET_THAI: + return "ISO-8859-11"; + case SC_CHARSET_8859_15: + return "ISO-8859-15"; + default: + return ""; + } +} + +#ifdef USE_PANGO + +void SurfaceImpl::SetConverter(int characterSet_) { + if (characterSet != characterSet_) { + characterSet = characterSet_; + conv.Open("UTF-8", CharacterSetID(characterSet), false); + } +} +#endif + +SurfaceImpl::SurfaceImpl() : et(singleByte), drawable(0), gc(0), ppixmap(0), +x(0), y(0), inited(false), createdGC(false) +#ifdef USE_PANGO +, pcontext(0), layout(0), characterSet(-1) +#endif +{ +} + +SurfaceImpl::~SurfaceImpl() { + Release(); +} + +void SurfaceImpl::Release() { + et = singleByte; + drawable = 0; + if (createdGC) { + createdGC = false; + gdk_gc_unref(gc); + } + gc = 0; + if (ppixmap) + gdk_pixmap_unref(ppixmap); + ppixmap = 0; +#ifdef USE_PANGO + if (layout) + g_object_unref(layout); + layout = 0; + if (pcontext) + g_object_unref(pcontext); + pcontext = 0; + conv.Close(); + characterSet = -1; +#endif + x = 0; + y = 0; + inited = false; + createdGC = false; +} + +bool SurfaceImpl::Initialised() { + return inited; +} + +// The WindowID argument is only used for Pango builds +#ifdef USE_PANGO +#define WID_NAME wid +#else +#define WID_NAME +#endif + +void SurfaceImpl::Init(WindowID WID_NAME) { + Release(); +#ifdef USE_PANGO + PLATFORM_ASSERT(wid); + pcontext = gtk_widget_create_pango_context(PWidget(wid)); + PLATFORM_ASSERT(pcontext); + layout = pango_layout_new(pcontext); + PLATFORM_ASSERT(layout); +#endif + inited = true; +} + +void SurfaceImpl::Init(SurfaceID sid, WindowID WID_NAME) { + PLATFORM_ASSERT(sid); + GdkDrawable *drawable_ = reinterpret_cast(sid); + Release(); +#ifdef USE_PANGO + PLATFORM_ASSERT(wid); + pcontext = gtk_widget_create_pango_context(PWidget(wid)); + layout = pango_layout_new(pcontext); +#endif + drawable = drawable_; + gc = gdk_gc_new(drawable_); + // Ask for lines that do not paint the last pixel so is like Win32 + gdk_gc_set_line_attributes(gc, 0, GDK_LINE_SOLID, GDK_CAP_NOT_LAST, GDK_JOIN_MITER); + createdGC = true; + inited = true; +} + +void SurfaceImpl::InitPixMap(int width, int height, Surface *surface_, WindowID WID_NAME) { + PLATFORM_ASSERT(surface_); + Release(); + SurfaceImpl *surfImpl = static_cast(surface_); + PLATFORM_ASSERT(surfImpl->drawable); +#ifdef USE_PANGO + PLATFORM_ASSERT(wid); + pcontext = gtk_widget_create_pango_context(PWidget(wid)); + PLATFORM_ASSERT(pcontext); + layout = pango_layout_new(pcontext); + PLATFORM_ASSERT(layout); +#endif + if (height > 0 && width > 0) + ppixmap = gdk_pixmap_new(surfImpl->drawable, width, height, -1); + drawable = ppixmap; + gc = gdk_gc_new(surfImpl->drawable); + // Ask for lines that do not paint the last pixel so is like Win32 + gdk_gc_set_line_attributes(gc, 0, GDK_LINE_SOLID, GDK_CAP_NOT_LAST, GDK_JOIN_MITER); + createdGC = true; + inited = true; +} + +void SurfaceImpl::PenColour(ColourAllocated fore) { + if (gc) { + GdkColor co; + co.pixel = fore.AsLong(); + gdk_gc_set_foreground(gc, &co); + } +} + +int SurfaceImpl::LogPixelsY() { + return 72; +} + +int SurfaceImpl::DeviceHeightFont(int points) { + int logPix = LogPixelsY(); + return (points * logPix + logPix / 2) / 72; +} + +void SurfaceImpl::MoveTo(int x_, int y_) { + x = x_; + y = y_; +} + +void SurfaceImpl::LineTo(int x_, int y_) { + if (drawable && gc) { + gdk_draw_line(drawable, gc, + x, y, + x_, y_); + } + x = x_; + y = y_; +} + +void SurfaceImpl::Polygon(Point *pts, int npts, ColourAllocated fore, + ColourAllocated back) { + GdkPoint gpts[20]; + if (npts < static_cast((sizeof(gpts) / sizeof(gpts[0])))) { + for (int i = 0;i < npts;i++) { + gpts[i].x = pts[i].x; + gpts[i].y = pts[i].y; + } + PenColour(back); + gdk_draw_polygon(drawable, gc, 1, gpts, npts); + PenColour(fore); + gdk_draw_polygon(drawable, gc, 0, gpts, npts); + } +} + +void SurfaceImpl::RectangleDraw(PRectangle rc, ColourAllocated fore, ColourAllocated back) { + if (gc && drawable) { + PenColour(back); + gdk_draw_rectangle(drawable, gc, 1, + rc.left + 1, rc.top + 1, + rc.right - rc.left - 2, rc.bottom - rc.top - 2); + + PenColour(fore); + // The subtraction of 1 off the width and height here shouldn't be needed but + // otherwise a different rectangle is drawn than would be done if the fill parameter == 1 + gdk_draw_rectangle(drawable, gc, 0, + rc.left, rc.top, + rc.right - rc.left - 1, rc.bottom - rc.top - 1); + } +} + +void SurfaceImpl::FillRectangle(PRectangle rc, ColourAllocated back) { + PenColour(back); + if (drawable && (rc.left < maxCoordinate)) { // Protect against out of range + gdk_draw_rectangle(drawable, gc, 1, + rc.left, rc.top, + rc.right - rc.left, rc.bottom - rc.top); + } +} + +void SurfaceImpl::FillRectangle(PRectangle rc, Surface &surfacePattern) { + if (static_cast(surfacePattern).drawable) { + // Tile pattern over rectangle + // Currently assumes 8x8 pattern + int widthPat = 8; + int heightPat = 8; + for (int xTile = rc.left; xTile < rc.right; xTile += widthPat) { + int widthx = (xTile + widthPat > rc.right) ? rc.right - xTile : widthPat; + for (int yTile = rc.top; yTile < rc.bottom; yTile += heightPat) { + int heighty = (yTile + heightPat > rc.bottom) ? rc.bottom - yTile : heightPat; + gdk_draw_pixmap(drawable, + gc, + static_cast(surfacePattern).drawable, + 0, 0, + xTile, yTile, + widthx, heighty); + } + } + } else { + // Something is wrong so try to show anyway + // Shows up black because colour not allocated + FillRectangle(rc, ColourAllocated(0)); + } +} + +void SurfaceImpl::RoundedRectangle(PRectangle rc, ColourAllocated fore, ColourAllocated back) { + if (((rc.right - rc.left) > 4) && ((rc.bottom - rc.top) > 4)) { + // Approximate a round rect with some cut off corners + Point pts[] = { + Point(rc.left + 2, rc.top), + Point(rc.right - 2, rc.top), + Point(rc.right, rc.top + 2), + Point(rc.right, rc.bottom - 2), + Point(rc.right - 2, rc.bottom), + Point(rc.left + 2, rc.bottom), + Point(rc.left, rc.bottom - 2), + Point(rc.left, rc.top + 2), + }; + Polygon(pts, sizeof(pts) / sizeof(pts[0]), fore, back); + } else { + RectangleDraw(rc, fore, back); + } +} + +#if GTK_MAJOR_VERSION >= 2 + +// Plot a point into a guint32 buffer symetrically to all 4 qudrants +static void AllFour(guint32 *pixels, int stride, int width, int height, int x, int y, guint32 val) { + pixels[y*stride+x] = val; + pixels[y*stride+width-1-x] = val; + pixels[(height-1-y)*stride+x] = val; + pixels[(height-1-y)*stride+width-1-x] = val; +} + +static unsigned int GetRValue(unsigned int co) { + return (co >> 16) & 0xff; +} + +static unsigned int GetGValue(unsigned int co) { + return (co >> 8) & 0xff; +} + +static unsigned int GetBValue(unsigned int co) { + return co & 0xff; +} + +#endif + +#if GTK_MAJOR_VERSION < 2 +void SurfaceImpl::AlphaRectangle(PRectangle rc, int , ColourAllocated , int , ColourAllocated outline, int , int ) { + if (gc && drawable) { + // Can't use GdkPixbuf on GTK+ 1.x, so draw an outline rather than use alpha. + PenColour(outline); + gdk_draw_rectangle(drawable, gc, 0, + rc.left, rc.top, + rc.right - rc.left - 1, rc.bottom - rc.top - 1); + } +} +#else +void SurfaceImpl::AlphaRectangle(PRectangle rc, int cornerSize, ColourAllocated fill, int alphaFill, + ColourAllocated outline, int alphaOutline, int flags) { + if (gc && drawable && rc.Width() > 0) { + int width = rc.Width(); + int height = rc.Height(); + // Ensure not distorted too much by corners when small + cornerSize = Platform::Minimum(cornerSize, (Platform::Minimum(width, height) / 2) - 2); + // Make a 32 bit deep pixbuf with alpha + GdkPixbuf *pixalpha = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, width, height); + + guint8 pixVal[4] = {0}; + guint32 valEmpty = *(reinterpret_cast(pixVal)); + pixVal[0] = GetRValue(fill.AsLong()); + pixVal[1] = GetGValue(fill.AsLong()); + pixVal[2] = GetBValue(fill.AsLong()); + pixVal[3] = alphaFill; + guint32 valFill = *(reinterpret_cast(pixVal)); + pixVal[0] = GetRValue(outline.AsLong()); + pixVal[1] = GetGValue(outline.AsLong()); + pixVal[2] = GetBValue(outline.AsLong()); + pixVal[3] = alphaOutline; + guint32 valOutline = *(reinterpret_cast(pixVal)); + guint32 *pixels = reinterpret_cast(gdk_pixbuf_get_pixels(pixalpha)); + int stride = gdk_pixbuf_get_rowstride(pixalpha) / 4; + for (int y=0; y(surfaceSource).drawable) { + gdk_draw_pixmap(drawable, + gc, + static_cast(surfaceSource).drawable, + from.x, from.y, + rc.left, rc.top, + rc.right - rc.left, rc.bottom - rc.top); + } +} + +static size_t UTF8Len(char ch) { + unsigned char uch = static_cast(ch); + if (uch < 0x80) + return 1; + else if (uch < (0x80 + 0x40 + 0x20)) + return 2; + else + return 3; +} + +char *UTF8FromLatin1(const char *s, int &len) { + char *utfForm = new char[len*2+1]; + size_t lenU = 0; + for (int i=0;i(s[i]); + if (uch < 0x80) { + utfForm[lenU++] = uch; + } else { + utfForm[lenU++] = static_cast(0xC0 | (uch >> 6)); + utfForm[lenU++] = static_cast(0x80 | (uch & 0x3f)); + } + } + utfForm[lenU] = '\0'; + len = lenU; + return utfForm; +} + +#ifdef USE_PANGO +static char *UTF8FromIconv(const Converter &conv, const char *s, int &len) { + if (conv) { + char *utfForm = new char[len*3+1]; + char *pin = const_cast(s); + size_t inLeft = len; + char *pout = utfForm; + size_t outLeft = len*3+1; + size_t conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft); + if (conversions != ((size_t)(-1))) { + *pout = '\0'; + len = pout - utfForm; + return utfForm; + } + delete []utfForm; + } + return 0; +} + +// Work out how many bytes are in a character by trying to convert using iconv, +// returning the first length that succeeds. +static size_t MultiByteLenFromIconv(const Converter &conv, const char *s, size_t len) { + for (size_t lenMB=1; (lenMB<4) && (lenMB <= len); lenMB++) { + char wcForm[2]; + char *pin = const_cast(s); + size_t inLeft = lenMB; + char *pout = wcForm; + size_t outLeft = 2; + size_t conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft); + if (conversions != ((size_t)(-1))) { + return lenMB; + } + } + return 1; +} + +static char *UTF8FromGdkWChar(GdkWChar *wctext, int wclen) { + char *utfForm = new char[wclen*3+1]; // Maximum of 3 UTF-8 bytes per character + size_t lenU = 0; + for (int i = 0; i < wclen && wctext[i]; i++) { + unsigned int uch = wctext[i]; + if (uch < 0x80) { + utfForm[lenU++] = static_cast(uch); + } else if (uch < 0x800) { + utfForm[lenU++] = static_cast(0xC0 | (uch >> 6)); + utfForm[lenU++] = static_cast(0x80 | (uch & 0x3f)); + } else { + utfForm[lenU++] = static_cast(0xE0 | (uch >> 12)); + utfForm[lenU++] = static_cast(0x80 | ((uch >> 6) & 0x3f)); + utfForm[lenU++] = static_cast(0x80 | (uch & 0x3f)); + } + } + utfForm[lenU] = '\0'; + return utfForm; +} + +static char *UTF8FromDBCS(const char *s, int &len) { + GdkWChar *wctext = new GdkWChar[len + 1]; + GdkWChar *wcp = wctext; + int wclen = gdk_mbstowcs(wcp, s, len); + if (wclen < 1) { + // In the annoying case when non-locale chars in the line. + // e.g. latin1 chars in Japanese locale. + delete []wctext; + return 0; + } + + char *utfForm = UTF8FromGdkWChar(wctext, wclen); + delete []wctext; + len = strlen(utfForm); + return utfForm; +} + +static size_t UTF8CharLength(const char *s) { + const unsigned char *us = reinterpret_cast(s); + unsigned char ch = *us; + if (ch < 0x80) { + return 1; + } else if (ch < 0x80 + 0x40 + 0x20) { + return 2; + } else { + return 3; + } +} + +#endif + +// On GTK+, wchar_t is 4 bytes + +const int maxLengthTextRun = 10000; + +void SurfaceImpl::DrawTextBase(PRectangle rc, Font &font_, int ybase, const char *s, int len, + ColourAllocated fore) { + PenColour(fore); + if (gc && drawable) { + int x = rc.left; +#ifdef USE_PANGO + if (PFont(font_)->pfd) { + char *utfForm = 0; + bool useGFree = false; + if (et == UTF8) { + pango_layout_set_text(layout, s, len); + } else { + if (!utfForm) { + SetConverter(PFont(font_)->characterSet); + utfForm = UTF8FromIconv(conv, s, len); + } + if (!utfForm) { // iconv failed so try DBCS if DBCS mode + if (et == dbcs) { + // Convert to utf8 + utfForm = UTF8FromDBCS(s, len); + } + } + if (!utfForm) { // iconv and DBCS failed so treat as Latin1 + utfForm = UTF8FromLatin1(s, len); + } + pango_layout_set_text(layout, utfForm, len); + } + pango_layout_set_font_description(layout, PFont(font_)->pfd); + PangoLayoutLine *pll = pango_layout_get_line(layout,0); + gdk_draw_layout_line(drawable, gc, x, ybase, pll); + if (useGFree) { + g_free(utfForm); + } else { + delete []utfForm; + } + return; + } +#endif + // Draw text as a series of segments to avoid limitations in X servers + const int segmentLength = 1000; + bool draw8bit = true; + if (et != singleByte) { + GdkWChar wctext[maxLengthTextRun]; + if (len >= maxLengthTextRun) + len = maxLengthTextRun-1; + int wclen; + if (et == UTF8) { + wclen = UTF16FromUTF8(s, len, + static_cast(static_cast(wctext)), maxLengthTextRun - 1); + } else { // dbcs, so convert using current locale + char sMeasure[maxLengthTextRun]; + memcpy(sMeasure, s, len); + sMeasure[len] = '\0'; + wclen = gdk_mbstowcs( + wctext, sMeasure, maxLengthTextRun - 1); + } + if (wclen > 0) { + draw8bit = false; + wctext[wclen] = L'\0'; + GdkWChar *wcp = wctext; + while ((wclen > 0) && (x < maxCoordinate)) { + int lenDraw = Platform::Minimum(wclen, segmentLength); + gdk_draw_text_wc(drawable, PFont(font_)->pfont, gc, + x, ybase, wcp, lenDraw); + wclen -= lenDraw; + if (wclen > 0) { // Avoid next calculation if possible as may be expensive + x += gdk_text_width_wc(PFont(font_)->pfont, + wcp, lenDraw); + } + wcp += lenDraw; + } + } + } + if (draw8bit) { + while ((len > 0) && (x < maxCoordinate)) { + int lenDraw = Platform::Minimum(len, segmentLength); + gdk_draw_text(drawable, PFont(font_)->pfont, gc, + x, ybase, s, lenDraw); + len -= lenDraw; + if (len > 0) { // Avoid next calculation if possible as may be expensive + x += gdk_text_width(PFont(font_)->pfont, s, lenDraw); + } + s += lenDraw; + } + } + } +} + +void SurfaceImpl::DrawTextNoClip(PRectangle rc, Font &font_, int ybase, const char *s, int len, + ColourAllocated fore, ColourAllocated back) { + FillRectangle(rc, back); + DrawTextBase(rc, font_, ybase, s, len, fore); +} + +// On GTK+, exactly same as DrawTextNoClip +void SurfaceImpl::DrawTextClipped(PRectangle rc, Font &font_, int ybase, const char *s, int len, + ColourAllocated fore, ColourAllocated back) { + FillRectangle(rc, back); + DrawTextBase(rc, font_, ybase, s, len, fore); +} + +void SurfaceImpl::DrawTextTransparent(PRectangle rc, Font &font_, int ybase, const char *s, int len, + ColourAllocated fore) { + // Avoid drawing spaces in transparent mode + for (int i=0;ipfd) { + if (len == 1) { + int width = PFont(font_)->CharWidth(*s, et); + if (width) { + positions[0] = width; + return; + } + } + PangoRectangle pos; + pango_layout_set_font_description(layout, PFont(font_)->pfd); + if (et == UTF8) { + // Simple and direct as UTF-8 is native Pango encoding + pango_layout_set_text(layout, s, len); + PangoLayoutIter *iter = pango_layout_get_iter(layout); + pango_layout_iter_get_cluster_extents(iter, NULL, &pos); + int i = 0; + while (pango_layout_iter_next_cluster(iter)) { + pango_layout_iter_get_cluster_extents(iter, NULL, &pos); + int position = PANGO_PIXELS(pos.x); + int curIndex = pango_layout_iter_get_index(iter); + int places = curIndex - i; + int distance = position - positions[i-1]; + while (i < curIndex) { + // Evenly distribute space among bytes of this cluster. + // Would be better to find number of characters and then + // divide evenly between characters with each byte of a character + // being at the same position. + positions[i] = position - (curIndex - 1 - i) * distance / places; + i++; + } + } + while (i < lenPositions) + positions[i++] = PANGO_PIXELS(pos.x + pos.width); + pango_layout_iter_free(iter); + PLATFORM_ASSERT(i == lenPositions); + } else { + int positionsCalculated = 0; + if (et == dbcs) { + SetConverter(PFont(font_)->characterSet); + char *utfForm = UTF8FromIconv(conv, s, len); + if (utfForm) { + // Convert to UTF-8 so can ask Pango for widths, then + // Loop through UTF-8 and DBCS forms, taking account of different + // character byte lengths. + Converter convMeasure("UCS-2", CharacterSetID(characterSet), false); + pango_layout_set_text(layout, utfForm, strlen(utfForm)); + int i = 0; + int utfIndex = 0; + PangoLayoutIter *iter = pango_layout_get_iter(layout); + pango_layout_iter_get_cluster_extents(iter, NULL, &pos); + while (pango_layout_iter_next_cluster(iter)) { + pango_layout_iter_get_cluster_extents (iter, NULL, &pos); + int position = PANGO_PIXELS(pos.x); + int utfIndexNext = pango_layout_iter_get_index(iter); + while (utfIndex < utfIndexNext) { + size_t lenChar = MultiByteLenFromIconv(convMeasure, s+i, len-i); + //size_t lenChar = mblen(s+i, MB_CUR_MAX); + while (lenChar--) { + positions[i++] = position; + positionsCalculated++; + } + utfIndex += UTF8CharLength(utfForm+utfIndex); + } + } + while (i < lenPositions) + positions[i++] = PANGO_PIXELS(pos.x + pos.width); + pango_layout_iter_free(iter); + delete []utfForm; + PLATFORM_ASSERT(i == lenPositions); + } + } + if (positionsCalculated < 1 ) { + // Either Latin1 or DBCS conversion failed so treat as Latin1. + bool useGFree = false; + SetConverter(PFont(font_)->characterSet); + char *utfForm = UTF8FromIconv(conv, s, len); + if (!utfForm) { + utfForm = UTF8FromLatin1(s, len); + } + pango_layout_set_text(layout, utfForm, len); + PangoLayoutIter *iter = pango_layout_get_iter(layout); + pango_layout_iter_get_cluster_extents(iter, NULL, &pos); + int i = 0; + int positionStart = 0; + int clusterStart = 0; + // Each Latin1 input character may take 1 or 2 bytes in UTF-8 + // and groups of up to 3 may be represented as ligatures. + while (pango_layout_iter_next_cluster(iter)) { + pango_layout_iter_get_cluster_extents(iter, NULL, &pos); + int position = PANGO_PIXELS(pos.x); + int distance = position - positionStart; + int clusterEnd = pango_layout_iter_get_index(iter); + int ligatureLength = g_utf8_strlen(utfForm + clusterStart, clusterEnd - clusterStart); + PLATFORM_ASSERT(ligatureLength > 0 && ligatureLength <= 3); + for (int charInLig=0; charInLigSetCharWidth(*s, positions[0], et); + } + return; + } +#endif + GdkFont *gf = PFont(font_)->pfont; + bool measure8bit = true; + if (et != singleByte) { + GdkWChar wctext[maxLengthTextRun]; + if (len >= maxLengthTextRun) + len = maxLengthTextRun-1; + int wclen; + if (et == UTF8) { + wclen = UTF16FromUTF8(s, len, + static_cast(static_cast(wctext)), maxLengthTextRun - 1); + } else { // dbcsMode, so convert using current locale + char sDraw[maxLengthTextRun]; + memcpy(sDraw, s, len); + sDraw[len] = '\0'; + wclen = gdk_mbstowcs( + wctext, sDraw, maxLengthTextRun - 1); + } + if (wclen > 0) { + measure8bit = false; + wctext[wclen] = L'\0'; + // Map widths back to utf-8 or DBCS input string + int i = 0; + for (int iU = 0; iU < wclen; iU++) { + int width = gdk_char_width_wc(gf, wctext[iU]); + totalWidth += width; + int lenChar; + if (et == UTF8) { + lenChar = UTF8Len(s[i]); + } else { + lenChar = mblen(s+i, MB_CUR_MAX); + if (lenChar < 0) + lenChar = 1; + } + while (lenChar--) { + positions[i++] = totalWidth; + } + } + while (i < len) { // In case of problems with lengths + positions[i++] = totalWidth; + } + } + } + if (measure8bit) { + // Either Latin1 or conversion failed so treat as Latin1. + for (int i = 0; i < len; i++) { + int width = gdk_char_width(gf, s[i]); + totalWidth += width; + positions[i] = totalWidth; + } + } + } else { + // No font so return an ascending range of values + for (int i = 0; i < len; i++) { + positions[i] = i + 1; + } + } +} + +int SurfaceImpl::WidthText(Font &font_, const char *s, int len) { + if (font_.GetID()) { +#ifdef USE_PANGO + if (PFont(font_)->pfd) { + char *utfForm = 0; + pango_layout_set_font_description(layout, PFont(font_)->pfd); + PangoRectangle pos; + bool useGFree = false; + if (et == UTF8) { + pango_layout_set_text(layout, s, len); + } else { + if (et == dbcs) { + // Convert to utf8 + utfForm = UTF8FromDBCS(s, len); + } + if (!utfForm) { // DBCS failed so treat as iconv + SetConverter(PFont(font_)->characterSet); + utfForm = UTF8FromIconv(conv, s, len); + } + if (!utfForm) { // g_locale_to_utf8 failed so treat as Latin1 + utfForm = UTF8FromLatin1(s, len); + } + pango_layout_set_text(layout, utfForm, len); + } + PangoLayoutLine *pangoLine = pango_layout_get_line(layout, 0); + pango_layout_line_get_extents(pangoLine, NULL, &pos); + if (useGFree) { + g_free(utfForm); + } else { + delete []utfForm; + } + return PANGO_PIXELS(pos.width); + } +#endif + if (et == UTF8) { + GdkWChar wctext[maxLengthTextRun]; + size_t wclen = UTF16FromUTF8(s, len, static_cast(static_cast(wctext)), + sizeof(wctext) / sizeof(GdkWChar) - 1); + wctext[wclen] = L'\0'; + return gdk_text_width_wc(PFont(font_)->pfont, wctext, wclen); + } else { + return gdk_text_width(PFont(font_)->pfont, s, len); + } + } else { + return 1; + } +} + +int SurfaceImpl::WidthChar(Font &font_, char ch) { + if (font_.GetID()) { +#ifdef USE_PANGO + if (PFont(font_)->pfd) { + return WidthText(font_, &ch, 1); + } +#endif + return gdk_char_width(PFont(font_)->pfont, ch); + } else { + return 1; + } +} + +// Three possible strategies for determining ascent and descent of font: +// 1) Call gdk_string_extents with string containing all letters, numbers and punctuation. +// 2) Use the ascent and descent fields of GdkFont. +// 3) Call gdk_string_extents with string as 1 but also including accented capitals. +// Smallest values given by 1 and largest by 3 with 2 in between. +// Techniques 1 and 2 sometimes chop off extreme portions of ascenders and +// descenders but are mostly OK except for accented characters like Å which are +// rarely used in code. + +// This string contains a good range of characters to test for size. +//const char largeSizeString[] = "ÂÃÅÄ `~!@#$%^&*()-_=+\\|[]{};:\"\'<,>.?/1234567890" +// "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; +#ifndef FAST_WAY +const char sizeString[] = "`~!@#$%^&*()-_=+\\|[]{};:\"\'<,>.?/1234567890" + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; +#endif + +int SurfaceImpl::Ascent(Font &font_) { + if (!(font_.GetID())) + return 1; +#ifdef FAST_WAY + FontMutexLock(); + int ascent = PFont(font_)->ascent; +#ifdef USE_PANGO + if ((ascent == 0) && (PFont(font_)->pfd)) { + PangoFontMetrics *metrics = pango_context_get_metrics(pcontext, + PFont(font_)->pfd, pango_context_get_language(pcontext)); + PFont(font_)->ascent = + PANGO_PIXELS(pango_font_metrics_get_ascent(metrics)); + pango_font_metrics_unref(metrics); + ascent = PFont(font_)->ascent; + } +#endif + if ((ascent == 0) && (PFont(font_)->pfont)) { + ascent = PFont(font_)->pfont->ascent; + } + if (ascent == 0) { + ascent = 1; + } + FontMutexUnlock(); + return ascent; +#else + + gint lbearing; + gint rbearing; + gint width; + gint ascent; + gint descent; + + gdk_string_extents(PFont(font_)->pfont, sizeString, + &lbearing, &rbearing, &width, &ascent, &descent); + return ascent; +#endif +} + +int SurfaceImpl::Descent(Font &font_) { + if (!(font_.GetID())) + return 1; +#ifdef FAST_WAY + +#ifdef USE_PANGO + if (PFont(font_)->pfd) { + PangoFontMetrics *metrics = pango_context_get_metrics(pcontext, + PFont(font_)->pfd, pango_context_get_language(pcontext)); + int descent = PANGO_PIXELS(pango_font_metrics_get_descent(metrics)); + pango_font_metrics_unref(metrics); + return descent; + } +#endif + return PFont(font_)->pfont->descent; +#else + + gint lbearing; + gint rbearing; + gint width; + gint ascent; + gint descent; + + gdk_string_extents(PFont(font_)->pfont, sizeString, + &lbearing, &rbearing, &width, &ascent, &descent); + return descent; +#endif +} + +int SurfaceImpl::InternalLeading(Font &) { + return 0; +} + +int SurfaceImpl::ExternalLeading(Font &) { + return 0; +} + +int SurfaceImpl::Height(Font &font_) { + return Ascent(font_) + Descent(font_); +} + +int SurfaceImpl::AverageCharWidth(Font &font_) { + return WidthChar(font_, 'n'); +} + +int SurfaceImpl::SetPalette(Palette *, bool) { + // Handled in palette allocation for GTK so this does nothing + return 0; +} + +void SurfaceImpl::SetClip(PRectangle rc) { + GdkRectangle area = {rc.left, rc.top, + rc.right - rc.left, rc.bottom - rc.top}; + gdk_gc_set_clip_rectangle(gc, &area); +} + +void SurfaceImpl::FlushCachedState() {} + +void SurfaceImpl::SetUnicodeMode(bool unicodeMode_) { + if (unicodeMode_) + et = UTF8; +} + +void SurfaceImpl::SetDBCSMode(int codePage) { + if (codePage && (codePage != SC_CP_UTF8)) + et = dbcs; +} + +Surface *Surface::Allocate() { + return new SurfaceImpl; +} + +Window::~Window() {} + +void Window::Destroy() { + if (id) + gtk_widget_destroy(GTK_WIDGET(id)); + id = 0; +} + +bool Window::HasFocus() { + return GTK_WIDGET_HAS_FOCUS(id); +} + +PRectangle Window::GetPosition() { + // Before any size allocated pretend its 1000 wide so not scrolled + PRectangle rc(0, 0, 1000, 1000); + if (id) { + rc.left = PWidget(id)->allocation.x; + rc.top = PWidget(id)->allocation.y; + if (PWidget(id)->allocation.width > 20) { + rc.right = rc.left + PWidget(id)->allocation.width; + rc.bottom = rc.top + PWidget(id)->allocation.height; + } + } + return rc; +} + +void Window::SetPosition(PRectangle rc) { +#if 1 + //gtk_widget_set_uposition(id, rc.left, rc.top); + GtkAllocation alloc; + alloc.x = rc.left; + alloc.y = rc.top; + alloc.width = rc.Width(); + alloc.height = rc.Height(); + gtk_widget_size_allocate(PWidget(id), &alloc); +#else + + gtk_widget_set_uposition(id, rc.left, rc.top); + gtk_widget_set_usize(id, rc.right - rc.left, rc.bottom - rc.top); +#endif +} + +void Window::SetPositionRelative(PRectangle rc, Window relativeTo) { + int ox = 0; + int oy = 0; + gdk_window_get_origin(PWidget(relativeTo.id)->window, &ox, &oy); + ox += rc.left; + if (ox < 0) + ox = 0; + oy += rc.top; + if (oy < 0) + oy = 0; + + /* do some corrections to fit into screen */ + int sizex = rc.right - rc.left; + int sizey = rc.bottom - rc.top; + int screenWidth = gdk_screen_width(); + int screenHeight = gdk_screen_height(); + if (sizex > screenWidth) + ox = 0; /* the best we can do */ + else if (ox + sizex > screenWidth) + ox = screenWidth - sizex; + if (oy + sizey > screenHeight) + oy = screenHeight - sizey; + + gtk_widget_set_uposition(PWidget(id), ox, oy); +#if 0 + + GtkAllocation alloc; + alloc.x = rc.left + ox; + alloc.y = rc.top + oy; + alloc.width = rc.right - rc.left; + alloc.height = rc.bottom - rc.top; + gtk_widget_size_allocate(id, &alloc); +#endif + gtk_widget_set_usize(PWidget(id), sizex, sizey); +} + +PRectangle Window::GetClientPosition() { + // On GTK+, the client position is the window position + return GetPosition(); +} + +void Window::Show(bool show) { + if (show) + gtk_widget_show(PWidget(id)); +} + +void Window::InvalidateAll() { + if (id) { + gtk_widget_queue_draw(PWidget(id)); + } +} + +void Window::InvalidateRectangle(PRectangle rc) { + if (id) { + gtk_widget_queue_draw_area(PWidget(id), + rc.left, rc.top, + rc.right - rc.left, rc.bottom - rc.top); + } +} + +void Window::SetFont(Font &) { + // Can not be done generically but only needed for ListBox +} + +void Window::SetCursor(Cursor curs) { + // We don't set the cursor to same value numerous times under gtk because + // it stores the cursor in the window once it's set + if (curs == cursorLast) + return; + + cursorLast = curs; + GdkCursor *gdkCurs; + switch (curs) { + case cursorText: + gdkCurs = gdk_cursor_new(GDK_XTERM); + break; + case cursorArrow: + gdkCurs = gdk_cursor_new(GDK_LEFT_PTR); + break; + case cursorUp: + gdkCurs = gdk_cursor_new(GDK_CENTER_PTR); + break; + case cursorWait: + gdkCurs = gdk_cursor_new(GDK_WATCH); + break; + case cursorHand: + gdkCurs = gdk_cursor_new(GDK_HAND2); + break; + case cursorReverseArrow: + gdkCurs = gdk_cursor_new(GDK_RIGHT_PTR); + break; + default: + gdkCurs = gdk_cursor_new(GDK_LEFT_PTR); + cursorLast = cursorArrow; + break; + } + + if (PWidget(id)->window) + gdk_window_set_cursor(PWidget(id)->window, gdkCurs); + gdk_cursor_destroy(gdkCurs); +} + +void Window::SetTitle(const char *s) { + gtk_window_set_title(GTK_WINDOW(id), s); +} + +/* Returns rectangle of monitor pt is on, both rect and pt are in Window's + gdk window coordinates */ +PRectangle Window::GetMonitorRect(Point pt) { + gint x_offset, y_offset; + pt = pt; + + gdk_window_get_origin(PWidget(id)->window, &x_offset, &y_offset); + +// gtk 2.2+ +#if GTK_MAJOR_VERSION > 2 || (GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION >= 2) + { + GdkScreen* screen; + gint monitor_num; + GdkRectangle rect; + + screen = gtk_widget_get_screen(PWidget(id)); + monitor_num = gdk_screen_get_monitor_at_point(screen, pt.x + x_offset, pt.y + y_offset); + gdk_screen_get_monitor_geometry(screen, monitor_num, &rect); + rect.x -= x_offset; + rect.y -= y_offset; + return PRectangle(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height); + } +#else + return PRectangle(-x_offset, -y_offset, (-x_offset) + gdk_screen_width(), + (-y_offset) + gdk_screen_height()); +#endif +} + +struct ListImage { + const char *xpm_data; +#if GTK_MAJOR_VERSION < 2 + GdkPixmap *pixmap; + GdkBitmap *bitmap; +#else + GdkPixbuf *pixbuf; +#endif +}; + +static void list_image_free(gpointer, gpointer value, gpointer) { + ListImage *list_image = (ListImage *) value; +#if GTK_MAJOR_VERSION < 2 + if (list_image->pixmap) + gdk_pixmap_unref(list_image->pixmap); + if (list_image->bitmap) + gdk_bitmap_unref(list_image->bitmap); +#else + if (list_image->pixbuf) + gdk_pixbuf_unref (list_image->pixbuf); +#endif + g_free(list_image); +} + +ListBox::ListBox() { +} + +ListBox::~ListBox() { +} + +#if GTK_MAJOR_VERSION >= 2 +enum { + PIXBUF_COLUMN, + TEXT_COLUMN, + N_COLUMNS +}; +#endif + +class ListBoxX : public ListBox { + WindowID list; + WindowID scroller; +#if GTK_MAJOR_VERSION < 2 + int current; +#endif + void *pixhash; + int lineHeight; + XPMSet xset; + bool unicodeMode; + int desiredVisibleRows; + unsigned int maxItemCharacters; + unsigned int aveCharWidth; +public: + CallBackAction doubleClickAction; + void *doubleClickActionData; + + ListBoxX() : list(0), pixhash(NULL), desiredVisibleRows(5), maxItemCharacters(0), + doubleClickAction(NULL), doubleClickActionData(NULL) { +#if GTK_MAJOR_VERSION < 2 + current = 0; +#endif + } + virtual ~ListBoxX() { + if (pixhash) { + g_hash_table_foreach((GHashTable *) pixhash, list_image_free, NULL); + g_hash_table_destroy((GHashTable *) pixhash); + } + } + virtual void SetFont(Font &font); + virtual void Create(Window &parent, int ctrlID, Point location_, int lineHeight_, bool unicodeMode_); + virtual void SetAverageCharWidth(int width); + virtual void SetVisibleRows(int rows); + virtual int GetVisibleRows() const; + virtual PRectangle GetDesiredRect(); + virtual int CaretFromEdge(); + virtual void Clear(); + virtual void Append(char *s, int type = -1); + virtual int Length(); + virtual void Select(int n); + virtual int GetSelection(); + virtual int Find(const char *prefix); + virtual void GetValue(int n, char *value, int len); + virtual void RegisterImage(int type, const char *xpm_data); + virtual void ClearRegisteredImages(); + virtual void SetDoubleClickAction(CallBackAction action, void *data) { + doubleClickAction = action; + doubleClickActionData = data; + } + virtual void SetList(const char* list, char separator, char typesep); +}; + +ListBox *ListBox::Allocate() { + ListBoxX *lb = new ListBoxX(); + return lb; +} + +#if GTK_MAJOR_VERSION < 2 +static void UnselectionAC(GtkWidget *, gint, gint, + GdkEventButton *, gpointer p) { + int *pi = reinterpret_cast(p); + *pi = -1; +} +static void SelectionAC(GtkWidget *, gint row, gint, + GdkEventButton *, gpointer p) { + int *pi = reinterpret_cast(p); + *pi = row; +} +#endif + +static gboolean ButtonPress(GtkWidget *, GdkEventButton* ev, gpointer p) { + ListBoxX* lb = reinterpret_cast(p); + if (ev->type == GDK_2BUTTON_PRESS && lb->doubleClickAction != NULL) { + lb->doubleClickAction(lb->doubleClickActionData); + return TRUE; + } + + return FALSE; +} + +#if GTK_MAJOR_VERSION >= 2 +/* Change the active color to the selected color so the listbox uses the color +scheme that it would use if it had the focus. */ +static void StyleSet(GtkWidget *w, GtkStyle*, void*) { + GtkStyle* style; + + g_return_if_fail(w != NULL); + + /* Copy the selected color to active. Note that the modify calls will cause + recursive calls to this function after the value is updated and w->style to + be set to a new object */ + style = gtk_widget_get_style(w); + if (style == NULL) + return; + if (!gdk_color_equal(&style->base[GTK_STATE_SELECTED], &style->base[GTK_STATE_ACTIVE])) + gtk_widget_modify_base(w, GTK_STATE_ACTIVE, &style->base[GTK_STATE_SELECTED]); + + style = gtk_widget_get_style(w); + if (style == NULL) + return; + if (!gdk_color_equal(&style->text[GTK_STATE_SELECTED], &style->text[GTK_STATE_ACTIVE])) + gtk_widget_modify_text(w, GTK_STATE_ACTIVE, &style->text[GTK_STATE_SELECTED]); +} +#endif + +void ListBoxX::Create(Window &, int, Point, int, bool) { + id = gtk_window_new(GTK_WINDOW_POPUP); + + GtkWidget *frame = gtk_frame_new(NULL); + gtk_widget_show(frame); + gtk_container_add(GTK_CONTAINER(GetID()), frame); + gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT); + gtk_container_set_border_width(GTK_CONTAINER(frame), 0); + + scroller = gtk_scrolled_window_new(NULL, NULL); + gtk_container_set_border_width(GTK_CONTAINER(scroller), 0); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroller), + GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); + gtk_container_add(GTK_CONTAINER(frame), PWidget(scroller)); + gtk_widget_show(PWidget(scroller)); + +#if GTK_MAJOR_VERSION < 2 + list = gtk_clist_new(1); + GtkWidget *wid = PWidget(list); // No code inside the GTK_OBJECT macro + gtk_widget_show(wid); + gtk_container_add(GTK_CONTAINER(PWidget(scroller)), wid); + gtk_clist_set_column_auto_resize(GTK_CLIST(wid), 0, TRUE); + gtk_clist_set_selection_mode(GTK_CLIST(wid), GTK_SELECTION_BROWSE); + gtk_signal_connect(GTK_OBJECT(wid), "unselect_row", + GTK_SIGNAL_FUNC(UnselectionAC), ¤t); + gtk_signal_connect(GTK_OBJECT(wid), "select_row", + GTK_SIGNAL_FUNC(SelectionAC), ¤t); + gtk_signal_connect(GTK_OBJECT(wid), "button_press_event", + GTK_SIGNAL_FUNC(ButtonPress), this); + gtk_clist_set_shadow_type(GTK_CLIST(wid), GTK_SHADOW_NONE); +#else + /* Tree and its model */ + GtkListStore *store = + gtk_list_store_new(N_COLUMNS, GDK_TYPE_PIXBUF, G_TYPE_STRING); + + list = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); + g_signal_connect(G_OBJECT(list), "style-set", G_CALLBACK(StyleSet), NULL); + + GtkTreeSelection *selection = + gtk_tree_view_get_selection(GTK_TREE_VIEW(list)); + gtk_tree_selection_set_mode(selection, GTK_SELECTION_SINGLE); + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(list), FALSE); + gtk_tree_view_set_reorderable(GTK_TREE_VIEW(list), FALSE); + + /* Columns */ + GtkTreeViewColumn *column = gtk_tree_view_column_new(); + gtk_tree_view_column_set_sizing(column, GTK_TREE_VIEW_COLUMN_FIXED); + gtk_tree_view_column_set_title(column, "Autocomplete"); + + GtkCellRenderer *renderer = gtk_cell_renderer_pixbuf_new(); + gtk_tree_view_column_pack_start(column, renderer, FALSE); + gtk_tree_view_column_add_attribute(column, renderer, + "pixbuf", PIXBUF_COLUMN); + + renderer = gtk_cell_renderer_text_new(); + gtk_cell_renderer_text_set_fixed_height_from_font(GTK_CELL_RENDERER_TEXT(renderer), 1); + gtk_tree_view_column_pack_start(column, renderer, TRUE); + gtk_tree_view_column_add_attribute(column, renderer, + "text", TEXT_COLUMN); + + gtk_tree_view_append_column(GTK_TREE_VIEW(list), column); + if (g_object_class_find_property(G_OBJECT_GET_CLASS(list), "fixed-height-mode")) + g_object_set(G_OBJECT(list), "fixed-height-mode", TRUE, NULL); + + GtkWidget *wid = PWidget(list); // No code inside the G_OBJECT macro + gtk_container_add(GTK_CONTAINER(PWidget(scroller)), wid); + gtk_widget_show(wid); + g_signal_connect(G_OBJECT(wid), "button_press_event", + G_CALLBACK(ButtonPress), this); +#endif + gtk_widget_realize(PWidget(id)); +} + +void ListBoxX::SetFont(Font &scint_font) { +#if GTK_MAJOR_VERSION < 2 + GtkStyle *style = gtk_widget_get_style(GTK_WIDGET(PWidget(list))); + if (!gdk_font_equal(style->font, PFont(scint_font)->pfont)) { + style = gtk_style_copy(style); + gdk_font_unref(style->font); + style->font = PFont(scint_font)->pfont; + gdk_font_ref(style->font); + gtk_widget_set_style(GTK_WIDGET(PWidget(list)), style); + gtk_style_unref(style); + } +#else + // Only do for Pango font as there have been crashes for GDK fonts + if (Created() && PFont(scint_font)->pfd) { + // Current font is Pango font + gtk_widget_modify_font(PWidget(list), PFont(scint_font)->pfd); + } +#endif +} + +void ListBoxX::SetAverageCharWidth(int width) { + aveCharWidth = width; +} + +void ListBoxX::SetVisibleRows(int rows) { + desiredVisibleRows = rows; +} + +int ListBoxX::GetVisibleRows() const { + return desiredVisibleRows; +} + +PRectangle ListBoxX::GetDesiredRect() { + // Before any size allocated pretend its 100 wide so not scrolled + PRectangle rc(0, 0, 100, 100); + if (id) { + int rows = Length(); + if ((rows == 0) || (rows > desiredVisibleRows)) + rows = desiredVisibleRows; + + GtkRequisition req; + int height; + + // First calculate height of the clist for our desired visible + // row count otherwise it tries to expand to the total # of rows +#if GTK_MAJOR_VERSION < 2 + int ythickness = PWidget(list)->style->klass->ythickness; + height = (rows * GTK_CLIST(list)->row_height + + rows + 1 + + 2 * (ythickness + + GTK_CONTAINER(PWidget(list))->border_width)); +#else + // Get cell height + int row_width=0; + int row_height=0; + GtkTreeViewColumn * column = + gtk_tree_view_get_column(GTK_TREE_VIEW(list), 0); + gtk_tree_view_column_cell_get_size(column, NULL, + NULL, NULL, &row_width, &row_height); + int ythickness = PWidget(list)->style->ythickness; + height = (rows * row_height + + 2 * (ythickness + + GTK_CONTAINER(PWidget(list))->border_width + 1)); +#endif + gtk_widget_set_usize(GTK_WIDGET(PWidget(list)), -1, height); + + // Get the size of the scroller because we set usize on the window + gtk_widget_size_request(GTK_WIDGET(scroller), &req); + rc.right = req.width; + rc.bottom = req.height; + + gtk_widget_set_usize(GTK_WIDGET(list), -1, -1); + int width = maxItemCharacters; + if (width < 12) + width = 12; + rc.right = width * (aveCharWidth + aveCharWidth / 3); + if (Length() > rows) + rc.right = rc.right + 16; + } + return rc; +} + +int ListBoxX::CaretFromEdge() { + return 4 + xset.GetWidth(); +} + +void ListBoxX::Clear() { +#if GTK_MAJOR_VERSION < 2 + gtk_clist_clear(GTK_CLIST(list)); +#else + GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(list)); + gtk_list_store_clear(GTK_LIST_STORE(model)); +#endif + maxItemCharacters = 0; +} + +#if GTK_MAJOR_VERSION < 2 +static void init_pixmap(ListImage *list_image, GtkWidget *window) { +#else +static void init_pixmap(ListImage *list_image) { +#endif + const char *textForm = list_image->xpm_data; + const char * const * xpm_lineform = reinterpret_cast(textForm); + const char **xpm_lineformfromtext = 0; + // The XPM data can be either in atext form as will be read from a file + // or in a line form (array of char *) as will be used for images defined in code. + // Test for text form and convert to line form + if ((0 == memcmp(textForm, "/* X", 4)) && (0 == memcmp(textForm, "/* XPM */", 9))) { + // Test done is two parts to avoid possibility of overstepping the memory + // if memcmp implemented strangely. Must be 4 bytes at least at destination. + xpm_lineformfromtext = XPM::LinesFormFromTextForm(textForm); + xpm_lineform = xpm_lineformfromtext; + } + + // Drop any existing pixmap/bitmap as data may have changed +#if GTK_MAJOR_VERSION < 2 + if (list_image->pixmap) + gdk_pixmap_unref(list_image->pixmap); + list_image->pixmap = NULL; + if (list_image->bitmap) + gdk_bitmap_unref(list_image->bitmap); + list_image->bitmap = NULL; + + list_image->pixmap = gdk_pixmap_colormap_create_from_xpm_d(NULL + , gtk_widget_get_colormap(window), &(list_image->bitmap), NULL + , (gchar **) xpm_lineform); + if (NULL == list_image->pixmap) { + if (list_image->bitmap) + gdk_bitmap_unref(list_image->bitmap); + list_image->bitmap = NULL; + } +#else + if (list_image->pixbuf) + gdk_pixbuf_unref(list_image->pixbuf); + list_image->pixbuf = + gdk_pixbuf_new_from_xpm_data((const gchar**)xpm_lineform); +#endif + delete []xpm_lineformfromtext; +} + +#define SPACING 5 + +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)); + } +#if GTK_MAJOR_VERSION < 2 + char * szs[] = { s, NULL }; + int rownum = gtk_clist_append(GTK_CLIST(list), szs); + if (list_image) { + if (NULL == list_image->pixmap) + init_pixmap(list_image, (GtkWidget *) list); + gtk_clist_set_pixtext(GTK_CLIST(list), rownum, 0, s, SPACING + , list_image->pixmap, list_image->bitmap); + } +#else + GtkTreeIter iter; + GtkListStore *store = + GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(list))); + gtk_list_store_append(GTK_LIST_STORE(store), &iter); + if (list_image) { + if (NULL == list_image->pixbuf) + init_pixmap(list_image); + if (list_image->pixbuf) { + gtk_list_store_set(GTK_LIST_STORE(store), &iter, + PIXBUF_COLUMN, list_image->pixbuf, + TEXT_COLUMN, s, -1); + } else { + gtk_list_store_set(GTK_LIST_STORE(store), &iter, + TEXT_COLUMN, s, -1); + } + } else { + gtk_list_store_set(GTK_LIST_STORE(store), &iter, + TEXT_COLUMN, s, -1); + } +#endif + size_t len = strlen(s); + if (maxItemCharacters < len) + maxItemCharacters = len; +} + +int ListBoxX::Length() { + if (id) +#if GTK_MAJOR_VERSION < 2 + return GTK_CLIST(list)->rows; +#else + return gtk_tree_model_iter_n_children(gtk_tree_view_get_model + (GTK_TREE_VIEW(list)), NULL); +#endif + return 0; +} + +void ListBoxX::Select(int n) { +#if GTK_MAJOR_VERSION < 2 + if (n == -1) { + gtk_clist_unselect_row(GTK_CLIST(list), current, 0); + } else { + gtk_clist_select_row(GTK_CLIST(list), n, 0); + gtk_clist_moveto(GTK_CLIST(list), n, 0, 0.5, 0.5); + } +#else + GtkTreeIter iter; + GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(list)); + GtkTreeSelection *selection = + gtk_tree_view_get_selection(GTK_TREE_VIEW(list)); + + if (n < 0) { + gtk_tree_selection_unselect_all(selection); + return; + } + + bool valid = gtk_tree_model_iter_nth_child(model, &iter, NULL, n) != FALSE; + if (valid) { + gtk_tree_selection_select_iter(selection, &iter); + + // Move the scrollbar to show the selection. + int total = Length(); + GtkAdjustment *adj = + gtk_tree_view_get_vadjustment(GTK_TREE_VIEW(list)); + gfloat value = ((gfloat)n / total) * (adj->upper - adj->lower) + + adj->lower - adj->page_size / 2; + + // Get cell height + int row_width; + int row_height; + GtkTreeViewColumn * column = + gtk_tree_view_get_column(GTK_TREE_VIEW(list), 0); + gtk_tree_view_column_cell_get_size(column, NULL, NULL, + NULL, &row_width, &row_height); + + int rows = Length(); + if ((rows == 0) || (rows > desiredVisibleRows)) + rows = desiredVisibleRows; + if (rows & 0x1) { + // Odd rows to display -- We are now in the middle. + // Align it so that we don't chop off rows. + value += (gfloat)row_height / 2.0; + } + // Clamp it. + value = (value < 0)? 0 : value; + value = (value > (adj->upper - adj->page_size))? + (adj->upper - adj->page_size) : value; + + // Set it. + gtk_adjustment_set_value(adj, value); + } else { + gtk_tree_selection_unselect_all(selection); + } +#endif +} + +int ListBoxX::GetSelection() { +#if GTK_MAJOR_VERSION < 2 + return current; +#else + GtkTreeIter iter; + GtkTreeModel *model; + GtkTreeSelection *selection; + selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(list)); + if (gtk_tree_selection_get_selected(selection, &model, &iter)) { + GtkTreePath *path = gtk_tree_model_get_path(model, &iter); + int *indices = gtk_tree_path_get_indices(path); + // Don't free indices. + if (indices) + return indices[0]; + } + return -1; +#endif +} + +int ListBoxX::Find(const char *prefix) { +#if GTK_MAJOR_VERSION < 2 + int count = Length(); + for (int i = 0; i < count; i++) { + char *s = 0; + gtk_clist_get_text(GTK_CLIST(list), i, 0, &s); + if (s && (0 == strncmp(prefix, s, strlen(prefix)))) { + return i; + } + } +#else + GtkTreeIter iter; + GtkTreeModel *model = + gtk_tree_view_get_model(GTK_TREE_VIEW(list)); + bool valid = gtk_tree_model_get_iter_first(model, &iter) != FALSE; + int i = 0; + while(valid) { + gchar *s; + gtk_tree_model_get(model, &iter, TEXT_COLUMN, &s, -1); + if (s && (0 == strncmp(prefix, s, strlen(prefix)))) { + return i; + } + valid = gtk_tree_model_iter_next(model, &iter) != FALSE; + i++; + } +#endif + return -1; +} + +void ListBoxX::GetValue(int n, char *value, int len) { + char *text = NULL; +#if GTK_MAJOR_VERSION < 2 + GtkCellType type = gtk_clist_get_cell_type(GTK_CLIST(list), n, 0); + switch (type) { + case GTK_CELL_TEXT: + gtk_clist_get_text(GTK_CLIST(list), n, 0, &text); + break; + case GTK_CELL_PIXTEXT: + gtk_clist_get_pixtext(GTK_CLIST(list), n, 0, &text, NULL, NULL, NULL); + break; + default: + break; + } +#else + GtkTreeIter iter; + GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(list)); + bool valid = gtk_tree_model_iter_nth_child(model, &iter, NULL, n) != FALSE; + if (valid) { + gtk_tree_model_get(model, &iter, TEXT_COLUMN, &text, -1); + } +#endif + if (text && len > 0) { + strncpy(value, text, len); + value[len - 1] = '\0'; + } else { + value[0] = '\0'; + } +} + +// g_return_if_fail causes unnecessary compiler warning in release compile. +#ifdef _MSC_VER +#pragma warning(disable: 4127) +#endif + +void ListBoxX::RegisterImage(int type, const char *xpm_data) { + g_return_if_fail(xpm_data); + + // Saved and use the saved copy so caller's copy can disappear. + xset.Add(type, xpm_data); + XPM *pxpm = xset.Get(type); + xpm_data = reinterpret_cast(pxpm->InLinesForm()); + + 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)); + if (list_image) { + // Drop icon already registered +#if GTK_MAJOR_VERSION < 2 + if (list_image->pixmap) + gdk_pixmap_unref(list_image->pixmap); + list_image->pixmap = 0; + if (list_image->bitmap) + gdk_bitmap_unref(list_image->bitmap); + list_image->bitmap = 0; +#else + if (list_image->pixbuf) + gdk_pixbuf_unref(list_image->pixbuf); + list_image->pixbuf = NULL; +#endif + list_image->xpm_data = xpm_data; + } else { + list_image = g_new0(ListImage, 1); + list_image->xpm_data = xpm_data; + g_hash_table_insert((GHashTable *) pixhash, GINT_TO_POINTER(type), + (gpointer) list_image); + } +} + +void ListBoxX::ClearRegisteredImages() { + xset.Clear(); +} + +void ListBoxX::SetList(const char* list, char separator, char typesep) { + Clear(); + int count = strlen(list) + 1; + char *words = new char[count]; + if (words) { + memcpy(words, list, count); + char *startword = words; + char *numword = NULL; + int i = 0; + for (; words[i]; i++) { + if (words[i] == separator) { + words[i] = '\0'; + if (numword) + *numword = '\0'; + Append(startword, numword?atoi(numword + 1):-1); + startword = words + i + 1; + numword = NULL; + } else if (words[i] == typesep) { + numword = words + i; + } + } + if (startword) { + if (numword) + *numword = '\0'; + Append(startword, numword?atoi(numword + 1):-1); + } + delete []words; + } +} + +Menu::Menu() : id(0) {} + +void Menu::CreatePopUp() { + Destroy(); + id = gtk_item_factory_new(GTK_TYPE_MENU, "
", NULL); +} + +void Menu::Destroy() { + if (id) +#if GTK_MAJOR_VERSION < 2 + gtk_object_unref(GTK_OBJECT(id)); +#else + g_object_unref(G_OBJECT(id)); +#endif + id = 0; +} + +void Menu::Show(Point pt, Window &) { + int screenHeight = gdk_screen_height(); + int screenWidth = gdk_screen_width(); + GtkItemFactory *factory = reinterpret_cast(id); + GtkWidget *widget = gtk_item_factory_get_widget(factory, "
"); + gtk_widget_show_all(widget); + GtkRequisition requisition; + gtk_widget_size_request(widget, &requisition); + if ((pt.x + requisition.width) > screenWidth) { + pt.x = screenWidth - requisition.width; + } + if ((pt.y + requisition.height) > screenHeight) { + pt.y = screenHeight - requisition.height; + } +#if GTK_MAJOR_VERSION >= 2 + gtk_item_factory_popup(factory, pt.x - 4, pt.y - 4, 3, + gtk_get_current_event_time()); +#else + gtk_item_factory_popup(factory, pt.x - 4, pt.y - 4, 3, 0); +#endif +} + +ElapsedTime::ElapsedTime() { + GTimeVal curTime; + g_get_current_time(&curTime); + bigBit = curTime.tv_sec; + littleBit = curTime.tv_usec; +} + +class DynamicLibraryImpl : public DynamicLibrary { +protected: + GModule* m; +public: + DynamicLibraryImpl(const char *modulePath) { + m = g_module_open(modulePath, G_MODULE_BIND_LAZY); + } + + virtual ~DynamicLibraryImpl() { + if (m != NULL) + g_module_close(m); + } + + // Use g_module_symbol to get a pointer to the relevant function. + virtual Function FindFunction(const char *name) { + if (m != NULL) { + gpointer fn_address = NULL; + gboolean status = g_module_symbol(m, name, &fn_address); + if (status) + return static_cast(fn_address); + else + return NULL; + } else + return NULL; + } + + virtual bool IsValid() { + return m != NULL; + } +}; + +DynamicLibrary *DynamicLibrary::Load(const char *modulePath) { + return static_cast( new DynamicLibraryImpl(modulePath) ); +} + +double ElapsedTime::Duration(bool reset) { + GTimeVal curTime; + g_get_current_time(&curTime); + long endBigBit = curTime.tv_sec; + long endLittleBit = curTime.tv_usec; + double result = 1000000.0 * (endBigBit - bigBit); + result += endLittleBit - littleBit; + result /= 1000000.0; + if (reset) { + bigBit = endBigBit; + littleBit = endLittleBit; + } + return result; +} + +ColourDesired Platform::Chrome() { + return ColourDesired(0xe0, 0xe0, 0xe0); +} + +ColourDesired Platform::ChromeHighlight() { + return ColourDesired(0xff, 0xff, 0xff); +} + +const char *Platform::DefaultFont() { +#ifdef G_OS_WIN32 + return "Lucida Console"; +#else +#ifdef USE_PANGO + return "!Sans"; +#else + return "lucidatypewriter"; +#endif +#endif +} + +int Platform::DefaultFontSize() { +#ifdef G_OS_WIN32 + return 10; +#else + return 12; +#endif +} + +unsigned int Platform::DoubleClickTime() { + return 500; // Half a second +} + +bool Platform::MouseButtonBounce() { + return true; +} + +void Platform::DebugDisplay(const char *s) { + fprintf(stderr, "%s", s); +} + +bool Platform::IsKeyDown(int) { + // TODO: discover state of keys in GTK+/X + return false; +} + +long Platform::SendScintilla( + WindowID w, unsigned int msg, unsigned long wParam, long lParam) { + return scintilla_send_message(SCINTILLA(w), msg, wParam, lParam); +} + +long Platform::SendScintillaPointer( + WindowID w, unsigned int msg, unsigned long wParam, void *lParam) { + return scintilla_send_message(SCINTILLA(w), msg, wParam, + reinterpret_cast(lParam)); +} + +bool Platform::IsDBCSLeadByte(int /* codePage */, char /* ch */) { + return false; +} + +int Platform::DBCSCharLength(int, const char *s) { + int bytes = mblen(s, MB_CUR_MAX); + if (bytes >= 1) + return bytes; + else + return 1; +} + +int Platform::DBCSCharMaxLength() { + return MB_CUR_MAX; + //return 2; +} + +// These are utility functions not really tied to a platform + +int Platform::Minimum(int a, int b) { + if (a < b) + return a; + else + return b; +} + +int Platform::Maximum(int a, int b) { + if (a > b) + return a; + else + return b; +} + +//#define TRACE + +#ifdef TRACE +void Platform::DebugPrintf(const char *format, ...) { + char buffer[2000]; + va_list pArguments; + va_start(pArguments, format); + vsprintf(buffer, format, pArguments); + va_end(pArguments); + Platform::DebugDisplay(buffer); +} +#else +void Platform::DebugPrintf(const char *, ...) {} + +#endif + +// Not supported for GTK+ +static bool assertionPopUps = true; + +bool Platform::ShowAssertionPopUps(bool assertionPopUps_) { + bool ret = assertionPopUps; + assertionPopUps = assertionPopUps_; + return ret; +} + +void Platform::Assert(const char *c, const char *file, int line) { + char buffer[2000]; + sprintf(buffer, "Assertion [%s] failed at %s %d", c, file, line); + strcat(buffer, "\r\n"); + Platform::DebugDisplay(buffer); + abort(); +} + +int Platform::Clamp(int val, int minVal, int maxVal) { + if (val > maxVal) + val = maxVal; + if (val < minVal) + val = minVal; + return val; +} + +void Platform_Initialise() { + FontMutexAllocate(); +} + +void Platform_Finalise() { + FontMutexFree(); +} diff --git a/scintilla/gtk/ScintillaGTK.cxx b/scintilla/gtk/ScintillaGTK.cxx new file mode 100644 index 00000000..551554c2 --- /dev/null +++ b/scintilla/gtk/ScintillaGTK.cxx @@ -0,0 +1,2714 @@ +// Scintilla source code edit control +// ScintillaGTK.cxx - GTK+ specific subclass of ScintillaBase +// Copyright 1998-2004 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include +#include + +#include "Platform.h" + +#if PLAT_GTK_WIN32 +#include "Windows.h" +#endif + +#include "Scintilla.h" +#include "ScintillaWidget.h" +#ifdef SCI_LEXER +#include "SciLexer.h" +#include "PropSet.h" +#include "Accessor.h" +#include "KeyWords.h" +#endif +#include "SVector.h" +#include "SplitVector.h" +#include "Partitioning.h" +#include "RunStyles.h" +#include "ContractionState.h" +#include "CellBuffer.h" +#include "CallTip.h" +#include "KeyMap.h" +#include "Indicator.h" +#include "XPM.h" +#include "LineMarker.h" +#include "Style.h" +#include "AutoComplete.h" +#include "ViewStyle.h" +#include "Decoration.h" +#include "CharClassify.h" +#include "Document.h" +#include "PositionCache.h" +#include "Editor.h" +#include "SString.h" +#include "ScintillaBase.h" +#include "UniConversion.h" + +#include "gtk/gtksignal.h" +#include "gtk/gtkmarshal.h" +#if GLIB_MAJOR_VERSION >= 2 +#include "scintilla-marshal.h" +#endif + +#ifdef SCI_LEXER +#include +#include +#include "ExternalLexer.h" +#endif + +#define INTERNATIONAL_INPUT + +#if !PLAT_GTK_WIN32 || GTK_MAJOR_VERSION >= 2 +#define USE_CONVERTER +#endif + +#ifdef USE_CONVERTER +#include "Converter.h" +#endif + +#ifdef _MSC_VER +// Constant conditional expressions are because of GTK+ headers +#pragma warning(disable: 4127) +// Ignore unreferenced local functions in GTK+ headers +#pragma warning(disable: 4505) +#endif + +#if GTK_CHECK_VERSION(2,6,0) +#define USE_GTK_CLIPBOARD +#endif + +#if GLIB_MAJOR_VERSION < 2 +#define OBJECT_CLASS GtkObjectClass +#else +#define OBJECT_CLASS GObjectClass +#endif + +extern char *UTF8FromLatin1(const char *s, int &len); + +class ScintillaGTK : public ScintillaBase { + _ScintillaObject *sci; + Window wText; + Window scrollbarv; + Window scrollbarh; + GtkObject *adjustmentv; + GtkObject *adjustmenth; + int scrollBarWidth; + int scrollBarHeight; + + // Because clipboard access is asynchronous, copyText is created by Copy +#ifndef USE_GTK_CLIPBOARD + SelectionText copyText; +#endif + + SelectionText primary; + + GdkEventButton evbtn; + bool capturedMouse; + bool dragWasDropped; + int lastKey; + + GtkWidgetClass *parentClass; + + static GdkAtom atomClipboard; + static GdkAtom atomUTF8; + static GdkAtom atomString; + static GdkAtom atomUriList; + static GdkAtom atomDROPFILES_DND; + GdkAtom atomSought; + +#if PLAT_GTK_WIN32 + CLIPFORMAT cfColumnSelect; +#endif + +#ifdef INTERNATIONAL_INPUT +#if GTK_MAJOR_VERSION < 2 + // Input context used for supporting internationalized key entry + GdkIC *ic; + GdkICAttr *ic_attr; +#else + Window wPreedit; + Window wPreeditDraw; + GtkIMContext *im_context; +#endif +#endif + + // Wheel mouse support + unsigned int linesPerScroll; + GTimeVal lastWheelMouseTime; + gint lastWheelMouseDirection; + gint wheelMouseIntensity; + + GdkRegion *rgnUpdate; + + // Private so ScintillaGTK objects can not be copied + ScintillaGTK(const ScintillaGTK &) : ScintillaBase() {} + ScintillaGTK &operator=(const ScintillaGTK &) { return * this; } + +public: + ScintillaGTK(_ScintillaObject *sci_); + virtual ~ScintillaGTK(); + static void ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_class, GtkContainerClass *container_class); +private: + virtual void Initialise(); + virtual void Finalise(); + virtual void DisplayCursor(Window::Cursor c); + virtual bool DragThreshold(Point ptStart, Point ptNow); + virtual void StartDrag(); + int TargetAsUTF8(char *text); + int EncodedFromUTF8(char *utf8, char *encoded); + virtual bool ValidCodePage(int codePage) const; +public: // Public for scintilla_send_message + virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam); +private: + virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam); + virtual void SetTicking(bool on); + virtual bool SetIdle(bool on); + virtual void SetMouseCapture(bool on); + virtual bool HaveMouseCapture(); + virtual bool PaintContains(PRectangle rc); + void FullPaint(); + virtual PRectangle GetClientRectangle(); + void SyncPaint(PRectangle rc); + virtual void ScrollText(int linesToMove); + virtual void SetVerticalScrollPos(); + virtual void SetHorizontalScrollPos(); + virtual bool ModifyScrollBars(int nMax, int nPage); + void ReconfigureScrollBars(); + virtual void NotifyChange(); + virtual void NotifyFocus(bool focus); + virtual void NotifyParent(SCNotification scn); + void NotifyKey(int key, int modifiers); + void NotifyURIDropped(const char *list); + const char *CharacterSetID() const; + virtual int KeyDefault(int key, int modifiers); + virtual void CopyToClipboard(const SelectionText &selectedText); + virtual void Copy(); + virtual void Paste(); + virtual void CreateCallTipWindow(PRectangle rc); + virtual void AddToPopUp(const char *label, int cmd = 0, bool enabled = true); + bool OwnPrimarySelection(); + virtual void ClaimSelection(); + void GetGtkSelectionText(GtkSelectionData *selectionData, SelectionText &selText); + void ReceivedSelection(GtkSelectionData *selection_data); + void ReceivedDrop(GtkSelectionData *selection_data); + static void GetSelection(GtkSelectionData *selection_data, guint info, SelectionText *selected); +#ifdef USE_GTK_CLIPBOARD + void StoreOnClipboard(SelectionText *clipText); + static void ClipboardGetSelection(GtkClipboard* clip, GtkSelectionData *selection_data, guint info, void *data); + static void ClipboardClearSelection(GtkClipboard* clip, void *data); +#endif + + void UnclaimSelection(GdkEventSelection *selection_event); + void Resize(int width, int height); + + // Callback functions + void RealizeThis(GtkWidget *widget); + static void Realize(GtkWidget *widget); + void UnRealizeThis(GtkWidget *widget); + static void UnRealize(GtkWidget *widget); + void MapThis(); + static void Map(GtkWidget *widget); + void UnMapThis(); + static void UnMap(GtkWidget *widget); + static gint CursorMoved(GtkWidget *widget, int xoffset, int yoffset, ScintillaGTK *sciThis); + static gint FocusIn(GtkWidget *widget, GdkEventFocus *event); + static gint FocusOut(GtkWidget *widget, GdkEventFocus *event); + static void SizeRequest(GtkWidget *widget, GtkRequisition *requisition); + static void SizeAllocate(GtkWidget *widget, GtkAllocation *allocation); + gint Expose(GtkWidget *widget, GdkEventExpose *ose); + static gint ExposeMain(GtkWidget *widget, GdkEventExpose *ose); + static void Draw(GtkWidget *widget, GdkRectangle *area); + void ForAll(GtkCallback callback, gpointer callback_data); + static void MainForAll(GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data); + + static void ScrollSignal(GtkAdjustment *adj, ScintillaGTK *sciThis); + static void ScrollHSignal(GtkAdjustment *adj, ScintillaGTK *sciThis); + gint PressThis(GdkEventButton *event); + static gint Press(GtkWidget *widget, GdkEventButton *event); + static gint MouseRelease(GtkWidget *widget, GdkEventButton *event); +#if PLAT_GTK_WIN32 || (GTK_MAJOR_VERSION >= 2) + static gint ScrollEvent(GtkWidget *widget, GdkEventScroll *event); +#endif + static gint Motion(GtkWidget *widget, GdkEventMotion *event); + gboolean KeyThis(GdkEventKey *event); + static gboolean KeyPress(GtkWidget *widget, GdkEventKey *event); + static gboolean KeyRelease(GtkWidget *widget, GdkEventKey *event); +#if GTK_MAJOR_VERSION >= 2 + static gboolean ExposePreedit(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis); + gboolean ExposePreeditThis(GtkWidget *widget, GdkEventExpose *ose); + static void Commit(GtkIMContext *context, char *str, ScintillaGTK *sciThis); + void CommitThis(char *str); + static void PreeditChanged(GtkIMContext *context, ScintillaGTK *sciThis); + void PreeditChangedThis(); +#endif + static gint StyleSetText(GtkWidget *widget, GtkStyle *previous, void*); + static gint RealizeText(GtkWidget *widget, void*); +#if GLIB_MAJOR_VERSION < 2 + static void Destroy(GtkObject *object); +#else + static void Destroy(GObject *object); +#endif + static void SelectionReceived(GtkWidget *widget, GtkSelectionData *selection_data, + guint time); + static void SelectionGet(GtkWidget *widget, GtkSelectionData *selection_data, + guint info, guint time); + static gint SelectionClear(GtkWidget *widget, GdkEventSelection *selection_event); +#if GTK_MAJOR_VERSION < 2 + static gint SelectionNotify(GtkWidget *widget, GdkEventSelection *selection_event); +#endif + static void DragBegin(GtkWidget *widget, GdkDragContext *context); + gboolean DragMotionThis(GdkDragContext *context, gint x, gint y, guint dragtime); + static gboolean DragMotion(GtkWidget *widget, GdkDragContext *context, + gint x, gint y, guint dragtime); + static void DragLeave(GtkWidget *widget, GdkDragContext *context, + guint time); + static void DragEnd(GtkWidget *widget, GdkDragContext *context); + static gboolean Drop(GtkWidget *widget, GdkDragContext *context, + gint x, gint y, guint time); + static void DragDataReceived(GtkWidget *widget, GdkDragContext *context, + gint x, gint y, GtkSelectionData *selection_data, guint info, guint time); + static void DragDataGet(GtkWidget *widget, GdkDragContext *context, + GtkSelectionData *selection_data, guint info, guint time); + static gint TimeOut(ScintillaGTK *sciThis); + static gint IdleCallback(ScintillaGTK *sciThis); + static void PopUpCB(ScintillaGTK *sciThis, guint action, GtkWidget *widget); + + gint ExposeTextThis(GtkWidget *widget, GdkEventExpose *ose); + static gint ExposeText(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis); + + static gint ExposeCT(GtkWidget *widget, GdkEventExpose *ose, CallTip *ct); + static gint PressCT(GtkWidget *widget, GdkEventButton *event, ScintillaGTK *sciThis); + + static sptr_t DirectFunction(ScintillaGTK *sciThis, + unsigned int iMessage, uptr_t wParam, sptr_t lParam); +}; + +enum { + COMMAND_SIGNAL, + NOTIFY_SIGNAL, + LAST_SIGNAL +}; + +static gint scintilla_signals[LAST_SIGNAL] = { 0 }; +#if GLIB_MAJOR_VERSION < 2 +static GtkWidgetClass *parent_class = NULL; +#endif + +enum { + TARGET_STRING, + TARGET_TEXT, + TARGET_COMPOUND_TEXT, + TARGET_UTF8_STRING, + TARGET_URI +}; + +GdkAtom ScintillaGTK::atomClipboard = 0; +GdkAtom ScintillaGTK::atomUTF8 = 0; +GdkAtom ScintillaGTK::atomString = 0; +GdkAtom ScintillaGTK::atomUriList = 0; +GdkAtom ScintillaGTK::atomDROPFILES_DND = 0; + +static const GtkTargetEntry clipboardCopyTargets[] = { + { "UTF8_STRING", 0, TARGET_UTF8_STRING }, + { "STRING", 0, TARGET_STRING }, +}; +static const gint nClipboardCopyTargets = sizeof(clipboardCopyTargets) / sizeof(clipboardCopyTargets[0]); + +static const GtkTargetEntry clipboardPasteTargets[] = { + { "text/uri-list", 0, TARGET_URI }, + { "UTF8_STRING", 0, TARGET_UTF8_STRING }, + { "STRING", 0, TARGET_STRING }, +}; +static const gint nClipboardPasteTargets = sizeof(clipboardPasteTargets) / sizeof(clipboardPasteTargets[0]); + +static GtkWidget *PWidget(Window &w) { + return reinterpret_cast(w.GetID()); +} + +static ScintillaGTK *ScintillaFromWidget(GtkWidget *widget) { + ScintillaObject *scio = reinterpret_cast(widget); + return reinterpret_cast(scio->pscin); +} + +ScintillaGTK::ScintillaGTK(_ScintillaObject *sci_) : + adjustmentv(0), adjustmenth(0), + scrollBarWidth(30), scrollBarHeight(30), + capturedMouse(false), dragWasDropped(false), + lastKey(0), parentClass(0), +#ifdef INTERNATIONAL_INPUT +#if GTK_MAJOR_VERSION < 2 + ic(NULL), + ic_attr(NULL), +#else + im_context(NULL), +#endif +#endif + lastWheelMouseDirection(0), + wheelMouseIntensity(0), + rgnUpdate(0) { + sci = sci_; + wMain = GTK_WIDGET(sci); + +#if PLAT_GTK_WIN32 + // There does not seem to be a real standard for indicating that the clipboard + // contains a rectangular selection, so copy Developer Studio. + cfColumnSelect = static_cast( + ::RegisterClipboardFormat("MSDEVColumnSelect")); + + // Get intellimouse parameters when running on win32; otherwise use + // reasonable default +#ifndef SPI_GETWHEELSCROLLLINES +#define SPI_GETWHEELSCROLLLINES 104 +#endif + ::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &linesPerScroll, 0); +#else + linesPerScroll = 4; +#endif + lastWheelMouseTime.tv_sec = 0; + lastWheelMouseTime.tv_usec = 0; + + Initialise(); +} + +ScintillaGTK::~ScintillaGTK() { +} + +void ScintillaGTK::RealizeThis(GtkWidget *widget) { + //Platform::DebugPrintf("ScintillaGTK::realize this\n"); + GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED); + GdkWindowAttr attrs; + attrs.window_type = GDK_WINDOW_CHILD; + attrs.x = widget->allocation.x; + attrs.y = widget->allocation.y; + attrs.width = widget->allocation.width; + attrs.height = widget->allocation.height; + attrs.wclass = GDK_INPUT_OUTPUT; + attrs.visual = gtk_widget_get_visual(widget); + attrs.colormap = gtk_widget_get_colormap(widget); + attrs.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK; + GdkCursor *cursor = gdk_cursor_new(GDK_XTERM); + attrs.cursor = cursor; + widget->window = gdk_window_new(gtk_widget_get_parent_window(widget), &attrs, + GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP | GDK_WA_CURSOR); + gdk_window_set_user_data(widget->window, widget); + gdk_window_set_background(widget->window, &widget->style->bg[GTK_STATE_NORMAL]); + gdk_window_show(widget->window); + gdk_cursor_destroy(cursor); + widget->style = gtk_style_attach(widget->style, widget->window); +#ifdef INTERNATIONAL_INPUT +#if GTK_MAJOR_VERSION < 2 + if (gdk_im_ready() && (ic_attr = gdk_ic_attr_new()) != NULL) { + gint width, height; + GdkColormap *colormap; + GdkEventMask mask; + GdkICAttr *attr = ic_attr; + GdkICAttributesType attrmask = GDK_IC_ALL_REQ; + GdkIMStyle style; + GdkIMStyle supported_style = (GdkIMStyle) (GDK_IM_PREEDIT_NONE | + GDK_IM_PREEDIT_NOTHING | + GDK_IM_PREEDIT_POSITION | + GDK_IM_STATUS_NONE | + GDK_IM_STATUS_NOTHING); + + if (widget->style && widget->style->font->type != GDK_FONT_FONTSET) + supported_style = (GdkIMStyle) ((int) supported_style & ~GDK_IM_PREEDIT_POSITION); + + attr->style = style = gdk_im_decide_style(supported_style); + attr->client_window = widget->window; + + if ((colormap = gtk_widget_get_colormap (widget)) != gtk_widget_get_default_colormap ()) { + attrmask = (GdkICAttributesType) ((int) attrmask | GDK_IC_PREEDIT_COLORMAP); + attr->preedit_colormap = colormap; + } + + switch (style & GDK_IM_PREEDIT_MASK) { + case GDK_IM_PREEDIT_POSITION: + if (widget->style && widget->style->font->type != GDK_FONT_FONTSET) { + g_warning("over-the-spot style requires fontset"); + break; + } + + attrmask = (GdkICAttributesType) ((int) attrmask | GDK_IC_PREEDIT_POSITION_REQ); + gdk_window_get_size(widget->window, &width, &height); + attr->spot_location.x = 0; + attr->spot_location.y = height; + attr->preedit_area.x = 0; + attr->preedit_area.y = 0; + attr->preedit_area.width = width; + attr->preedit_area.height = height; + attr->preedit_fontset = widget->style->font; + + break; + } + ic = gdk_ic_new(attr, attrmask); + + if (ic == NULL) { + g_warning("Can't create input context."); + } else { + mask = gdk_window_get_events(widget->window); + mask = (GdkEventMask) ((int) mask | gdk_ic_get_events(ic)); + gdk_window_set_events(widget->window, mask); + + if (GTK_WIDGET_HAS_FOCUS(widget)) + gdk_im_begin(ic, widget->window); + } + } +#else + wPreedit = gtk_window_new(GTK_WINDOW_POPUP); + wPreeditDraw = gtk_drawing_area_new(); + GtkWidget *predrw = PWidget(wPreeditDraw); // No code inside the G_OBJECT macro + g_signal_connect(G_OBJECT(predrw), "expose_event", + G_CALLBACK(ExposePreedit), this); + gtk_container_add(GTK_CONTAINER(PWidget(wPreedit)), predrw); + gtk_widget_realize(PWidget(wPreedit)); + gtk_widget_realize(predrw); + gtk_widget_show(predrw); + + im_context = gtk_im_multicontext_new(); + g_signal_connect(G_OBJECT(im_context), "commit", + G_CALLBACK(Commit), this); + g_signal_connect(G_OBJECT(im_context), "preedit_changed", + G_CALLBACK(PreeditChanged), this); + gtk_im_context_set_client_window(im_context, widget->window); +#endif +#endif + GtkWidget *widtxt = PWidget(wText); // // No code inside the G_OBJECT macro +#if GLIB_MAJOR_VERSION < 2 + gtk_signal_connect_after(GTK_OBJECT(widtxt), "style_set", + GtkSignalFunc(ScintillaGTK::StyleSetText), NULL); + gtk_signal_connect_after(GTK_OBJECT(widtxt), "realize", + GtkSignalFunc(ScintillaGTK::RealizeText), NULL); +#else + g_signal_connect_after(G_OBJECT(widtxt), "style_set", + G_CALLBACK(ScintillaGTK::StyleSetText), NULL); + g_signal_connect_after(G_OBJECT(widtxt), "realize", + G_CALLBACK(ScintillaGTK::RealizeText), NULL); +#endif + gtk_widget_realize(widtxt); + gtk_widget_realize(PWidget(scrollbarv)); + gtk_widget_realize(PWidget(scrollbarh)); +} + +void ScintillaGTK::Realize(GtkWidget *widget) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + sciThis->RealizeThis(widget); +} + +void ScintillaGTK::UnRealizeThis(GtkWidget *widget) { + if (GTK_WIDGET_MAPPED(widget)) { + gtk_widget_unmap(widget); + } + GTK_WIDGET_UNSET_FLAGS(widget, GTK_REALIZED); + gtk_widget_unrealize(PWidget(wText)); + gtk_widget_unrealize(PWidget(scrollbarv)); + gtk_widget_unrealize(PWidget(scrollbarh)); +#ifdef INTERNATIONAL_INPUT +#if GTK_MAJOR_VERSION < 2 + if (ic) { + gdk_ic_destroy(ic); + ic = NULL; + } + if (ic_attr) { + gdk_ic_attr_destroy(ic_attr); + ic_attr = NULL; + } +#else + gtk_widget_unrealize(PWidget(wPreedit)); + gtk_widget_unrealize(PWidget(wPreeditDraw)); + g_object_unref(im_context); + im_context = NULL; +#endif +#endif + if (GTK_WIDGET_CLASS(parentClass)->unrealize) + GTK_WIDGET_CLASS(parentClass)->unrealize(widget); + + Finalise(); +} + +void ScintillaGTK::UnRealize(GtkWidget *widget) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + sciThis->UnRealizeThis(widget); +} + +static void MapWidget(GtkWidget *widget) { + if (widget && + GTK_WIDGET_VISIBLE(widget) && + !GTK_WIDGET_MAPPED(widget)) { + gtk_widget_map(widget); + } +} + +void ScintillaGTK::MapThis() { + //Platform::DebugPrintf("ScintillaGTK::map this\n"); + GTK_WIDGET_SET_FLAGS(PWidget(wMain), GTK_MAPPED); + MapWidget(PWidget(wText)); + MapWidget(PWidget(scrollbarh)); + MapWidget(PWidget(scrollbarv)); + wMain.SetCursor(Window::cursorArrow); + scrollbarv.SetCursor(Window::cursorArrow); + scrollbarh.SetCursor(Window::cursorArrow); + ChangeSize(); + gdk_window_show(PWidget(wMain)->window); +} + +void ScintillaGTK::Map(GtkWidget *widget) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + sciThis->MapThis(); +} + +void ScintillaGTK::UnMapThis() { + //Platform::DebugPrintf("ScintillaGTK::unmap this\n"); + GTK_WIDGET_UNSET_FLAGS(PWidget(wMain), GTK_MAPPED); + DropGraphics(); + gdk_window_hide(PWidget(wMain)->window); + gtk_widget_unmap(PWidget(wText)); + gtk_widget_unmap(PWidget(scrollbarh)); + gtk_widget_unmap(PWidget(scrollbarv)); +} + +void ScintillaGTK::UnMap(GtkWidget *widget) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + sciThis->UnMapThis(); +} + +void ScintillaGTK::ForAll(GtkCallback callback, gpointer callback_data) { + (*callback) (PWidget(wText), callback_data); + (*callback) (PWidget(scrollbarv), callback_data); + (*callback) (PWidget(scrollbarh), callback_data); +} + +void ScintillaGTK::MainForAll(GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data) { + ScintillaGTK *sciThis = ScintillaFromWidget((GtkWidget *)container); + + if (callback != NULL && include_internals) { + sciThis->ForAll(callback, callback_data); + } +} + +#ifdef INTERNATIONAL_INPUT +#if GTK_MAJOR_VERSION < 2 +gint ScintillaGTK::CursorMoved(GtkWidget *widget, int xoffset, int yoffset, ScintillaGTK *sciThis) { + if (GTK_WIDGET_HAS_FOCUS(widget) && gdk_im_ready() && sciThis->ic && + (gdk_ic_get_style(sciThis->ic) & GDK_IM_PREEDIT_POSITION)) { + sciThis->ic_attr->spot_location.x = xoffset; + sciThis->ic_attr->spot_location.y = yoffset; + gdk_ic_set_attr(sciThis->ic, sciThis->ic_attr, GDK_IC_SPOT_LOCATION); + } + return FALSE; +} +#else +gint ScintillaGTK::CursorMoved(GtkWidget *, int xoffset, int yoffset, ScintillaGTK *sciThis) { + GdkRectangle area; + area.x = xoffset; + area.y = yoffset; + area.width = 1; + area.height = 1; + gtk_im_context_set_cursor_location(sciThis->im_context, &area); + return FALSE; +} +#endif +#else +gint ScintillaGTK::CursorMoved(GtkWidget *, int, int, ScintillaGTK *) { + return FALSE; +} +#endif + +gint ScintillaGTK::FocusIn(GtkWidget *widget, GdkEventFocus * /*event*/) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + //Platform::DebugPrintf("ScintillaGTK::focus in %x\n", sciThis); + GTK_WIDGET_SET_FLAGS(widget, GTK_HAS_FOCUS); + sciThis->SetFocusState(true); + +#ifdef INTERNATIONAL_INPUT +#if GTK_MAJOR_VERSION < 2 + if (sciThis->ic) + gdk_im_begin(sciThis->ic, widget->window); +#else + if (sciThis->im_context != NULL) { + gchar *str = NULL; + gint cursor_pos; + + gtk_im_context_get_preedit_string(sciThis->im_context, &str, NULL, &cursor_pos); + if (PWidget(sciThis->wPreedit) != NULL) { + if (strlen(str) > 0) { + gtk_widget_show(PWidget(sciThis->wPreedit)); + } else { + gtk_widget_hide(PWidget(sciThis->wPreedit)); + } + } + g_free(str); + gtk_im_context_focus_in(sciThis->im_context); + } +#endif +#endif + + return FALSE; +} + +gint ScintillaGTK::FocusOut(GtkWidget *widget, GdkEventFocus * /*event*/) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + //Platform::DebugPrintf("ScintillaGTK::focus out %x\n", sciThis); + GTK_WIDGET_UNSET_FLAGS(widget, GTK_HAS_FOCUS); + sciThis->SetFocusState(false); + +#ifdef INTERNATIONAL_INPUT +#if GTK_MAJOR_VERSION < 2 + gdk_im_end(); +#else + if (PWidget(sciThis->wPreedit) != NULL) + gtk_widget_hide(PWidget(sciThis->wPreedit)); + if (sciThis->im_context != NULL) + gtk_im_context_focus_out(sciThis->im_context); +#endif +#endif + + return FALSE; +} + +void ScintillaGTK::SizeRequest(GtkWidget *widget, GtkRequisition *requisition) { + requisition->width = 600; + requisition->height = gdk_screen_height(); + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + GtkRequisition child_requisition; + gtk_widget_size_request(PWidget(sciThis->scrollbarh), &child_requisition); + gtk_widget_size_request(PWidget(sciThis->scrollbarv), &child_requisition); +} + +void ScintillaGTK::SizeAllocate(GtkWidget *widget, GtkAllocation *allocation) { + widget->allocation = *allocation; + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + if (GTK_WIDGET_REALIZED(widget)) + gdk_window_move_resize(widget->window, + widget->allocation.x, + widget->allocation.y, + widget->allocation.width, + widget->allocation.height); + + sciThis->Resize(allocation->width, allocation->height); + +#ifdef INTERNATIONAL_INPUT +#if GTK_MAJOR_VERSION < 2 + if (sciThis->ic && (gdk_ic_get_style(sciThis->ic) & GDK_IM_PREEDIT_POSITION)) { + gint width, height; + + gdk_window_get_size(widget->window, &width, &height); + sciThis->ic_attr->preedit_area.width = width; + sciThis->ic_attr->preedit_area.height = height; + + gdk_ic_set_attr(sciThis->ic, sciThis->ic_attr, GDK_IC_PREEDIT_AREA); + } +#endif +#endif +} + +void ScintillaGTK::Initialise() { + //Platform::DebugPrintf("ScintillaGTK::Initialise\n"); + parentClass = reinterpret_cast( + gtk_type_class(gtk_container_get_type())); + + GTK_WIDGET_SET_FLAGS(PWidget(wMain), GTK_CAN_FOCUS); + GTK_WIDGET_SET_FLAGS(GTK_WIDGET(PWidget(wMain)), GTK_SENSITIVE); + gtk_widget_set_events(PWidget(wMain), + GDK_EXPOSURE_MASK + | GDK_STRUCTURE_MASK + | GDK_KEY_PRESS_MASK + | GDK_KEY_RELEASE_MASK + | GDK_FOCUS_CHANGE_MASK + | GDK_LEAVE_NOTIFY_MASK + | GDK_BUTTON_PRESS_MASK + | GDK_BUTTON_RELEASE_MASK + | GDK_POINTER_MOTION_MASK + | GDK_POINTER_MOTION_HINT_MASK); + + wText = gtk_drawing_area_new(); + gtk_widget_set_parent(PWidget(wText), PWidget(wMain)); + GtkWidget *widtxt = PWidget(wText); // No code inside the G_OBJECT macro + gtk_widget_show(widtxt); +#if GLIB_MAJOR_VERSION < 2 + gtk_signal_connect(GTK_OBJECT(widtxt), "expose_event", + GtkSignalFunc(ScintillaGTK::ExposeText), this); +#else + g_signal_connect(G_OBJECT(widtxt), "expose_event", + G_CALLBACK(ScintillaGTK::ExposeText), this); +#endif + gtk_widget_set_events(widtxt, GDK_EXPOSURE_MASK); +#if GTK_MAJOR_VERSION >= 2 + // Avoid background drawing flash + gtk_widget_set_double_buffered(widtxt, FALSE); +#endif + gtk_drawing_area_size(GTK_DRAWING_AREA(widtxt), + 100,100); + adjustmentv = gtk_adjustment_new(0.0, 0.0, 201.0, 1.0, 20.0, 20.0); + scrollbarv = gtk_vscrollbar_new(GTK_ADJUSTMENT(adjustmentv)); + GTK_WIDGET_UNSET_FLAGS(PWidget(scrollbarv), GTK_CAN_FOCUS); +#if GLIB_MAJOR_VERSION < 2 + gtk_signal_connect(adjustmentv, "value_changed", + GtkSignalFunc(ScrollSignal), this); +#else + g_signal_connect(G_OBJECT(adjustmentv), "value_changed", + G_CALLBACK(ScrollSignal), this); +#endif + gtk_widget_set_parent(PWidget(scrollbarv), PWidget(wMain)); + gtk_widget_show(PWidget(scrollbarv)); + + adjustmenth = gtk_adjustment_new(0.0, 0.0, 101.0, 1.0, 20.0, 20.0); + scrollbarh = gtk_hscrollbar_new(GTK_ADJUSTMENT(adjustmenth)); + GTK_WIDGET_UNSET_FLAGS(PWidget(scrollbarh), GTK_CAN_FOCUS); +#if GLIB_MAJOR_VERSION < 2 + gtk_signal_connect(adjustmenth, "value_changed", + GtkSignalFunc(ScrollHSignal), this); +#else + g_signal_connect(G_OBJECT(adjustmenth), "value_changed", + G_CALLBACK(ScrollHSignal), this); +#endif + gtk_widget_set_parent(PWidget(scrollbarh), PWidget(wMain)); + gtk_widget_show(PWidget(scrollbarh)); + + gtk_widget_grab_focus(PWidget(wMain)); + + gtk_selection_add_targets(GTK_WIDGET(PWidget(wMain)), GDK_SELECTION_PRIMARY, + clipboardCopyTargets, nClipboardCopyTargets); + +#ifndef USE_GTK_CLIPBOARD + gtk_selection_add_targets(GTK_WIDGET(PWidget(wMain)), atomClipboard, + clipboardPasteTargets, nClipboardPasteTargets); +#endif + + gtk_drag_dest_set(GTK_WIDGET(PWidget(wMain)), + GTK_DEST_DEFAULT_ALL, clipboardPasteTargets, nClipboardPasteTargets, + static_cast(GDK_ACTION_COPY | GDK_ACTION_MOVE)); + +#if GLIB_MAJOR_VERSION >= 2 + // Set caret period based on GTK settings + gboolean blinkOn = false; + if (g_object_class_find_property(G_OBJECT_GET_CLASS( + G_OBJECT(gtk_settings_get_default())), "gtk-cursor-blink")) { + g_object_get(G_OBJECT( + gtk_settings_get_default()), "gtk-cursor-blink", &blinkOn, NULL); + } + if (blinkOn && + g_object_class_find_property(G_OBJECT_GET_CLASS( + G_OBJECT(gtk_settings_get_default())), "gtk-cursor-blink-time")) { + gint value; + g_object_get(G_OBJECT( + gtk_settings_get_default()), "gtk-cursor-blink-time", &value, NULL); + caret.period = gint(value / 1.75); + } else { + caret.period = 0; + } +#endif + + SetTicking(true); +} + +void ScintillaGTK::Finalise() { + SetTicking(false); + ScintillaBase::Finalise(); +} + +void ScintillaGTK::DisplayCursor(Window::Cursor c) { + if (cursorMode == SC_CURSORNORMAL) + wText.SetCursor(c); + else + wText.SetCursor(static_cast(cursorMode)); +} + +bool ScintillaGTK::DragThreshold(Point ptStart, Point ptNow) { +#if GTK_MAJOR_VERSION < 2 + return Editor::DragThreshold(ptStart, ptNow); +#else + return gtk_drag_check_threshold(GTK_WIDGET(PWidget(wMain)), + ptStart.x, ptStart.y, ptNow.x, ptNow.y); +#endif +} + +void ScintillaGTK::StartDrag() { + dragWasDropped = false; + inDragDrop = ddDragging; + GtkTargetList *tl = gtk_target_list_new(clipboardCopyTargets, nClipboardCopyTargets); + gtk_drag_begin(GTK_WIDGET(PWidget(wMain)), + tl, + static_cast(GDK_ACTION_COPY | GDK_ACTION_MOVE), + evbtn.button, + reinterpret_cast(&evbtn)); +} + +#ifdef USE_CONVERTER +static char *ConvertText(int *lenResult, char *s, size_t len, const char *charSetDest, + const char *charSetSource, bool transliterations) { + *lenResult = 0; + char *destForm = 0; + Converter conv(charSetDest, charSetSource, transliterations); + if (conv) { + destForm = new char[len*3+1]; + char *pin = s; + size_t inLeft = len; + char *pout = destForm; + size_t outLeft = len*3+1; + size_t conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft); + if (conversions == ((size_t)(-1))) { +fprintf(stderr, "iconv %s->%s failed for %s\n", charSetSource, charSetDest, static_cast(s)); + delete []destForm; + destForm = 0; + } else { +//fprintf(stderr, "iconv OK %s %d\n", destForm, pout - destForm); + *pout = '\0'; + *lenResult = pout - destForm; + } + } else { +fprintf(stderr, "Can not iconv %s %s\n", charSetDest, charSetSource); + } + if (!destForm) { + destForm = new char[1]; + destForm[0] = '\0'; + *lenResult = 0; + } + return destForm; +} +#endif + +// Returns the target converted to UTF8. +// Return the length in bytes. +int ScintillaGTK::TargetAsUTF8(char *text) { + int targetLength = targetEnd - targetStart; + if (IsUnicodeMode()) { + if (text) { + pdoc->GetCharRange(text, targetStart, targetLength); + } + } else { + // Need to convert +#ifdef USE_CONVERTER + const char *charSetBuffer = CharacterSetID(); + if (*charSetBuffer) { +//~ fprintf(stderr, "AsUTF8 %s %d %0d-%0d\n", charSetBuffer, targetLength, targetStart, targetEnd); + char *s = new char[targetLength]; + if (s) { + pdoc->GetCharRange(s, targetStart, targetLength); +//~ fprintf(stderr, " \"%s\"\n", s); + if (text) { + char *tmputf = ConvertText(&targetLength, s, targetLength, "UTF-8", charSetBuffer, false); + memcpy(text, tmputf, targetLength); + delete []tmputf; +//~ fprintf(stderr, " \"%s\"\n", text); + } + delete []s; + } + } else { + if (text) { + pdoc->GetCharRange(text, targetStart, targetLength); + } + } +#else + // Fail + return 0; +#endif + } +//~ fprintf(stderr, "Length = %d bytes\n", targetLength); + return targetLength; +} + +// Translates a nul terminated UTF8 string into the document encoding. +// Return the length of the result in bytes. +int ScintillaGTK::EncodedFromUTF8(char *utf8, char *encoded) { + int inputLength = (lengthForEncode >= 0) ? lengthForEncode : strlen(utf8); + if (IsUnicodeMode()) { + if (encoded) { + memcpy(encoded, utf8, inputLength); + } + return inputLength; + } else { + // Need to convert +#ifdef USE_CONVERTER + const char *charSetBuffer = CharacterSetID(); + if (*charSetBuffer) { +//~ fprintf(stderr, "Encode %s %d\n", charSetBuffer, inputLength); + int outLength = 0; + char *tmpEncoded = ConvertText(&outLength, utf8, inputLength, charSetBuffer, "UTF-8", true); + if (tmpEncoded) { +//~ fprintf(stderr, " \"%s\"\n", tmpEncoded); + if (encoded) { + memcpy(encoded, tmpEncoded, outLength); + } + delete []tmpEncoded; + } + return outLength; + } else { + if (encoded) { + memcpy(encoded, utf8, inputLength); + } + return inputLength; + } +#endif + } + // Fail + return 0; +} + +bool ScintillaGTK::ValidCodePage(int codePage) const { + return codePage == 0 || codePage == SC_CP_UTF8 || codePage == SC_CP_DBCS; +} + +sptr_t ScintillaGTK::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) { + switch (iMessage) { + + case SCI_GRABFOCUS: + gtk_widget_grab_focus(PWidget(wMain)); + break; + + case SCI_GETDIRECTFUNCTION: + return reinterpret_cast(DirectFunction); + + case SCI_GETDIRECTPOINTER: + return reinterpret_cast(this); + +#ifdef SCI_LEXER + case SCI_LOADLEXERLIBRARY: + LexerManager::GetInstance()->Load(reinterpret_cast(wParam)); + break; +#endif + case SCI_TARGETASUTF8: + return TargetAsUTF8(reinterpret_cast(lParam)); + + case SCI_ENCODEDFROMUTF8: + return EncodedFromUTF8(reinterpret_cast(wParam), + reinterpret_cast(lParam)); + + default: + return ScintillaBase::WndProc(iMessage, wParam, lParam); + } + return 0l; +} + +sptr_t ScintillaGTK::DefWndProc(unsigned int, uptr_t, sptr_t) { + return 0; +} + +void ScintillaGTK::SetTicking(bool on) { + if (timer.ticking != on) { + timer.ticking = on; + if (timer.ticking) { + timer.tickerID = reinterpret_cast(gtk_timeout_add(timer.tickSize, (GtkFunction)TimeOut, this)); + } else { + gtk_timeout_remove(GPOINTER_TO_UINT(timer.tickerID)); + } + } + timer.ticksToWait = caret.period; +} + +bool ScintillaGTK::SetIdle(bool on) { + if (on) { + // Start idler, if it's not running. + if (idler.state == false) { + idler.state = true; + idler.idlerID = reinterpret_cast + (gtk_idle_add((GtkFunction)IdleCallback, this)); + } + } else { + // Stop idler, if it's running + if (idler.state == true) { + idler.state = false; + gtk_idle_remove(GPOINTER_TO_UINT(idler.idlerID)); + } + } + return true; +} + +void ScintillaGTK::SetMouseCapture(bool on) { + if (mouseDownCaptures) { + if (on) { + gtk_grab_add(GTK_WIDGET(PWidget(wMain))); + } else { + gtk_grab_remove(GTK_WIDGET(PWidget(wMain))); + } + } + capturedMouse = on; +} + +bool ScintillaGTK::HaveMouseCapture() { + return capturedMouse; +} + +bool ScintillaGTK::PaintContains(PRectangle rc) { + bool contains = true; + if (paintState == painting) { + if (!rcPaint.Contains(rc)) { + contains = false; + } else if (rgnUpdate) { + GdkRectangle grc = {rc.left, rc.top, + rc.right - rc.left, rc.bottom - rc.top}; + if (gdk_region_rect_in(rgnUpdate, &grc) != GDK_OVERLAP_RECTANGLE_IN) { + contains = false; + } + } + } + return contains; +} + +// Redraw all of text area. This paint will not be abandoned. +void ScintillaGTK::FullPaint() { +#if GTK_MAJOR_VERSION < 2 + paintState = painting; + rcPaint = GetClientRectangle(); + //Platform::DebugPrintf("ScintillaGTK::FullPaint %0d,%0d %0d,%0d\n", + // rcPaint.left, rcPaint.top, rcPaint.right, rcPaint.bottom); + paintingAllText = true; + if ((PWidget(wText))->window) { + Surface *sw = Surface::Allocate(); + if (sw) { + sw->Init(PWidget(wText)->window, PWidget(wText)); + Paint(sw, rcPaint); + sw->Release(); + delete sw; + } + } + paintState = notPainting; +#else + wText.InvalidateAll(); +#endif +} + +PRectangle ScintillaGTK::GetClientRectangle() { + PRectangle rc = wMain.GetClientPosition(); + if (verticalScrollBarVisible) + rc.right -= scrollBarWidth; + if (horizontalScrollBarVisible && (wrapState == eWrapNone)) + rc.bottom -= scrollBarHeight; + // Move to origin + rc.right -= rc.left; + rc.bottom -= rc.top; + rc.left = 0; + rc.top = 0; + return rc; +} + +// Synchronously paint a rectangle of the window. +void ScintillaGTK::SyncPaint(PRectangle rc) { + paintState = painting; + rcPaint = rc; + PRectangle rcClient = GetClientRectangle(); + paintingAllText = rcPaint.Contains(rcClient); + if ((PWidget(wText))->window) { + Surface *sw = Surface::Allocate(); + if (sw) { + sw->Init(PWidget(wText)->window, PWidget(wText)); + Paint(sw, rc); + sw->Release(); + delete sw; + } + } + if (paintState == paintAbandoned) { + // Painting area was insufficient to cover new styling or brace highlight positions + FullPaint(); + } + paintState = notPainting; +} + +void ScintillaGTK::ScrollText(int linesToMove) { + int diff = vs.lineHeight * -linesToMove; + //Platform::DebugPrintf("ScintillaGTK::ScrollText %d %d %0d,%0d %0d,%0d\n", linesToMove, diff, + // rc.left, rc.top, rc.right, rc.bottom); + GtkWidget *wi = PWidget(wText); + +#if GTK_MAJOR_VERSION < 2 + PRectangle rc = GetClientRectangle(); + GdkGC *gc = gdk_gc_new(wi->window); + + // Set up gc so we get GraphicsExposures from gdk_draw_pixmap + // which calls XCopyArea + gdk_gc_set_exposures(gc, TRUE); + + // Redraw exposed bit : scrolling upwards + if (diff > 0) { + gdk_draw_pixmap(wi->window, + gc, wi->window, + 0, diff, + 0, 0, + rc.Width()-1, rc.Height() - diff); + SyncPaint(PRectangle(0, rc.Height() - diff, + rc.Width(), rc.Height()+1)); + + // Redraw exposed bit : scrolling downwards + } else { + gdk_draw_pixmap(wi->window, + gc, wi->window, + 0, 0, + 0, -diff, + rc.Width()-1, rc.Height() + diff); + SyncPaint(PRectangle(0, 0, rc.Width(), -diff)); + } + + // Look for any graphics expose + GdkEvent* event; + while ((event = gdk_event_get_graphics_expose(wi->window)) != NULL) { + gtk_widget_event(wi, event); + if (event->expose.count == 0) { + gdk_event_free(event); + break; + } + gdk_event_free(event); + } + + gdk_gc_unref(gc); +#else + gdk_window_scroll(wi->window, 0, -diff); + gdk_window_process_updates(wi->window, FALSE); +#endif +} + +void ScintillaGTK::SetVerticalScrollPos() { + DwellEnd(true); + gtk_adjustment_set_value(GTK_ADJUSTMENT(adjustmentv), topLine); +} + +void ScintillaGTK::SetHorizontalScrollPos() { + DwellEnd(true); + gtk_adjustment_set_value(GTK_ADJUSTMENT(adjustmenth), xOffset / 2); +} + +bool ScintillaGTK::ModifyScrollBars(int nMax, int nPage) { + bool modified = false; + int pageScroll = LinesToScroll(); + + if (GTK_ADJUSTMENT(adjustmentv)->upper != (nMax + 1) || + GTK_ADJUSTMENT(adjustmentv)->page_size != nPage || + GTK_ADJUSTMENT(adjustmentv)->page_increment != pageScroll) { + GTK_ADJUSTMENT(adjustmentv)->upper = nMax + 1; + GTK_ADJUSTMENT(adjustmentv)->page_size = nPage; + GTK_ADJUSTMENT(adjustmentv)->page_increment = pageScroll; + gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmentv)); + modified = true; + } + + PRectangle rcText = GetTextRectangle(); + int horizEndPreferred = scrollWidth; + if (horizEndPreferred < 0) + horizEndPreferred = 0; + unsigned int pageWidth = rcText.Width(); + unsigned int pageIncrement = pageWidth / 3; + unsigned int charWidth = vs.styles[STYLE_DEFAULT].aveCharWidth; + if (GTK_ADJUSTMENT(adjustmenth)->upper != horizEndPreferred || + GTK_ADJUSTMENT(adjustmenth)->page_size != pageWidth || + GTK_ADJUSTMENT(adjustmenth)->page_increment != pageIncrement || + GTK_ADJUSTMENT(adjustmenth)->step_increment != charWidth) { + GTK_ADJUSTMENT(adjustmenth)->upper = horizEndPreferred; + GTK_ADJUSTMENT(adjustmenth)->step_increment = charWidth; + GTK_ADJUSTMENT(adjustmenth)->page_size = pageWidth; + GTK_ADJUSTMENT(adjustmenth)->page_increment = pageIncrement; + gtk_adjustment_changed(GTK_ADJUSTMENT(adjustmenth)); + modified = true; + } + return modified; +} + +void ScintillaGTK::ReconfigureScrollBars() { + PRectangle rc = wMain.GetClientPosition(); + Resize(rc.Width(), rc.Height()); +} + +void ScintillaGTK::NotifyChange() { +#if GLIB_MAJOR_VERSION < 2 + gtk_signal_emit(GTK_OBJECT(sci), scintilla_signals[COMMAND_SIGNAL], + Platform::LongFromTwoShorts(GetCtrlID(), SCEN_CHANGE), PWidget(wMain)); +#else + g_signal_emit(G_OBJECT(sci), scintilla_signals[COMMAND_SIGNAL], 0, + Platform::LongFromTwoShorts(GetCtrlID(), SCEN_CHANGE), PWidget(wMain)); +#endif +} + +void ScintillaGTK::NotifyFocus(bool focus) { +#if GLIB_MAJOR_VERSION < 2 + gtk_signal_emit(GTK_OBJECT(sci), scintilla_signals[COMMAND_SIGNAL], + Platform::LongFromTwoShorts + (GetCtrlID(), focus ? SCEN_SETFOCUS : SCEN_KILLFOCUS), PWidget(wMain)); +#else + g_signal_emit(G_OBJECT(sci), scintilla_signals[COMMAND_SIGNAL], 0, + Platform::LongFromTwoShorts + (GetCtrlID(), focus ? SCEN_SETFOCUS : SCEN_KILLFOCUS), PWidget(wMain)); +#endif +} + +void ScintillaGTK::NotifyParent(SCNotification scn) { + scn.nmhdr.hwndFrom = PWidget(wMain); + scn.nmhdr.idFrom = GetCtrlID(); +#if GLIB_MAJOR_VERSION < 2 + gtk_signal_emit(GTK_OBJECT(sci), scintilla_signals[NOTIFY_SIGNAL], + GetCtrlID(), &scn); +#else + g_signal_emit(G_OBJECT(sci), scintilla_signals[NOTIFY_SIGNAL], 0, + GetCtrlID(), &scn); +#endif +} + +void ScintillaGTK::NotifyKey(int key, int modifiers) { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_KEY; + scn.ch = key; + scn.modifiers = modifiers; + + NotifyParent(scn); +} + +void ScintillaGTK::NotifyURIDropped(const char *list) { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_URIDROPPED; + scn.text = list; + + NotifyParent(scn); +} + +const char *CharacterSetID(int characterSet); + +const char *ScintillaGTK::CharacterSetID() const { + return ::CharacterSetID(vs.styles[STYLE_DEFAULT].characterSet); +} + +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); +} + +void ScintillaGTK::CopyToClipboard(const SelectionText &selectedText) { +#ifndef USE_GTK_CLIPBOARD + copyText.Copy(selectedText); + gtk_selection_owner_set(GTK_WIDGET(PWidget(wMain)), + atomClipboard, + GDK_CURRENT_TIME); +#else + SelectionText *clipText = new SelectionText(); + clipText->Copy(selectedText); + StoreOnClipboard(clipText); +#endif +} + +void ScintillaGTK::Copy() { + if (currentPos != anchor) { +#ifndef USE_GTK_CLIPBOARD + CopySelectionRange(©Text); + gtk_selection_owner_set(GTK_WIDGET(PWidget(wMain)), + atomClipboard, + GDK_CURRENT_TIME); +#else + SelectionText *clipText = new SelectionText(); + CopySelectionRange(clipText); + StoreOnClipboard(clipText); +#endif +#if PLAT_GTK_WIN32 + if (selType == selRectangle) { + ::OpenClipboard(NULL); + ::SetClipboardData(cfColumnSelect, 0); + ::CloseClipboard(); + } +#endif + } +} + +void ScintillaGTK::Paste() { + atomSought = atomUTF8; + gtk_selection_convert(GTK_WIDGET(PWidget(wMain)), + atomClipboard, atomSought, GDK_CURRENT_TIME); +} + +void ScintillaGTK::CreateCallTipWindow(PRectangle rc) { + if (!ct.wCallTip.Created()) { + ct.wCallTip = gtk_window_new(GTK_WINDOW_POPUP); + ct.wDraw = gtk_drawing_area_new(); + GtkWidget *widcdrw = PWidget(ct.wDraw); // // No code inside the G_OBJECT macro + gtk_container_add(GTK_CONTAINER(PWidget(ct.wCallTip)), widcdrw); +#if GLIB_MAJOR_VERSION < 2 + gtk_signal_connect(GTK_OBJECT(widcdrw), "expose_event", + GtkSignalFunc(ScintillaGTK::ExposeCT), &ct); + gtk_signal_connect(GTK_OBJECT(widcdrw), "button_press_event", + GtkSignalFunc(ScintillaGTK::PressCT), static_cast(this)); +#else + g_signal_connect(G_OBJECT(widcdrw), "expose_event", + G_CALLBACK(ScintillaGTK::ExposeCT), &ct); + g_signal_connect(G_OBJECT(widcdrw), "button_press_event", + G_CALLBACK(ScintillaGTK::PressCT), static_cast(this)); +#endif + gtk_widget_set_events(widcdrw, + GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK); + } + gtk_drawing_area_size(GTK_DRAWING_AREA(PWidget(ct.wDraw)), + rc.Width(), rc.Height()); + ct.wDraw.Show(); + if (PWidget(ct.wCallTip)->window) { + gdk_window_resize(PWidget(ct.wCallTip)->window, rc.Width(), rc.Height()); + } +} + +void ScintillaGTK::AddToPopUp(const char *label, int cmd, bool enabled) { + char fulllabel[200]; + strcpy(fulllabel, "/"); + strcat(fulllabel, label); + GtkItemFactoryCallback menuSig = GtkItemFactoryCallback(PopUpCB); + GtkItemFactoryEntry itemEntry = { + fulllabel, NULL, + menuSig, + cmd, + const_cast(label[0] ? "" : ""), +#if GTK_MAJOR_VERSION >= 2 + NULL +#endif + }; + gtk_item_factory_create_item(GTK_ITEM_FACTORY(popup.GetID()), + &itemEntry, this, 1); + if (cmd) { + GtkWidget *item = gtk_item_factory_get_widget_by_action( + reinterpret_cast(popup.GetID()), cmd); + if (item) + gtk_widget_set_sensitive(item, enabled); + } +} + +bool ScintillaGTK::OwnPrimarySelection() { + return ((gdk_selection_owner_get(GDK_SELECTION_PRIMARY) + == GTK_WIDGET(PWidget(wMain))->window) && + (GTK_WIDGET(PWidget(wMain))->window != NULL)); +} + +void ScintillaGTK::ClaimSelection() { + // X Windows has a 'primary selection' as well as the clipboard. + // Whenever the user selects some text, we become the primary selection + if (currentPos != anchor && GTK_WIDGET_REALIZED(GTK_WIDGET(PWidget(wMain)))) { + primarySelection = true; + gtk_selection_owner_set(GTK_WIDGET(PWidget(wMain)), + GDK_SELECTION_PRIMARY, GDK_CURRENT_TIME); + primary.Free(); + } else if (OwnPrimarySelection()) { + primarySelection = true; + if (primary.s == NULL) + gtk_selection_owner_set(NULL, GDK_SELECTION_PRIMARY, GDK_CURRENT_TIME); + } else { + primarySelection = false; + primary.Free(); + } +} + +// Detect rectangular text, convert line ends to current mode, convert from or to UTF-8 +void ScintillaGTK::GetGtkSelectionText(GtkSelectionData *selectionData, SelectionText &selText) { + char *data = reinterpret_cast(selectionData->data); + int len = selectionData->length; + GdkAtom selectionType = selectionData->type; + + // Return empty string if selection is not a string + if ((selectionType != GDK_TARGET_STRING) && (selectionType != atomUTF8)) { + char *empty = new char[1]; + empty[0] = '\0'; + selText.Set(empty, 0, SC_CP_UTF8, 0, false, false); + return; + } + + // Check for "\n\0" ending to string indicating that selection is rectangular + bool isRectangular; +#if PLAT_GTK_WIN32 + isRectangular = ::IsClipboardFormatAvailable(cfColumnSelect) != 0; +#else + isRectangular = ((len > 2) && (data[len - 1] == 0 && data[len - 2] == '\n')); +#endif + + char *dest; + if (selectionType == GDK_TARGET_STRING) { + dest = Document::TransformLineEnds(&len, data, len, pdoc->eolMode); + if (IsUnicodeMode()) { + // Unknown encoding so assume in Latin1 + char *destPrevious = dest; + dest = UTF8FromLatin1(dest, len); + selText.Set(dest, len, SC_CP_UTF8, 0, selText.rectangular, false); + delete []destPrevious; + } else { + // Assume buffer is in same encoding as selection + selText.Set(dest, len, pdoc->dbcsCodePage, + vs.styles[STYLE_DEFAULT].characterSet, isRectangular, false); + } + } else { // UTF-8 + dest = Document::TransformLineEnds(&len, data, len, pdoc->eolMode); + selText.Set(dest, len, SC_CP_UTF8, 0, isRectangular, false); +#ifdef USE_CONVERTER + const char *charSetBuffer = CharacterSetID(); + if (!IsUnicodeMode() && *charSetBuffer) { +//fprintf(stderr, "Convert to locale %s\n", CharacterSetID()); + // Convert to locale + dest = ConvertText(&len, selText.s, selText.len, charSetBuffer, "UTF-8", true); + selText.Set(dest, len, pdoc->dbcsCodePage, + vs.styles[STYLE_DEFAULT].characterSet, selText.rectangular, false); + } +#endif + } +} + +void ScintillaGTK::ReceivedSelection(GtkSelectionData *selection_data) { + if ((selection_data->selection == atomClipboard) || + (selection_data->selection == GDK_SELECTION_PRIMARY)) { + if ((atomSought == atomUTF8) && (selection_data->length <= 0)) { + atomSought = atomString; + gtk_selection_convert(GTK_WIDGET(PWidget(wMain)), + selection_data->selection, atomSought, GDK_CURRENT_TIME); + } else if ((selection_data->length > 0) && + ((selection_data->type == GDK_TARGET_STRING) || (selection_data->type == atomUTF8))) { + SelectionText selText; + GetGtkSelectionText(selection_data, selText); + + pdoc->BeginUndoAction(); + if (selection_data->selection != GDK_SELECTION_PRIMARY) { + ClearSelection(); + } + int selStart = SelectionStart(); + + if (selText.rectangular) { + PasteRectangular(selStart, selText.s, selText.len); + } else { + pdoc->InsertString(currentPos, selText.s, selText.len); + SetEmptySelection(currentPos + selText.len); + } + pdoc->EndUndoAction(); + EnsureCaretVisible(); + } + } +// else fprintf(stderr, "Target non string %d %d\n", (int)(selection_data->type), +// (int)(atomUTF8)); + Redraw(); +} + +void ScintillaGTK::ReceivedDrop(GtkSelectionData *selection_data) { + dragWasDropped = true; + if (selection_data->type == atomUriList || selection_data->type == atomDROPFILES_DND) { + char *ptr = new char[selection_data->length + 1]; + ptr[selection_data->length] = '\0'; + memcpy(ptr, selection_data->data, selection_data->length); + NotifyURIDropped(ptr); + delete []ptr; + } else if ((selection_data->type == GDK_TARGET_STRING) || (selection_data->type == atomUTF8)) { + if (selection_data->length > 0) { + SelectionText selText; + GetGtkSelectionText(selection_data, selText); + DropAt(posDrop, selText.s, false, selText.rectangular); + } + } else if (selection_data->length > 0) { + //~ fprintf(stderr, "ReceivedDrop other %p\n", static_cast(selection_data->type)); + } + Redraw(); +} + + + +void ScintillaGTK::GetSelection(GtkSelectionData *selection_data, guint info, SelectionText *text) { +#if PLAT_GTK_WIN32 + // Many native win32 programs require \n line endings, so make a copy of + // the clip text now with newlines converted. Use { } to hide symbols + // from code below + SelectionText *newline_normalized = NULL; + { + int tmpstr_len; + char *tmpstr = Document::TransformLineEnds(&tmpstr_len, text->s, text->len, SC_EOL_LF); + newline_normalized = new SelectionText(); + newline_normalized->Set(tmpstr, tmpstr_len, SC_CP_UTF8, 0, text->rectangular, false); + text = newline_normalized; + } +#endif + +#if GTK_MAJOR_VERSION >= 2 + // Convert text to utf8 if it isn't already + SelectionText *converted = 0; + if ((text->codePage != SC_CP_UTF8) && (info == TARGET_UTF8_STRING)) { + const char *charSet = ::CharacterSetID(text->characterSet); + if (*charSet) { + int new_len; + char* tmputf = ConvertText(&new_len, text->s, text->len, "UTF-8", charSet, false); + converted = new SelectionText(); + converted->Set(tmputf, new_len, SC_CP_UTF8, 0, text->rectangular, false); + text = converted; + } + } + + // Here is a somewhat evil kludge. + // As I can not work out how to store data on the clipboard in multiple formats + // and need some way to mark the clipping as being stream or rectangular, + // the terminating \0 is included in the length for rectangular clippings. + // All other tested aplications behave benignly by ignoring the \0. + // The #if is here because on Windows cfColumnSelect clip entry is used + // instead as standard indicator of rectangularness (so no need to kludge) + int len = strlen(text->s); +#if PLAT_GTK_WIN32 == 0 + if (text->rectangular) + len++; +#endif + + if (info == TARGET_UTF8_STRING) { + gtk_selection_data_set_text(selection_data, text->s, len); + } else { + gtk_selection_data_set(selection_data, + static_cast(GDK_SELECTION_TYPE_STRING), + 8, reinterpret_cast(text->s), len); + } + delete converted; + +#else /* Gtk 1 */ + char *selBuffer = text->s; + + char *tmputf = 0; + if ((info == TARGET_UTF8_STRING) || (info == TARGET_STRING)) { + int len = strlen(selBuffer); +#ifdef USE_CONVERTER + // Possible character set conversion + const char *charSetBuffer = ::CharacterSetID(text->characterSet); + if (info == TARGET_UTF8_STRING) { + //fprintf(stderr, "Copy to clipboard as UTF-8\n"); + if (text->codePage != SC_CP_UTF8) { + // Convert to UTF-8 + //fprintf(stderr, "Convert to UTF-8 from %s\n", charSetBuffer); + tmputf = ConvertText(&len, selBuffer, len, "UTF-8", charSetBuffer, false); + selBuffer = tmputf; + } + } else if (info == TARGET_STRING) { + if (text->codePage == SC_CP_UTF8) { + //fprintf(stderr, "Convert to locale %s\n", charSetBuffer); + // Convert to locale + tmputf = ConvertText(&len, selBuffer, len, charSetBuffer, "UTF-8", true); + selBuffer = tmputf; + } + } +#endif + + // Here is a somewhat evil kludge. + // As I can not work out how to store data on the clipboard in multiple formats + // and need some way to mark the clipping as being stream or rectangular, + // the terminating \0 is included in the length for rectangular clippings. + // All other tested aplications behave benignly by ignoring the \0. + // The #if is here because on Windows cfColumnSelect clip entry is used + // instead as standard indicator of rectangularness (so no need to kludge) +#if PLAT_GTK_WIN32 == 0 + if (text->rectangular) + len++; +#endif + gtk_selection_data_set(selection_data, + (info == TARGET_STRING) ? + static_cast(GDK_SELECTION_TYPE_STRING) : atomUTF8, + 8, reinterpret_cast(selBuffer), + len); + } else if ((info == TARGET_TEXT) || (info == TARGET_COMPOUND_TEXT)) { + guchar *text; + GdkAtom encoding; + gint format; + gint new_length; + + gdk_string_to_compound_text(reinterpret_cast(selBuffer), + &encoding, &format, &text, &new_length); + gtk_selection_data_set(selection_data, encoding, format, text, new_length); + gdk_free_compound_text(text); + } + + delete []tmputf; +#endif /* Gtk >= 2 */ + +#if PLAT_GTK_WIN32 + delete newline_normalized; +#endif +} + +#ifdef USE_GTK_CLIPBOARD +void ScintillaGTK::StoreOnClipboard(SelectionText *clipText) { + GtkClipboard *clipBoard = + gtk_widget_get_clipboard(GTK_WIDGET(PWidget(wMain)), atomClipboard); + if (clipBoard == NULL) // Occurs if widget isn't in a toplevel + return; + + if (gtk_clipboard_set_with_data(clipBoard, clipboardCopyTargets, nClipboardCopyTargets, + ClipboardGetSelection, ClipboardClearSelection, clipText)) { + gtk_clipboard_set_can_store(clipBoard, clipboardCopyTargets, nClipboardCopyTargets); + } +} + +void ScintillaGTK::ClipboardGetSelection(GtkClipboard *, GtkSelectionData *selection_data, guint info, void *data) { + GetSelection(selection_data, info, static_cast(data)); +} + +void ScintillaGTK::ClipboardClearSelection(GtkClipboard *, void *data) { + SelectionText *obj = static_cast(data); + delete obj; +} +#endif + +void ScintillaGTK::UnclaimSelection(GdkEventSelection *selection_event) { + //Platform::DebugPrintf("UnclaimSelection\n"); + if (selection_event->selection == GDK_SELECTION_PRIMARY) { + //Platform::DebugPrintf("UnclaimPrimarySelection\n"); + if (!OwnPrimarySelection()) { + primary.Free(); + primarySelection = false; + FullPaint(); + } + } +} + +void ScintillaGTK::Resize(int width, int height) { + //Platform::DebugPrintf("Resize %d %d\n", width, height); + //printf("Resize %d %d\n", width, height); + + // Not always needed, but some themes can have different sizes of scrollbars + scrollBarWidth = GTK_WIDGET(PWidget(scrollbarv))->requisition.width; + scrollBarHeight = GTK_WIDGET(PWidget(scrollbarh))->requisition.height; + + // These allocations should never produce negative sizes as they would wrap around to huge + // unsigned numbers inside GTK+ causing warnings. + bool showSBHorizontal = horizontalScrollBarVisible && (wrapState == eWrapNone); + int horizontalScrollBarHeight = scrollBarHeight; + if (!showSBHorizontal) + horizontalScrollBarHeight = 0; + int verticalScrollBarHeight = scrollBarWidth; + if (!verticalScrollBarVisible) + verticalScrollBarHeight = 0; + + GtkAllocation alloc; + if (showSBHorizontal) { + gtk_widget_show(GTK_WIDGET(PWidget(scrollbarh))); + alloc.x = 0; + alloc.y = height - scrollBarHeight; + alloc.width = Platform::Maximum(1, width - scrollBarWidth) + 1; + alloc.height = horizontalScrollBarHeight; + gtk_widget_size_allocate(GTK_WIDGET(PWidget(scrollbarh)), &alloc); + } else { + gtk_widget_hide(GTK_WIDGET(PWidget(scrollbarh))); + } + + if (verticalScrollBarVisible) { + gtk_widget_show(GTK_WIDGET(PWidget(scrollbarv))); + alloc.x = width - scrollBarWidth; + alloc.y = 0; + alloc.width = scrollBarWidth; + alloc.height = Platform::Maximum(1, height - scrollBarHeight) + 1; + if (!showSBHorizontal) + alloc.height += scrollBarWidth-1; + gtk_widget_size_allocate(GTK_WIDGET(PWidget(scrollbarv)), &alloc); + } else { + gtk_widget_hide(GTK_WIDGET(PWidget(scrollbarv))); + } + if (GTK_WIDGET_MAPPED(PWidget(wMain))) { + ChangeSize(); + } + + alloc.x = 0; + alloc.y = 0; + alloc.width = Platform::Maximum(1, width - scrollBarWidth); + alloc.height = Platform::Maximum(1, height - scrollBarHeight); + if (!showSBHorizontal) + alloc.height += scrollBarHeight; + if (!verticalScrollBarVisible) + alloc.width += scrollBarWidth; + gtk_widget_size_allocate(GTK_WIDGET(PWidget(wText)), &alloc); +} + +static void SetAdjustmentValue(GtkObject *object, int value) { + GtkAdjustment *adjustment = GTK_ADJUSTMENT(object); + int maxValue = static_cast( + adjustment->upper - adjustment->page_size); + if (value > maxValue) + value = maxValue; + if (value < 0) + value = 0; + gtk_adjustment_set_value(adjustment, value); +} + +gint ScintillaGTK::PressThis(GdkEventButton *event) { + //Platform::DebugPrintf("Press %x time=%d state = %x button = %x\n",this,event->time, event->state, event->button); + // Do not use GTK+ double click events as Scintilla has its own double click detection + if (event->type != GDK_BUTTON_PRESS) + return FALSE; + + evbtn = *event; + Point pt; + pt.x = int(event->x); + pt.y = int(event->y); + PRectangle rcClient = GetClientRectangle(); + //Platform::DebugPrintf("Press %0d,%0d in %0d,%0d %0d,%0d\n", + // pt.x, pt.y, rcClient.left, rcClient.top, rcClient.right, rcClient.bottom); + if ((pt.x > rcClient.right) || (pt.y > rcClient.bottom)) { + Platform::DebugPrintf("Bad location\n"); + return FALSE; + } + + bool ctrl = (event->state & GDK_CONTROL_MASK) != 0; + + gtk_widget_grab_focus(PWidget(wMain)); + if (event->button == 1) { + // On X, instead of sending literal modifiers use control instead of alt + // This is because most X window managers grab alt + click for moving +#if !PLAT_GTK_WIN32 + ButtonDown(pt, event->time, + (event->state & GDK_SHIFT_MASK) != 0, + (event->state & GDK_CONTROL_MASK) != 0, + (event->state & GDK_CONTROL_MASK) != 0); +#else + ButtonDown(pt, event->time, + (event->state & GDK_SHIFT_MASK) != 0, + (event->state & GDK_CONTROL_MASK) != 0, + (event->state & GDK_MOD1_MASK) != 0); +#endif + } else if (event->button == 2) { + // Grab the primary selection if it exists + Position pos = PositionFromLocation(pt); + if (OwnPrimarySelection() && primary.s == NULL) + CopySelectionRange(&primary); + + SetSelection(pos, pos); + atomSought = atomUTF8; + gtk_selection_convert(GTK_WIDGET(PWidget(wMain)), GDK_SELECTION_PRIMARY, + atomSought, event->time); + } else if (event->button == 3) { + if (displayPopupMenu) { + // PopUp menu + // Convert to screen + int ox = 0; + int oy = 0; + gdk_window_get_origin(PWidget(wMain)->window, &ox, &oy); + ContextMenu(Point(pt.x + ox, pt.y + oy)); + } else { + return FALSE; + } + } else if (event->button == 4) { + // Wheel scrolling up (only GTK 1.x does it this way) + if (ctrl) + SetAdjustmentValue(adjustmenth, (xOffset / 2) - 6); + else + SetAdjustmentValue(adjustmentv, topLine - 3); + } else if (event->button == 5) { + // Wheel scrolling down (only GTK 1.x does it this way) + if (ctrl) + SetAdjustmentValue(adjustmenth, (xOffset / 2) + 6); + else + SetAdjustmentValue(adjustmentv, topLine + 3); + } +#if GTK_MAJOR_VERSION >= 2 + return TRUE; +#else + return FALSE; +#endif +} + +gint ScintillaGTK::Press(GtkWidget *widget, GdkEventButton *event) { + if (event->window != widget->window) + return FALSE; + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + return sciThis->PressThis(event); +} + +gint ScintillaGTK::MouseRelease(GtkWidget *widget, GdkEventButton *event) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + //Platform::DebugPrintf("Release %x %d %d\n",sciThis,event->time,event->state); + if (!sciThis->HaveMouseCapture()) + return FALSE; + if (event->button == 1) { + Point pt; + pt.x = int(event->x); + pt.y = int(event->y); + //Platform::DebugPrintf("Up %x %x %d %d %d\n", + // sciThis,event->window,event->time, pt.x, pt.y); + if (event->window != PWidget(sciThis->wMain)->window) + // If mouse released on scroll bar then the position is relative to the + // scrollbar, not the drawing window so just repeat the most recent point. + pt = sciThis->ptMouseLast; + sciThis->ButtonUp(pt, event->time, (event->state & 4) != 0); + } + return FALSE; +} + +// win32gtk and GTK >= 2 use SCROLL_* events instead of passing the +// button4/5/6/7 events to the GTK app +#if PLAT_GTK_WIN32 || (GTK_MAJOR_VERSION >= 2) +gint ScintillaGTK::ScrollEvent(GtkWidget *widget, + GdkEventScroll *event) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + + if (widget == NULL || event == NULL) + return FALSE; + + // Compute amount and direction to scroll (even tho on win32 there is + // intensity of scrolling info in the native message, gtk doesn't + // support this so we simulate similarly adaptive scrolling) + // Note that this is disabled on OS X (Darwin) where the X11 server already has + // and adaptive scrolling algorithm that fights with this one + int cLineScroll; +#if defined(__MWERKS__) || defined(__APPLE_CPP__) || defined(__APPLE_CC__) + cLineScroll = sciThis->linesPerScroll; + if (cLineScroll == 0) + cLineScroll = 4; + sciThis->wheelMouseIntensity = cLineScroll; +#else + int timeDelta = 1000000; + GTimeVal curTime; + g_get_current_time(&curTime); + if (curTime.tv_sec == sciThis->lastWheelMouseTime.tv_sec) + timeDelta = curTime.tv_usec - sciThis->lastWheelMouseTime.tv_usec; + else if (curTime.tv_sec == sciThis->lastWheelMouseTime.tv_sec + 1) + timeDelta = 1000000 + (curTime.tv_usec - sciThis->lastWheelMouseTime.tv_usec); + if ((event->direction == sciThis->lastWheelMouseDirection) && (timeDelta < 250000)) { + if (sciThis->wheelMouseIntensity < 12) + sciThis->wheelMouseIntensity++; + cLineScroll = sciThis->wheelMouseIntensity; + } else { + cLineScroll = sciThis->linesPerScroll; + if (cLineScroll == 0) + cLineScroll = 4; + sciThis->wheelMouseIntensity = cLineScroll; + } +#endif + if (event->direction == GDK_SCROLL_UP || event->direction == GDK_SCROLL_LEFT) { + cLineScroll *= -1; + } + g_get_current_time(&sciThis->lastWheelMouseTime); + sciThis->lastWheelMouseDirection = event->direction; + + // Note: Unpatched versions of win32gtk don't set the 'state' value so + // only regular scrolling is supported there. Also, unpatched win32gtk + // issues spurious button 2 mouse events during wheeling, which can cause + // problems (a patch for both was submitted by archaeopteryx.com on 13Jun2001) + + // Data zoom not supported + if (event->state & GDK_SHIFT_MASK) { + return FALSE; + } + + // Horizontal scrolling + if (event->direction == GDK_SCROLL_LEFT || event->direction == GDK_SCROLL_RIGHT) { + sciThis->HorizontalScrollTo(sciThis->xOffset + cLineScroll); + + // Text font size zoom + } else if (event->state & GDK_CONTROL_MASK) { + if (cLineScroll < 0) { + sciThis->KeyCommand(SCI_ZOOMIN); + } else { + sciThis->KeyCommand(SCI_ZOOMOUT); + } + + // Regular scrolling + } else { + sciThis->ScrollTo(sciThis->topLine + cLineScroll); + } + return TRUE; +} +#endif + +gint ScintillaGTK::Motion(GtkWidget *widget, GdkEventMotion *event) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + //Platform::DebugPrintf("Motion %x %d\n",sciThis,event->time); + if (event->window != widget->window) + return FALSE; + int x = 0; + int y = 0; + GdkModifierType state; + if (event->is_hint) { + gdk_window_get_pointer(event->window, &x, &y, &state); + } else { + x = static_cast(event->x); + y = static_cast(event->y); + state = static_cast(event->state); + } + //Platform::DebugPrintf("Move %x %x %d %c %d %d\n", + // sciThis,event->window,event->time,event->is_hint? 'h' :'.', x, y); + Point pt(x, y); + sciThis->ButtonMove(pt); + return FALSE; +} + +// Map the keypad keys to their equivalent functions +static int KeyTranslate(int keyIn) { + switch (keyIn) { + case GDK_ISO_Left_Tab: + return SCK_TAB; + case GDK_KP_Down: + return SCK_DOWN; + case GDK_KP_Up: + return SCK_UP; + case GDK_KP_Left: + return SCK_LEFT; + case GDK_KP_Right: + return SCK_RIGHT; + case GDK_KP_Home: + return SCK_HOME; + case GDK_KP_End: + return SCK_END; + case GDK_KP_Page_Up: + return SCK_PRIOR; + case GDK_KP_Page_Down: + return SCK_NEXT; + case GDK_KP_Delete: + return SCK_DELETE; + case GDK_KP_Insert: + return SCK_INSERT; + case GDK_KP_Enter: + return SCK_RETURN; + + case GDK_Down: + return SCK_DOWN; + case GDK_Up: + return SCK_UP; + case GDK_Left: + return SCK_LEFT; + case GDK_Right: + return SCK_RIGHT; + case GDK_Home: + return SCK_HOME; + case GDK_End: + return SCK_END; + case GDK_Page_Up: + return SCK_PRIOR; + case GDK_Page_Down: + return SCK_NEXT; + case GDK_Delete: + return SCK_DELETE; + case GDK_Insert: + return SCK_INSERT; + case GDK_Escape: + return SCK_ESCAPE; + case GDK_BackSpace: + return SCK_BACK; + case GDK_Tab: + return SCK_TAB; + case GDK_Return: + return SCK_RETURN; + case GDK_KP_Add: + return SCK_ADD; + case GDK_KP_Subtract: + return SCK_SUBTRACT; + case GDK_KP_Divide: + return SCK_DIVIDE; + case GDK_Super_L: + return SCK_WIN; + case GDK_Super_R: + return SCK_RWIN; + case GDK_Menu: + return SCK_MENU; + default: + return keyIn; + } +} + +gboolean ScintillaGTK::KeyThis(GdkEventKey *event) { + //fprintf(stderr, "SC-key: %d %x [%s]\n", + // event->keyval, event->state, (event->length > 0) ? event->string : "empty"); +#if GTK_MAJOR_VERSION >= 2 + if (gtk_im_context_filter_keypress(im_context, event)) { + return 1; + } +#endif + if (!event->keyval) { + return true; + } + + bool shift = (event->state & GDK_SHIFT_MASK) != 0; + bool ctrl = (event->state & GDK_CONTROL_MASK) != 0; + bool alt = (event->state & GDK_MOD1_MASK) != 0; + guint key = event->keyval; + if (ctrl && (key < 128)) + key = toupper(key); + else if (!ctrl && (key >= GDK_KP_Multiply && key <= GDK_KP_9)) + key &= 0x7F; + // Hack for keys over 256 and below command keys but makes Hungarian work. + // This will have to change for Unicode + else if (key >= 0xFE00) + key = KeyTranslate(key); +#if GTK_MAJOR_VERSION < 2 + else if (!IsUnicodeMode() && (key >= 0x100) && (key < 0x1000)) + key &= 0xff; +#endif + + bool consumed = false; + bool added = KeyDown(key, shift, ctrl, alt, &consumed) != 0; + if (!consumed) + consumed = added; + //fprintf(stderr, "SK-key: %d %x %x\n",event->keyval, event->state, consumed); + if (event->keyval == 0xffffff && event->length > 0) { + ClearSelection(); + if (pdoc->InsertCString(CurrentPosition(), event->string)) { + MovePositionTo(CurrentPosition() + event->length); + } + } + return consumed; +} + +gboolean ScintillaGTK::KeyPress(GtkWidget *widget, GdkEventKey *event) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + return sciThis->KeyThis(event); +} + +gboolean ScintillaGTK::KeyRelease(GtkWidget *, GdkEventKey * /*event*/) { + //Platform::DebugPrintf("SC-keyrel: %d %x %3s\n",event->keyval, event->state, event->string); + return FALSE; +} + +#if GTK_MAJOR_VERSION >= 2 +gboolean ScintillaGTK::ExposePreedit(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis) { + return sciThis->ExposePreeditThis(widget, ose); +} + +gboolean ScintillaGTK::ExposePreeditThis(GtkWidget *widget, GdkEventExpose *ose) { + gchar *str; + gint cursor_pos; + PangoAttrList *attrs; + + gtk_im_context_get_preedit_string(im_context, &str, &attrs, &cursor_pos); + PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), str); + pango_layout_set_attributes(layout, attrs); + + GdkGC *gc = gdk_gc_new(widget->window); + GdkColor color[2] = { {0, 0x0000, 0x0000, 0x0000}, + {0, 0xffff, 0xffff, 0xffff}}; + gdk_color_alloc(gdk_colormap_get_system(), color); + gdk_color_alloc(gdk_colormap_get_system(), color + 1); + + gdk_gc_set_foreground(gc, color + 1); + gdk_draw_rectangle(widget->window, gc, TRUE, ose->area.x, ose->area.y, + ose->area.width, ose->area.height); + + gdk_gc_set_foreground(gc, color); + gdk_gc_set_background(gc, color + 1); + gdk_draw_layout(widget->window, gc, 0, 0, layout); + + gdk_gc_unref(gc); + g_free(str); + pango_attr_list_unref(attrs); + g_object_unref(layout); + return TRUE; +} + +void ScintillaGTK::Commit(GtkIMContext *, char *str, ScintillaGTK *sciThis) { + sciThis->CommitThis(str); +} + +void ScintillaGTK::CommitThis(char *utfVal) { + //~ fprintf(stderr, "Commit '%s'\n", utfVal); + if (IsUnicodeMode()) { + AddCharUTF(utfVal,strlen(utfVal)); + } else { + const char *source = CharacterSetID(); + if (*source) { + Converter conv(source, "UTF-8", true); + if (conv) { + char localeVal[4]="\0\0\0"; + char *pin = utfVal; + size_t inLeft = strlen(utfVal); + char *pout = localeVal; + size_t outLeft = sizeof(localeVal); + size_t conversions = conv.Convert(&pin, &inLeft, &pout, &outLeft); + if (conversions != ((size_t)(-1))) { + *pout = '\0'; + for (int i=0; localeVal[i]; i++) { + AddChar(localeVal[i]); + } + } else { + fprintf(stderr, "Conversion failed '%s'\n", utfVal); + } + } + } + } +} + +void ScintillaGTK::PreeditChanged(GtkIMContext *, ScintillaGTK *sciThis) { + sciThis->PreeditChangedThis(); +} + +void ScintillaGTK::PreeditChangedThis() { + gchar *str; + PangoAttrList *attrs; + gint cursor_pos; + gtk_im_context_get_preedit_string(im_context, &str, &attrs, &cursor_pos); + if (strlen(str) > 0){ + PangoLayout *layout = gtk_widget_create_pango_layout(PWidget(wText), str); + pango_layout_set_attributes(layout, attrs); + + gint w, h; + pango_layout_get_pixel_size(layout, &w, &h); + g_object_unref(layout); + + gint x, y; + gdk_window_get_origin((PWidget(wText))->window, &x, &y); + + Point pt = LocationFromPosition(currentPos); + if (pt.x < 0) + pt.x = 0; + if (pt.y < 0) + pt.y = 0; + + gtk_window_move(GTK_WINDOW(PWidget(wPreedit)), x+pt.x, y+pt.y); + gtk_window_resize(GTK_WINDOW(PWidget(wPreedit)), w, h); + gtk_widget_show(PWidget(wPreedit)); + gtk_widget_queue_draw_area(PWidget(wPreeditDraw), 0, 0, w, h); + } else { + gtk_widget_hide(PWidget(wPreedit)); + } + g_free(str); + pango_attr_list_unref(attrs); +} +#endif + +gint ScintillaGTK::StyleSetText(GtkWidget *widget, GtkStyle *, void*) { + if (widget->window != NULL) + gdk_window_set_back_pixmap(widget->window, NULL, FALSE); + return FALSE; +} + +gint ScintillaGTK::RealizeText(GtkWidget *widget, void*) { + if (widget->window != NULL) + gdk_window_set_back_pixmap(widget->window, NULL, FALSE); + return FALSE; +} + +#if GLIB_MAJOR_VERSION < 2 +void ScintillaGTK::Destroy(GtkObject *object) +#else +void ScintillaGTK::Destroy(GObject *object) +#endif +{ + ScintillaObject *scio = reinterpret_cast(object); + // This avoids a double destruction + if (!scio->pscin) + return; + ScintillaGTK *sciThis = reinterpret_cast(scio->pscin); + //Platform::DebugPrintf("Destroying %x %x\n", sciThis, object); + sciThis->Finalise(); + +#if GLIB_MAJOR_VERSION < 2 + if (GTK_OBJECT_CLASS(parent_class)->destroy) + (* GTK_OBJECT_CLASS(parent_class)->destroy)(object); +#else + // IS ANYTHING NEEDED ? +#endif + + delete sciThis; + scio->pscin = 0; +} + +static void DrawChild(GtkWidget *widget, GdkRectangle *area) { + GdkRectangle areaIntersect; + if (widget && + GTK_WIDGET_DRAWABLE(widget) && + gtk_widget_intersect(widget, area, &areaIntersect)) { + gtk_widget_draw(widget, &areaIntersect); + } +} + +void ScintillaGTK::Draw(GtkWidget *widget, GdkRectangle *area) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + //Platform::DebugPrintf("Draw %p %0d,%0d %0d,%0d\n", widget, area->x, area->y, area->width, area->height); + PRectangle rcPaint(area->x, area->y, area->x + area->width, area->y + area->height); + sciThis->SyncPaint(rcPaint); + if (GTK_WIDGET_DRAWABLE(PWidget(sciThis->wMain))) { + DrawChild(PWidget(sciThis->scrollbarh), area); + DrawChild(PWidget(sciThis->scrollbarv), area); + } + +#ifdef INTERNATIONAL_INPUT + Point pt = sciThis->LocationFromPosition(sciThis->currentPos); + pt.y += sciThis->vs.lineHeight - 2; + if (pt.x < 0) pt.x = 0; + if (pt.y < 0) pt.y = 0; + CursorMoved(widget, pt.x, pt.y, sciThis); +#endif +} + +gint ScintillaGTK::ExposeTextThis(GtkWidget * /*widget*/, GdkEventExpose *ose) { + paintState = painting; + + rcPaint.left = ose->area.x; + rcPaint.top = ose->area.y; + rcPaint.right = ose->area.x + ose->area.width; + rcPaint.bottom = ose->area.y + ose->area.height; + + PLATFORM_ASSERT(rgnUpdate == NULL); +#if GTK_MAJOR_VERSION >= 2 + rgnUpdate = gdk_region_copy(ose->region); +#endif + PRectangle rcClient = GetClientRectangle(); + paintingAllText = rcPaint.Contains(rcClient); + Surface *surfaceWindow = Surface::Allocate(); + if (surfaceWindow) { + surfaceWindow->Init(PWidget(wText)->window, PWidget(wText)); + Paint(surfaceWindow, rcPaint); + surfaceWindow->Release(); + delete surfaceWindow; + } + if (paintState == paintAbandoned) { + // Painting area was insufficient to cover new styling or brace highlight positions + FullPaint(); + } + paintState = notPainting; + + if (rgnUpdate) { + gdk_region_destroy(rgnUpdate); + } + rgnUpdate = 0; + + return FALSE; +} + +gint ScintillaGTK::ExposeText(GtkWidget *widget, GdkEventExpose *ose, ScintillaGTK *sciThis) { + return sciThis->ExposeTextThis(widget, ose); +} + +gint ScintillaGTK::ExposeMain(GtkWidget *widget, GdkEventExpose *ose) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + //Platform::DebugPrintf("Expose Main %0d,%0d %0d,%0d\n", + //ose->area.x, ose->area.y, ose->area.width, ose->area.height); + return sciThis->Expose(widget, ose); +} + +gint ScintillaGTK::Expose(GtkWidget *, GdkEventExpose *ose) { + //fprintf(stderr, "Expose %0d,%0d %0d,%0d\n", + //ose->area.x, ose->area.y, ose->area.width, ose->area.height); + +#if GTK_MAJOR_VERSION < 2 + + paintState = painting; + + rcPaint.left = ose->area.x; + rcPaint.top = ose->area.y; + rcPaint.right = ose->area.x + ose->area.width; + rcPaint.bottom = ose->area.y + ose->area.height; + + PRectangle rcClient = GetClientRectangle(); + paintingAllText = rcPaint.Contains(rcClient); + Surface *surfaceWindow = Surface::Allocate(); + if (surfaceWindow) { + surfaceWindow->Init(PWidget(wMain)->window, PWidget(wMain)); + + // Fill the corner between the scrollbars + if (verticalScrollBarVisible) { + if (horizontalScrollBarVisible && (wrapState == eWrapNone)) { + PRectangle rcCorner = wMain.GetClientPosition(); + rcCorner.left = rcCorner.right - scrollBarWidth + 1; + rcCorner.top = rcCorner.bottom - scrollBarHeight + 1; + //fprintf(stderr, "Corner %0d,%0d %0d,%0d\n", + //rcCorner.left, rcCorner.top, rcCorner.right, rcCorner.bottom); + surfaceWindow->FillRectangle(rcCorner, + vs.styles[STYLE_LINENUMBER].back.allocated); + } + } + + //Paint(surfaceWindow, rcPaint); + surfaceWindow->Release(); + delete surfaceWindow; + } + if (paintState == paintAbandoned) { + // Painting area was insufficient to cover new styling or brace highlight positions + FullPaint(); + } + paintState = notPainting; + +#else + // For GTK+ 2, the text is painted in ExposeText + gtk_container_propagate_expose( + GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarh), ose); + gtk_container_propagate_expose( + GTK_CONTAINER(PWidget(wMain)), PWidget(scrollbarv), ose); +#endif + + return FALSE; +} + +void ScintillaGTK::ScrollSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) { + sciThis->ScrollTo(static_cast(adj->value), false); +} + +void ScintillaGTK::ScrollHSignal(GtkAdjustment *adj, ScintillaGTK *sciThis) { + sciThis->HorizontalScrollTo(static_cast(adj->value * 2)); +} + +void ScintillaGTK::SelectionReceived(GtkWidget *widget, + GtkSelectionData *selection_data, guint) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + //Platform::DebugPrintf("Selection received\n"); + sciThis->ReceivedSelection(selection_data); +} + +void ScintillaGTK::SelectionGet(GtkWidget *widget, + GtkSelectionData *selection_data, guint info, guint) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + //Platform::DebugPrintf("Selection get\n"); + if (selection_data->selection == GDK_SELECTION_PRIMARY) { + if (sciThis->primary.s == NULL) { + sciThis->CopySelectionRange(&sciThis->primary); + } + sciThis->GetSelection(selection_data, info, &sciThis->primary); + } +#ifndef USE_GTK_CLIPBOARD + else { + sciThis->GetSelection(selection_data, info, &sciThis->copyText); + } +#endif +} + +gint ScintillaGTK::SelectionClear(GtkWidget *widget, GdkEventSelection *selection_event) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + //Platform::DebugPrintf("Selection clear\n"); + sciThis->UnclaimSelection(selection_event); + return gtk_selection_clear(widget, selection_event); +} + +#if GTK_MAJOR_VERSION < 2 +gint ScintillaGTK::SelectionNotify(GtkWidget *widget, GdkEventSelection *selection_event) { + //Platform::DebugPrintf("Selection notify\n"); + return gtk_selection_notify(widget, selection_event); +} +#endif + +void ScintillaGTK::DragBegin(GtkWidget *, GdkDragContext *) { + //Platform::DebugPrintf("DragBegin\n"); +} + +gboolean ScintillaGTK::DragMotionThis(GdkDragContext *context, + gint x, gint y, guint dragtime) { + Point npt(x, y); + SetDragPosition(PositionFromLocation(npt)); + GdkDragAction preferredAction = context->suggested_action; + int pos = PositionFromLocation(npt); + if ((inDragDrop == ddDragging) && (0 == PositionInSelection(pos))) { + // Avoid dragging selection onto itself as that produces a move + // with no real effect but which creates undo actions. + preferredAction = static_cast(0); + } else if (context->actions == static_cast + (GDK_ACTION_COPY | GDK_ACTION_MOVE)) { + preferredAction = GDK_ACTION_MOVE; + } + gdk_drag_status(context, preferredAction, dragtime); + return FALSE; +} + +gboolean ScintillaGTK::DragMotion(GtkWidget *widget, GdkDragContext *context, + gint x, gint y, guint dragtime) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + return sciThis->DragMotionThis(context, x, y, dragtime); +} + +void ScintillaGTK::DragLeave(GtkWidget *widget, GdkDragContext * /*context*/, guint) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + sciThis->SetDragPosition(invalidPosition); + //Platform::DebugPrintf("DragLeave %x\n", sciThis); +} + +void ScintillaGTK::DragEnd(GtkWidget *widget, GdkDragContext * /*context*/) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + // If drag did not result in drop here or elsewhere + if (!sciThis->dragWasDropped) + sciThis->SetEmptySelection(sciThis->posDrag); + sciThis->SetDragPosition(invalidPosition); + //Platform::DebugPrintf("DragEnd %x %d\n", sciThis, sciThis->dragWasDropped); + sciThis->inDragDrop = ddNone; +} + +gboolean ScintillaGTK::Drop(GtkWidget *widget, GdkDragContext * /*context*/, + gint, gint, guint) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + //Platform::DebugPrintf("Drop %x\n", sciThis); + sciThis->SetDragPosition(invalidPosition); + return FALSE; +} + +void ScintillaGTK::DragDataReceived(GtkWidget *widget, GdkDragContext * /*context*/, + gint, gint, GtkSelectionData *selection_data, guint /*info*/, guint) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + sciThis->ReceivedDrop(selection_data); + sciThis->SetDragPosition(invalidPosition); +} + +void ScintillaGTK::DragDataGet(GtkWidget *widget, GdkDragContext *context, + GtkSelectionData *selection_data, guint info, guint) { + ScintillaGTK *sciThis = ScintillaFromWidget(widget); + sciThis->dragWasDropped = true; + if (sciThis->currentPos != sciThis->anchor) { + sciThis->GetSelection(selection_data, info, &sciThis->drag); + } + if (context->action == GDK_ACTION_MOVE) { + int selStart = sciThis->SelectionStart(); + int selEnd = sciThis->SelectionEnd(); + if (sciThis->posDrop > selStart) { + if (sciThis->posDrop > selEnd) + sciThis->posDrop = sciThis->posDrop - (selEnd - selStart); + else + sciThis->posDrop = selStart; + sciThis->posDrop = sciThis->pdoc->ClampPositionIntoDocument(sciThis->posDrop); + } + sciThis->ClearSelection(); + } + sciThis->SetDragPosition(invalidPosition); +} + +int ScintillaGTK::TimeOut(ScintillaGTK *sciThis) { + sciThis->Tick(); + return 1; +} + +int ScintillaGTK::IdleCallback(ScintillaGTK *sciThis) { + // Idler will be automatically stoped, if there is nothing + // to do while idle. + bool ret = sciThis->Idle(); + if (ret == false) { + // FIXME: This will remove the idler from GTK, we don't want to + // remove it as it is removed automatically when this function + // returns false (although, it should be harmless). + sciThis->SetIdle(false); + } + return ret; +} + +void ScintillaGTK::PopUpCB(ScintillaGTK *sciThis, guint action, GtkWidget *) { + if (action) { + sciThis->Command(action); + } +} + +gint ScintillaGTK::PressCT(GtkWidget *widget, GdkEventButton *event, ScintillaGTK *sciThis) { + if (event->window != widget->window) + return FALSE; + if (event->type != GDK_BUTTON_PRESS) + return FALSE; + Point pt; + pt.x = int(event->x); + pt.y = int(event->y); + sciThis->ct.MouseClick(pt); + sciThis->CallTipClick(); +#if GTK_MAJOR_VERSION >= 2 + return TRUE; +#else + return FALSE; +#endif +} + +gint ScintillaGTK::ExposeCT(GtkWidget *widget, GdkEventExpose * /*ose*/, CallTip *ctip) { + Surface *surfaceWindow = Surface::Allocate(); + if (surfaceWindow) { + surfaceWindow->Init(widget->window, widget); + ctip->PaintCT(surfaceWindow); + surfaceWindow->Release(); + delete surfaceWindow; + } + return TRUE; +} + +sptr_t ScintillaGTK::DirectFunction( + ScintillaGTK *sciThis, unsigned int iMessage, uptr_t wParam, sptr_t lParam) { + return sciThis->WndProc(iMessage, wParam, lParam); +} + +sptr_t scintilla_send_message(ScintillaObject *sci, unsigned int iMessage, uptr_t wParam, sptr_t lParam) { + ScintillaGTK *psci = reinterpret_cast(sci->pscin); + return psci->WndProc(iMessage, wParam, lParam); +} + +static void scintilla_class_init(ScintillaClass *klass); +static void scintilla_init(ScintillaObject *sci); + +extern void Platform_Initialise(); +extern void Platform_Finalise(); + +#if GLIB_MAJOR_VERSION < 2 +GtkType scintilla_get_type() { + static GtkType scintilla_type = 0; + + if (!scintilla_type) { + Platform_Initialise(); + static GtkTypeInfo scintilla_info = { + "Scintilla", + sizeof (ScintillaObject), + sizeof (ScintillaClass), + (GtkClassInitFunc) scintilla_class_init, + (GtkObjectInitFunc) scintilla_init, + (gpointer) NULL, + (gpointer) NULL, + 0 + }; + + scintilla_type = gtk_type_unique(gtk_container_get_type(), &scintilla_info); + } + + return scintilla_type; +} +#else +GType scintilla_get_type() { + static GType scintilla_type = 0; + + if (!scintilla_type) { + scintilla_type = g_type_from_name("Scintilla"); + if (!scintilla_type) { + static GTypeInfo scintilla_info = { + (guint16) sizeof (ScintillaClass), + NULL, //(GBaseInitFunc) + NULL, //(GBaseFinalizeFunc) + (GClassInitFunc) scintilla_class_init, + NULL, //(GClassFinalizeFunc) + NULL, //gconstpointer data + (guint16) sizeof (ScintillaObject), + 0, //n_preallocs + (GInstanceInitFunc) scintilla_init, + NULL //(GTypeValueTable*) + }; + + scintilla_type = g_type_register_static( + GTK_TYPE_CONTAINER, "Scintilla", &scintilla_info, (GTypeFlags) 0); + } + } + + return scintilla_type; +} +#endif + +void ScintillaGTK::ClassInit(OBJECT_CLASS* object_class, GtkWidgetClass *widget_class, GtkContainerClass *container_class) { +#if GLIB_MAJOR_VERSION >= 2 + Platform_Initialise(); +#endif + atomClipboard = gdk_atom_intern("CLIPBOARD", FALSE); + atomUTF8 = gdk_atom_intern("UTF8_STRING", FALSE); + atomString = GDK_SELECTION_TYPE_STRING; + atomUriList = gdk_atom_intern("text/uri-list", FALSE); + atomDROPFILES_DND = gdk_atom_intern("DROPFILES_DND", FALSE); + + // Define default signal handlers for the class: Could move more + // of the signal handlers here (those that currently attached to wDraw + // in Initialise() may require coordinate translation?) + +#if GLIB_MAJOR_VERSION < 2 + object_class->destroy = Destroy; +#else + object_class->finalize = Destroy; +#endif + widget_class->size_request = SizeRequest; + widget_class->size_allocate = SizeAllocate; + widget_class->expose_event = ExposeMain; +#if GTK_MAJOR_VERSION < 2 + widget_class->draw = Draw; +#endif + widget_class->motion_notify_event = Motion; + widget_class->button_press_event = Press; + widget_class->button_release_event = MouseRelease; +#if PLAT_GTK_WIN32 || (GTK_MAJOR_VERSION >= 2) + widget_class->scroll_event = ScrollEvent; +#endif + widget_class->key_press_event = KeyPress; + widget_class->key_release_event = KeyRelease; + widget_class->focus_in_event = FocusIn; + widget_class->focus_out_event = FocusOut; + widget_class->selection_received = SelectionReceived; + widget_class->selection_get = SelectionGet; + widget_class->selection_clear_event = SelectionClear; +#if GTK_MAJOR_VERSION < 2 + widget_class->selection_notify_event = SelectionNotify; +#endif + + widget_class->drag_data_received = DragDataReceived; + widget_class->drag_motion = DragMotion; + widget_class->drag_leave = DragLeave; + widget_class->drag_end = DragEnd; + widget_class->drag_drop = Drop; + widget_class->drag_data_get = DragDataGet; + + widget_class->realize = Realize; + widget_class->unrealize = UnRealize; + widget_class->map = Map; + widget_class->unmap = UnMap; + + container_class->forall = MainForAll; +} + +#if GLIB_MAJOR_VERSION < 2 +#define GTK_CLASS_TYPE(c) (c->type) +#define SIG_MARSHAL gtk_marshal_NONE__INT_POINTER +#define MARSHAL_ARGUMENTS GTK_TYPE_INT, GTK_TYPE_POINTER +#else +#define SIG_MARSHAL scintilla_marshal_NONE__INT_POINTER +#define MARSHAL_ARGUMENTS G_TYPE_INT, G_TYPE_POINTER +#endif + +static void scintilla_class_init(ScintillaClass *klass) { + OBJECT_CLASS *object_class = (OBJECT_CLASS*) klass; + GtkWidgetClass *widget_class = (GtkWidgetClass*) klass; + GtkContainerClass *container_class = (GtkContainerClass*) klass; + +#if GLIB_MAJOR_VERSION < 2 + parent_class = (GtkWidgetClass*) gtk_type_class(gtk_container_get_type()); + + scintilla_signals[COMMAND_SIGNAL] = gtk_signal_new( + "command", + GTK_RUN_LAST, + GTK_CLASS_TYPE(object_class), + GTK_SIGNAL_OFFSET(ScintillaClass, command), + SIG_MARSHAL, + GTK_TYPE_NONE, + 2, MARSHAL_ARGUMENTS); + + scintilla_signals[NOTIFY_SIGNAL] = gtk_signal_new( + SCINTILLA_NOTIFY, + GTK_RUN_LAST, + GTK_CLASS_TYPE(object_class), + GTK_SIGNAL_OFFSET(ScintillaClass, notify), + SIG_MARSHAL, + GTK_TYPE_NONE, + 2, MARSHAL_ARGUMENTS); + gtk_object_class_add_signals(object_class, + reinterpret_cast(scintilla_signals), LAST_SIGNAL); +#else + GSignalFlags sigflags = GSignalFlags(G_SIGNAL_ACTION | G_SIGNAL_RUN_LAST); + scintilla_signals[COMMAND_SIGNAL] = g_signal_new( + "command", + G_TYPE_FROM_CLASS(object_class), + sigflags, + G_STRUCT_OFFSET(ScintillaClass, command), + NULL, //(GSignalAccumulator) + NULL, //(gpointer) + SIG_MARSHAL, + G_TYPE_NONE, + 2, MARSHAL_ARGUMENTS); + + scintilla_signals[NOTIFY_SIGNAL] = g_signal_new( + SCINTILLA_NOTIFY, + G_TYPE_FROM_CLASS(object_class), + sigflags, + G_STRUCT_OFFSET(ScintillaClass, notify), + NULL, + NULL, + SIG_MARSHAL, + G_TYPE_NONE, + 2, MARSHAL_ARGUMENTS); +#endif + klass->command = NULL; + klass->notify = NULL; + + ScintillaGTK::ClassInit(object_class, widget_class, container_class); +} + +static void scintilla_init(ScintillaObject *sci) { + GTK_WIDGET_SET_FLAGS(sci, GTK_CAN_FOCUS); + sci->pscin = new ScintillaGTK(sci); +} + +GtkWidget* scintilla_new() { +#if GLIB_MAJOR_VERSION < 2 + return GTK_WIDGET(gtk_type_new(scintilla_get_type())); +#else + return GTK_WIDGET(g_object_new(scintilla_get_type(), NULL)); +#endif +} + +void scintilla_set_id(ScintillaObject *sci, uptr_t id) { + ScintillaGTK *psci = reinterpret_cast(sci->pscin); + psci->ctrlID = id; +} + +void scintilla_release_resources(void) { + Platform_Finalise(); +} diff --git a/scintilla/gtk/deps.mak b/scintilla/gtk/deps.mak new file mode 100644 index 00000000..13569be7 --- /dev/null +++ b/scintilla/gtk/deps.mak @@ -0,0 +1,311 @@ +PlatGTK.o: PlatGTK.cxx \ + ../include/Scintilla.h ../include/ScintillaWidget.h \ + ../src/UniConversion.h ../src/XPM.h Converter.h +ScintillaGTK.o: ScintillaGTK.cxx \ + ../include/Scintilla.h ../include/ScintillaWidget.h \ + ../include/SciLexer.h ../include/PropSet.h ../include/SString.h \ + ../include/Accessor.h ../include/KeyWords.h ../src/ContractionState.h \ + ../src/SVector.h ../src/SplitVector.h ../src/Partitioning.h \ + ../src/CellBuffer.h ../src/CallTip.h ../src/KeyMap.h ../src/Indicator.h \ + ../src/XPM.h ../src/LineMarker.h ../src/Style.h ../src/AutoComplete.h \ + ../src/ViewStyle.h ../src/RunStyles.h ../src/Decoration.h \ + ../src/CharClassify.h ../src/Document.h ../src/PositionCache.h \ + ../src/Editor.h ../include/SString.h ../src/ScintillaBase.h \ + ../src/UniConversion.h scintilla-marshal.h ../src/ExternalLexer.h \ + Converter.h +AutoComplete.o: ../src/AutoComplete.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../src/AutoComplete.h +CallTip.o: ../src/CallTip.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/CallTip.h +CellBuffer.o: ../src/CellBuffer.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/SVector.h ../src/SplitVector.h \ + ../src/Partitioning.h ../src/CellBuffer.h +CharClassify.o: ../src/CharClassify.cxx ../src/CharClassify.h +ContractionState.o: ../src/ContractionState.cxx ../include/Platform.h \ + ../src/ContractionState.h +Decoration.o: ../src/Decoration.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/SplitVector.h ../src/Partitioning.h \ + ../src/RunStyles.h ../src/Decoration.h +DocumentAccessor.o: ../src/DocumentAccessor.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../src/SVector.h \ + ../include/Accessor.h ../src/DocumentAccessor.h ../src/SplitVector.h \ + ../src/Partitioning.h ../src/RunStyles.h ../src/CellBuffer.h \ + ../include/Scintilla.h ../src/CharClassify.h ../src/Decoration.h \ + ../src/Document.h +Document.o: ../src/Document.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/SVector.h ../src/SplitVector.h \ + ../src/Partitioning.h ../src/RunStyles.h ../src/CellBuffer.h \ + ../src/CharClassify.h ../src/Decoration.h ../src/Document.h \ + ../src/RESearch.h +Editor.o: ../src/Editor.cxx ../include/Platform.h ../include/Scintilla.h \ + ../src/ContractionState.h ../src/SVector.h ../src/SplitVector.h \ + ../src/Partitioning.h ../src/CellBuffer.h ../src/KeyMap.h \ + ../src/RunStyles.h ../src/Indicator.h ../src/XPM.h ../src/LineMarker.h \ + ../src/Style.h ../src/ViewStyle.h ../src/CharClassify.h \ + ../src/Decoration.h ../src/Document.h ../src/PositionCache.h \ + ../src/Editor.h +ExternalLexer.o: ../src/ExternalLexer.cxx ../include/Platform.h \ + ../include/Scintilla.h ../include/SciLexer.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/DocumentAccessor.h \ + ../include/KeyWords.h ../src/ExternalLexer.h +Indicator.o: ../src/Indicator.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/Indicator.h +KeyMap.o: ../src/KeyMap.cxx ../include/Platform.h ../include/Scintilla.h \ + ../src/KeyMap.h +KeyWords.o: ../src/KeyWords.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexAda.o: ../src/LexAda.cxx ../include/Platform.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/PropSet.h ../include/SString.h \ + ../include/KeyWords.h ../include/SciLexer.h ../include/SString.h +LexAPDL.o: ../src/LexAPDL.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexAsm.o: ../src/LexAsm.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexAsn1.o: ../src/LexAsn1.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexAU3.o: ../src/LexAU3.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexAVE.o: ../src/LexAVE.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexBaan.o: ../src/LexBaan.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexBash.o: ../src/LexBash.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../include/KeyWords.h \ + ../include/Scintilla.h ../include/SciLexer.h +LexBasic.o: ../src/LexBasic.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexBullant.o: ../src/LexBullant.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexCaml.o: ../src/LexCaml.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexCLW.o: ../src/LexCLW.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexCmake.o: ../src/LexCmake.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexConf.o: ../src/LexConf.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../include/KeyWords.h \ + ../include/Scintilla.h ../include/SciLexer.h +LexCPP.o: ../src/LexCPP.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h \ + ../src/CharacterSet.h +LexCrontab.o: ../src/LexCrontab.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexCsound.o: ../src/LexCsound.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexCSS.o: ../src/LexCSS.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexD.o: ../src/LexD.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexEiffel.o: ../src/LexEiffel.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexErlang.o: ../src/LexErlang.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexEScript.o: ../src/LexEScript.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexFlagship.o: ../src/LexFlagship.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexForth.o: ../src/LexForth.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexFortran.o: ../src/LexFortran.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexGAP.o: ../src/LexGAP.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexGui4Cli.o: ../src/LexGui4Cli.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexHaskell.o: ../src/LexHaskell.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexHTML.o: ../src/LexHTML.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h \ + ../src/CharacterSet.h +LexInno.o: ../src/LexInno.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexKix.o: ../src/LexKix.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexLisp.o: ../src/LexLisp.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../include/KeyWords.h \ + ../include/Scintilla.h ../include/SciLexer.h ../src/StyleContext.h +LexLout.o: ../src/LexLout.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexLua.o: ../src/LexLua.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexMatlab.o: ../src/LexMatlab.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexMetapost.o: ../src/LexMetapost.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h \ + ../src/StyleContext.h +LexMMIXAL.o: ../src/LexMMIXAL.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexMPT.o: ../src/LexMPT.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../include/KeyWords.h \ + ../include/Scintilla.h ../include/SciLexer.h ../include/SString.h +LexMSSQL.o: ../src/LexMSSQL.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexNsis.o: ../src/LexNsis.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../include/KeyWords.h \ + ../include/Scintilla.h ../include/SciLexer.h +LexOpal.o: ../src/LexOpal.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../include/KeyWords.h \ + ../include/Scintilla.h ../include/SciLexer.h ../src/StyleContext.h +LexOthers.o: ../src/LexOthers.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexPascal.o: ../src/LexPascal.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h \ + ../src/StyleContext.h +LexPB.o: ../src/LexPB.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexPerl.o: ../src/LexPerl.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../include/KeyWords.h \ + ../include/Scintilla.h ../include/SciLexer.h +LexPLM.o: ../src/LexPLM.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../include/KeyWords.h \ + ../include/Scintilla.h ../include/SciLexer.h ../src/StyleContext.h +LexPOV.o: ../src/LexPOV.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexProgress.o: ../src/LexProgress.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexPS.o: ../src/LexPS.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexPython.o: ../src/LexPython.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexRebol.o: ../src/LexRebol.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h \ + ../src/StyleContext.h +LexRuby.o: ../src/LexRuby.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../include/KeyWords.h \ + ../include/Scintilla.h ../include/SciLexer.h +LexScriptol.o: ../src/LexScriptol.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexSmalltalk.o: ../src/LexSmalltalk.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexSpecman.o: ../src/LexSpecman.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexSpice.o: ../src/LexSpice.cxx ../include/Platform.h \ + ../include/Accessor.h ../src/StyleContext.h ../include/PropSet.h \ + ../include/SString.h ../include/KeyWords.h ../include/SciLexer.h \ + ../include/SString.h +LexSQL.o: ../src/LexSQL.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexTADS3.o: ../src/LexTADS3.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexTCL.o: ../src/LexTCL.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexTeX.o: ../src/LexTeX.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../include/KeyWords.h \ + ../include/Scintilla.h ../include/SciLexer.h ../src/StyleContext.h +LexVB.o: ../src/LexVB.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexVerilog.o: ../src/LexVerilog.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h ../include/KeyWords.h ../include/Scintilla.h \ + ../include/SciLexer.h +LexVHDL.o: ../src/LexVHDL.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LexYAML.o: ../src/LexYAML.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/StyleContext.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h +LineMarker.o: ../src/LineMarker.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/XPM.h ../src/LineMarker.h +PositionCache.o: ../src/PositionCache.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/ContractionState.h ../src/SVector.h \ + ../src/SplitVector.h ../src/Partitioning.h ../src/CellBuffer.h \ + ../src/KeyMap.h ../src/RunStyles.h ../src/Indicator.h ../src/XPM.h \ + ../src/LineMarker.h ../src/Style.h ../src/ViewStyle.h \ + ../src/CharClassify.h ../src/Decoration.h ../src/Document.h \ + ../src/PositionCache.h +PropSet.o: ../src/PropSet.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h +RESearch.o: ../src/RESearch.cxx ../src/CharClassify.h ../src/RESearch.h +RunStyles.o: ../src/RunStyles.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/SplitVector.h ../src/Partitioning.h \ + ../src/RunStyles.h +ScintillaBase.o: ../src/ScintillaBase.cxx ../include/Platform.h \ + ../include/Scintilla.h ../include/PropSet.h ../include/SString.h \ + ../include/SciLexer.h ../include/Accessor.h ../src/DocumentAccessor.h \ + ../include/KeyWords.h ../src/ContractionState.h ../src/SVector.h \ + ../src/SplitVector.h ../src/Partitioning.h ../src/RunStyles.h \ + ../src/CellBuffer.h ../src/CallTip.h ../src/KeyMap.h ../src/Indicator.h \ + ../src/XPM.h ../src/LineMarker.h ../src/Style.h ../src/ViewStyle.h \ + ../src/AutoComplete.h ../src/CharClassify.h ../src/Decoration.h \ + ../src/Document.h ../src/PositionCache.h ../src/Editor.h \ + ../src/ScintillaBase.h +StyleContext.o: ../src/StyleContext.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h +Style.o: ../src/Style.cxx ../include/Platform.h ../include/Scintilla.h \ + ../src/Style.h +UniConversion.o: ../src/UniConversion.cxx ../src/UniConversion.h +ViewStyle.o: ../src/ViewStyle.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/SplitVector.h ../src/Partitioning.h \ + ../src/RunStyles.h ../src/Indicator.h ../src/XPM.h ../src/LineMarker.h \ + ../src/Style.h ../src/ViewStyle.h +WindowAccessor.o: ../src/WindowAccessor.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/WindowAccessor.h ../include/Scintilla.h +XPM.o: ../src/XPM.cxx ../include/Platform.h ../src/XPM.h diff --git a/scintilla/gtk/makefile b/scintilla/gtk/makefile new file mode 100644 index 00000000..da57c916 --- /dev/null +++ b/scintilla/gtk/makefile @@ -0,0 +1,97 @@ +# Make file for Scintilla on Linux or compatible OS +# Copyright 1998-2001 by Neil Hodgson +# The License.txt file describes the conditions under which this software may be distributed. +# This makefile assumes GCC 3.1 is used and changes will be needed to use other compilers. +# GNU make does not like \r\n line endings so should be saved to CVS in binary form. +# Builds for GTK+ 2 if available else GTK+ 1. +# To force GTK+ 2 build, define GTK2 on the make command line. +# To force GTK+ 1 build, define GTK1 on the make command line. + +.SUFFIXES: .cxx .c .o .h .a +CC = g++ +CCOMP = gcc +AR = ar +RANLIB = touch + +ifeq ($(shell uname),Darwin) +RANLIB = ranlib +endif + +COMPLIB=../bin/scintilla.a + +vpath %.h ../src ../include +vpath %.cxx ../src + +INCLUDEDIRS=-I ../include -I ../src +CXXBASEFLAGS=-Wall -Wno-missing-braces -Wno-char-subscripts -pedantic -Os -DGTK -DSCI_LEXER $(INCLUDEDIRS) + +ifdef NOTHREADS +THREADFLAGS=-DG_THREADS_IMPL_NONE +else +THREADFLAGS= +endif + +ifdef DEBUG +CXXFLAGS=-DDEBUG -g $(CXXBASEFLAGS) $(THREADFLAGS) +else +CXXFLAGS=-DNDEBUG -Os $(CXXBASEFLAGS) $(THREADFLAGS) +endif + +# If explicit setting of GTK1 or GTK2 then use that else look for +# pkg-config which is an OK indication that GTK2 is available +ifdef GTK2 +CONFIGFLAGS=$(shell pkg-config --cflags gtk+-2.0) +MARSHALLER=scintilla-marshal.o +else +ifdef GTK1 +CONFIGFLAGS=$(shell gtk-config --cflags) +else +ifneq (,$(findstring /,$(shell whereis pkg-config))) +CONFIGFLAGS=$(shell pkg-config --cflags gtk+-2.0) +MARSHALLER=scintilla-marshal.o +else +CONFIGFLAGS=$(shell gtk-config --cflags) +endif +endif +endif + +.cxx.o: + $(CC) $(CONFIGFLAGS) $(CXXFLAGS) -c $< +.c.o: + $(CCOMP) $(CONFIGFLAGS) $(CXXFLAGS) -w -c $< + +#++Autogenerated -- run src/LexGen.py to regenerate +#**LEXOBJS=\\\n\(\*.o \) +LEXOBJS=\ +LexAbaqus.o LexAda.o LexAPDL.o LexAsm.o LexAsn1.o LexASY.o LexAU3.o LexAVE.o \ +LexBaan.o LexBash.o LexBasic.o LexBullant.o LexCaml.o LexCLW.o LexCmake.o \ +LexConf.o LexCPP.o LexCrontab.o LexCsound.o LexCSS.o LexD.o LexEiffel.o \ +LexErlang.o LexEScript.o LexFlagship.o LexForth.o LexFortran.o LexGAP.o \ +LexGui4Cli.o LexHaskell.o LexHTML.o LexInno.o LexKix.o LexLisp.o LexLout.o \ +LexLua.o LexMagik.o LexMatlab.o LexMetapost.o LexMMIXAL.o LexMPT.o LexMSSQL.o \ +LexNsis.o LexObjC.o LexOpal.o LexOthers.o LexPascal.o LexPB.o LexPerl.o \ +LexPLM.o LexPOV.o LexPowerShell.o LexProgress.o LexPS.o LexPython.o LexR.o \ +LexRebol.o LexRuby.o LexScriptol.o LexSearchResult.o LexSmalltalk.o \ +LexSpecman.o LexSpice.o LexSQL.o LexTADS3.o LexTCL.o LexTeX.o LexUser.o \ +LexVB.o LexVerilog.o LexVHDL.o LexYAML.o +#--Autogenerated -- end of automatically generated section + +all: $(COMPLIB) + +clean: + rm -f *.o $(COMPLIB) + +deps: + $(CC) -MM $(CONFIGFLAGS) $(CXXFLAGS) *.cxx ../src/*.cxx | sed -e 's/\/usr.* //' | grep [a-zA-Z] >deps.mak + +$(COMPLIB): DocumentAccessor.o WindowAccessor.o KeyWords.o StyleContext.o \ + CharClassify.o Decoration.o Document.o CallTip.o \ + ScintillaBase.o ContractionState.o Editor.o ExternalLexer.o PropSet.o PlatGTK.o \ + KeyMap.o LineMarker.o PositionCache.o ScintillaGTK.o CellBuffer.o ViewStyle.o \ + RESearch.o RunStyles.o Style.o Indicator.o AutoComplete.o UniConversion.o XPM.o \ + $(MARSHALLER) $(LEXOBJS) + $(AR) rc $@ $^ + $(RANLIB) $@ + +# Automatically generate header dependencies with "make deps" +include deps.mak diff --git a/scintilla/gtk/scintilla-marshal.c b/scintilla/gtk/scintilla-marshal.c new file mode 100644 index 00000000..02da1843 --- /dev/null +++ b/scintilla/gtk/scintilla-marshal.c @@ -0,0 +1,86 @@ + +#include + + +#ifdef G_ENABLE_DEBUG +#define g_marshal_value_peek_boolean(v) g_value_get_boolean (v) +#define g_marshal_value_peek_char(v) g_value_get_char (v) +#define g_marshal_value_peek_uchar(v) g_value_get_uchar (v) +#define g_marshal_value_peek_int(v) g_value_get_int (v) +#define g_marshal_value_peek_uint(v) g_value_get_uint (v) +#define g_marshal_value_peek_long(v) g_value_get_long (v) +#define g_marshal_value_peek_ulong(v) g_value_get_ulong (v) +#define g_marshal_value_peek_int64(v) g_value_get_int64 (v) +#define g_marshal_value_peek_uint64(v) g_value_get_uint64 (v) +#define g_marshal_value_peek_enum(v) g_value_get_enum (v) +#define g_marshal_value_peek_flags(v) g_value_get_flags (v) +#define g_marshal_value_peek_float(v) g_value_get_float (v) +#define g_marshal_value_peek_double(v) g_value_get_double (v) +#define g_marshal_value_peek_string(v) (char*) g_value_get_string (v) +#define g_marshal_value_peek_param(v) g_value_get_param (v) +#define g_marshal_value_peek_boxed(v) g_value_get_boxed (v) +#define g_marshal_value_peek_pointer(v) g_value_get_pointer (v) +#define g_marshal_value_peek_object(v) g_value_get_object (v) +#else /* !G_ENABLE_DEBUG */ +/* WARNING: This code accesses GValues directly, which is UNSUPPORTED API. + * Do not access GValues directly in your code. Instead, use the + * g_value_get_*() functions + */ +#define g_marshal_value_peek_boolean(v) (v)->data[0].v_int +#define g_marshal_value_peek_char(v) (v)->data[0].v_int +#define g_marshal_value_peek_uchar(v) (v)->data[0].v_uint +#define g_marshal_value_peek_int(v) (v)->data[0].v_int +#define g_marshal_value_peek_uint(v) (v)->data[0].v_uint +#define g_marshal_value_peek_long(v) (v)->data[0].v_long +#define g_marshal_value_peek_ulong(v) (v)->data[0].v_ulong +#define g_marshal_value_peek_int64(v) (v)->data[0].v_int64 +#define g_marshal_value_peek_uint64(v) (v)->data[0].v_uint64 +#define g_marshal_value_peek_enum(v) (v)->data[0].v_int +#define g_marshal_value_peek_flags(v) (v)->data[0].v_uint +#define g_marshal_value_peek_float(v) (v)->data[0].v_float +#define g_marshal_value_peek_double(v) (v)->data[0].v_double +#define g_marshal_value_peek_string(v) (v)->data[0].v_pointer +#define g_marshal_value_peek_param(v) (v)->data[0].v_pointer +#define g_marshal_value_peek_boxed(v) (v)->data[0].v_pointer +#define g_marshal_value_peek_pointer(v) (v)->data[0].v_pointer +#define g_marshal_value_peek_object(v) (v)->data[0].v_pointer +#endif /* !G_ENABLE_DEBUG */ + + +/* NONE:INT,POINTER (scintilla-marshal.list:1) */ +void +scintilla_marshal_VOID__INT_POINTER (GClosure *closure, + GValue *return_value, + guint n_param_values, + const GValue *param_values, + gpointer invocation_hint, + gpointer marshal_data) +{ + typedef void (*GMarshalFunc_VOID__INT_POINTER) (gpointer data1, + gint arg_1, + gpointer arg_2, + gpointer data2); + register GMarshalFunc_VOID__INT_POINTER callback; + register GCClosure *cc = (GCClosure*) closure; + register gpointer data1, data2; + + g_return_if_fail (n_param_values == 3); + + if (G_CCLOSURE_SWAP_DATA (closure)) + { + data1 = closure->data; + data2 = g_value_peek_pointer (param_values + 0); + } + else + { + data1 = g_value_peek_pointer (param_values + 0); + data2 = closure->data; + } + callback = (GMarshalFunc_VOID__INT_POINTER) (marshal_data ? marshal_data : cc->callback); + + callback (data1, + g_marshal_value_peek_int (param_values + 1), + g_marshal_value_peek_pointer (param_values + 2), + data2); +} + diff --git a/scintilla/gtk/scintilla-marshal.h b/scintilla/gtk/scintilla-marshal.h new file mode 100644 index 00000000..28e94ccc --- /dev/null +++ b/scintilla/gtk/scintilla-marshal.h @@ -0,0 +1,21 @@ + +#ifndef __scintilla_marshal_MARSHAL_H__ +#define __scintilla_marshal_MARSHAL_H__ + +#include + +G_BEGIN_DECLS + +/* NONE:INT,POINTER (scintilla-marshal.list:1) */ +extern void scintilla_marshal_VOID__INT_POINTER (GClosure *closure, + GValue *return_value, + guint n_param_values, + const GValue *param_values, + gpointer invocation_hint, + gpointer marshal_data); +#define scintilla_marshal_NONE__INT_POINTER scintilla_marshal_VOID__INT_POINTER + +G_END_DECLS + +#endif /* __scintilla_marshal_MARSHAL_H__ */ + diff --git a/scintilla/gtk/scintilla-marshal.list b/scintilla/gtk/scintilla-marshal.list new file mode 100644 index 00000000..b3cd2aa8 --- /dev/null +++ b/scintilla/gtk/scintilla-marshal.list @@ -0,0 +1 @@ +NONE:INT,POINTER diff --git a/scintilla/gtk/scintilla.mak b/scintilla/gtk/scintilla.mak new file mode 100644 index 00000000..a06706f3 --- /dev/null +++ b/scintilla/gtk/scintilla.mak @@ -0,0 +1,592 @@ +# Make file for GTK+/Scintilla on Windows Visual C++ +# Borland C++ does not work +# Copyright 1998-2000 by Neil Hodgson +# The License.txt file describes the conditions under which this software may be distributed. +# This makefile is for using Visual C++ with nmake or Borland C++ with make depending on +# the setting of the VENDOR macro. If no VENDOR is defined n the command line then +# the tool used is automatically detected. +# Usage for Microsoft: +# nmake -f scintilla.mak +# Usage for Borland: +# make -f scintilla.mak +# For debug versions define DEBUG on the command line, for Borland: +# make DEBUG=1 -f scintilla.mak +# The main makefile uses mingw32 gcc and may be more current than this file. + +.SUFFIXES: .cxx + +DIR_O=. +DIR_BIN=..\bin + +COMPONENT=$(DIR_BIN)\Scintilla.dll +LEXCOMPONENT=$(DIR_BIN)\SciLexer.dll +STATIC_LIB=$(DIR_BIN)\Scintilla-static.lib + +!IFNDEF VENDOR +!IFDEF _NMAKE_VER +#Microsoft nmake so make default VENDOR MICROSOFT +VENDOR=MICROSOFT +!ELSE +VENDOR=BORLAND +!ENDIF +!ENDIF + +!IF "$(VENDOR)"=="MICROSOFT" + +CC=cl +RC=rc +LD=link + +!IFDEF USE_GTK2 +MARSHALLER=$(DIR_O)\scintilla-marshal.obj +GTK_TOP= ../../gtk2 +TOP = $(GTK_TOP) +!INCLUDE $(TOP)/glib/build/win32/make.msc + +GTK_INCLUDES= -I$(GTK_TOP)/gtk+ \ + -I$(GTK_TOP)/gtk+/gdk \ + -I$(GTK_TOP)/glib/glib \ + -I$(GTK_TOP)/glib/gmodule \ + -I$(GTK_TOP)/glib \ + -I$(GTK_TOP)\libiconv\include \ + -I$(GTK_TOP)\pango \ + -I$(GTK_TOP)\atk +ALL_GTK_LIBS=$(GTK2_LIBS) $(GLIB_LIBS) $(LIBICONV_LIBS) +!ELSE +GTK_TOP= ../../win32gtk +GTK_INCLUDES= -I $(GTK_TOP)/gtk+ -I $(GTK_TOP)/gtk+/gdk -I $(GTK_TOP)/glib -I $(GTK_TOP)/glib/gmodule +ALL_GTK_LIBS=$(GTK_TOP)/gtk+/gtk/gtk-1.3.lib \ + $(GTK_TOP)/gtk+/gdk/gdk-1.3.lib \ + $(GTK_TOP)/glib/gmodule/gmodule-1.3.lib \ + $(GTK_TOP)/glib/glib-1.3.lib +!ENDIF + +INCLUDEDIRS=-I ../include -I ../src $(GTK_INCLUDES) +CXXFLAGS=/TP /W4 -DGTK -D_CRT_SECURE_NO_DEPRECATE=1 +CFLAGS=/W4 -DGTK +# For something scary:/Wp64 +CXXDEBUG=/Zi /Od /MDd -DDEBUG +CXXNDEBUG=/Ox /MD -DNDEBUG +NAMEFLAG=-Fo +LDFLAGS=/opt:nowin98 +LDDEBUG=/DEBUG +#LIBS=KERNEL32.lib USER32.lib GDI32.lib IMM32.lib OLE32.LIB +LIBS=$(ALL_GTK_LIBS) + +!IFDEF QUIET +CC=@$(CC) +CXXDEBUG=$(CXXDEBUG) /nologo +CXXNDEBUG=$(CXXNDEBUG) /nologo +LDFLAGS=$(LDFLAGS) /nologo +!ENDIF + +!ELSE +# BORLAND +!error Borland C++ not supported + +CC=bcc32 +RC=brcc32 -r +LD=ilink32 + +INCLUDEDIRS=-I../include -I../src +CXXFLAGS = -v +CXXFLAGS=-P -tWM -w -w-prc -w-inl -RT- -x- +# Above turns off warnings for clarfying parentheses and inlines with for not expanded +CXXDEBUG=-v -DDEBUG +CXXNDEBUG=-O1 -DNDEBUG +NAMEFLAG=-o +LDFLAGS= +LDDEBUG=-v +LIBS=import32 cw32mt + +!ENDIF + +!IFDEF DEBUG +CXXFLAGS=$(CXXFLAGS) $(CXXDEBUG) +LDFLAGS=$(LDDEBUG) $(LDFLAGS) +!ELSE +CXXFLAGS=$(CXXFLAGS) $(CXXNDEBUG) +!ENDIF + +#ALL: $(STATIC_LIB) $(COMPONENT) $(LEXCOMPONENT) $(DIR_O)\ScintillaGTKS.obj $(DIR_O)\WindowAccessor.obj +ALL: $(STATIC_LIB) $(DIR_O)\ScintillaGTKS.obj $(DIR_O)\WindowAccessor.obj + +clean:: + -del /q $(DIR_O)\*.obj $(DIR_O)\*.pdb $(COMPONENT) $(LEXCOMPONENT) $(DIR_O)\*.res $(DIR_BIN)\*.map + +SOBJS=\ + $(DIR_O)\AutoComplete.obj \ + $(DIR_O)\CallTip.obj \ + $(DIR_O)\CellBuffer.obj \ + $(DIR_O)\ContractionState.obj \ + $(DIR_O)\CharClassify.obj \ + $(DIR_O)\Decoration.obj \ + $(DIR_O)\Document.obj \ + $(DIR_O)\Editor.obj \ + $(DIR_O)\ExternalLexer.obj \ + $(DIR_O)\Indicator.obj \ + $(DIR_O)\KeyMap.obj \ + $(DIR_O)\LineMarker.obj \ + $(DIR_O)\PlatGTK.obj \ + $(DIR_O)\PositionCache.obj \ + $(MARSHALLER) \ + $(DIR_O)\RESearch.obj \ + $(DIR_O)\RunStyles.obj \ + $(DIR_O)\PropSet.obj \ + $(DIR_O)\ScintillaBase.obj \ + $(DIR_O)\ScintillaGTK.obj \ + $(DIR_O)\Style.obj \ + $(DIR_O)\UniConversion.obj \ + $(DIR_O)\ViewStyle.obj \ + $(DIR_O)\XPM.obj + +#++Autogenerated -- run src/LexGen.py to regenerate +#**LEXOBJS=\\\n\(\t$(DIR_O)\\\*.obj \\\n\) +LEXOBJS=\ + $(DIR_O)\LexAbaqus.obj \ + $(DIR_O)\LexAda.obj \ + $(DIR_O)\LexAPDL.obj \ + $(DIR_O)\LexAsm.obj \ + $(DIR_O)\LexAsn1.obj \ + $(DIR_O)\LexASY.obj \ + $(DIR_O)\LexAU3.obj \ + $(DIR_O)\LexAVE.obj \ + $(DIR_O)\LexBaan.obj \ + $(DIR_O)\LexBash.obj \ + $(DIR_O)\LexBasic.obj \ + $(DIR_O)\LexBullant.obj \ + $(DIR_O)\LexCaml.obj \ + $(DIR_O)\LexCLW.obj \ + $(DIR_O)\LexCmake.obj \ + $(DIR_O)\LexConf.obj \ + $(DIR_O)\LexCPP.obj \ + $(DIR_O)\LexCrontab.obj \ + $(DIR_O)\LexCsound.obj \ + $(DIR_O)\LexCSS.obj \ + $(DIR_O)\LexD.obj \ + $(DIR_O)\LexEiffel.obj \ + $(DIR_O)\LexErlang.obj \ + $(DIR_O)\LexEScript.obj \ + $(DIR_O)\LexFlagship.obj \ + $(DIR_O)\LexForth.obj \ + $(DIR_O)\LexFortran.obj \ + $(DIR_O)\LexGAP.obj \ + $(DIR_O)\LexGui4Cli.obj \ + $(DIR_O)\LexHaskell.obj \ + $(DIR_O)\LexHTML.obj \ + $(DIR_O)\LexInno.obj \ + $(DIR_O)\LexKix.obj \ + $(DIR_O)\LexLisp.obj \ + $(DIR_O)\LexLout.obj \ + $(DIR_O)\LexLua.obj \ + $(DIR_O)\LexMagik.obj \ + $(DIR_O)\LexMatlab.obj \ + $(DIR_O)\LexMetapost.obj \ + $(DIR_O)\LexMMIXAL.obj \ + $(DIR_O)\LexMPT.obj \ + $(DIR_O)\LexMSSQL.obj \ + $(DIR_O)\LexNsis.obj \ + $(DIR_O)\LexObjC.obj \ + $(DIR_O)\LexOpal.obj \ + $(DIR_O)\LexOthers.obj \ + $(DIR_O)\LexPascal.obj \ + $(DIR_O)\LexPB.obj \ + $(DIR_O)\LexPerl.obj \ + $(DIR_O)\LexPLM.obj \ + $(DIR_O)\LexPOV.obj \ + $(DIR_O)\LexPowerShell.obj \ + $(DIR_O)\LexProgress.obj \ + $(DIR_O)\LexPS.obj \ + $(DIR_O)\LexPython.obj \ + $(DIR_O)\LexR.obj \ + $(DIR_O)\LexRebol.obj \ + $(DIR_O)\LexRuby.obj \ + $(DIR_O)\LexScriptol.obj \ + $(DIR_O)\LexSearchResult.obj \ + $(DIR_O)\LexSmalltalk.obj \ + $(DIR_O)\LexSpecman.obj \ + $(DIR_O)\LexSpice.obj \ + $(DIR_O)\LexSQL.obj \ + $(DIR_O)\LexTADS3.obj \ + $(DIR_O)\LexTCL.obj \ + $(DIR_O)\LexTeX.obj \ + $(DIR_O)\LexUser.obj \ + $(DIR_O)\LexVB.obj \ + $(DIR_O)\LexVerilog.obj \ + $(DIR_O)\LexVHDL.obj \ + $(DIR_O)\LexYAML.obj \ + +#--Autogenerated -- end of automatically generated section + +LOBJS=\ + $(DIR_O)\AutoComplete.obj \ + $(DIR_O)\CallTip.obj \ + $(DIR_O)\CellBuffer.obj \ + $(DIR_O)\ContractionState.obj \ + $(DIR_O)\CharClassify.obj \ + $(DIR_O)\Decoration.obj \ + $(DIR_O)\Document.obj \ + $(DIR_O)\DocumentAccessor.obj \ + $(DIR_O)\Editor.obj \ + $(DIR_O)\Indicator.obj \ + $(DIR_O)\KeyMap.obj \ + $(DIR_O)\KeyWords.obj \ + $(DIR_O)\LineMarker.obj \ + $(DIR_O)\PlatGTK.obj \ + $(DIR_O)\PositionCache.obj \ + $(MARSHALLER) \ + $(DIR_O)\RESearch.obj \ + $(DIR_O)\RunStyles.obj \ + $(DIR_O)\PropSet.obj \ + $(DIR_O)\ScintillaBaseL.obj \ + $(DIR_O)\ScintillaGTKL.obj \ + $(DIR_O)\Style.obj \ + $(DIR_O)\StyleContext.obj \ + $(DIR_O)\UniConversion.obj \ + $(DIR_O)\ViewStyle.obj \ + $(DIR_O)\XPM.obj \ + $(DIR_O)\ExternalLexer.obj \ + $(LEXOBJS) + +!IF "$(VENDOR)"=="MICROSOFT" + +$(STATIC_LIB): $(LOBJS) #$(DIR_O)\ScintRes.res + lib.exe /OUT:$@ $(LOBJS) $(LIBS) + +$(COMPONENT): $(SOBJS) #$(DIR_O)\ScintRes.res + $(LD) $(LDFLAGS) /DLL /OUT:$@ $(SOBJS) $(LIBS) + +$(DIR_O)\ScintRes.res : ScintRes.rc + $(RC) /fo$@ $(*B).rc + +$(LEXCOMPONENT): $(LOBJS) #$(DIR_O)\ScintRes.res + $(LD) $(LDFLAGS) /DLL /OUT:$@ $(LOBJS) $(LIBS) + +!ELSE + +$(STATIC_LIB): $(LOBJS) #$(DIR_O)\ScintRes.res + $(LD) /OUT:$@ $(LOBJS) $(LIBS) + +$(COMPONENT): $(SOBJS) ScintRes.res + $(LD) $(LDFLAGS) -Tpd -c c0d32 $(SOBJS), $@, , $(LIBS), , ScintRes.res + +$(DIR_O)\ScintRes.res: ScintRes.rc + $(RC) $*.rc + +$(LEXCOMPONENT): $(LOBJS) + $(LD) $(LDFLAGS) -Tpd -c c0d32 $(LOBJS), $@, , $(LIBS), , ScintRes.res + +!ENDIF + +# Define how to build all the objects and what they depend on + +# Most of the source is in ..\src with a couple in this directory +{..\src}.cxx{$(DIR_O)}.obj: + $(CC) $(INCLUDEDIRS) $(CXXFLAGS) -c $(NAMEFLAG)$@ $< +{.}.cxx{$(DIR_O)}.obj: + $(CC) $(INCLUDEDIRS) $(CXXFLAGS) -c $(NAMEFLAG)$@ $< +{.}.c{$(DIR_O)}.obj: + $(CC) $(INCLUDEDIRS) $(CFLAGS) -c $(NAMEFLAG)$@ $< + +# Some source files are compiled into more than one object because of different conditional compilation +$(DIR_O)\ScintillaBaseL.obj: ..\src\ScintillaBase.cxx + $(CC) $(INCLUDEDIRS) $(CXXFLAGS) -DSCI_LEXER -c $(NAMEFLAG)$@ ..\src\ScintillaBase.cxx + +$(DIR_O)\ScintillaGTKL.obj: ScintillaGTK.cxx + $(CC) $(INCLUDEDIRS) $(CXXFLAGS) -DSCI_LEXER -c $(NAMEFLAG)$@ ScintillaGTK.cxx + +$(DIR_O)\ScintillaGTKS.obj: ScintillaGTK.cxx + $(CC) $(INCLUDEDIRS) $(CXXFLAGS) -DSTATIC_BUILD -c $(NAMEFLAG)$@ ScintillaGTK.cxx + +# Dependencies + +# All lexers depend on this set of headers +LEX_HEADERS=..\include\Platform.h ..\include\PropSet.h \ + ..\include\SString.h ..\include\Accessor.h ..\include\KeyWords.h \ + ..\include\Scintilla.h ..\include\SciLexer.h ..\src\StyleContext.h + +$(DIR_O)\AutoComplete.obj: ../src/AutoComplete.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../src/AutoComplete.h + +$(DIR_O)\CallTip.obj: ../src/CallTip.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/CallTip.h + +$(DIR_O)\CellBuffer.obj: ../src/CellBuffer.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/SVector.h ../src/SplitVector.h \ + ../src/Partitioning.h ../src/CellBuffer.h + +$(DIR_O)\CharClassify.obj: ../src/CharClassify.cxx ../src/CharClassify.h + +$(DIR_O)\ContractionState.obj: ../src/ContractionState.cxx ../include/Platform.h \ + ../src/ContractionState.h + +$(DIR_O)\Document.obj: ../src/Document.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/SVector.h ../src/SplitVector.h \ + ../src/Partitioning.h ../src/CellBuffer.h ../src/CharClassify.h \ + ../src/Document.h ../src/RESearch.h + +$(DIR_O)\DocumentAccessor.obj: ../src/DocumentAccessor.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../src/SVector.h \ + ../include/Accessor.h ../src/DocumentAccessor.h ../src/SplitVector.h \ + ../src/Partitioning.h ../src/CellBuffer.h ../include/Scintilla.h \ + ../src/CharClassify.h ../src/Document.h + +$(DIR_O)\Editor.obj: ../src/Editor.cxx ../include/Platform.h ../include/Scintilla.h \ + ../src/ContractionState.h ../src/SVector.h ../src/SplitVector.h \ + ../src/Partitioning.h ../src/CellBuffer.h ../src/KeyMap.h \ + ../src/RunStyles.h ../src/Indicator.h ../src/XPM.h ../src/LineMarker.h \ + ../src/Style.h ../src/ViewStyle.h ../src/CharClassify.h \ + ../src/Document.h ../src/Editor.h ../src/PositionCache.h + +$(DIR_O)\ExternalLexer.obj: ../src/ExternalLexer.cxx ../include/Platform.h \ + ../include/Scintilla.h ../include/SciLexer.h ../include/PropSet.h \ + ../include/SString.h ../include/Accessor.h ../src/DocumentAccessor.h \ + ../include/KeyWords.h ../src/ExternalLexer.h + +$(DIR_O)\Indicator.obj: ../src/Indicator.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/SplitVector.h ../src/Partitioning.h \ + ../src/RunStyles.h ../src/Indicator.h + +$(DIR_O)\KeyMap.obj: ../src/KeyMap.cxx ../include/Platform.h ../include/Scintilla.h \ + ../src/KeyMap.h + +$(DIR_O)\KeyWords.obj: ../src/KeyWords.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/KeyWords.h ../include/Scintilla.h ../include/SciLexer.h + +#++Autogenerated -- run src/LexGen.py to regenerate +#**\n\($(DIR_O)\\\*.obj: ..\\src\\\*.cxx $(LEX_HEADERS)\n\n\) + +$(DIR_O)\LexAbaqus.obj: ..\src\LexAbaqus.cxx $(LEX_HEADERS) + +$(DIR_O)\LexAda.obj: ..\src\LexAda.cxx $(LEX_HEADERS) + +$(DIR_O)\LexAPDL.obj: ..\src\LexAPDL.cxx $(LEX_HEADERS) + +$(DIR_O)\LexAsm.obj: ..\src\LexAsm.cxx $(LEX_HEADERS) + +$(DIR_O)\LexAsn1.obj: ..\src\LexAsn1.cxx $(LEX_HEADERS) + +$(DIR_O)\LexASY.obj: ..\src\LexASY.cxx $(LEX_HEADERS) + +$(DIR_O)\LexAU3.obj: ..\src\LexAU3.cxx $(LEX_HEADERS) + +$(DIR_O)\LexAVE.obj: ..\src\LexAVE.cxx $(LEX_HEADERS) + +$(DIR_O)\LexBaan.obj: ..\src\LexBaan.cxx $(LEX_HEADERS) + +$(DIR_O)\LexBash.obj: ..\src\LexBash.cxx $(LEX_HEADERS) + +$(DIR_O)\LexBasic.obj: ..\src\LexBasic.cxx $(LEX_HEADERS) + +$(DIR_O)\LexBullant.obj: ..\src\LexBullant.cxx $(LEX_HEADERS) + +$(DIR_O)\LexCaml.obj: ..\src\LexCaml.cxx $(LEX_HEADERS) + +$(DIR_O)\LexCLW.obj: ..\src\LexCLW.cxx $(LEX_HEADERS) + +$(DIR_O)\LexCmake.obj: ..\src\LexCmake.cxx $(LEX_HEADERS) + +$(DIR_O)\LexConf.obj: ..\src\LexConf.cxx $(LEX_HEADERS) + +$(DIR_O)\LexCPP.obj: ..\src\LexCPP.cxx $(LEX_HEADERS) + +$(DIR_O)\LexCrontab.obj: ..\src\LexCrontab.cxx $(LEX_HEADERS) + +$(DIR_O)\LexCsound.obj: ..\src\LexCsound.cxx $(LEX_HEADERS) + +$(DIR_O)\LexCSS.obj: ..\src\LexCSS.cxx $(LEX_HEADERS) + +$(DIR_O)\LexD.obj: ..\src\LexD.cxx $(LEX_HEADERS) + +$(DIR_O)\LexEiffel.obj: ..\src\LexEiffel.cxx $(LEX_HEADERS) + +$(DIR_O)\LexErlang.obj: ..\src\LexErlang.cxx $(LEX_HEADERS) + +$(DIR_O)\LexEScript.obj: ..\src\LexEScript.cxx $(LEX_HEADERS) + +$(DIR_O)\LexFlagship.obj: ..\src\LexFlagship.cxx $(LEX_HEADERS) + +$(DIR_O)\LexForth.obj: ..\src\LexForth.cxx $(LEX_HEADERS) + +$(DIR_O)\LexFortran.obj: ..\src\LexFortran.cxx $(LEX_HEADERS) + +$(DIR_O)\LexGAP.obj: ..\src\LexGAP.cxx $(LEX_HEADERS) + +$(DIR_O)\LexGui4Cli.obj: ..\src\LexGui4Cli.cxx $(LEX_HEADERS) + +$(DIR_O)\LexHaskell.obj: ..\src\LexHaskell.cxx $(LEX_HEADERS) + +$(DIR_O)\LexHTML.obj: ..\src\LexHTML.cxx $(LEX_HEADERS) + +$(DIR_O)\LexInno.obj: ..\src\LexInno.cxx $(LEX_HEADERS) + +$(DIR_O)\LexKix.obj: ..\src\LexKix.cxx $(LEX_HEADERS) + +$(DIR_O)\LexLisp.obj: ..\src\LexLisp.cxx $(LEX_HEADERS) + +$(DIR_O)\LexLout.obj: ..\src\LexLout.cxx $(LEX_HEADERS) + +$(DIR_O)\LexLua.obj: ..\src\LexLua.cxx $(LEX_HEADERS) + +$(DIR_O)\LexMagik.obj: ..\src\LexMagik.cxx $(LEX_HEADERS) + +$(DIR_O)\LexMatlab.obj: ..\src\LexMatlab.cxx $(LEX_HEADERS) + +$(DIR_O)\LexMetapost.obj: ..\src\LexMetapost.cxx $(LEX_HEADERS) + +$(DIR_O)\LexMMIXAL.obj: ..\src\LexMMIXAL.cxx $(LEX_HEADERS) + +$(DIR_O)\LexMPT.obj: ..\src\LexMPT.cxx $(LEX_HEADERS) + +$(DIR_O)\LexMSSQL.obj: ..\src\LexMSSQL.cxx $(LEX_HEADERS) + +$(DIR_O)\LexNsis.obj: ..\src\LexNsis.cxx $(LEX_HEADERS) + +$(DIR_O)\LexObjC.obj: ..\src\LexObjC.cxx $(LEX_HEADERS) + +$(DIR_O)\LexOpal.obj: ..\src\LexOpal.cxx $(LEX_HEADERS) + +$(DIR_O)\LexOthers.obj: ..\src\LexOthers.cxx $(LEX_HEADERS) + +$(DIR_O)\LexPascal.obj: ..\src\LexPascal.cxx $(LEX_HEADERS) + +$(DIR_O)\LexPB.obj: ..\src\LexPB.cxx $(LEX_HEADERS) + +$(DIR_O)\LexPerl.obj: ..\src\LexPerl.cxx $(LEX_HEADERS) + +$(DIR_O)\LexPLM.obj: ..\src\LexPLM.cxx $(LEX_HEADERS) + +$(DIR_O)\LexPOV.obj: ..\src\LexPOV.cxx $(LEX_HEADERS) + +$(DIR_O)\LexPowerShell.obj: ..\src\LexPowerShell.cxx $(LEX_HEADERS) + +$(DIR_O)\LexProgress.obj: ..\src\LexProgress.cxx $(LEX_HEADERS) + +$(DIR_O)\LexPS.obj: ..\src\LexPS.cxx $(LEX_HEADERS) + +$(DIR_O)\LexPython.obj: ..\src\LexPython.cxx $(LEX_HEADERS) + +$(DIR_O)\LexR.obj: ..\src\LexR.cxx $(LEX_HEADERS) + +$(DIR_O)\LexRebol.obj: ..\src\LexRebol.cxx $(LEX_HEADERS) + +$(DIR_O)\LexRuby.obj: ..\src\LexRuby.cxx $(LEX_HEADERS) + +$(DIR_O)\LexScriptol.obj: ..\src\LexScriptol.cxx $(LEX_HEADERS) + +$(DIR_O)\LexSearchResult.obj: ..\src\LexSearchResult.cxx $(LEX_HEADERS) + +$(DIR_O)\LexSmalltalk.obj: ..\src\LexSmalltalk.cxx $(LEX_HEADERS) + +$(DIR_O)\LexSpecman.obj: ..\src\LexSpecman.cxx $(LEX_HEADERS) + +$(DIR_O)\LexSpice.obj: ..\src\LexSpice.cxx $(LEX_HEADERS) + +$(DIR_O)\LexSQL.obj: ..\src\LexSQL.cxx $(LEX_HEADERS) + +$(DIR_O)\LexTADS3.obj: ..\src\LexTADS3.cxx $(LEX_HEADERS) + +$(DIR_O)\LexTCL.obj: ..\src\LexTCL.cxx $(LEX_HEADERS) + +$(DIR_O)\LexTeX.obj: ..\src\LexTeX.cxx $(LEX_HEADERS) + +$(DIR_O)\LexUser.obj: ..\src\LexUser.cxx $(LEX_HEADERS) + +$(DIR_O)\LexVB.obj: ..\src\LexVB.cxx $(LEX_HEADERS) + +$(DIR_O)\LexVerilog.obj: ..\src\LexVerilog.cxx $(LEX_HEADERS) + +$(DIR_O)\LexVHDL.obj: ..\src\LexVHDL.cxx $(LEX_HEADERS) + +$(DIR_O)\LexYAML.obj: ..\src\LexYAML.cxx $(LEX_HEADERS) + + +#--Autogenerated -- end of automatically generated section + +$(DIR_O)\LineMarker.obj: ../src/LineMarker.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/XPM.h ../src/LineMarker.h + +$(DIR_O)\PlatGTK.obj: PlatGTK.cxx ../include/Platform.h \ + ../src/UniConversion.h ../src/XPM.h + +$(DIR_O)\PositionCache.obj: ../src/Editor.cxx ../include/Platform.h ../include/Scintilla.h \ + ../src/ContractionState.h ../src/SVector.h ../src/SplitVector.h \ + ../src/Partitioning.h ../src/CellBuffer.h ../src/KeyMap.h \ + ../src/RunStyles.h ../src/Indicator.h ../src/XPM.h ../src/LineMarker.h \ + ../src/Style.h ../src/ViewStyle.h ../src/CharClassify.h \ + ../src/Decoration.h ../src/Document.h ../src/Editor.h ../src/PositionCache.h + +$(DIR_O)\PropSet.obj: ../src/PropSet.cxx ../include/Platform.h ../include/PropSet.h \ + ../include/SString.h + +$(DIR_O)\RESearch.obj: ../src/RESearch.cxx ../src/CharClassify.h ../src/RESearch.h + +$(DIR_O)\RunStyles.obj: ../src/RunStyles.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/SplitVector.h ../src/Partitioning.h \ + ../src/RunStyles.h + +$(DIR_O)\ScintillaBase.obj: ../src/ScintillaBase.cxx ../include/Platform.h \ + ../include/Scintilla.h ../include/PropSet.h ../include/SString.h \ + ../src/ContractionState.h ../src/SVector.h ../src/SplitVector.h \ + ../src/Partitioning.h ../src/RunStyles.h ../src/CellBuffer.h \ + ../src/CallTip.h ../src/KeyMap.h ../src/Indicator.h ../src/XPM.h \ + ../src/LineMarker.h ../src/Style.h ../src/ViewStyle.h \ + ../src/AutoComplete.h ../src/CharClassify.h ../src/Document.h \ + ../src/Editor.h ../src/ScintillaBase.h + +$(DIR_O)\ScintillaBaseL.obj: ../src/ScintillaBase.cxx ../include/Platform.h \ + ../include/Scintilla.h ../include/PropSet.h ../include/SString.h \ + ../src/ContractionState.h ../src/SVector.h ../src/SplitVector.h \ + ../src/Partitioning.h ../src/RunStyles.h ../src/CellBuffer.h \ + ../src/CallTip.h ../src/KeyMap.h ../src/Indicator.h ../src/XPM.h \ + ../src/LineMarker.h ../src/Style.h ../src/ViewStyle.h \ + ../src/AutoComplete.h ../src/CharClassify.h ../src/Document.h \ + ../src/Editor.h ../src/ScintillaBase.h + +$(DIR_O)\ScintillaGTK.obj: ScintillaGTK.cxx ../include/Platform.h \ + ../include/Scintilla.h ../include/SString.h ../src/ContractionState.h \ + ../src/SVector.h ../src/SplitVector.h ../src/Partitioning.h \ + ../src/RunStyles.h ../src/CellBuffer.h ../src/CallTip.h ../src/KeyMap.h \ + ../src/Indicator.h ../src/XPM.h ../src/LineMarker.h ../src/Style.h \ + ../src/AutoComplete.h ../src/ViewStyle.h ../src/CharClassify.h \ + ../src/Document.h ../src/Editor.h ../src/ScintillaBase.h \ + ../src/UniConversion.h + +$(DIR_O)\ScintillaGTKL.obj: ScintillaGTK.cxx ../include/Platform.h \ + ../include/Scintilla.h ../include/SString.h ../src/ContractionState.h \ + ../src/SVector.h ../src/SplitVector.h ../src/Partitioning.h \ + ../src/RunStyles.h ../src/CellBuffer.h ../src/CallTip.h ../src/KeyMap.h \ + ../src/Indicator.h ../src/XPM.h ../src/LineMarker.h ../src/Style.h \ + ../src/AutoComplete.h ../src/ViewStyle.h ../src/CharClassify.h \ + ../src/Document.h ../src/Editor.h ../src/ScintillaBase.h \ + ../src/UniConversion.h + +$(DIR_O)\ScintillaGTKS.obj: ScintillaGTK.cxx ../include/Platform.h \ + ../include/Scintilla.h ../include/SString.h ../src/ContractionState.h \ + ../src/SVector.h ../src/SplitVector.h ../src/Partitioning.h \ + ../src/RunStyles.h ../src/CellBuffer.h ../src/CallTip.h ../src/KeyMap.h \ + ../src/Indicator.h ../src/XPM.h ../src/LineMarker.h ../src/Style.h \ + ../src/AutoComplete.h ../src/ViewStyle.h ../src/CharClassify.h \ + ../src/Document.h ../src/Editor.h ../src/ScintillaBase.h \ + ../src/UniConversion.h + +$(DIR_O)\Style.obj: ../src/Style.cxx ../include/Platform.h ../include/Scintilla.h \ + ../src/Style.h + +$(DIR_O)\StyleContext.obj: ../src/StyleContext.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../src/StyleContext.h + +$(DIR_O)\UniConversion.obj: ../src/UniConversion.cxx ../src/UniConversion.h + +$(DIR_O)\ViewStyle.obj: ../src/ViewStyle.cxx ../include/Platform.h \ + ../include/Scintilla.h ../src/SplitVector.h ../src/Partitioning.h \ + ../src/RunStyles.h ../src/Indicator.h ../src/XPM.h ../src/LineMarker.h \ + ../src/Style.h ../src/ViewStyle.h + +$(DIR_O)\WindowAccessor.obj: ../src/WindowAccessor.cxx ../include/Platform.h \ + ../include/PropSet.h ../include/SString.h ../include/Accessor.h \ + ../include/WindowAccessor.h ../include/Scintilla.h + +$(DIR_O)\XPM.obj: ../src/XPM.cxx ../include/Platform.h ../src/XPM.h diff --git a/scintilla/include/Accessor.h b/scintilla/include/Accessor.h new file mode 100644 index 00000000..bfe4d4dc --- /dev/null +++ b/scintilla/include/Accessor.h @@ -0,0 +1,79 @@ +// Scintilla source code edit control +/** @file Accessor.h + ** Rapid easy access to contents of a Scintilla. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +enum { wsSpace = 1, wsTab = 2, wsSpaceTab = 4, wsInconsistent=8}; + +class Accessor; + +typedef bool (*PFNIsCommentLeader)(Accessor &styler, int pos, int len); + +/** + * Interface to data in a Scintilla. + */ +class Accessor { +protected: + enum {extremePosition=0x7FFFFFFF}; + /** @a bufferSize is a trade off between time taken to copy the characters + * and retrieval overhead. + * @a slopSize positions the buffer before the desired position + * in case there is some backtracking. */ + enum {bufferSize=4000, slopSize=bufferSize/8}; + char buf[bufferSize+1]; + int startPos; + int endPos; + int codePage; + + virtual bool InternalIsLeadByte(char ch)=0; + virtual void Fill(int position)=0; + +public: + Accessor() : startPos(extremePosition), endPos(0), codePage(0) {} + virtual ~Accessor() {} + char operator[](int position) { + if (position < startPos || position >= endPos) { + Fill(position); + } + return buf[position - startPos]; + } + /** Safe version of operator[], returning a defined value for invalid position. */ + char SafeGetCharAt(int position, char chDefault=' ') { + if (position < startPos || position >= endPos) { + Fill(position); + if (position < startPos || position >= endPos) { + // Position is outside range of document + return chDefault; + } + } + return buf[position - startPos]; + } + bool IsLeadByte(char ch) { + return codePage && InternalIsLeadByte(ch); + } + void SetCodePage(int codePage_) { codePage = codePage_; } + + virtual bool Match(int pos, const char *s)=0; + virtual char StyleAt(int position)=0; + virtual int GetLine(int position)=0; + virtual int LineStart(int line)=0; + virtual int LevelAt(int line)=0; + virtual int Length()=0; + virtual void Flush()=0; + virtual int GetLineState(int line)=0; + virtual int SetLineState(int line, int state)=0; + virtual int GetPropertyInt(const char *key, int defaultValue=0)=0; + virtual char *GetProperties()=0; + + // Style setting + virtual void StartAt(unsigned int start, char chMask=31)=0; + virtual void SetFlags(char chFlags_, char chWhile_)=0; + virtual unsigned int GetStartSegment()=0; + virtual void StartSegment(unsigned int pos)=0; + virtual void ColourTo(unsigned int pos, int chAttr)=0; + virtual void SetLevel(int line, int level)=0; + virtual int IndentAmount(int line, int *flags, PFNIsCommentLeader pfnIsCommentLeader = 0)=0; + virtual void IndicatorFill(int start, int end, int indicator, int value)=0; +}; diff --git a/scintilla/include/Face.py b/scintilla/include/Face.py new file mode 100644 index 00000000..59ada3dc --- /dev/null +++ b/scintilla/include/Face.py @@ -0,0 +1,107 @@ +# Module for reading and parsing Scintilla.iface file +import string + +def sanitiseLine(line): + if line[-1:] == '\n': line = line[:-1] + if string.find(line, "##") != -1: + line = line[:string.find(line, "##")] + line = string.strip(line) + return line + +def decodeFunction(featureVal): + retType, rest = string.split(featureVal, " ", 1) + nameIdent, params = string.split(rest, "(") + name, value = string.split(nameIdent, "=") + params, rest = string.split(params, ")") + param1, param2 = string.split(params, ",")[0:2] + return retType, name, value, param1, param2 + +def decodeEvent(featureVal): + retType, rest = string.split(featureVal, " ", 1) + nameIdent, params = string.split(rest, "(") + name, value = string.split(nameIdent, "=") + return retType, name, value + +def decodeParam(p): + param = string.strip(p) + type = "" + name = "" + value = "" + if " " in param: + type, nv = string.split(param, " ") + if "=" in nv: + name, value = string.split(nv, "=") + else: + name = nv + return type, name, value + +class Face: + + def __init__(self): + self.order = [] + self.features = {} + self.values = {} + self.events = {} + + def ReadFromFile(self, name): + currentCategory = "" + currentComment = [] + currentCommentFinished = 0 + file = open(name) + for line in file.readlines(): + line = sanitiseLine(line) + if line: + if line[0] == "#": + if line[1] == " ": + if currentCommentFinished: + currentComment = [] + currentCommentFinished = 0 + currentComment.append(line[2:]) + else: + currentCommentFinished = 1 + featureType, featureVal = string.split(line, " ", 1) + if featureType in ["fun", "get", "set"]: + retType, name, value, param1, param2 = decodeFunction(featureVal) + p1 = decodeParam(param1) + p2 = decodeParam(param2) + self.features[name] = { + "FeatureType": featureType, + "ReturnType": retType, + "Value": value, + "Param1Type": p1[0], "Param1Name": p1[1], "Param1Value": p1[2], + "Param2Type": p2[0], "Param2Name": p2[1], "Param2Value": p2[2], + "Category": currentCategory, "Comment": currentComment + } + if self.values.has_key(value): + raise "Duplicate value " + value + " " + name + self.values[value] = 1 + self.order.append(name) + elif featureType == "evt": + retType, name, value = decodeEvent(featureVal) + self.features[name] = { + "FeatureType": featureType, + "ReturnType": retType, + "Value": value, + "Category": currentCategory, "Comment": currentComment + } + if self.events.has_key(value): + raise "Duplicate event " + value + " " + name + self.events[value] = 1 + self.order.append(name) + elif featureType == "cat": + currentCategory = featureVal + elif featureType == "val": + name, value = string.split(featureVal, "=", 1) + self.features[name] = { + "FeatureType": featureType, + "Category": currentCategory, + "Value": value } + self.order.append(name) + elif featureType == "enu" or featureType == "lex": + name, value = string.split(featureVal, "=", 1) + self.features[name] = { + "FeatureType": featureType, + "Category": currentCategory, + "Value": value } + self.order.append(name) + diff --git a/scintilla/include/HFacer.py b/scintilla/include/HFacer.py new file mode 100644 index 00000000..eacffe56 --- /dev/null +++ b/scintilla/include/HFacer.py @@ -0,0 +1,76 @@ +# HFacer.py - regenerate the Scintilla.h and SciLexer.h files from the Scintilla.iface interface +# definition file. +# The header files are copied to a temporary file apart from the section between a //++Autogenerated +# comment and a //--Autogenerated comment which is generated by the printHFile and printLexHFile +# functions. After the temporary file is created, it is copied back to the original file name. + +import string +import sys +import os +import Face + +def Contains(s,sub): + return string.find(s, sub) != -1 + +def printLexHFile(f,out): + for name in f.order: + v = f.features[name] + if v["FeatureType"] in ["val"]: + if Contains(name, "SCE_") or Contains(name, "SCLEX_"): + out.write("#define " + name + " " + v["Value"] + "\n") + +def printHFile(f,out): + for name in f.order: + v = f.features[name] + if v["Category"] != "Deprecated": + if v["FeatureType"] in ["fun", "get", "set"]: + featureDefineName = "SCI_" + string.upper(name) + out.write("#define " + featureDefineName + " " + v["Value"] + "\n") + elif v["FeatureType"] in ["evt"]: + featureDefineName = "SCN_" + string.upper(name) + out.write("#define " + featureDefineName + " " + v["Value"] + "\n") + elif v["FeatureType"] in ["val"]: + if not (Contains(name, "SCE_") or Contains(name, "SCLEX_")): + out.write("#define " + name + " " + v["Value"] + "\n") + +def CopyWithInsertion(input, output, genfn, definition): + copying = 1 + for line in input.readlines(): + if copying: + output.write(line) + if Contains(line, "//++Autogenerated"): + copying = 0 + genfn(definition, output) + if Contains(line, "//--Autogenerated"): + copying = 1 + output.write(line) + +def contents(filename): + f = file(filename) + t = f.read() + f.close() + return t + +def Regenerate(filename, genfn, definition): + inText = contents(filename) + tempname = "HFacer.tmp" + out = open(tempname,"w") + hfile = open(filename) + CopyWithInsertion(hfile, out, genfn, definition) + out.close() + hfile.close() + outText = contents(tempname) + if inText == outText: + os.unlink(tempname) + else: + os.unlink(filename) + os.rename(tempname, filename) + +f = Face.Face() +try: + f.ReadFromFile("Scintilla.iface") + Regenerate("Scintilla.h", printHFile, f) + Regenerate("SciLexer.h", printLexHFile, f) + print "Maximum ID is", max([x for x in f.values if int(x) < 3000]) +except: + raise diff --git a/scintilla/include/KeyWords.h b/scintilla/include/KeyWords.h new file mode 100644 index 00000000..b9f88ac0 --- /dev/null +++ b/scintilla/include/KeyWords.h @@ -0,0 +1,90 @@ +// Scintilla source code edit control +/** @file KeyWords.h + ** Colourise for particular languages. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +typedef void (*LexerFunction)(unsigned int startPos, int lengthDoc, int initStyle, + WordList *keywordlists[], Accessor &styler); + +/** + * A LexerModule is responsible for lexing and folding a particular language. + * The class maintains a list of LexerModules which can be searched to find a + * module appropriate to a particular language. + */ +class LexerModule { +protected: + const LexerModule *next; + int language; + LexerFunction fnLexer; + LexerFunction fnFolder; + const char * const * wordListDescriptions; + int styleBits; + + static const LexerModule *base; + static int nextLanguage; + +public: + const char *languageName; + LexerModule(int language_, + LexerFunction fnLexer_, + const char *languageName_=0, + LexerFunction fnFolder_=0, + const char * const wordListDescriptions_[] = NULL, + int styleBits_=5); + virtual ~LexerModule() { + } + int GetLanguage() const { return language; } + + // -1 is returned if no WordList information is available + int GetNumWordLists() const; + const char *GetWordListDescription(int index) const; + + int GetStyleBitsNeeded() const; + + virtual void Lex(unsigned int startPos, int lengthDoc, int initStyle, + WordList *keywordlists[], Accessor &styler) const; + virtual void Fold(unsigned int startPos, int lengthDoc, int initStyle, + WordList *keywordlists[], Accessor &styler) const; + static const LexerModule *Find(int language); + static const LexerModule *Find(const char *languageName); +}; + +#ifdef SCI_NAMESPACE +} +#endif + +/** + * Check if a character is a space. + * This is ASCII specific but is safe with chars >= 0x80. + */ +inline bool isspacechar(unsigned char ch) { + return (ch == ' ') || ((ch >= 0x09) && (ch <= 0x0d)); +} + +inline bool iswordchar(char ch) { + return isascii(ch) && (isalnum(ch) || ch == '.' || ch == '_'); +} + +inline bool iswordstart(char ch) { + return isascii(ch) && (isalnum(ch) || ch == '_'); +} + +inline bool isoperator(char ch) { + if (isascii(ch) && isalnum(ch)) + return false; + // '.' left out as it is used to make up numbers + if (ch == '%' || ch == '^' || ch == '&' || ch == '*' || + ch == '(' || ch == ')' || ch == '-' || ch == '+' || + ch == '=' || ch == '|' || ch == '{' || ch == '}' || + ch == '[' || ch == ']' || ch == ':' || ch == ';' || + ch == '<' || ch == '>' || ch == ',' || ch == '/' || + ch == '?' || ch == '!' || ch == '.' || ch == '~') + return true; + return false; +} diff --git a/scintilla/include/Platform.h b/scintilla/include/Platform.h new file mode 100644 index 00000000..5ad09f20 --- /dev/null +++ b/scintilla/include/Platform.h @@ -0,0 +1,564 @@ +// Scintilla source code edit control +/** @file Platform.h + ** Interface to platform facilities. Also includes some basic utilities. + ** Implemented in PlatGTK.cxx for GTK+/Linux, PlatWin.cxx for Windows, and PlatWX.cxx for wxWindows. + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef PLATFORM_H +#define PLATFORM_H + +// PLAT_GTK = GTK+ on Linux or Win32 +// PLAT_GTK_WIN32 is defined additionally when running PLAT_GTK under Win32 +// PLAT_WIN = Win32 API on Win32 OS +// PLAT_WX is wxWindows on any supported platform + +//*******************************************************// + +// TODO: add your specific platform header here: + +// Win32 example: +#include + +//*******************************************************// + +#define PLAT_GTK 0 +#define PLAT_GTK_WIN32 0 +#define PLAT_MACOSX 0 +#define PLAT_WIN 0 +#define PLAT_WX 0 +#define PLAT_FOX 0 + +#if defined(FOX) +#undef PLAT_FOX +#define PLAT_FOX 1 + +#elif defined(__WX__) +#undef PLAT_WX +#define PLAT_WX 1 + +#elif defined(GTK) +#undef PLAT_GTK +#define PLAT_GTK 1 + +#ifdef _MSC_VER +#undef PLAT_GTK_WIN32 +#define PLAT_GTK_WIN32 1 +#endif + +#elif defined(MACOSX) +#undef PLAT_MACOSX +#define PLAT_MACOSX 1 + +#else +#undef PLAT_WIN +#define PLAT_WIN 1 + +#endif + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +// Underlying the implementation of the platform classes are platform specific types. +// Sometimes these need to be passed around by client code so they are defined here + +typedef void *FontID; +typedef void *SurfaceID; +typedef void *WindowID; +typedef void *MenuID; +typedef void *TickerID; +typedef void *Function; +typedef void *IdlerID; + +/** + * A geometric point class. + * Point is exactly the same as the Win32 POINT and GTK+ GdkPoint so can be used interchangeably. + */ +class Point { +public: + int x; + int y; + + explicit Point(int x_=0, int y_=0) : x(x_), y(y_) { + } + + // Other automatically defined methods (assignment, copy constructor, destructor) are fine + + static Point FromLong(long lpoint); +}; + +/** + * A geometric rectangle class. + * PRectangle is exactly the same as the Win32 RECT so can be used interchangeably. + * PRectangles contain their top and left sides, but not their right and bottom sides. + */ +class PRectangle { +public: + int left; + int top; + int right; + int bottom; + + PRectangle(int left_=0, int top_=0, int right_=0, int bottom_ = 0) : + left(left_), top(top_), right(right_), bottom(bottom_) { + } + + // Other automatically defined methods (assignment, copy constructor, destructor) are fine + + bool operator==(PRectangle &rc) { + return (rc.left == left) && (rc.right == right) && + (rc.top == top) && (rc.bottom == bottom); + } + bool Contains(Point pt) { + return (pt.x >= left) && (pt.x <= right) && + (pt.y >= top) && (pt.y <= bottom); + } + bool Contains(PRectangle rc) { + return (rc.left >= left) && (rc.right <= right) && + (rc.top >= top) && (rc.bottom <= bottom); + } + bool Intersects(PRectangle other) { + return (right > other.left) && (left < other.right) && + (bottom > other.top) && (top < other.bottom); + } + void Move(int xDelta, int yDelta) { + left += xDelta; + top += yDelta; + right += xDelta; + bottom += yDelta; + } + int Width() { return right - left; } + int Height() { return bottom - top; } + bool Empty() { + return (Height() <= 0) || (Width() <= 0); + } +}; + +/** + * In some circumstances, including Win32 in paletted mode and GTK+, each colour + * must be allocated before use. The desired colours are held in the ColourDesired class, + * and after allocation the allocation entry is stored in the ColourAllocated class. In other + * circumstances, such as Win32 in true colour mode, the allocation process just copies + * the RGB values from the desired to the allocated class. + * As each desired colour requires allocation before it can be used, the ColourPair class + * holds both a ColourDesired and a ColourAllocated + * The Palette class is responsible for managing the palette of colours which contains a + * list of ColourPair objects and performs the allocation. + */ + +/** + * Holds a desired RGB colour. + */ +class ColourDesired { + long co; +public: + ColourDesired(long lcol=0) { + co = lcol; + } + + ColourDesired(unsigned int red, unsigned int green, unsigned int blue) { + Set(red, green, blue); + } + + bool operator==(const ColourDesired &other) const { + return co == other.co; + } + + void Set(long lcol) { + co = lcol; + } + + void Set(unsigned int red, unsigned int green, unsigned int blue) { + co = red | (green << 8) | (blue << 16); + } + + static inline unsigned int ValueOfHex(const char ch) { + if (ch >= '0' && ch <= '9') + return ch - '0'; + else if (ch >= 'A' && ch <= 'F') + return ch - 'A' + 10; + else if (ch >= 'a' && ch <= 'f') + return ch - 'a' + 10; + else + return 0; + } + + void Set(const char *val) { + if (*val == '#') { + val++; + } + unsigned int r = ValueOfHex(val[0]) * 16 + ValueOfHex(val[1]); + unsigned int g = ValueOfHex(val[2]) * 16 + ValueOfHex(val[3]); + unsigned int b = ValueOfHex(val[4]) * 16 + ValueOfHex(val[5]); + Set(r, g, b); + } + + long AsLong() const { + return co; + } + + unsigned int GetRed() { + return co & 0xff; + } + + unsigned int GetGreen() { + return (co >> 8) & 0xff; + } + + unsigned int GetBlue() { + return (co >> 16) & 0xff; + } +}; + +/** + * Holds an allocated RGB colour which may be an approximation to the desired colour. + */ +class ColourAllocated { + long coAllocated; + +public: + + ColourAllocated(long lcol=0) { + coAllocated = lcol; + } + + void Set(long lcol) { + coAllocated = lcol; + } + + long AsLong() const { + return coAllocated; + } +}; + +/** + * Colour pairs hold a desired colour and an allocated colour. + */ +struct ColourPair { + ColourDesired desired; + ColourAllocated allocated; + + ColourPair(ColourDesired desired_=ColourDesired(0,0,0)) { + desired = desired_; + allocated.Set(desired.AsLong()); + } + void Copy() { + allocated.Set(desired.AsLong()); + } +}; + +class Window; // Forward declaration for Palette + +/** + * Colour palette management. + */ +class Palette { + int used; + int size; + ColourPair *entries; +#if PLAT_GTK + void *allocatedPalette; // GdkColor * + int allocatedLen; +#endif + // Private so Palette objects can not be copied + Palette(const Palette &) {} + Palette &operator=(const Palette &) { return *this; } +public: +#if PLAT_WIN + void *hpal; +#endif + bool allowRealization; + + Palette(); + ~Palette(); + + void Release(); + + /** + * This method either adds a colour to the list of wanted colours (want==true) + * or retrieves the allocated colour back to the ColourPair. + * This is one method to make it easier to keep the code for wanting and retrieving in sync. + */ + void WantFind(ColourPair &cp, bool want); + + void Allocate(Window &w); +}; + +/** + * Font management. + */ +class Font { +protected: + FontID id; +#if PLAT_WX + int ascent; +#endif + // Private so Font objects can not be copied + Font(const Font &) {} + Font &operator=(const Font &) { id=0; return *this; } +public: + Font(); + virtual ~Font(); + + virtual void Create(const char *faceName, int characterSet, int size, + bool bold, bool italic, bool extraFontFlag=false); + virtual void Release(); + + FontID GetID() { return id; } + // Alias another font - caller guarantees not to Release + void SetID(FontID id_) { id = id_; } + friend class Surface; + friend class SurfaceImpl; +}; + +/** + * A surface abstracts a place to draw. + */ +class Surface { +private: + // Private so Surface objects can not be copied + Surface(const Surface &) {} + Surface &operator=(const Surface &) { return *this; } +public: + Surface() {}; + virtual ~Surface() {}; + static Surface *Allocate(); + + virtual void Init(WindowID wid)=0; + virtual void Init(SurfaceID sid, WindowID wid)=0; + virtual void InitPixMap(int width, int height, Surface *surface_, WindowID wid)=0; + + virtual void Release()=0; + virtual bool Initialised()=0; + virtual void PenColour(ColourAllocated fore)=0; + virtual int LogPixelsY()=0; + virtual int DeviceHeightFont(int points)=0; + virtual void MoveTo(int x_, int y_)=0; + virtual void LineTo(int x_, int y_)=0; + virtual void Polygon(Point *pts, int npts, ColourAllocated fore, ColourAllocated back)=0; + virtual void RectangleDraw(PRectangle rc, ColourAllocated fore, ColourAllocated back)=0; + virtual void FillRectangle(PRectangle rc, ColourAllocated back)=0; + virtual void FillRectangle(PRectangle rc, Surface &surfacePattern)=0; + virtual void RoundedRectangle(PRectangle rc, ColourAllocated fore, ColourAllocated back)=0; + virtual void AlphaRectangle(PRectangle rc, int cornerSize, ColourAllocated fill, int alphaFill, + ColourAllocated outline, int alphaOutline, int flags)=0; + virtual void Ellipse(PRectangle rc, ColourAllocated fore, ColourAllocated back)=0; + virtual void Copy(PRectangle rc, Point from, Surface &surfaceSource)=0; + + virtual void DrawTextNoClip(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back)=0; + virtual void DrawTextClipped(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore, ColourAllocated back)=0; + virtual void DrawTextTransparent(PRectangle rc, Font &font_, int ybase, const char *s, int len, ColourAllocated fore)=0; + virtual void MeasureWidths(Font &font_, const char *s, int len, int *positions)=0; + virtual int WidthText(Font &font_, const char *s, int len)=0; + virtual int WidthChar(Font &font_, char ch)=0; + virtual int Ascent(Font &font_)=0; + virtual int Descent(Font &font_)=0; + virtual int InternalLeading(Font &font_)=0; + virtual int ExternalLeading(Font &font_)=0; + virtual int Height(Font &font_)=0; + virtual int AverageCharWidth(Font &font_)=0; + + virtual int SetPalette(Palette *pal, bool inBackGround)=0; + virtual void SetClip(PRectangle rc)=0; + virtual void FlushCachedState()=0; + + virtual void SetUnicodeMode(bool unicodeMode_)=0; + virtual void SetDBCSMode(int codePage)=0; +}; + +/** + * A simple callback action passing one piece of untyped user data. + */ +typedef void (*CallBackAction)(void*); + +/** + * Class to hide the details of window manipulation. + * Does not own the window which will normally have a longer life than this object. + */ +class Window { +protected: + WindowID id; +#if PLAT_MACOSX + void *windowRef; + void *control; +#endif +public: + Window() : id(0), cursorLast(cursorInvalid) { +#if PLAT_MACOSX + windowRef = 0; + control = 0; +#endif + } + Window(const Window &source) : id(source.id), cursorLast(cursorInvalid) { +#if PLAT_MACOSX + windowRef = 0; + control = 0; +#endif + } + virtual ~Window(); + Window &operator=(WindowID id_) { + id = id_; + return *this; + } + WindowID GetID() const { return id; } + bool Created() const { return id != 0; } + void Destroy(); + bool HasFocus(); + PRectangle GetPosition(); + void SetPosition(PRectangle rc); + void SetPositionRelative(PRectangle rc, Window relativeTo); + PRectangle GetClientPosition(); + void Show(bool show=true); + void InvalidateAll(); + void InvalidateRectangle(PRectangle rc); + virtual void SetFont(Font &font); + enum Cursor { cursorInvalid, cursorText, cursorArrow, cursorUp, cursorWait, cursorHoriz, cursorVert, cursorReverseArrow, cursorHand }; + void SetCursor(Cursor curs); + void SetTitle(const char *s); + PRectangle GetMonitorRect(Point pt); +#if PLAT_MACOSX + void SetWindow(void *ref) { windowRef = ref; }; + void SetControl(void *_control) { control = _control; }; +#endif +private: + Cursor cursorLast; +}; + +/** + * Listbox management. + */ + +class ListBox : public Window { +public: + ListBox(); + virtual ~ListBox(); + static ListBox *Allocate(); + + virtual void SetFont(Font &font)=0; + virtual void Create(Window &parent, int ctrlID, Point location, int lineHeight_, bool unicodeMode_)=0; + virtual void SetAverageCharWidth(int width)=0; + virtual void SetVisibleRows(int rows)=0; + virtual int GetVisibleRows() const=0; + virtual PRectangle GetDesiredRect()=0; + virtual int CaretFromEdge()=0; + virtual void Clear()=0; + virtual void Append(char *s, int type = -1)=0; + virtual int Length()=0; + virtual void Select(int n)=0; + virtual int GetSelection()=0; + virtual int Find(const char *prefix)=0; + virtual void GetValue(int n, char *value, int len)=0; + virtual void RegisterImage(int type, const char *xpm_data)=0; + virtual void ClearRegisteredImages()=0; + virtual void SetDoubleClickAction(CallBackAction, void *)=0; + virtual void SetList(const char* list, char separator, char typesep)=0; +}; + +/** + * Menu management. + */ +class Menu { + MenuID id; +public: + Menu(); + MenuID GetID() { return id; } + void CreatePopUp(); + void Destroy(); + void Show(Point pt, Window &w); +}; + +class ElapsedTime { + long bigBit; + long littleBit; +public: + ElapsedTime(); + double Duration(bool reset=false); +}; + +/** + * Dynamic Library (DLL/SO/...) loading + */ +class DynamicLibrary { +public: + virtual ~DynamicLibrary() {}; + + /// @return Pointer to function "name", or NULL on failure. + virtual Function FindFunction(const char *name) = 0; + + /// @return true if the library was loaded successfully. + virtual bool IsValid() = 0; + + /// @return An instance of a DynamicLibrary subclass with "modulePath" loaded. + static DynamicLibrary *Load(const char *modulePath); +}; + +/** + * Platform class used to retrieve system wide parameters such as double click speed + * and chrome colour. Not a creatable object, more of a module with several functions. + */ +class Platform { + // Private so Platform objects can not be copied + Platform(const Platform &) {} + Platform &operator=(const Platform &) { return *this; } +public: + // Should be private because no new Platforms are ever created + // but gcc warns about this + Platform() {} + ~Platform() {} + static ColourDesired Chrome(); + static ColourDesired ChromeHighlight(); + static const char *DefaultFont(); + static int DefaultFontSize(); + static unsigned int DoubleClickTime(); + static bool MouseButtonBounce(); + static void DebugDisplay(const char *s); + static bool IsKeyDown(int key); + static long SendScintilla( + WindowID w, unsigned int msg, unsigned long wParam=0, long lParam=0); + static long SendScintillaPointer( + WindowID w, unsigned int msg, unsigned long wParam=0, void *lParam=0); + static bool IsDBCSLeadByte(int codePage, char ch); + static int DBCSCharLength(int codePage, const char *s); + static int DBCSCharMaxLength(); + + // These are utility functions not really tied to a platform + static int Minimum(int a, int b); + static int Maximum(int a, int b); + // Next three assume 16 bit shorts and 32 bit longs + static long LongFromTwoShorts(short a,short b) { + return (a) | ((b) << 16); + } + static short HighShortFromLong(long x) { + return static_cast(x >> 16); + } + static short LowShortFromLong(long x) { + return static_cast(x & 0xffff); + } + static void DebugPrintf(const char *format, ...); + static bool ShowAssertionPopUps(bool assertionPopUps_); + static void Assert(const char *c, const char *file, int line); + static int Clamp(int val, int minVal, int maxVal); +}; + +#ifdef NDEBUG +#define PLATFORM_ASSERT(c) ((void)0) +#else +#ifdef SCI_NAMESPACE +#define PLATFORM_ASSERT(c) ((c) ? (void)(0) : Scintilla::Platform::Assert(#c, __FILE__, __LINE__)) +#else +#define PLATFORM_ASSERT(c) ((c) ? (void)(0) : Platform::Assert(#c, __FILE__, __LINE__)) +#endif +#endif + +#ifdef SCI_NAMESPACE +} +#endif + +// Shut up annoying Visual C++ warnings: +#ifdef _MSC_VER +#pragma warning(disable: 4244 4309 4514 4710) +#endif + +#endif diff --git a/scintilla/include/PropSet.h b/scintilla/include/PropSet.h new file mode 100644 index 00000000..488d3bbf --- /dev/null +++ b/scintilla/include/PropSet.h @@ -0,0 +1,104 @@ +// Scintilla source code edit control +/** @file PropSet.h + ** A Java style properties file module. + **/ +// Copyright 1998-2002 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef PROPSET_H +#define PROPSET_H +#include "SString.h" + +bool EqualCaseInsensitive(const char *a, const char *b); + +bool isprefix(const char *target, const char *prefix); + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +struct Property { + unsigned int hash; + char *key; + char *val; + Property *next; + Property() : hash(0), key(0), val(0), next(0) {} +}; + +/** + */ +class PropSet { +protected: + enum { hashRoots=31 }; + Property *props[hashRoots]; + Property *enumnext; + int enumhash; + static unsigned int HashString(const char *s, size_t len) { + unsigned int ret = 0; + while (len--) { + ret <<= 4; + ret ^= *s; + s++; + } + return ret; + } + +public: + PropSet *superPS; + PropSet(); + ~PropSet(); + void Set(const char *key, const char *val, int lenKey=-1, int lenVal=-1); + void Set(const char *keyVal); + void Unset(const char *key, int lenKey=-1); + void SetMultiple(const char *s); + SString Get(const char *key) const; + SString GetExpanded(const char *key) const; + SString Expand(const char *withVars, int maxExpands=100) const; + int GetInt(const char *key, int defaultValue=0) const; + void Clear(); + char *ToString() const; // Caller must delete[] the return value + +private: + // copy-value semantics not implemented + PropSet(const PropSet ©); + void operator=(const PropSet &assign); +}; + +/** + */ +class WordList { +public: + // Each word contains at least one character - a empty word acts as sentinel at the end. + char **words; + char *list; + int len; + bool onlyLineEnds; ///< Delimited by any white space or only line ends + bool sorted; + int starts[256]; + WordList(bool onlyLineEnds_ = false) : + words(0), list(0), len(0), onlyLineEnds(onlyLineEnds_), + sorted(false) + {} + ~WordList() { Clear(); } + operator bool() { return len ? true : false; } + void Clear(); + void Set(const char *s); + bool InList(const char *s); + bool InListAbbreviated(const char *s, const char marker); +}; + +inline bool IsAlphabetic(unsigned int ch) { + return ((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z')); +} + +#ifdef SCI_NAMESPACE +} +#endif + +#ifdef _MSC_VER +// Visual C++ doesn't like the private copy idiom for disabling +// the default copy constructor and operator=, but it's fine. +#pragma warning(disable: 4511 4512) +#endif + +#endif diff --git a/scintilla/include/SString.h b/scintilla/include/SString.h new file mode 100644 index 00000000..e376f59c --- /dev/null +++ b/scintilla/include/SString.h @@ -0,0 +1,289 @@ +// SciTE - Scintilla based Text Editor +/** @file SString.h + ** A simple string class. + **/ +// Copyright 1998-2004 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef SSTRING_H +#define SSTRING_H + + +// These functions are implemented because each platform calls them something different. +int CompareCaseInsensitive(const char *a, const char *b); +int CompareNCaseInsensitive(const char *a, const char *b, size_t len); +bool EqualCaseInsensitive(const char *a, const char *b); + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +// Define another string class. +// While it would be 'better' to use std::string, that doubles the executable size. +// An SString may contain embedded nul characters. + +/** + * Base class from which the two other classes (SBuffer & SString) + * are derived. + */ +class SContainer { +public: + /** Type of string lengths (sizes) and positions (indexes). */ + typedef size_t lenpos_t; + /** Out of bounds value indicating that the string argument should be measured. */ + enum { measure_length=0xffffffffU}; + +protected: + char *s; ///< The C string + lenpos_t sSize; ///< The size of the buffer, less 1: ie. the maximum size of the string + + SContainer() : s(0), sSize(0) {} + ~SContainer() { + delete []s; // Suppose it was allocated using StringAllocate + s = 0; + sSize = 0; + } + /** Size of buffer. */ + lenpos_t size() const { + if (s) { + return sSize; + } else { + return 0; + } + } +public: + /** + * Allocate uninitialized memory big enough to fit a string of the given length. + * @return the pointer to the new string + */ + static char *StringAllocate(lenpos_t len); + /** + * Duplicate a buffer/C string. + * Allocate memory of the given size, or big enough to fit the string if length isn't given; + * then copy the given string in the allocated memory. + * @return the pointer to the new string + */ + static char *StringAllocate( + const char *s, ///< The string to duplicate + lenpos_t len=measure_length); ///< The length of memory to allocate. Optional. +}; + + +/** + * @brief A string buffer class. + * + * Main use is to ask an API the length of a string it can provide, + * then to allocate a buffer of the given size, and to provide this buffer + * to the API to put the string. + * This class is intended to be shortlived, to be transformed as SString + * as soon as it holds the string, so it has little members. + * Note: we assume the buffer is filled by the API. If the length can be shorter, + * we should set sLen to strlen(sb.ptr()) in related SString constructor and assignment. + */ +class SBuffer : protected SContainer { +public: + SBuffer(lenpos_t len) { + s = StringAllocate(len); + if (s) { + *s = '\0'; + sSize = len; + } else { + sSize = 0; + } + } +private: + /// Copy constructor + // Here only to be on the safe size, user should avoid returning SBuffer values. + SBuffer(const SBuffer &source) : SContainer() { + s = StringAllocate(source.s, source.sSize); + sSize = (s) ? source.sSize : 0; + } + /// Default assignment operator + // Same here, shouldn't be used + SBuffer &operator=(const SBuffer &source) { + if (this != &source) { + delete []s; + s = StringAllocate(source.s, source.sSize); + sSize = (s) ? source.sSize : 0; + } + return *this; + } +public: + /** Provide direct read/write access to buffer. */ + char *ptr() { + return s; + } + /** Ownership of the buffer have been taken, so release it. */ + void reset() { + s = 0; + sSize = 0; + } + /** Size of buffer. */ + lenpos_t size() const { + return SContainer::size(); + } +}; + + +/** + * @brief A simple string class. + * + * Hold the length of the string for quick operations, + * can have a buffer bigger than the string to avoid too many memory allocations and copies. + * May have embedded zeroes as a result of @a substitute, but relies too heavily on C string + * functions to allow reliable manipulations of these strings, other than simple appends, etc. + */ +class SString : protected SContainer { + lenpos_t sLen; ///< The size of the string in s + lenpos_t sizeGrowth; ///< Minimum growth size when appending strings + enum { sizeGrowthDefault = 64 }; + + bool grow(lenpos_t lenNew); + SString &assign(const char *sOther, lenpos_t sSize_=measure_length); + +public: + SString() : sLen(0), sizeGrowth(sizeGrowthDefault) {} + SString(const SString &source) : SContainer(), sizeGrowth(sizeGrowthDefault) { + s = StringAllocate(source.s, source.sLen); + sSize = sLen = (s) ? source.sLen : 0; + } + SString(const char *s_) : sizeGrowth(sizeGrowthDefault) { + s = StringAllocate(s_); + sSize = sLen = (s) ? strlen(s) : 0; + } + SString(SBuffer &buf) : sizeGrowth(sizeGrowthDefault) { + s = buf.ptr(); + sSize = sLen = buf.size(); + // Consumes the given buffer! + buf.reset(); + } + SString(const char *s_, lenpos_t first, lenpos_t last) : sizeGrowth(sizeGrowthDefault) { + // note: expects the "last" argument to point one beyond the range end (a la STL iterators) + s = StringAllocate(s_ + first, last - first); + sSize = sLen = (s) ? last - first : 0; + } + SString(int i); + SString(double d, int precision); + ~SString() { + sLen = 0; + } + void clear() { + if (s) { + *s = '\0'; + } + sLen = 0; + } + /** Size of buffer. */ + lenpos_t size() const { + return SContainer::size(); + } + /** Size of string in buffer. */ + lenpos_t length() const { + return sLen; + } + /** Read access to a character of the string. */ + char operator[](lenpos_t i) const { + return (s && i < sSize) ? s[i] : '\0'; + } + SString &operator=(const char *source) { + return assign(source); + } + SString &operator=(const SString &source) { + if (this != &source) { + assign(source.s, source.sLen); + } + return *this; + } + bool operator==(const SString &sOther) const; + bool operator!=(const SString &sOther) const { + return !operator==(sOther); + } + bool operator==(const char *sOther) const; + bool operator!=(const char *sOther) const { + return !operator==(sOther); + } + bool contains(char ch) const { + return (s && *s) ? strchr(s, ch) != 0 : false; + } + void setsizegrowth(lenpos_t sizeGrowth_) { + sizeGrowth = sizeGrowth_; + } + const char *c_str() const { + return s ? s : ""; + } + /** Give ownership of buffer to caller which must use delete[] to free buffer. */ + char *detach() { + char *sRet = s; + s = 0; + sSize = 0; + sLen = 0; + return sRet; + } + SString substr(lenpos_t subPos, lenpos_t subLen=measure_length) const; + SString &lowercase(lenpos_t subPos = 0, lenpos_t subLen=measure_length); + SString &uppercase(lenpos_t subPos = 0, lenpos_t subLen=measure_length); + SString &append(const char *sOther, lenpos_t sLenOther=measure_length, char sep = '\0'); + SString &operator+=(const char *sOther) { + return append(sOther, static_cast(measure_length)); + } + SString &operator+=(const SString &sOther) { + return append(sOther.s, sOther.sLen); + } + SString &operator+=(char ch) { + return append(&ch, 1); + } + SString &appendwithseparator(const char *sOther, char sep) { + return append(sOther, strlen(sOther), sep); + } + SString &insert(lenpos_t pos, const char *sOther, lenpos_t sLenOther=measure_length); + + /** + * Remove @a len characters from the @a pos position, included. + * Characters at pos + len and beyond replace characters at pos. + * If @a len is 0, or greater than the length of the string + * starting at @a pos, the string is just truncated at @a pos. + */ + void remove(lenpos_t pos, lenpos_t len); + + SString &change(lenpos_t pos, char ch) { + if (pos < sLen) { // character changed must be in string bounds + *(s + pos) = ch; + } + return *this; + } + /** Read an integral numeric value from the string. */ + int value() const { + return s ? atoi(s) : 0; + } + bool startswith(const char *prefix); + bool endswith(const char *suffix); + int search(const char *sFind, lenpos_t start=0) const; + bool contains(const char *sFind) const { + return search(sFind) >= 0; + } + int substitute(char chFind, char chReplace); + int substitute(const char *sFind, const char *sReplace); + int remove(const char *sFind) { + return substitute(sFind, ""); + } +}; + + +/** + * Duplicate a C string. + * Allocate memory of the given size, or big enough to fit the string if length isn't given; + * then copy the given string in the allocated memory. + * @return the pointer to the new string + */ +inline char *StringDup( + const char *s, ///< The string to duplicate + SContainer::lenpos_t len=SContainer::measure_length) ///< The length of memory to allocate. Optional. +{ + return SContainer::StringAllocate(s, len); +} + +#ifdef SCI_NAMESPACE +} +#endif + +#endif diff --git a/scintilla/include/SciLexer.h b/scintilla/include/SciLexer.h new file mode 100644 index 00000000..f31531c4 --- /dev/null +++ b/scintilla/include/SciLexer.h @@ -0,0 +1,1285 @@ +// Scintilla source code edit control +/** @file SciLexer.h + ** Interface to the added lexer functions in the SciLexer version of the edit control. + **/ +// Copyright 1998-2002 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +// Most of this file is automatically generated from the Scintilla.iface interface definition +// file which contains any comments about the definitions. HFacer.py does the generation. + +#ifndef SCILEXER_H +#define SCILEXER_H + +// SciLexer features - not in standard Scintilla + +//++Autogenerated -- start of section automatically generated from Scintilla.iface +#define SCLEX_CONTAINER 0 +#define SCLEX_NULL 1 +#define SCLEX_PYTHON 2 +#define SCLEX_CPP 3 +#define SCLEX_HTML 4 +#define SCLEX_XML 5 +#define SCLEX_PERL 6 +#define SCLEX_SQL 7 +#define SCLEX_VB 8 +#define SCLEX_PROPERTIES 9 +#define SCLEX_ERRORLIST 10 +#define SCLEX_MAKEFILE 11 +#define SCLEX_BATCH 12 +#define SCLEX_XCODE 13 +#define SCLEX_LATEX 14 +#define SCLEX_LUA 15 +#define SCLEX_DIFF 16 +#define SCLEX_CONF 17 +#define SCLEX_PASCAL 18 +#define SCLEX_AVE 19 +#define SCLEX_ADA 20 +#define SCLEX_LISP 21 +#define SCLEX_RUBY 22 +#define SCLEX_EIFFEL 23 +#define SCLEX_EIFFELKW 24 +#define SCLEX_TCL 25 +#define SCLEX_NNCRONTAB 26 +#define SCLEX_BULLANT 27 +#define SCLEX_VBSCRIPT 28 +#define SCLEX_BAAN 31 +#define SCLEX_MATLAB 32 +#define SCLEX_SCRIPTOL 33 +#define SCLEX_ASM 34 +#define SCLEX_CPPNOCASE 35 +#define SCLEX_FORTRAN 36 +#define SCLEX_F77 37 +#define SCLEX_CSS 38 +#define SCLEX_POV 39 +#define SCLEX_LOUT 40 +#define SCLEX_ESCRIPT 41 +#define SCLEX_PS 42 +#define SCLEX_NSIS 43 +#define SCLEX_MMIXAL 44 +#define SCLEX_CLW 45 +#define SCLEX_CLWNOCASE 46 +#define SCLEX_LOT 47 +#define SCLEX_YAML 48 +#define SCLEX_TEX 49 +#define SCLEX_METAPOST 50 +#define SCLEX_POWERBASIC 51 +#define SCLEX_FORTH 52 +#define SCLEX_ERLANG 53 +#define SCLEX_OCTAVE 54 +#define SCLEX_MSSQL 55 +#define SCLEX_VERILOG 56 +#define SCLEX_KIX 57 +#define SCLEX_GUI4CLI 58 +#define SCLEX_SPECMAN 59 +#define SCLEX_AU3 60 +#define SCLEX_APDL 61 +#define SCLEX_BASH 62 +#define SCLEX_ASN1 63 +#define SCLEX_VHDL 64 +#define SCLEX_CAML 65 +#define SCLEX_BLITZBASIC 66 +#define SCLEX_PUREBASIC 67 +#define SCLEX_HASKELL 68 +#define SCLEX_PHPSCRIPT 69 +#define SCLEX_TADS3 70 +#define SCLEX_REBOL 71 +#define SCLEX_SMALLTALK 72 +#define SCLEX_FLAGSHIP 73 +#define SCLEX_CSOUND 74 +#define SCLEX_FREEBASIC 75 +#define SCLEX_INNOSETUP 76 +#define SCLEX_OPAL 77 +#define SCLEX_SPICE 78 +#define SCLEX_D 79 +#define SCLEX_CMAKE 80 +#define SCLEX_GAP 81 +#define SCLEX_PLM 82 +#define SCLEX_PROGRESS 83 +#define SCLEX_ABAQUS 84 +#define SCLEX_ASYMPTOTE 85 +#define SCLEX_R 86 +#define SCLEX_MAGIK 87 +#define SCLEX_POWERSHELL 88 +#define SCLEX_SEARCHRESULT 98 +#define SCLEX_OBJC 99 +#define SCLEX_USER 100 +#define SCLEX_AUTOMATIC 1000 + +//For All lexer +//#define SCE_UNIVERSAL_SELECT_STYLE 30 +#define SCE_UNIVERSAL_FOUND_STYLE 31 +#define SCE_UNIVERSAL_FOUND_STYLE_2 29 +#define SCE_UNIVERSAL_FOUND_STYLE_INC 28 +#define SCE_UNIVERSAL_TAGMATCH 27 +#define SCE_UNIVERSAL_TAGATTR 26 +#define SCE_UNIVERSAL_FOUND_STYLE_EXT1 25 +#define SCE_UNIVERSAL_FOUND_STYLE_EXT2 24 +#define SCE_UNIVERSAL_FOUND_STYLE_EXT3 23 +#define SCE_UNIVERSAL_FOUND_STYLE_EXT4 22 +#define SCE_UNIVERSAL_FOUND_STYLE_EXT5 21 + +#define SCE_P_DEFAULT 0 +#define SCE_P_COMMENTLINE 1 +#define SCE_P_NUMBER 2 +#define SCE_P_STRING 3 +#define SCE_P_CHARACTER 4 +#define SCE_P_WORD 5 +#define SCE_P_TRIPLE 6 +#define SCE_P_TRIPLEDOUBLE 7 +#define SCE_P_CLASSNAME 8 +#define SCE_P_DEFNAME 9 +#define SCE_P_OPERATOR 10 +#define SCE_P_IDENTIFIER 11 +#define SCE_P_COMMENTBLOCK 12 +#define SCE_P_STRINGEOL 13 +#define SCE_P_WORD2 14 +#define SCE_P_DECORATOR 15 +#define SCE_C_DEFAULT 0 +#define SCE_C_COMMENT 1 +#define SCE_C_COMMENTLINE 2 +#define SCE_C_COMMENTDOC 3 +#define SCE_C_NUMBER 4 +#define SCE_C_WORD 5 +#define SCE_C_STRING 6 +#define SCE_C_CHARACTER 7 +#define SCE_C_UUID 8 +#define SCE_C_PREPROCESSOR 9 +#define SCE_C_OPERATOR 10 +#define SCE_C_IDENTIFIER 11 +#define SCE_C_STRINGEOL 12 +#define SCE_C_VERBATIM 13 +#define SCE_C_REGEX 14 +#define SCE_C_COMMENTLINEDOC 15 +#define SCE_C_WORD2 16 +#define SCE_C_COMMENTDOCKEYWORD 17 +#define SCE_C_COMMENTDOCKEYWORDERROR 18 +#define SCE_C_GLOBALCLASS 19 +#define SCE_D_DEFAULT 0 +#define SCE_D_COMMENT 1 +#define SCE_D_COMMENTLINE 2 +#define SCE_D_COMMENTDOC 3 +#define SCE_D_COMMENTNESTED 4 +#define SCE_D_NUMBER 5 +#define SCE_D_WORD 6 +#define SCE_D_WORD2 7 +#define SCE_D_WORD3 8 +#define SCE_D_TYPEDEF 9 +#define SCE_D_STRING 10 +#define SCE_D_STRINGEOL 11 +#define SCE_D_CHARACTER 12 +#define SCE_D_OPERATOR 13 +#define SCE_D_IDENTIFIER 14 +#define SCE_D_COMMENTLINEDOC 15 +#define SCE_D_COMMENTDOCKEYWORD 16 +#define SCE_D_COMMENTDOCKEYWORDERROR 17 + +#define SCE_SEARCHRESULT_DEFAULT 0 +#define SCE_SEARCHRESULT_SEARCH_HEADER 1 +#define SCE_SEARCHRESULT_FILE_HEADER 2 +#define SCE_SEARCHRESULT_LINE_NUMBER 3 +#define SCE_SEARCHRESULT_WORD2SEARCH 4 +#define SCE_SEARCHRESULT_HIGHLIGHT_LINE 5 +#define SCE_SEARCHRESULT_CURRENT_LINE 6 + +#define SCE_OBJC_DIRECTIVE 20 +#define SCE_OBJC_QUALIFIER 21 + +#define SCE_USER_DEFAULT 0 +#define SCE_USER_COMMENT 1 +#define SCE_USER_COMMENTLINE 2 +#define SCE_USER_NUMBER 4 +#define SCE_USER_WORD1 5 +#define SCE_USER_WORD2 6 +#define SCE_USER_WORD3 7 +#define SCE_USER_WORD4 8 +#define SCE_USER_OPERATOR 10 +#define SCE_USER_IDENTIFIER 11 +#define SCE_USER_BLOCK_OPERATOR_OPEN 12 +#define SCE_USER_BLOCK_OPERATOR_CLOSE 13 +#define SCE_USER_DELIMITER1 14 +#define SCE_USER_DELIMITER2 15 +#define SCE_USER_DELIMITER3 16 + +#define SCE_TCL_DEFAULT 0 +#define SCE_TCL_COMMENT 1 +#define SCE_TCL_COMMENTLINE 2 +#define SCE_TCL_NUMBER 3 +#define SCE_TCL_WORD_IN_QUOTE 4 +#define SCE_TCL_IN_QUOTE 5 +#define SCE_TCL_OPERATOR 6 +#define SCE_TCL_IDENTIFIER 7 +#define SCE_TCL_SUBSTITUTION 8 +#define SCE_TCL_SUB_BRACE 9 +#define SCE_TCL_MODIFIER 10 +#define SCE_TCL_EXPAND 11 +#define SCE_TCL_WORD 12 +#define SCE_TCL_WORD2 13 +#define SCE_TCL_WORD3 14 +#define SCE_TCL_WORD4 15 +#define SCE_TCL_WORD5 16 +#define SCE_TCL_WORD6 17 +#define SCE_TCL_WORD7 18 +#define SCE_TCL_WORD8 19 +#define SCE_TCL_COMMENT_BOX 20 +#define SCE_TCL_BLOCK_COMMENT 21 +#define SCE_H_DEFAULT 0 +#define SCE_H_TAG 1 +#define SCE_H_TAGUNKNOWN 2 +#define SCE_H_ATTRIBUTE 3 +#define SCE_H_ATTRIBUTEUNKNOWN 4 +#define SCE_H_NUMBER 5 +#define SCE_H_DOUBLESTRING 6 +#define SCE_H_SINGLESTRING 7 +#define SCE_H_OTHER 8 +#define SCE_H_COMMENT 9 +#define SCE_H_ENTITY 10 +#define SCE_H_TAGEND 11 +#define SCE_H_XMLSTART 12 +#define SCE_H_XMLEND 13 +#define SCE_H_SCRIPT 14 +#define SCE_H_ASP 15 +#define SCE_H_ASPAT 16 +#define SCE_H_CDATA 17 +#define SCE_H_QUESTION 18 +#define SCE_H_VALUE 19 +#define SCE_H_XCCOMMENT 20 +#define SCE_H_SGML_DEFAULT 21 +#define SCE_H_SGML_COMMAND 22 +#define SCE_H_SGML_1ST_PARAM 23 +#define SCE_H_SGML_DOUBLESTRING 24 +#define SCE_H_SGML_SIMPLESTRING 25 +#define SCE_H_SGML_ERROR 26 +#define SCE_H_SGML_SPECIAL 27 +#define SCE_H_SGML_ENTITY 28 +#define SCE_H_SGML_COMMENT 29 +#define SCE_H_SGML_1ST_PARAM_COMMENT 30 +#define SCE_H_SGML_BLOCK_DEFAULT 31 +#define SCE_HJ_START 40 +#define SCE_HJ_DEFAULT 41 +#define SCE_HJ_COMMENT 42 +#define SCE_HJ_COMMENTLINE 43 +#define SCE_HJ_COMMENTDOC 44 +#define SCE_HJ_NUMBER 45 +#define SCE_HJ_WORD 46 +#define SCE_HJ_KEYWORD 47 +#define SCE_HJ_DOUBLESTRING 48 +#define SCE_HJ_SINGLESTRING 49 +#define SCE_HJ_SYMBOLS 50 +#define SCE_HJ_STRINGEOL 51 +#define SCE_HJ_REGEX 52 +#define SCE_HJA_START 55 +#define SCE_HJA_DEFAULT 56 +#define SCE_HJA_COMMENT 57 +#define SCE_HJA_COMMENTLINE 58 +#define SCE_HJA_COMMENTDOC 59 +#define SCE_HJA_NUMBER 60 +#define SCE_HJA_WORD 61 +#define SCE_HJA_KEYWORD 62 +#define SCE_HJA_DOUBLESTRING 63 +#define SCE_HJA_SINGLESTRING 64 +#define SCE_HJA_SYMBOLS 65 +#define SCE_HJA_STRINGEOL 66 +#define SCE_HJA_REGEX 67 +#define SCE_HB_START 70 +#define SCE_HB_DEFAULT 71 +#define SCE_HB_COMMENTLINE 72 +#define SCE_HB_NUMBER 73 +#define SCE_HB_WORD 74 +#define SCE_HB_STRING 75 +#define SCE_HB_IDENTIFIER 76 +#define SCE_HB_STRINGEOL 77 +#define SCE_HBA_START 80 +#define SCE_HBA_DEFAULT 81 +#define SCE_HBA_COMMENTLINE 82 +#define SCE_HBA_NUMBER 83 +#define SCE_HBA_WORD 84 +#define SCE_HBA_STRING 85 +#define SCE_HBA_IDENTIFIER 86 +#define SCE_HBA_STRINGEOL 87 +#define SCE_HP_START 90 +#define SCE_HP_DEFAULT 91 +#define SCE_HP_COMMENTLINE 92 +#define SCE_HP_NUMBER 93 +#define SCE_HP_STRING 94 +#define SCE_HP_CHARACTER 95 +#define SCE_HP_WORD 96 +#define SCE_HP_TRIPLE 97 +#define SCE_HP_TRIPLEDOUBLE 98 +#define SCE_HP_CLASSNAME 99 +#define SCE_HP_DEFNAME 100 +#define SCE_HP_OPERATOR 101 +#define SCE_HP_IDENTIFIER 102 +#define SCE_HPHP_COMPLEX_VARIABLE 104 +#define SCE_HPA_START 105 +#define SCE_HPA_DEFAULT 106 +#define SCE_HPA_COMMENTLINE 107 +#define SCE_HPA_NUMBER 108 +#define SCE_HPA_STRING 109 +#define SCE_HPA_CHARACTER 110 +#define SCE_HPA_WORD 111 +#define SCE_HPA_TRIPLE 112 +#define SCE_HPA_TRIPLEDOUBLE 113 +#define SCE_HPA_CLASSNAME 114 +#define SCE_HPA_DEFNAME 115 +#define SCE_HPA_OPERATOR 116 +#define SCE_HPA_IDENTIFIER 117 +#define SCE_HPHP_DEFAULT 118 +#define SCE_HPHP_HSTRING 119 +#define SCE_HPHP_SIMPLESTRING 120 +#define SCE_HPHP_WORD 121 +#define SCE_HPHP_NUMBER 122 +#define SCE_HPHP_VARIABLE 123 +#define SCE_HPHP_COMMENT 124 +#define SCE_HPHP_COMMENTLINE 125 +#define SCE_HPHP_HSTRING_VARIABLE 126 +#define SCE_HPHP_OPERATOR 127 +#define SCE_PL_DEFAULT 0 +#define SCE_PL_ERROR 1 +#define SCE_PL_COMMENTLINE 2 +#define SCE_PL_POD 3 +#define SCE_PL_NUMBER 4 +#define SCE_PL_WORD 5 +#define SCE_PL_STRING 6 +#define SCE_PL_CHARACTER 7 +#define SCE_PL_PUNCTUATION 8 +#define SCE_PL_PREPROCESSOR 9 +#define SCE_PL_OPERATOR 10 +#define SCE_PL_IDENTIFIER 11 +#define SCE_PL_SCALAR 12 +#define SCE_PL_ARRAY 13 +#define SCE_PL_HASH 14 +#define SCE_PL_SYMBOLTABLE 15 +#define SCE_PL_VARIABLE_INDEXER 16 +#define SCE_PL_REGEX 17 +#define SCE_PL_REGSUBST 18 +#define SCE_PL_LONGQUOTE 19 +#define SCE_PL_BACKTICKS 20 +#define SCE_PL_DATASECTION 21 +#define SCE_PL_HERE_DELIM 22 +#define SCE_PL_HERE_Q 23 +#define SCE_PL_HERE_QQ 24 +#define SCE_PL_HERE_QX 25 +#define SCE_PL_STRING_Q 26 +#define SCE_PL_STRING_QQ 27 +#define SCE_PL_STRING_QX 28 +#define SCE_PL_STRING_QR 29 +#define SCE_PL_STRING_QW 30 +#define SCE_PL_POD_VERB 31 +#define SCE_PL_SUB_PROTOTYPE 40 +#define SCE_PL_FORMAT_IDENT 41 +#define SCE_PL_FORMAT 42 +#define SCE_RB_DEFAULT 0 +#define SCE_RB_ERROR 1 +#define SCE_RB_COMMENTLINE 2 +#define SCE_RB_POD 3 +#define SCE_RB_NUMBER 4 +#define SCE_RB_WORD 5 +#define SCE_RB_STRING 6 +#define SCE_RB_CHARACTER 7 +#define SCE_RB_CLASSNAME 8 +#define SCE_RB_DEFNAME 9 +#define SCE_RB_OPERATOR 10 +#define SCE_RB_IDENTIFIER 11 +#define SCE_RB_REGEX 12 +#define SCE_RB_GLOBAL 13 +#define SCE_RB_SYMBOL 14 +#define SCE_RB_MODULE_NAME 15 +#define SCE_RB_INSTANCE_VAR 16 +#define SCE_RB_CLASS_VAR 17 +#define SCE_RB_BACKTICKS 18 +#define SCE_RB_DATASECTION 19 +#define SCE_RB_HERE_DELIM 20 +#define SCE_RB_HERE_Q 21 +#define SCE_RB_HERE_QQ 22 +#define SCE_RB_HERE_QX 23 +#define SCE_RB_STRING_Q 24 +#define SCE_RB_STRING_QQ 25 +#define SCE_RB_STRING_QX 26 +#define SCE_RB_STRING_QR 27 +#define SCE_RB_STRING_QW 28 +#define SCE_RB_WORD_DEMOTED 29 +#define SCE_RB_STDIN 30 +#define SCE_RB_STDOUT 31 +#define SCE_RB_STDERR 40 +#define SCE_RB_UPPER_BOUND 41 +#define SCE_B_DEFAULT 0 +#define SCE_B_COMMENT 1 +#define SCE_B_NUMBER 2 +#define SCE_B_KEYWORD 3 +#define SCE_B_STRING 4 +#define SCE_B_PREPROCESSOR 5 +#define SCE_B_OPERATOR 6 +#define SCE_B_IDENTIFIER 7 +#define SCE_B_DATE 8 +#define SCE_B_STRINGEOL 9 +#define SCE_B_KEYWORD2 10 +#define SCE_B_KEYWORD3 11 +#define SCE_B_KEYWORD4 12 +#define SCE_B_CONSTANT 13 +#define SCE_B_ASM 14 +#define SCE_B_LABEL 15 +#define SCE_B_ERROR 16 +#define SCE_B_HEXNUMBER 17 +#define SCE_B_BINNUMBER 18 +#define SCE_PROPS_DEFAULT 0 +#define SCE_PROPS_COMMENT 1 +#define SCE_PROPS_SECTION 2 +#define SCE_PROPS_ASSIGNMENT 3 +#define SCE_PROPS_DEFVAL 4 +#define SCE_PROPS_KEY 5 +#define SCE_L_DEFAULT 0 +#define SCE_L_COMMAND 1 +#define SCE_L_TAG 2 +#define SCE_L_MATH 3 +#define SCE_L_COMMENT 4 +#define SCE_LUA_DEFAULT 0 +#define SCE_LUA_COMMENT 1 +#define SCE_LUA_COMMENTLINE 2 +#define SCE_LUA_COMMENTDOC 3 +#define SCE_LUA_NUMBER 4 +#define SCE_LUA_WORD 5 +#define SCE_LUA_STRING 6 +#define SCE_LUA_CHARACTER 7 +#define SCE_LUA_LITERALSTRING 8 +#define SCE_LUA_PREPROCESSOR 9 +#define SCE_LUA_OPERATOR 10 +#define SCE_LUA_IDENTIFIER 11 +#define SCE_LUA_STRINGEOL 12 +#define SCE_LUA_WORD2 13 +#define SCE_LUA_WORD3 14 +#define SCE_LUA_WORD4 15 +#define SCE_LUA_WORD5 16 +#define SCE_LUA_WORD6 17 +#define SCE_LUA_WORD7 18 +#define SCE_LUA_WORD8 19 +#define SCE_ERR_DEFAULT 0 +#define SCE_ERR_PYTHON 1 +#define SCE_ERR_GCC 2 +#define SCE_ERR_MS 3 +#define SCE_ERR_CMD 4 +#define SCE_ERR_BORLAND 5 +#define SCE_ERR_PERL 6 +#define SCE_ERR_NET 7 +#define SCE_ERR_LUA 8 +#define SCE_ERR_CTAG 9 +#define SCE_ERR_DIFF_CHANGED 10 +#define SCE_ERR_DIFF_ADDITION 11 +#define SCE_ERR_DIFF_DELETION 12 +#define SCE_ERR_DIFF_MESSAGE 13 +#define SCE_ERR_PHP 14 +#define SCE_ERR_ELF 15 +#define SCE_ERR_IFC 16 +#define SCE_ERR_IFORT 17 +#define SCE_ERR_ABSF 18 +#define SCE_ERR_TIDY 19 +#define SCE_ERR_JAVA_STACK 20 +#define SCE_ERR_VALUE 21 +#define SCE_BAT_DEFAULT 0 +#define SCE_BAT_COMMENT 1 +#define SCE_BAT_WORD 2 +#define SCE_BAT_LABEL 3 +#define SCE_BAT_HIDE 4 +#define SCE_BAT_COMMAND 5 +#define SCE_BAT_IDENTIFIER 6 +#define SCE_BAT_OPERATOR 7 +#define SCE_MAKE_DEFAULT 0 +#define SCE_MAKE_COMMENT 1 +#define SCE_MAKE_PREPROCESSOR 2 +#define SCE_MAKE_IDENTIFIER 3 +#define SCE_MAKE_OPERATOR 4 +#define SCE_MAKE_TARGET 5 +#define SCE_MAKE_IDEOL 9 +#define SCE_DIFF_DEFAULT 0 +#define SCE_DIFF_COMMENT 1 +#define SCE_DIFF_COMMAND 2 +#define SCE_DIFF_HEADER 3 +#define SCE_DIFF_POSITION 4 +#define SCE_DIFF_DELETED 5 +#define SCE_DIFF_ADDED 6 +#define SCE_CONF_DEFAULT 0 +#define SCE_CONF_COMMENT 1 +#define SCE_CONF_NUMBER 2 +#define SCE_CONF_IDENTIFIER 3 +#define SCE_CONF_EXTENSION 4 +#define SCE_CONF_PARAMETER 5 +#define SCE_CONF_STRING 6 +#define SCE_CONF_OPERATOR 7 +#define SCE_CONF_IP 8 +#define SCE_CONF_DIRECTIVE 9 +#define SCE_AVE_DEFAULT 0 +#define SCE_AVE_COMMENT 1 +#define SCE_AVE_NUMBER 2 +#define SCE_AVE_WORD 3 +#define SCE_AVE_STRING 6 +#define SCE_AVE_ENUM 7 +#define SCE_AVE_STRINGEOL 8 +#define SCE_AVE_IDENTIFIER 9 +#define SCE_AVE_OPERATOR 10 +#define SCE_AVE_WORD1 11 +#define SCE_AVE_WORD2 12 +#define SCE_AVE_WORD3 13 +#define SCE_AVE_WORD4 14 +#define SCE_AVE_WORD5 15 +#define SCE_AVE_WORD6 16 +#define SCE_ADA_DEFAULT 0 +#define SCE_ADA_WORD 1 +#define SCE_ADA_IDENTIFIER 2 +#define SCE_ADA_NUMBER 3 +#define SCE_ADA_DELIMITER 4 +#define SCE_ADA_CHARACTER 5 +#define SCE_ADA_CHARACTEREOL 6 +#define SCE_ADA_STRING 7 +#define SCE_ADA_STRINGEOL 8 +#define SCE_ADA_LABEL 9 +#define SCE_ADA_COMMENTLINE 10 +#define SCE_ADA_ILLEGAL 11 +#define SCE_BAAN_DEFAULT 0 +#define SCE_BAAN_COMMENT 1 +#define SCE_BAAN_COMMENTDOC 2 +#define SCE_BAAN_NUMBER 3 +#define SCE_BAAN_WORD 4 +#define SCE_BAAN_STRING 5 +#define SCE_BAAN_PREPROCESSOR 6 +#define SCE_BAAN_OPERATOR 7 +#define SCE_BAAN_IDENTIFIER 8 +#define SCE_BAAN_STRINGEOL 9 +#define SCE_BAAN_WORD2 10 +#define SCE_LISP_DEFAULT 0 +#define SCE_LISP_COMMENT 1 +#define SCE_LISP_NUMBER 2 +#define SCE_LISP_KEYWORD 3 +#define SCE_LISP_KEYWORD_KW 4 +#define SCE_LISP_SYMBOL 5 +#define SCE_LISP_STRING 6 +#define SCE_LISP_STRINGEOL 8 +#define SCE_LISP_IDENTIFIER 9 +#define SCE_LISP_OPERATOR 10 +#define SCE_LISP_SPECIAL 11 +#define SCE_LISP_MULTI_COMMENT 12 +#define SCE_EIFFEL_DEFAULT 0 +#define SCE_EIFFEL_COMMENTLINE 1 +#define SCE_EIFFEL_NUMBER 2 +#define SCE_EIFFEL_WORD 3 +#define SCE_EIFFEL_STRING 4 +#define SCE_EIFFEL_CHARACTER 5 +#define SCE_EIFFEL_OPERATOR 6 +#define SCE_EIFFEL_IDENTIFIER 7 +#define SCE_EIFFEL_STRINGEOL 8 +#define SCE_NNCRONTAB_DEFAULT 0 +#define SCE_NNCRONTAB_COMMENT 1 +#define SCE_NNCRONTAB_TASK 2 +#define SCE_NNCRONTAB_SECTION 3 +#define SCE_NNCRONTAB_KEYWORD 4 +#define SCE_NNCRONTAB_MODIFIER 5 +#define SCE_NNCRONTAB_ASTERISK 6 +#define SCE_NNCRONTAB_NUMBER 7 +#define SCE_NNCRONTAB_STRING 8 +#define SCE_NNCRONTAB_ENVIRONMENT 9 +#define SCE_NNCRONTAB_IDENTIFIER 10 +#define SCE_FORTH_DEFAULT 0 +#define SCE_FORTH_COMMENT 1 +#define SCE_FORTH_COMMENT_ML 2 +#define SCE_FORTH_IDENTIFIER 3 +#define SCE_FORTH_CONTROL 4 +#define SCE_FORTH_KEYWORD 5 +#define SCE_FORTH_DEFWORD 6 +#define SCE_FORTH_PREWORD1 7 +#define SCE_FORTH_PREWORD2 8 +#define SCE_FORTH_NUMBER 9 +#define SCE_FORTH_STRING 10 +#define SCE_FORTH_LOCALE 11 +#define SCE_MATLAB_DEFAULT 0 +#define SCE_MATLAB_COMMENT 1 +#define SCE_MATLAB_COMMAND 2 +#define SCE_MATLAB_NUMBER 3 +#define SCE_MATLAB_KEYWORD 4 +#define SCE_MATLAB_STRING 5 +#define SCE_MATLAB_OPERATOR 6 +#define SCE_MATLAB_IDENTIFIER 7 +#define SCE_MATLAB_DOUBLEQUOTESTRING 8 +#define SCE_SCRIPTOL_DEFAULT 0 +#define SCE_SCRIPTOL_WHITE 1 +#define SCE_SCRIPTOL_COMMENTLINE 2 +#define SCE_SCRIPTOL_PERSISTENT 3 +#define SCE_SCRIPTOL_CSTYLE 4 +#define SCE_SCRIPTOL_COMMENTBLOCK 5 +#define SCE_SCRIPTOL_NUMBER 6 +#define SCE_SCRIPTOL_STRING 7 +#define SCE_SCRIPTOL_CHARACTER 8 +#define SCE_SCRIPTOL_STRINGEOL 9 +#define SCE_SCRIPTOL_KEYWORD 10 +#define SCE_SCRIPTOL_OPERATOR 11 +#define SCE_SCRIPTOL_IDENTIFIER 12 +#define SCE_SCRIPTOL_TRIPLE 13 +#define SCE_SCRIPTOL_CLASSNAME 14 +#define SCE_SCRIPTOL_PREPROCESSOR 15 +#define SCE_ASM_DEFAULT 0 +#define SCE_ASM_COMMENT 1 +#define SCE_ASM_NUMBER 2 +#define SCE_ASM_STRING 3 +#define SCE_ASM_OPERATOR 4 +#define SCE_ASM_IDENTIFIER 5 +#define SCE_ASM_CPUINSTRUCTION 6 +#define SCE_ASM_MATHINSTRUCTION 7 +#define SCE_ASM_REGISTER 8 +#define SCE_ASM_DIRECTIVE 9 +#define SCE_ASM_DIRECTIVEOPERAND 10 +#define SCE_ASM_COMMENTBLOCK 11 +#define SCE_ASM_CHARACTER 12 +#define SCE_ASM_STRINGEOL 13 +#define SCE_ASM_EXTINSTRUCTION 14 +#define SCE_F_DEFAULT 0 +#define SCE_F_COMMENT 1 +#define SCE_F_NUMBER 2 +#define SCE_F_STRING1 3 +#define SCE_F_STRING2 4 +#define SCE_F_STRINGEOL 5 +#define SCE_F_OPERATOR 6 +#define SCE_F_IDENTIFIER 7 +#define SCE_F_WORD 8 +#define SCE_F_WORD2 9 +#define SCE_F_WORD3 10 +#define SCE_F_PREPROCESSOR 11 +#define SCE_F_OPERATOR2 12 +#define SCE_F_LABEL 13 +#define SCE_F_CONTINUATION 14 +#define SCE_CSS_DEFAULT 0 +#define SCE_CSS_TAG 1 +#define SCE_CSS_CLASS 2 +#define SCE_CSS_PSEUDOCLASS 3 +#define SCE_CSS_UNKNOWN_PSEUDOCLASS 4 +#define SCE_CSS_OPERATOR 5 +#define SCE_CSS_IDENTIFIER 6 +#define SCE_CSS_UNKNOWN_IDENTIFIER 7 +#define SCE_CSS_VALUE 8 +#define SCE_CSS_COMMENT 9 +#define SCE_CSS_ID 10 +#define SCE_CSS_IMPORTANT 11 +#define SCE_CSS_DIRECTIVE 12 +#define SCE_CSS_DOUBLESTRING 13 +#define SCE_CSS_SINGLESTRING 14 +#define SCE_CSS_IDENTIFIER2 15 +#define SCE_CSS_ATTRIBUTE 16 +#define SCE_POV_DEFAULT 0 +#define SCE_POV_COMMENT 1 +#define SCE_POV_COMMENTLINE 2 +#define SCE_POV_NUMBER 3 +#define SCE_POV_OPERATOR 4 +#define SCE_POV_IDENTIFIER 5 +#define SCE_POV_STRING 6 +#define SCE_POV_STRINGEOL 7 +#define SCE_POV_DIRECTIVE 8 +#define SCE_POV_BADDIRECTIVE 9 +#define SCE_POV_WORD2 10 +#define SCE_POV_WORD3 11 +#define SCE_POV_WORD4 12 +#define SCE_POV_WORD5 13 +#define SCE_POV_WORD6 14 +#define SCE_POV_WORD7 15 +#define SCE_POV_WORD8 16 +#define SCE_LOUT_DEFAULT 0 +#define SCE_LOUT_COMMENT 1 +#define SCE_LOUT_NUMBER 2 +#define SCE_LOUT_WORD 3 +#define SCE_LOUT_WORD2 4 +#define SCE_LOUT_WORD3 5 +#define SCE_LOUT_WORD4 6 +#define SCE_LOUT_STRING 7 +#define SCE_LOUT_OPERATOR 8 +#define SCE_LOUT_IDENTIFIER 9 +#define SCE_LOUT_STRINGEOL 10 +#define SCE_ESCRIPT_DEFAULT 0 +#define SCE_ESCRIPT_COMMENT 1 +#define SCE_ESCRIPT_COMMENTLINE 2 +#define SCE_ESCRIPT_COMMENTDOC 3 +#define SCE_ESCRIPT_NUMBER 4 +#define SCE_ESCRIPT_WORD 5 +#define SCE_ESCRIPT_STRING 6 +#define SCE_ESCRIPT_OPERATOR 7 +#define SCE_ESCRIPT_IDENTIFIER 8 +#define SCE_ESCRIPT_BRACE 9 +#define SCE_ESCRIPT_WORD2 10 +#define SCE_ESCRIPT_WORD3 11 +#define SCE_PS_DEFAULT 0 +#define SCE_PS_COMMENT 1 +#define SCE_PS_DSC_COMMENT 2 +#define SCE_PS_DSC_VALUE 3 +#define SCE_PS_NUMBER 4 +#define SCE_PS_NAME 5 +#define SCE_PS_KEYWORD 6 +#define SCE_PS_LITERAL 7 +#define SCE_PS_IMMEVAL 8 +#define SCE_PS_PAREN_ARRAY 9 +#define SCE_PS_PAREN_DICT 10 +#define SCE_PS_PAREN_PROC 11 +#define SCE_PS_TEXT 12 +#define SCE_PS_HEXSTRING 13 +#define SCE_PS_BASE85STRING 14 +#define SCE_PS_BADSTRINGCHAR 15 +#define SCE_NSIS_DEFAULT 0 +#define SCE_NSIS_COMMENT 1 +#define SCE_NSIS_STRINGDQ 2 +#define SCE_NSIS_STRINGLQ 3 +#define SCE_NSIS_STRINGRQ 4 +#define SCE_NSIS_FUNCTION 5 +#define SCE_NSIS_VARIABLE 6 +#define SCE_NSIS_LABEL 7 +#define SCE_NSIS_USERDEFINED 8 +#define SCE_NSIS_SECTIONDEF 9 +#define SCE_NSIS_SUBSECTIONDEF 10 +#define SCE_NSIS_IFDEFINEDEF 11 +#define SCE_NSIS_MACRODEF 12 +#define SCE_NSIS_STRINGVAR 13 +#define SCE_NSIS_NUMBER 14 +#define SCE_NSIS_SECTIONGROUP 15 +#define SCE_NSIS_PAGEEX 16 +#define SCE_NSIS_FUNCTIONDEF 17 +#define SCE_NSIS_COMMENTBOX 18 +#define SCE_MMIXAL_LEADWS 0 +#define SCE_MMIXAL_COMMENT 1 +#define SCE_MMIXAL_LABEL 2 +#define SCE_MMIXAL_OPCODE 3 +#define SCE_MMIXAL_OPCODE_PRE 4 +#define SCE_MMIXAL_OPCODE_VALID 5 +#define SCE_MMIXAL_OPCODE_UNKNOWN 6 +#define SCE_MMIXAL_OPCODE_POST 7 +#define SCE_MMIXAL_OPERANDS 8 +#define SCE_MMIXAL_NUMBER 9 +#define SCE_MMIXAL_REF 10 +#define SCE_MMIXAL_CHAR 11 +#define SCE_MMIXAL_STRING 12 +#define SCE_MMIXAL_REGISTER 13 +#define SCE_MMIXAL_HEX 14 +#define SCE_MMIXAL_OPERATOR 15 +#define SCE_MMIXAL_SYMBOL 16 +#define SCE_MMIXAL_INCLUDE 17 +#define SCE_CLW_DEFAULT 0 +#define SCE_CLW_LABEL 1 +#define SCE_CLW_COMMENT 2 +#define SCE_CLW_STRING 3 +#define SCE_CLW_USER_IDENTIFIER 4 +#define SCE_CLW_INTEGER_CONSTANT 5 +#define SCE_CLW_REAL_CONSTANT 6 +#define SCE_CLW_PICTURE_STRING 7 +#define SCE_CLW_KEYWORD 8 +#define SCE_CLW_COMPILER_DIRECTIVE 9 +#define SCE_CLW_RUNTIME_EXPRESSIONS 10 +#define SCE_CLW_BUILTIN_PROCEDURES_FUNCTION 11 +#define SCE_CLW_STRUCTURE_DATA_TYPE 12 +#define SCE_CLW_ATTRIBUTE 13 +#define SCE_CLW_STANDARD_EQUATE 14 +#define SCE_CLW_ERROR 15 +#define SCE_CLW_DEPRECATED 16 +#define SCE_LOT_DEFAULT 0 +#define SCE_LOT_HEADER 1 +#define SCE_LOT_BREAK 2 +#define SCE_LOT_SET 3 +#define SCE_LOT_PASS 4 +#define SCE_LOT_FAIL 5 +#define SCE_LOT_ABORT 6 +#define SCE_YAML_DEFAULT 0 +#define SCE_YAML_COMMENT 1 +#define SCE_YAML_IDENTIFIER 2 +#define SCE_YAML_KEYWORD 3 +#define SCE_YAML_NUMBER 4 +#define SCE_YAML_REFERENCE 5 +#define SCE_YAML_DOCUMENT 6 +#define SCE_YAML_TEXT 7 +#define SCE_YAML_ERROR 8 +#define SCE_YAML_OPERATOR 9 +#define SCE_TEX_DEFAULT 0 +#define SCE_TEX_SPECIAL 1 +#define SCE_TEX_GROUP 2 +#define SCE_TEX_SYMBOL 3 +#define SCE_TEX_COMMAND 4 +#define SCE_TEX_TEXT 5 +#define SCE_METAPOST_DEFAULT 0 +#define SCE_METAPOST_SPECIAL 1 +#define SCE_METAPOST_GROUP 2 +#define SCE_METAPOST_SYMBOL 3 +#define SCE_METAPOST_COMMAND 4 +#define SCE_METAPOST_TEXT 5 +#define SCE_METAPOST_EXTRA 6 +#define SCE_ERLANG_DEFAULT 0 +#define SCE_ERLANG_COMMENT 1 +#define SCE_ERLANG_VARIABLE 2 +#define SCE_ERLANG_NUMBER 3 +#define SCE_ERLANG_KEYWORD 4 +#define SCE_ERLANG_STRING 5 +#define SCE_ERLANG_OPERATOR 6 +#define SCE_ERLANG_ATOM 7 +#define SCE_ERLANG_FUNCTION_NAME 8 +#define SCE_ERLANG_CHARACTER 9 +#define SCE_ERLANG_MACRO 10 +#define SCE_ERLANG_RECORD 11 +#define SCE_ERLANG_SEPARATOR 12 +#define SCE_ERLANG_NODE_NAME 13 +#define SCE_ERLANG_UNKNOWN 31 +#define SCE_MSSQL_DEFAULT 0 +#define SCE_MSSQL_COMMENT 1 +#define SCE_MSSQL_LINE_COMMENT 2 +#define SCE_MSSQL_NUMBER 3 +#define SCE_MSSQL_STRING 4 +#define SCE_MSSQL_OPERATOR 5 +#define SCE_MSSQL_IDENTIFIER 6 +#define SCE_MSSQL_VARIABLE 7 +#define SCE_MSSQL_COLUMN_NAME 8 +#define SCE_MSSQL_STATEMENT 9 +#define SCE_MSSQL_DATATYPE 10 +#define SCE_MSSQL_SYSTABLE 11 +#define SCE_MSSQL_GLOBAL_VARIABLE 12 +#define SCE_MSSQL_FUNCTION 13 +#define SCE_MSSQL_STORED_PROCEDURE 14 +#define SCE_MSSQL_DEFAULT_PREF_DATATYPE 15 +#define SCE_MSSQL_COLUMN_NAME_2 16 +#define SCE_V_DEFAULT 0 +#define SCE_V_COMMENT 1 +#define SCE_V_COMMENTLINE 2 +#define SCE_V_COMMENTLINEBANG 3 +#define SCE_V_NUMBER 4 +#define SCE_V_WORD 5 +#define SCE_V_STRING 6 +#define SCE_V_WORD2 7 +#define SCE_V_WORD3 8 +#define SCE_V_PREPROCESSOR 9 +#define SCE_V_OPERATOR 10 +#define SCE_V_IDENTIFIER 11 +#define SCE_V_STRINGEOL 12 +#define SCE_V_USER 19 +#define SCE_KIX_DEFAULT 0 +#define SCE_KIX_COMMENT 1 +#define SCE_KIX_STRING1 2 +#define SCE_KIX_STRING2 3 +#define SCE_KIX_NUMBER 4 +#define SCE_KIX_VAR 5 +#define SCE_KIX_MACRO 6 +#define SCE_KIX_KEYWORD 7 +#define SCE_KIX_FUNCTIONS 8 +#define SCE_KIX_OPERATOR 9 +#define SCE_KIX_IDENTIFIER 31 +#define SCE_GC_DEFAULT 0 +#define SCE_GC_COMMENTLINE 1 +#define SCE_GC_COMMENTBLOCK 2 +#define SCE_GC_GLOBAL 3 +#define SCE_GC_EVENT 4 +#define SCE_GC_ATTRIBUTE 5 +#define SCE_GC_CONTROL 6 +#define SCE_GC_COMMAND 7 +#define SCE_GC_STRING 8 +#define SCE_GC_OPERATOR 9 +#define SCE_SN_DEFAULT 0 +#define SCE_SN_CODE 1 +#define SCE_SN_COMMENTLINE 2 +#define SCE_SN_COMMENTLINEBANG 3 +#define SCE_SN_NUMBER 4 +#define SCE_SN_WORD 5 +#define SCE_SN_STRING 6 +#define SCE_SN_WORD2 7 +#define SCE_SN_WORD3 8 +#define SCE_SN_PREPROCESSOR 9 +#define SCE_SN_OPERATOR 10 +#define SCE_SN_IDENTIFIER 11 +#define SCE_SN_STRINGEOL 12 +#define SCE_SN_REGEXTAG 13 +#define SCE_SN_SIGNAL 14 +#define SCE_SN_USER 19 +#define SCE_AU3_DEFAULT 0 +#define SCE_AU3_COMMENT 1 +#define SCE_AU3_COMMENTBLOCK 2 +#define SCE_AU3_NUMBER 3 +#define SCE_AU3_FUNCTION 4 +#define SCE_AU3_KEYWORD 5 +#define SCE_AU3_MACRO 6 +#define SCE_AU3_STRING 7 +#define SCE_AU3_OPERATOR 8 +#define SCE_AU3_VARIABLE 9 +#define SCE_AU3_SENT 10 +#define SCE_AU3_PREPROCESSOR 11 +#define SCE_AU3_SPECIAL 12 +#define SCE_AU3_EXPAND 13 +#define SCE_AU3_COMOBJ 14 +#define SCE_AU3_UDF 15 +#define SCE_APDL_DEFAULT 0 +#define SCE_APDL_COMMENT 1 +#define SCE_APDL_COMMENTBLOCK 2 +#define SCE_APDL_NUMBER 3 +#define SCE_APDL_STRING 4 +#define SCE_APDL_OPERATOR 5 +#define SCE_APDL_WORD 6 +#define SCE_APDL_PROCESSOR 7 +#define SCE_APDL_COMMAND 8 +#define SCE_APDL_SLASHCOMMAND 9 +#define SCE_APDL_STARCOMMAND 10 +#define SCE_APDL_ARGUMENT 11 +#define SCE_APDL_FUNCTION 12 +#define SCE_SH_DEFAULT 0 +#define SCE_SH_ERROR 1 +#define SCE_SH_COMMENTLINE 2 +#define SCE_SH_NUMBER 3 +#define SCE_SH_WORD 4 +#define SCE_SH_STRING 5 +#define SCE_SH_CHARACTER 6 +#define SCE_SH_OPERATOR 7 +#define SCE_SH_IDENTIFIER 8 +#define SCE_SH_SCALAR 9 +#define SCE_SH_PARAM 10 +#define SCE_SH_BACKTICKS 11 +#define SCE_SH_HERE_DELIM 12 +#define SCE_SH_HERE_Q 13 +#define SCE_ASN1_DEFAULT 0 +#define SCE_ASN1_COMMENT 1 +#define SCE_ASN1_IDENTIFIER 2 +#define SCE_ASN1_STRING 3 +#define SCE_ASN1_OID 4 +#define SCE_ASN1_SCALAR 5 +#define SCE_ASN1_KEYWORD 6 +#define SCE_ASN1_ATTRIBUTE 7 +#define SCE_ASN1_DESCRIPTOR 8 +#define SCE_ASN1_TYPE 9 +#define SCE_ASN1_OPERATOR 10 +#define SCE_VHDL_DEFAULT 0 +#define SCE_VHDL_COMMENT 1 +#define SCE_VHDL_COMMENTLINEBANG 2 +#define SCE_VHDL_NUMBER 3 +#define SCE_VHDL_STRING 4 +#define SCE_VHDL_OPERATOR 5 +#define SCE_VHDL_IDENTIFIER 6 +#define SCE_VHDL_STRINGEOL 7 +#define SCE_VHDL_KEYWORD 8 +#define SCE_VHDL_STDOPERATOR 9 +#define SCE_VHDL_ATTRIBUTE 10 +#define SCE_VHDL_STDFUNCTION 11 +#define SCE_VHDL_STDPACKAGE 12 +#define SCE_VHDL_STDTYPE 13 +#define SCE_VHDL_USERWORD 14 +#define SCE_CAML_DEFAULT 0 +#define SCE_CAML_IDENTIFIER 1 +#define SCE_CAML_TAGNAME 2 +#define SCE_CAML_KEYWORD 3 +#define SCE_CAML_KEYWORD2 4 +#define SCE_CAML_KEYWORD3 5 +#define SCE_CAML_LINENUM 6 +#define SCE_CAML_OPERATOR 7 +#define SCE_CAML_NUMBER 8 +#define SCE_CAML_CHAR 9 +#define SCE_CAML_STRING 11 +#define SCE_CAML_COMMENT 12 +#define SCE_CAML_COMMENT1 13 +#define SCE_CAML_COMMENT2 14 +#define SCE_CAML_COMMENT3 15 +#define SCE_HA_DEFAULT 0 +#define SCE_HA_IDENTIFIER 1 +#define SCE_HA_KEYWORD 2 +#define SCE_HA_NUMBER 3 +#define SCE_HA_STRING 4 +#define SCE_HA_CHARACTER 5 +#define SCE_HA_CLASS 6 +#define SCE_HA_MODULE 7 +#define SCE_HA_CAPITAL 8 +#define SCE_HA_DATA 9 +#define SCE_HA_IMPORT 10 +#define SCE_HA_OPERATOR 11 +#define SCE_HA_INSTANCE 12 +#define SCE_HA_COMMENTLINE 13 +#define SCE_HA_COMMENTBLOCK 14 +#define SCE_HA_COMMENTBLOCK2 15 +#define SCE_HA_COMMENTBLOCK3 16 +#define SCE_T3_DEFAULT 0 +#define SCE_T3_X_DEFAULT 1 +#define SCE_T3_PREPROCESSOR 2 +#define SCE_T3_BLOCK_COMMENT 3 +#define SCE_T3_LINE_COMMENT 4 +#define SCE_T3_OPERATOR 5 +#define SCE_T3_KEYWORD 6 +#define SCE_T3_NUMBER 7 +#define SCE_T3_IDENTIFIER 8 +#define SCE_T3_S_STRING 9 +#define SCE_T3_D_STRING 10 +#define SCE_T3_X_STRING 11 +#define SCE_T3_LIB_DIRECTIVE 12 +#define SCE_T3_MSG_PARAM 13 +#define SCE_T3_HTML_TAG 14 +#define SCE_T3_HTML_DEFAULT 15 +#define SCE_T3_HTML_STRING 16 +#define SCE_T3_USER1 17 +#define SCE_T3_USER2 18 +#define SCE_T3_USER3 19 +#define SCE_T3_BRACE 20 +#define SCE_REBOL_DEFAULT 0 +#define SCE_REBOL_COMMENTLINE 1 +#define SCE_REBOL_COMMENTBLOCK 2 +#define SCE_REBOL_PREFACE 3 +#define SCE_REBOL_OPERATOR 4 +#define SCE_REBOL_CHARACTER 5 +#define SCE_REBOL_QUOTEDSTRING 6 +#define SCE_REBOL_BRACEDSTRING 7 +#define SCE_REBOL_NUMBER 8 +#define SCE_REBOL_PAIR 9 +#define SCE_REBOL_TUPLE 10 +#define SCE_REBOL_BINARY 11 +#define SCE_REBOL_MONEY 12 +#define SCE_REBOL_ISSUE 13 +#define SCE_REBOL_TAG 14 +#define SCE_REBOL_FILE 15 +#define SCE_REBOL_EMAIL 16 +#define SCE_REBOL_URL 17 +#define SCE_REBOL_DATE 18 +#define SCE_REBOL_TIME 19 +#define SCE_REBOL_IDENTIFIER 20 +#define SCE_REBOL_WORD 21 +#define SCE_REBOL_WORD2 22 +#define SCE_REBOL_WORD3 23 +#define SCE_REBOL_WORD4 24 +#define SCE_REBOL_WORD5 25 +#define SCE_REBOL_WORD6 26 +#define SCE_REBOL_WORD7 27 +#define SCE_REBOL_WORD8 28 +#define SCE_SQL_DEFAULT 0 +#define SCE_SQL_COMMENT 1 +#define SCE_SQL_COMMENTLINE 2 +#define SCE_SQL_COMMENTDOC 3 +#define SCE_SQL_NUMBER 4 +#define SCE_SQL_WORD 5 +#define SCE_SQL_STRING 6 +#define SCE_SQL_CHARACTER 7 +#define SCE_SQL_SQLPLUS 8 +#define SCE_SQL_SQLPLUS_PROMPT 9 +#define SCE_SQL_OPERATOR 10 +#define SCE_SQL_IDENTIFIER 11 +#define SCE_SQL_SQLPLUS_COMMENT 13 +#define SCE_SQL_COMMENTLINEDOC 15 +#define SCE_SQL_WORD2 16 +#define SCE_SQL_COMMENTDOCKEYWORD 17 +#define SCE_SQL_COMMENTDOCKEYWORDERROR 18 +#define SCE_SQL_USER1 19 +#define SCE_SQL_USER2 20 +#define SCE_SQL_USER3 21 +#define SCE_SQL_USER4 22 +#define SCE_SQL_QUOTEDIDENTIFIER 23 +#define SCE_ST_DEFAULT 0 +#define SCE_ST_STRING 1 +#define SCE_ST_NUMBER 2 +#define SCE_ST_COMMENT 3 +#define SCE_ST_SYMBOL 4 +#define SCE_ST_BINARY 5 +#define SCE_ST_BOOL 6 +#define SCE_ST_SELF 7 +#define SCE_ST_SUPER 8 +#define SCE_ST_NIL 9 +#define SCE_ST_GLOBAL 10 +#define SCE_ST_RETURN 11 +#define SCE_ST_SPECIAL 12 +#define SCE_ST_KWSEND 13 +#define SCE_ST_ASSIGN 14 +#define SCE_ST_CHARACTER 15 +#define SCE_ST_SPEC_SEL 16 +#define SCE_FS_DEFAULT 0 +#define SCE_FS_COMMENT 1 +#define SCE_FS_COMMENTLINE 2 +#define SCE_FS_COMMENTDOC 3 +#define SCE_FS_COMMENTLINEDOC 4 +#define SCE_FS_COMMENTDOCKEYWORD 5 +#define SCE_FS_COMMENTDOCKEYWORDERROR 6 +#define SCE_FS_KEYWORD 7 +#define SCE_FS_KEYWORD2 8 +#define SCE_FS_KEYWORD3 9 +#define SCE_FS_KEYWORD4 10 +#define SCE_FS_NUMBER 11 +#define SCE_FS_STRING 12 +#define SCE_FS_PREPROCESSOR 13 +#define SCE_FS_OPERATOR 14 +#define SCE_FS_IDENTIFIER 15 +#define SCE_FS_DATE 16 +#define SCE_FS_STRINGEOL 17 +#define SCE_FS_CONSTANT 18 +#define SCE_FS_ASM 19 +#define SCE_FS_LABEL 20 +#define SCE_FS_ERROR 21 +#define SCE_FS_HEXNUMBER 22 +#define SCE_FS_BINNUMBER 23 +#define SCE_CSOUND_DEFAULT 0 +#define SCE_CSOUND_COMMENT 1 +#define SCE_CSOUND_NUMBER 2 +#define SCE_CSOUND_OPERATOR 3 +#define SCE_CSOUND_INSTR 4 +#define SCE_CSOUND_IDENTIFIER 5 +#define SCE_CSOUND_OPCODE 6 +#define SCE_CSOUND_HEADERSTMT 7 +#define SCE_CSOUND_USERKEYWORD 8 +#define SCE_CSOUND_COMMENTBLOCK 9 +#define SCE_CSOUND_PARAM 10 +#define SCE_CSOUND_ARATE_VAR 11 +#define SCE_CSOUND_KRATE_VAR 12 +#define SCE_CSOUND_IRATE_VAR 13 +#define SCE_CSOUND_GLOBAL_VAR 14 +#define SCE_CSOUND_STRINGEOL 15 +#define SCE_INNO_DEFAULT 0 +#define SCE_INNO_COMMENT 1 +#define SCE_INNO_KEYWORD 2 +#define SCE_INNO_PARAMETER 3 +#define SCE_INNO_SECTION 4 +#define SCE_INNO_PREPROC 5 +#define SCE_INNO_PREPROC_INLINE 6 +#define SCE_INNO_COMMENT_PASCAL 7 +#define SCE_INNO_KEYWORD_PASCAL 8 +#define SCE_INNO_KEYWORD_USER 9 +#define SCE_INNO_STRING_DOUBLE 10 +#define SCE_INNO_STRING_SINGLE 11 +#define SCE_INNO_IDENTIFIER 12 +#define SCE_OPAL_SPACE 0 +#define SCE_OPAL_COMMENT_BLOCK 1 +#define SCE_OPAL_COMMENT_LINE 2 +#define SCE_OPAL_INTEGER 3 +#define SCE_OPAL_KEYWORD 4 +#define SCE_OPAL_SORT 5 +#define SCE_OPAL_STRING 6 +#define SCE_OPAL_PAR 7 +#define SCE_OPAL_BOOL_CONST 8 +#define SCE_OPAL_DEFAULT 32 +#define SCE_SPICE_DEFAULT 0 +#define SCE_SPICE_IDENTIFIER 1 +#define SCE_SPICE_KEYWORD 2 +#define SCE_SPICE_KEYWORD2 3 +#define SCE_SPICE_KEYWORD3 4 +#define SCE_SPICE_NUMBER 5 +#define SCE_SPICE_DELIMITER 6 +#define SCE_SPICE_VALUE 7 +#define SCE_SPICE_COMMENTLINE 8 +#define SCE_CMAKE_DEFAULT 0 +#define SCE_CMAKE_COMMENT 1 +#define SCE_CMAKE_STRINGDQ 2 +#define SCE_CMAKE_STRINGLQ 3 +#define SCE_CMAKE_STRINGRQ 4 +#define SCE_CMAKE_COMMANDS 5 +#define SCE_CMAKE_PARAMETERS 6 +#define SCE_CMAKE_VARIABLE 7 +#define SCE_CMAKE_USERDEFINED 8 +#define SCE_CMAKE_WHILEDEF 9 +#define SCE_CMAKE_FOREACHDEF 10 +#define SCE_CMAKE_IFDEFINEDEF 11 +#define SCE_CMAKE_MACRODEF 12 +#define SCE_CMAKE_STRINGVAR 13 +#define SCE_CMAKE_NUMBER 14 +#define SCE_GAP_DEFAULT 0 +#define SCE_GAP_IDENTIFIER 1 +#define SCE_GAP_KEYWORD 2 +#define SCE_GAP_KEYWORD2 3 +#define SCE_GAP_KEYWORD3 4 +#define SCE_GAP_KEYWORD4 5 +#define SCE_GAP_STRING 6 +#define SCE_GAP_CHAR 7 +#define SCE_GAP_OPERATOR 8 +#define SCE_GAP_COMMENT 9 +#define SCE_GAP_NUMBER 10 +#define SCE_GAP_STRINGEOL 11 +#define SCE_PLM_DEFAULT 0 +#define SCE_PLM_COMMENT 1 +#define SCE_PLM_STRING 2 +#define SCE_PLM_NUMBER 3 +#define SCE_PLM_IDENTIFIER 4 +#define SCE_PLM_OPERATOR 5 +#define SCE_PLM_CONTROL 6 +#define SCE_PLM_KEYWORD 7 +#define SCE_4GL_DEFAULT 0 +#define SCE_4GL_NUMBER 1 +#define SCE_4GL_WORD 2 +#define SCE_4GL_STRING 3 +#define SCE_4GL_CHARACTER 4 +#define SCE_4GL_PREPROCESSOR 5 +#define SCE_4GL_OPERATOR 6 +#define SCE_4GL_IDENTIFIER 7 +#define SCE_4GL_BLOCK 8 +#define SCE_4GL_END 9 +#define SCE_4GL_COMMENT1 10 +#define SCE_4GL_COMMENT2 11 +#define SCE_4GL_COMMENT3 12 +#define SCE_4GL_COMMENT4 13 +#define SCE_4GL_COMMENT5 14 +#define SCE_4GL_COMMENT6 15 +#define SCE_4GL_DEFAULT_ 16 +#define SCE_4GL_NUMBER_ 17 +#define SCE_4GL_WORD_ 18 +#define SCE_4GL_STRING_ 19 +#define SCE_4GL_CHARACTER_ 20 +#define SCE_4GL_PREPROCESSOR_ 21 +#define SCE_4GL_OPERATOR_ 22 +#define SCE_4GL_IDENTIFIER_ 23 +#define SCE_4GL_BLOCK_ 24 +#define SCE_4GL_END_ 25 +#define SCE_4GL_COMMENT1_ 26 +#define SCE_4GL_COMMENT2_ 27 +#define SCE_4GL_COMMENT3_ 28 +#define SCE_4GL_COMMENT4_ 29 +#define SCE_4GL_COMMENT5_ 30 +#define SCE_4GL_COMMENT6_ 31 +#define SCE_ABAQUS_DEFAULT 0 +#define SCE_ABAQUS_COMMENT 1 +#define SCE_ABAQUS_COMMENTBLOCK 2 +#define SCE_ABAQUS_NUMBER 3 +#define SCE_ABAQUS_STRING 4 +#define SCE_ABAQUS_OPERATOR 5 +#define SCE_ABAQUS_WORD 6 +#define SCE_ABAQUS_PROCESSOR 7 +#define SCE_ABAQUS_COMMAND 8 +#define SCE_ABAQUS_SLASHCOMMAND 9 +#define SCE_ABAQUS_STARCOMMAND 10 +#define SCE_ABAQUS_ARGUMENT 11 +#define SCE_ABAQUS_FUNCTION 12 +#define SCE_ASY_DEFAULT 0 +#define SCE_ASY_COMMENT 1 +#define SCE_ASY_COMMENTLINE 2 +#define SCE_ASY_NUMBER 3 +#define SCE_ASY_WORD 4 +#define SCE_ASY_STRING 5 +#define SCE_ASY_CHARACTER 6 +#define SCE_ASY_OPERATOR 7 +#define SCE_ASY_IDENTIFIER 8 +#define SCE_ASY_STRINGEOL 9 +#define SCE_ASY_COMMENTLINEDOC 10 +#define SCE_ASY_WORD2 11 +#define SCE_R_DEFAULT 0 +#define SCE_R_COMMENT 1 +#define SCE_R_KWORD 2 +#define SCE_R_BASEKWORD 3 +#define SCE_R_OTHERKWORD 4 +#define SCE_R_NUMBER 5 +#define SCE_R_STRING 6 +#define SCE_R_STRING2 7 +#define SCE_R_OPERATOR 8 +#define SCE_R_IDENTIFIER 9 +#define SCE_R_INFIX 10 +#define SCE_R_INFIXEOL 11 +#define SCE_MAGIK_DEFAULT 0 +#define SCE_MAGIK_COMMENT 1 +#define SCE_MAGIK_HYPER_COMMENT 16 +#define SCE_MAGIK_STRING 2 +#define SCE_MAGIK_CHARACTER 3 +#define SCE_MAGIK_NUMBER 4 +#define SCE_MAGIK_IDENTIFIER 5 +#define SCE_MAGIK_OPERATOR 6 +#define SCE_MAGIK_FLOW 7 +#define SCE_MAGIK_CONTAINER 8 +#define SCE_MAGIK_BRACKET_BLOCK 9 +#define SCE_MAGIK_BRACE_BLOCK 10 +#define SCE_MAGIK_SQBRACKET_BLOCK 11 +#define SCE_MAGIK_UNKNOWN_KEYWORD 12 +#define SCE_MAGIK_KEYWORD 13 +#define SCE_MAGIK_PRAGMA 14 +#define SCE_MAGIK_SYMBOL 15 +#define SCE_POWERSHELL_DEFAULT 0 +#define SCE_POWERSHELL_COMMENT 1 +#define SCE_POWERSHELL_STRING 2 +#define SCE_POWERSHELL_CHARACTER 3 +#define SCE_POWERSHELL_NUMBER 4 +#define SCE_POWERSHELL_VARIABLE 5 +#define SCE_POWERSHELL_OPERATOR 6 +#define SCE_POWERSHELL_IDENTIFIER 7 +#define SCE_POWERSHELL_KEYWORD 8 +#define SCE_POWERSHELL_CMDLET 9 +#define SCE_POWERSHELL_ALIAS 10 +#define SCLEX_ASP 29 +#define SCLEX_PHP 30 +//--Autogenerated -- end of section automatically generated from Scintilla.iface + +#endif diff --git a/scintilla/include/Scintilla.h b/scintilla/include/Scintilla.h new file mode 100644 index 00000000..62a6cc57 --- /dev/null +++ b/scintilla/include/Scintilla.h @@ -0,0 +1,861 @@ +// Scintilla source code edit control +/** @file Scintilla.h + ** Interface to the edit control. + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +// Most of this file is automatically generated from the Scintilla.iface interface definition +// file which contains any comments about the definitions. HFacer.py does the generation. + +#ifndef SCINTILLA_H +#define SCINTILLA_H + +#if LCCWIN +typedef BOOL bool; +#endif + +#if PLAT_WIN +// Return false on failure: +bool Scintilla_RegisterClasses(void *hInstance); +bool Scintilla_ReleaseResources(); +#endif +int Scintilla_LinkLexers(); + +// Here should be placed typedefs for uptr_t, an unsigned integer type large enough to +// hold a pointer and sptr_t, a signed integer large enough to hold a pointer. +// May need to be changed for 64 bit platforms. +#if _MSC_VER >= 1300 +#include +#endif +#ifdef MAXULONG_PTR +typedef ULONG_PTR uptr_t; +typedef LONG_PTR sptr_t; +#else +typedef unsigned long uptr_t; +typedef long sptr_t; +#endif + +typedef sptr_t (*SciFnDirect)(sptr_t ptr, unsigned int iMessage, uptr_t wParam, sptr_t lParam); + +//++Autogenerated -- start of section automatically generated from Scintilla.iface +#define INVALID_POSITION -1 +#define SCI_START 2000 +#define SCI_OPTIONAL_START 3000 +#define SCI_LEXER_START 4000 +#define SCI_ADDTEXT 2001 +#define SCI_ADDSTYLEDTEXT 2002 +#define SCI_INSERTTEXT 2003 +#define SCI_CLEARALL 2004 +#define SCI_CLEARDOCUMENTSTYLE 2005 +#define SCI_GETLENGTH 2006 +#define SCI_GETCHARAT 2007 +#define SCI_GETCURRENTPOS 2008 +#define SCI_GETANCHOR 2009 +#define SCI_GETSTYLEAT 2010 +#define SCI_REDO 2011 +#define SCI_SETUNDOCOLLECTION 2012 +#define SCI_SELECTALL 2013 +#define SCI_SETSAVEPOINT 2014 +#define SCI_GETSTYLEDTEXT 2015 +#define SCI_CANREDO 2016 +#define SCI_MARKERLINEFROMHANDLE 2017 +#define SCI_MARKERDELETEHANDLE 2018 +#define SCI_GETUNDOCOLLECTION 2019 +#define SCWS_INVISIBLE 0 +#define SCWS_VISIBLEALWAYS 1 +#define SCWS_VISIBLEAFTERINDENT 2 +#define SCI_GETVIEWWS 2020 +#define SCI_SETVIEWWS 2021 +#define SCI_POSITIONFROMPOINT 2022 +#define SCI_POSITIONFROMPOINTCLOSE 2023 +#define SCI_GOTOLINE 2024 +#define SCI_GOTOPOS 2025 +#define SCI_SETANCHOR 2026 +#define SCI_GETCURLINE 2027 +#define SCI_GETENDSTYLED 2028 +#define SC_EOL_CRLF 0 +#define SC_EOL_CR 1 +#define SC_EOL_LF 2 +#define SCI_CONVERTEOLS 2029 +#define SCI_GETEOLMODE 2030 +#define SCI_SETEOLMODE 2031 +#define SCI_STARTSTYLING 2032 +#define SCI_SETSTYLING 2033 +#define SCI_GETBUFFEREDDRAW 2034 +#define SCI_SETBUFFEREDDRAW 2035 +#define SCI_SETTABWIDTH 2036 +#define SCI_GETTABWIDTH 2121 +#define SC_CP_UTF8 65001 +#define SC_CP_DBCS 1 +#define SCI_SETCODEPAGE 2037 +#define SCI_SETUSEPALETTE 2039 +#define MARKER_MAX 31 +#define SC_MARK_CIRCLE 0 +#define SC_MARK_ROUNDRECT 1 +#define SC_MARK_ARROW 2 +#define SC_MARK_SMALLRECT 3 +#define SC_MARK_SHORTARROW 4 +#define SC_MARK_EMPTY 5 +#define SC_MARK_ARROWDOWN 6 +#define SC_MARK_MINUS 7 +#define SC_MARK_PLUS 8 +#define SC_MARK_VLINE 9 +#define SC_MARK_LCORNER 10 +#define SC_MARK_TCORNER 11 +#define SC_MARK_BOXPLUS 12 +#define SC_MARK_BOXPLUSCONNECTED 13 +#define SC_MARK_BOXMINUS 14 +#define SC_MARK_BOXMINUSCONNECTED 15 +#define SC_MARK_LCORNERCURVE 16 +#define SC_MARK_TCORNERCURVE 17 +#define SC_MARK_CIRCLEPLUS 18 +#define SC_MARK_CIRCLEPLUSCONNECTED 19 +#define SC_MARK_CIRCLEMINUS 20 +#define SC_MARK_CIRCLEMINUSCONNECTED 21 +#define SC_MARK_BACKGROUND 22 +#define SC_MARK_DOTDOTDOT 23 +#define SC_MARK_ARROWS 24 +#define SC_MARK_PIXMAP 25 +#define SC_MARK_FULLRECT 26 +#define SC_MARK_LEFTRECT 27 +#define SC_MARK_CHARACTER 10000 +#define SC_MARKNUM_FOLDEREND 25 +#define SC_MARKNUM_FOLDEROPENMID 26 +#define SC_MARKNUM_FOLDERMIDTAIL 27 +#define SC_MARKNUM_FOLDERTAIL 28 +#define SC_MARKNUM_FOLDERSUB 29 +#define SC_MARKNUM_FOLDER 30 +#define SC_MARKNUM_FOLDEROPEN 31 +#define SC_MASK_FOLDERS 0xFE000000 +#define SCI_MARKERDEFINE 2040 +#define SCI_MARKERSETFORE 2041 +#define SCI_MARKERSETBACK 2042 +#define SCI_MARKERADD 2043 +#define SCI_MARKERDELETE 2044 +#define SCI_MARKERDELETEALL 2045 +#define SCI_MARKERGET 2046 +#define SCI_MARKERNEXT 2047 +#define SCI_MARKERPREVIOUS 2048 +#define SCI_MARKERDEFINEPIXMAP 2049 +#define SCI_MARKERADDSET 2466 +#define SCI_MARKERSETALPHA 2476 +#define SC_MARGIN_SYMBOL 0 +#define SC_MARGIN_NUMBER 1 +#define SC_MARGIN_BACK 2 +#define SC_MARGIN_FORE 3 +#define SCI_SETMARGINTYPEN 2240 +#define SCI_GETMARGINTYPEN 2241 +#define SCI_SETMARGINWIDTHN 2242 +#define SCI_GETMARGINWIDTHN 2243 +#define SCI_SETMARGINMASKN 2244 +#define SCI_GETMARGINMASKN 2245 +#define SCI_SETMARGINSENSITIVEN 2246 +#define SCI_GETMARGINSENSITIVEN 2247 +#define STYLE_DEFAULT 32 +#define STYLE_LINENUMBER 33 +#define STYLE_BRACELIGHT 34 +#define STYLE_BRACEBAD 35 +#define STYLE_CONTROLCHAR 36 +#define STYLE_INDENTGUIDE 37 +#define STYLE_CALLTIP 38 +#define STYLE_LASTPREDEFINED 39 +#define STYLE_MAX 255 +#define SC_CHARSET_ANSI 0 +#define SC_CHARSET_DEFAULT 1 +#define SC_CHARSET_BALTIC 186 +#define SC_CHARSET_CHINESEBIG5 136 +#define SC_CHARSET_EASTEUROPE 238 +#define SC_CHARSET_GB2312 134 +#define SC_CHARSET_GREEK 161 +#define SC_CHARSET_HANGUL 129 +#define SC_CHARSET_MAC 77 +#define SC_CHARSET_OEM 255 +#define SC_CHARSET_RUSSIAN 204 +#define SC_CHARSET_CYRILLIC 1251 +#define SC_CHARSET_SHIFTJIS 128 +#define SC_CHARSET_SYMBOL 2 +#define SC_CHARSET_TURKISH 162 +#define SC_CHARSET_JOHAB 130 +#define SC_CHARSET_HEBREW 177 +#define SC_CHARSET_ARABIC 178 +#define SC_CHARSET_VIETNAMESE 163 +#define SC_CHARSET_THAI 222 +#define SC_CHARSET_8859_15 1000 +#define SCI_STYLECLEARALL 2050 +#define SCI_STYLESETFORE 2051 +#define SCI_STYLESETBACK 2052 +#define SCI_STYLESETBOLD 2053 +#define SCI_STYLESETITALIC 2054 +#define SCI_STYLESETSIZE 2055 +#define SCI_STYLESETFONT 2056 +#define SCI_STYLESETEOLFILLED 2057 +#define SCI_STYLERESETDEFAULT 2058 +#define SCI_STYLESETUNDERLINE 2059 +#define SC_CASE_MIXED 0 +#define SC_CASE_UPPER 1 +#define SC_CASE_LOWER 2 +#define SCI_STYLEGETFORE 2481 +#define SCI_STYLEGETBACK 2482 +#define SCI_STYLEGETBOLD 2483 +#define SCI_STYLEGETITALIC 2484 +#define SCI_STYLEGETSIZE 2485 +#define SCI_STYLEGETFONT 2486 +#define SCI_STYLEGETEOLFILLED 2487 +#define SCI_STYLEGETUNDERLINE 2488 +#define SCI_STYLEGETCASE 2489 +#define SCI_STYLEGETCHARACTERSET 2490 +#define SCI_STYLEGETVISIBLE 2491 +#define SCI_STYLEGETCHANGEABLE 2492 +#define SCI_STYLEGETHOTSPOT 2493 +#define SCI_STYLESETCASE 2060 +#define SCI_STYLESETCHARACTERSET 2066 +#define SCI_STYLESETHOTSPOT 2409 +#define SCI_SETSELFORE 2067 +#define SCI_SETSELBACK 2068 +#define SCI_GETSELALPHA 2477 +#define SCI_SETSELALPHA 2478 +#define SCI_GETSELEOLFILLED 2479 +#define SCI_SETSELEOLFILLED 2480 +#define SCI_SETCARETFORE 2069 +#define SCI_ASSIGNCMDKEY 2070 +#define SCI_CLEARCMDKEY 2071 +#define SCI_CLEARALLCMDKEYS 2072 +#define SCI_SETSTYLINGEX 2073 +#define SCI_STYLESETVISIBLE 2074 +#define SCI_GETCARETPERIOD 2075 +#define SCI_SETCARETPERIOD 2076 +#define SCI_SETWORDCHARS 2077 +#define SCI_BEGINUNDOACTION 2078 +#define SCI_ENDUNDOACTION 2079 +#define INDIC_PLAIN 0 +#define INDIC_SQUIGGLE 1 +#define INDIC_TT 2 +#define INDIC_DIAGONAL 3 +#define INDIC_STRIKE 4 +#define INDIC_HIDDEN 5 +#define INDIC_BOX 6 +#define INDIC_ROUNDBOX 7 +#define INDIC_MAX 31 +#define INDIC_CONTAINER 8 +#define INDIC0_MASK 0x20 +#define INDIC1_MASK 0x40 +#define INDIC2_MASK 0x80 +#define INDICS_MASK 0xE0 +#define SCI_INDICSETSTYLE 2080 +#define SCI_INDICGETSTYLE 2081 +#define SCI_INDICSETFORE 2082 +#define SCI_INDICGETFORE 2083 +#define SCI_INDICSETUNDER 2510 +#define SCI_INDICGETUNDER 2511 +#define SCI_INDICSETALPHA 3097 +#define SCI_INDICGETALPHA 3098 +#define SCI_SETWHITESPACEFORE 2084 +#define SCI_SETWHITESPACEBACK 2085 +#define SCI_SETSTYLEBITS 2090 +#define SCI_GETSTYLEBITS 2091 +#define SCI_SETLINESTATE 2092 +#define SCI_GETLINESTATE 2093 +#define SCI_GETMAXLINESTATE 2094 +#define SCI_GETCARETLINEVISIBLE 2095 +#define SCI_SETCARETLINEVISIBLE 2096 +#define SCI_GETCARETLINEVISIBLEALWAYS 3095 +#define SCI_SETCARETLINEVISIBLEALWAYS 3096 +#define SCI_GETCARETLINEBACK 2097 +#define SCI_SETCARETLINEBACK 2098 +#define SCI_STYLESETCHANGEABLE 2099 +#define SCI_AUTOCSHOW 2100 +#define SCI_AUTOCCANCEL 2101 +#define SCI_AUTOCACTIVE 2102 +#define SCI_AUTOCPOSSTART 2103 +#define SCI_AUTOCCOMPLETE 2104 +#define SCI_AUTOCSTOPS 2105 +#define SCI_AUTOCSETSEPARATOR 2106 +#define SCI_AUTOCGETSEPARATOR 2107 +#define SCI_AUTOCSELECT 2108 +#define SCI_AUTOCSETCANCELATSTART 2110 +#define SCI_AUTOCGETCANCELATSTART 2111 +#define SCI_AUTOCSETFILLUPS 2112 +#define SCI_AUTOCSETCHOOSESINGLE 2113 +#define SCI_AUTOCGETCHOOSESINGLE 2114 +#define SCI_AUTOCSETIGNORECASE 2115 +#define SCI_AUTOCGETIGNORECASE 2116 +#define SCI_USERLISTSHOW 2117 +#define SCI_AUTOCSETAUTOHIDE 2118 +#define SCI_AUTOCGETAUTOHIDE 2119 +#define SCI_AUTOCSETDROPRESTOFWORD 2270 +#define SCI_AUTOCGETDROPRESTOFWORD 2271 +#define SCI_REGISTERIMAGE 2405 +#define SCI_CLEARREGISTEREDIMAGES 2408 +#define SCI_AUTOCGETTYPESEPARATOR 2285 +#define SCI_AUTOCSETTYPESEPARATOR 2286 +#define SCI_AUTOCSETMAXWIDTH 2208 +#define SCI_AUTOCGETMAXWIDTH 2209 +#define SCI_AUTOCSETMAXHEIGHT 2210 +#define SCI_AUTOCGETMAXHEIGHT 2211 +#define SCI_SETINDENT 2122 +#define SCI_GETINDENT 2123 +#define SCI_SETUSETABS 2124 +#define SCI_GETUSETABS 2125 +#define SCI_SETLINEINDENTATION 2126 +#define SCI_GETLINEINDENTATION 2127 +#define SCI_GETLINEINDENTPOSITION 2128 +#define SCI_GETCOLUMN 2129 +#define SCI_SETHSCROLLBAR 2130 +#define SCI_GETHSCROLLBAR 2131 +#define SC_IV_NONE 0 +#define SC_IV_REAL 1 +#define SC_IV_LOOKFORWARD 2 +#define SC_IV_LOOKBOTH 3 +#define SCI_SETINDENTATIONGUIDES 2132 +#define SCI_GETINDENTATIONGUIDES 2133 +#define SCI_SETHIGHLIGHTGUIDE 2134 +#define SCI_GETHIGHLIGHTGUIDE 2135 +#define SCI_GETLINEENDPOSITION 2136 +#define SCI_GETCODEPAGE 2137 +#define SCI_GETCARETFORE 2138 +#define SCI_GETUSEPALETTE 2139 +#define SCI_GETREADONLY 2140 +#define SCI_SETCURRENTPOS 2141 +#define SCI_SETSELECTIONSTART 2142 +#define SCI_GETSELECTIONSTART 2143 +#define SCI_SETSELECTIONEND 2144 +#define SCI_GETSELECTIONEND 2145 +#define SCI_SETPRINTMAGNIFICATION 2146 +#define SCI_GETPRINTMAGNIFICATION 2147 +#define SC_PRINT_NORMAL 0 +#define SC_PRINT_INVERTLIGHT 1 +#define SC_PRINT_BLACKONWHITE 2 +#define SC_PRINT_COLOURONWHITE 3 +#define SC_PRINT_COLOURONWHITEDEFAULTBG 4 +#define SCI_SETPRINTCOLOURMODE 2148 +#define SCI_GETPRINTCOLOURMODE 2149 +#define SCFIND_WHOLEWORD 2 +#define SCFIND_MATCHCASE 4 +#define SCFIND_WORDSTART 0x00100000 +#define SCFIND_REGEXP 0x00200000 +#define SCFIND_POSIX 0x00400000 +#define SCI_FINDTEXT 2150 +#define SCI_FORMATRANGE 2151 +#define SCI_GETFIRSTVISIBLELINE 2152 +#define SCI_GETLINE 2153 +#define SCI_GETLINECOUNT 2154 +#define SCI_SETMARGINLEFT 2155 +#define SCI_GETMARGINLEFT 2156 +#define SCI_SETMARGINRIGHT 2157 +#define SCI_GETMARGINRIGHT 2158 +#define SCI_GETMODIFY 2159 +#define SCI_SETSEL 2160 +#define SCI_GETSELTEXT 2161 +#define SCI_GETTEXTRANGE 2162 +#define SCI_HIDESELECTION 2163 +#define SCI_POINTXFROMPOSITION 2164 +#define SCI_POINTYFROMPOSITION 2165 +#define SCI_LINEFROMPOSITION 2166 +#define SCI_POSITIONFROMLINE 2167 +#define SCI_LINESCROLL 2168 +#define SCI_SCROLLCARET 2169 +#define SCI_REPLACESEL 2170 +#define SCI_SETREADONLY 2171 +#define SCI_NULL 2172 +#define SCI_CANPASTE 2173 +#define SCI_CANUNDO 2174 +#define SCI_EMPTYUNDOBUFFER 2175 +#define SCI_UNDO 2176 +#define SCI_CUT 2177 +#define SCI_COPY 2178 +#define SCI_PASTE 2179 +#define SCI_CLEAR 2180 +#define SCI_SETTEXT 2181 +#define SCI_GETTEXT 2182 +#define SCI_GETTEXTLENGTH 2183 +#define SCI_GETDIRECTFUNCTION 2184 +#define SCI_GETDIRECTPOINTER 2185 +#define SCI_SETOVERTYPE 2186 +#define SCI_GETOVERTYPE 2187 +#define SCI_SETCARETWIDTH 2188 +#define SCI_GETCARETWIDTH 2189 +#define SCI_SETTARGETSTART 2190 +#define SCI_GETTARGETSTART 2191 +#define SCI_SETTARGETEND 2192 +#define SCI_GETTARGETEND 2193 +#define SCI_REPLACETARGET 2194 +#define SCI_REPLACETARGETRE 2195 +#define SCI_SEARCHINTARGET 2197 +#define SCI_SETSEARCHFLAGS 2198 +#define SCI_GETSEARCHFLAGS 2199 +#define SCI_CALLTIPSHOW 2200 +#define SCI_CALLTIPCANCEL 2201 +#define SCI_CALLTIPACTIVE 2202 +#define SCI_CALLTIPPOSSTART 2203 +#define SCI_CALLTIPSETHLT 2204 +#define SCI_CALLTIPSETBACK 2205 +#define SCI_CALLTIPSETFORE 2206 +#define SCI_CALLTIPSETFOREHLT 2207 +#define SCI_CALLTIPUSESTYLE 2212 +#define SCI_VISIBLEFROMDOCLINE 2220 +#define SCI_DOCLINEFROMVISIBLE 2221 +#define SCI_WRAPCOUNT 2235 +#define SC_FOLDLEVELBASE 0x400 +#define SC_FOLDLEVELWHITEFLAG 0x1000 +#define SC_FOLDLEVELHEADERFLAG 0x2000 +#define SC_FOLDLEVELBOXHEADERFLAG 0x4000 +#define SC_FOLDLEVELBOXFOOTERFLAG 0x8000 +#define SC_FOLDLEVELCONTRACTED 0x10000 +#define SC_FOLDLEVELUNINDENT 0x20000 +#define SC_FOLDLEVELNUMBERMASK 0x0FFF +#define SCI_SETFOLDLEVEL 2222 +#define SCI_GETFOLDLEVEL 2223 +#define SCI_GETLASTCHILD 2224 +#define SCI_GETFOLDPARENT 2225 +#define SCI_SHOWLINES 2226 +#define SCI_HIDELINES 2227 +#define SCI_GETLINEVISIBLE 2228 +#define SCI_SETFOLDEXPANDED 2229 +#define SCI_GETFOLDEXPANDED 2230 +#define SCI_TOGGLEFOLD 2231 +#define SCI_ENSUREVISIBLE 2232 +#define SC_FOLDFLAG_LINEBEFORE_EXPANDED 0x0002 +#define SC_FOLDFLAG_LINEBEFORE_CONTRACTED 0x0004 +#define SC_FOLDFLAG_LINEAFTER_EXPANDED 0x0008 +#define SC_FOLDFLAG_LINEAFTER_CONTRACTED 0x0010 +#define SC_FOLDFLAG_LEVELNUMBERS 0x0040 +#define SC_FOLDFLAG_BOX 0x0001 +#define SCI_SETFOLDFLAGS 2233 +#define SCI_ENSUREVISIBLEENFORCEPOLICY 2234 +#define SCI_SETTABINDENTS 2260 +#define SCI_GETTABINDENTS 2261 +#define SCI_SETBACKSPACEUNINDENTS 2262 +#define SCI_GETBACKSPACEUNINDENTS 2263 +#define SC_TIME_FOREVER 10000000 +#define SCI_SETMOUSEDWELLTIME 2264 +#define SCI_GETMOUSEDWELLTIME 2265 +#define SCI_WORDSTARTPOSITION 2266 +#define SCI_WORDENDPOSITION 2267 +#define SC_WRAP_NONE 0 +#define SC_WRAP_WORD 1 +#define SC_WRAP_CHAR 2 +#define SCI_SETWRAPMODE 2268 +#define SCI_GETWRAPMODE 2269 +#define SC_WRAPVISUALFLAG_NONE 0x0000 +#define SC_WRAPVISUALFLAG_END 0x0001 +#define SC_WRAPVISUALFLAG_START 0x0002 +#define SCI_SETWRAPVISUALFLAGS 2460 +#define SCI_GETWRAPVISUALFLAGS 2461 +#define SC_WRAPVISUALFLAGLOC_DEFAULT 0x0000 +#define SC_WRAPVISUALFLAGLOC_END_BY_TEXT 0x0001 +#define SC_WRAPVISUALFLAGLOC_START_BY_TEXT 0x0002 +#define SCI_SETWRAPVISUALFLAGSLOCATION 2462 +#define SCI_GETWRAPVISUALFLAGSLOCATION 2463 +#define SCI_SETWRAPSTARTINDENT 2464 +#define SCI_GETWRAPSTARTINDENT 2465 +#define SC_CACHE_NONE 0 +#define SC_CACHE_CARET 1 +#define SC_CACHE_PAGE 2 +#define SC_CACHE_DOCUMENT 3 +#define SCI_SETLAYOUTCACHE 2272 +#define SCI_GETLAYOUTCACHE 2273 +#define SCI_SETSCROLLWIDTH 2274 +#define SCI_GETSCROLLWIDTH 2275 +#define SCI_SETSCROLLWIDTHTRACKING 2516 +#define SCI_GETSCROLLWIDTHTRACKING 2517 +#define SCI_TEXTWIDTH 2276 +#define SCI_SETENDATLASTLINE 2277 +#define SCI_GETENDATLASTLINE 2278 +#define SCI_TEXTHEIGHT 2279 +#define SCI_SETVSCROLLBAR 2280 +#define SCI_GETVSCROLLBAR 2281 +#define SCI_APPENDTEXT 2282 +#define SCI_GETTWOPHASEDRAW 2283 +#define SCI_SETTWOPHASEDRAW 2284 +#define SCI_TARGETFROMSELECTION 2287 +#define SCI_LINESJOIN 2288 +#define SCI_LINESSPLIT 2289 +#define SCI_SETFOLDMARGINCOLOUR 2290 +#define SCI_SETFOLDMARGINHICOLOUR 2291 +#define SCI_LINEDOWN 2300 +#define SCI_LINEDOWNEXTEND 2301 +#define SCI_LINEUP 2302 +#define SCI_LINEUPEXTEND 2303 +#define SCI_CHARLEFT 2304 +#define SCI_CHARLEFTEXTEND 2305 +#define SCI_CHARRIGHT 2306 +#define SCI_CHARRIGHTEXTEND 2307 +#define SCI_WORDLEFT 2308 +#define SCI_WORDLEFTEXTEND 2309 +#define SCI_WORDRIGHT 2310 +#define SCI_WORDRIGHTEXTEND 2311 +#define SCI_HOME 2312 +#define SCI_HOMEEXTEND 2313 +#define SCI_LINEEND 2314 +#define SCI_LINEENDEXTEND 2315 +#define SCI_DOCUMENTSTART 2316 +#define SCI_DOCUMENTSTARTEXTEND 2317 +#define SCI_DOCUMENTEND 2318 +#define SCI_DOCUMENTENDEXTEND 2319 +#define SCI_PAGEUP 2320 +#define SCI_PAGEUPEXTEND 2321 +#define SCI_PAGEDOWN 2322 +#define SCI_PAGEDOWNEXTEND 2323 +#define SCI_EDITTOGGLEOVERTYPE 2324 +#define SCI_CANCEL 2325 +#define SCI_DELETEBACK 2326 +#define SCI_TAB 2327 +#define SCI_BACKTAB 2328 +#define SCI_NEWLINE 2329 +#define SCI_FORMFEED 2330 +#define SCI_VCHOME 2331 +#define SCI_VCHOMEEXTEND 2332 +#define SCI_ZOOMIN 2333 +#define SCI_ZOOMOUT 2334 +#define SCI_DELWORDLEFT 2335 +#define SCI_DELWORDRIGHT 2336 +#define SCI_DELWORDRIGHTEND 2518 +#define SCI_LINECUT 2337 +#define SCI_LINEDELETE 2338 +#define SCI_LINETRANSPOSE 2339 +#define SCI_LINEDUPLICATE 2404 +#define SCI_LOWERCASE 2340 +#define SCI_UPPERCASE 2341 +#define SCI_LINESCROLLDOWN 2342 +#define SCI_LINESCROLLUP 2343 +#define SCI_DELETEBACKNOTLINE 2344 +#define SCI_HOMEDISPLAY 2345 +#define SCI_HOMEDISPLAYEXTEND 2346 +#define SCI_LINEENDDISPLAY 2347 +#define SCI_LINEENDDISPLAYEXTEND 2348 +#define SCI_HOMEWRAP 2349 +#define SCI_HOMEWRAPEXTEND 2450 +#define SCI_LINEENDWRAP 2451 +#define SCI_LINEENDWRAPEXTEND 2452 +#define SCI_VCHOMEWRAP 2453 +#define SCI_VCHOMEWRAPEXTEND 2454 +#define SCI_LINECOPY 2455 +#define SCI_MOVECARETINSIDEVIEW 2401 +#define SCI_LINELENGTH 2350 +#define SCI_BRACEHIGHLIGHT 2351 +#define SCI_BRACEBADLIGHT 2352 +#define SCI_BRACEMATCH 2353 +#define SCI_GETVIEWEOL 2355 +#define SCI_SETVIEWEOL 2356 +#define SCI_GETDOCPOINTER 2357 +#define SCI_SETDOCPOINTER 2358 +#define SCI_SETMODEVENTMASK 2359 +#define EDGE_NONE 0 +#define EDGE_LINE 1 +#define EDGE_BACKGROUND 2 +#define SCI_GETEDGECOLUMN 2360 +#define SCI_SETEDGECOLUMN 2361 +#define SCI_GETEDGEMODE 2362 +#define SCI_SETEDGEMODE 2363 +#define SCI_GETEDGECOLOUR 2364 +#define SCI_SETEDGECOLOUR 2365 +#define SCI_SEARCHANCHOR 2366 +#define SCI_SEARCHNEXT 2367 +#define SCI_SEARCHPREV 2368 +#define SCI_LINESONSCREEN 2370 +#define SCI_USEPOPUP 2371 +#define SCI_SELECTIONISRECTANGLE 2372 +#define SCI_SETZOOM 2373 +#define SCI_GETZOOM 2374 +#define SCI_CREATEDOCUMENT 2375 +#define SCI_ADDREFDOCUMENT 2376 +#define SCI_RELEASEDOCUMENT 2377 +#define SCI_GETMODEVENTMASK 2378 +#define SCI_SETFOCUS 2380 +#define SCI_GETFOCUS 2381 +#define SCI_SETSTATUS 2382 +#define SCI_GETSTATUS 2383 +#define SCI_SETMOUSEDOWNCAPTURES 2384 +#define SCI_GETMOUSEDOWNCAPTURES 2385 +#define SC_CURSORNORMAL -1 +#define SC_CURSORWAIT 4 +#define SCI_SETCURSOR 2386 +#define SCI_GETCURSOR 2387 +#define SCI_SETCONTROLCHARSYMBOL 2388 +#define SCI_GETCONTROLCHARSYMBOL 2389 +#define SCI_WORDPARTLEFT 2390 +#define SCI_WORDPARTLEFTEXTEND 2391 +#define SCI_WORDPARTRIGHT 2392 +#define SCI_WORDPARTRIGHTEXTEND 2393 +#define VISIBLE_SLOP 0x01 +#define VISIBLE_STRICT 0x04 +#define SCI_SETVISIBLEPOLICY 2394 +#define SCI_DELLINELEFT 2395 +#define SCI_DELLINERIGHT 2396 +#define SCI_SETXOFFSET 2397 +#define SCI_GETXOFFSET 2398 +#define SCI_CHOOSECARETX 2399 +#define SCI_GRABFOCUS 2400 +#define CARET_SLOP 0x01 +#define CARET_STRICT 0x04 +#define CARET_JUMPS 0x10 +#define CARET_EVEN 0x08 +#define SCI_SETXCARETPOLICY 2402 +#define SCI_SETYCARETPOLICY 2403 +#define SCI_SETPRINTWRAPMODE 2406 +#define SCI_GETPRINTWRAPMODE 2407 +#define SCI_SETHOTSPOTACTIVEFORE 2410 +#define SCI_GETHOTSPOTACTIVEFORE 2494 +#define SCI_SETHOTSPOTACTIVEBACK 2411 +#define SCI_GETHOTSPOTACTIVEBACK 2495 +#define SCI_SETHOTSPOTACTIVEUNDERLINE 2412 +#define SCI_GETHOTSPOTACTIVEUNDERLINE 2496 +#define SCI_SETHOTSPOTSINGLELINE 2421 +#define SCI_GETHOTSPOTSINGLELINE 2497 +#define SCI_PARADOWN 2413 +#define SCI_PARADOWNEXTEND 2414 +#define SCI_PARAUP 2415 +#define SCI_PARAUPEXTEND 2416 +#define SCI_POSITIONBEFORE 2417 +#define SCI_POSITIONAFTER 2418 +#define SCI_COPYRANGE 2419 +#define SCI_COPYTEXT 2420 +#define SC_SEL_STREAM 0 +#define SC_SEL_RECTANGLE 1 +#define SC_SEL_LINES 2 +#define SCI_SETSELECTIONMODE 2422 +#define SCI_GETSELECTIONMODE 2423 +#define SCI_GETLINESELSTARTPOSITION 2424 +#define SCI_GETLINESELENDPOSITION 2425 +#define SCI_LINEDOWNRECTEXTEND 2426 +#define SCI_LINEUPRECTEXTEND 2427 +#define SCI_CHARLEFTRECTEXTEND 2428 +#define SCI_CHARRIGHTRECTEXTEND 2429 +#define SCI_HOMERECTEXTEND 2430 +#define SCI_VCHOMERECTEXTEND 2431 +#define SCI_LINEENDRECTEXTEND 2432 +#define SCI_PAGEUPRECTEXTEND 2433 +#define SCI_PAGEDOWNRECTEXTEND 2434 +#define SCI_STUTTEREDPAGEUP 2435 +#define SCI_STUTTEREDPAGEUPEXTEND 2436 +#define SCI_STUTTEREDPAGEDOWN 2437 +#define SCI_STUTTEREDPAGEDOWNEXTEND 2438 +#define SCI_WORDLEFTEND 2439 +#define SCI_WORDLEFTENDEXTEND 2440 +#define SCI_WORDRIGHTEND 2441 +#define SCI_WORDRIGHTENDEXTEND 2442 +#define SCI_SETWHITESPACECHARS 2443 +#define SCI_SETCHARSDEFAULT 2444 +#define SCI_AUTOCGETCURRENT 2445 +#define SCI_ALLOCATE 2446 +#define SCI_TARGETASUTF8 2447 +#define SCI_SETLENGTHFORENCODE 2448 +#define SCI_ENCODEDFROMUTF8 2449 +#define SCI_FINDCOLUMN 2456 +#define SCI_GETCARETSTICKY 2457 +#define SCI_SETCARETSTICKY 2458 +#define SCI_TOGGLECARETSTICKY 2459 +#define SCI_SETPASTECONVERTENDINGS 2467 +#define SCI_GETPASTECONVERTENDINGS 2468 +#define SCI_SELECTIONDUPLICATE 2469 +#define SC_ALPHA_TRANSPARENT 0 +#define SC_ALPHA_OPAQUE 255 +#define SC_ALPHA_NOALPHA 256 +#define SCI_SETCARETLINEBACKALPHA 2470 +#define SCI_GETCARETLINEBACKALPHA 2471 +#define CARETSTYLE_INVISIBLE 0 +#define CARETSTYLE_LINE 1 +#define CARETSTYLE_BLOCK 2 +#define SCI_SETCARETSTYLE 2512 +#define SCI_GETCARETSTYLE 2513 +#define SCI_SETINDICATORCURRENT 2500 +#define SCI_GETINDICATORCURRENT 2501 +#define SCI_SETINDICATORVALUE 2502 +#define SCI_GETINDICATORVALUE 2503 +#define SCI_INDICATORFILLRANGE 2504 +#define SCI_INDICATORCLEARRANGE 2505 +#define SCI_INDICATORALLONFOR 2506 +#define SCI_INDICATORVALUEAT 2507 +#define SCI_INDICATORSTART 2508 +#define SCI_INDICATOREND 2509 +#define SCI_SETPOSITIONCACHE 2514 +#define SCI_GETPOSITIONCACHE 2515 +#define SCI_COPYALLOWLINE 2519 +#define SCI_STARTRECORD 3001 +#define SCI_STOPRECORD 3002 +#define SCI_SETLEXER 4001 +#define SCI_GETLEXER 4002 +#define SCI_COLOURISE 4003 +#define SCI_SETPROPERTY 4004 +#define KEYWORDSET_MAX 8 +#define SCI_SETKEYWORDS 4005 +#define SCI_SETLEXERLANGUAGE 4006 +#define SCI_LOADLEXERLIBRARY 4007 +#define SCI_GETPROPERTY 4008 +#define SCI_GETPROPERTYEXPANDED 4009 +#define SCI_GETPROPERTYINT 4010 +#define SCI_GETSTYLEBITSNEEDED 4011 +#define SC_MOD_INSERTTEXT 0x1 +#define SC_MOD_DELETETEXT 0x2 +#define SC_MOD_CHANGESTYLE 0x4 +#define SC_MOD_CHANGEFOLD 0x8 +#define SC_PERFORMED_USER 0x10 +#define SC_PERFORMED_UNDO 0x20 +#define SC_PERFORMED_REDO 0x40 +#define SC_MULTISTEPUNDOREDO 0x80 +#define SC_LASTSTEPINUNDOREDO 0x100 +#define SC_MOD_CHANGEMARKER 0x200 +#define SC_MOD_BEFOREINSERT 0x400 +#define SC_MOD_BEFOREDELETE 0x800 +#define SC_MULTILINEUNDOREDO 0x1000 +#define SC_STARTACTION 0x2000 +#define SC_MOD_CHANGEINDICATOR 0x4000 +#define SC_MOD_CHANGELINESTATE 0x8000 +#define SC_MODEVENTMASKALL 0xFFFF +#define SC_SEARCHRESULT_LINEBUFFERMAXLENGTH 1024 +#define SCEN_CHANGE 768 +#define SCEN_SETFOCUS 512 +#define SCEN_KILLFOCUS 256 +#define SCK_DOWN 300 +#define SCK_UP 301 +#define SCK_LEFT 302 +#define SCK_RIGHT 303 +#define SCK_HOME 304 +#define SCK_END 305 +#define SCK_PRIOR 306 +#define SCK_NEXT 307 +#define SCK_DELETE 308 +#define SCK_INSERT 309 +#define SCK_ESCAPE 7 +#define SCK_BACK 8 +#define SCK_TAB 9 +#define SCK_RETURN 13 +#define SCK_ADD 310 +#define SCK_SUBTRACT 311 +#define SCK_DIVIDE 312 +#define SCK_WIN 313 +#define SCK_RWIN 314 +#define SCK_MENU 315 +#define SCMOD_NORM 0 +#define SCMOD_SHIFT 1 +#define SCMOD_CTRL 2 +#define SCMOD_ALT 4 +#define SCN_STYLENEEDED 2000 +#define SCN_CHARADDED 2001 +#define SCN_SAVEPOINTREACHED 2002 +#define SCN_SAVEPOINTLEFT 2003 +#define SCN_MODIFYATTEMPTRO 2004 +#define SCN_KEY 2005 +#define SCN_DOUBLECLICK 2006 +#define SCN_UPDATEUI 2007 +#define SCN_MODIFIED 2008 +#define SCN_MACRORECORD 2009 +#define SCN_MARGINCLICK 2010 +#define SCN_NEEDSHOWN 2011 +#define SCN_PAINTED 2013 +#define SCN_USERLISTSELECTION 2014 +#define SCN_URIDROPPED 2015 +#define SCN_DWELLSTART 2016 +#define SCN_DWELLEND 2017 +#define SCN_ZOOM 2018 +#define SCN_HOTSPOTCLICK 2019 +#define SCN_HOTSPOTDOUBLECLICK 2020 +#define SCN_CALLTIPCLICK 2021 +#define SCN_AUTOCSELECTION 2022 +#define SCN_INDICATORCLICK 2023 +#define SCN_INDICATORRELEASE 2024 + +#define SCN_SCROLLED 2080 +//--Autogenerated -- end of section automatically generated from Scintilla.iface + +// These structures are defined to be exactly the same shape as the Win32 +// CHARRANGE, TEXTRANGE, FINDTEXTEX, FORMATRANGE, and NMHDR structs. +// So older code that treats Scintilla as a RichEdit will work. + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +struct CharacterRange { + long cpMin; + long cpMax; +}; + +struct TextRange { + struct CharacterRange chrg; + char *lpstrText; +}; + +struct TextToFind { + struct CharacterRange chrg; + char *lpstrText; + struct CharacterRange chrgText; +}; + +#ifdef PLATFORM_H + +// This structure is used in printing and requires some of the graphics types +// from Platform.h. Not needed by most client code. + +struct RangeToFormat { + SurfaceID hdc; + SurfaceID hdcTarget; + PRectangle rc; + PRectangle rcPage; + CharacterRange chrg; +}; + +#endif + +struct NotifyHeader { + // Compatible with Windows NMHDR. + // hwndFrom is really an environment specific window handle or pointer + // but most clients of Scintilla.h do not have this type visible. + void *hwndFrom; + uptr_t idFrom; + unsigned int code; +}; + +struct SCNotification { + struct NotifyHeader nmhdr; + int position; // SCN_STYLENEEDED, SCN_MODIFIED, SCN_DWELLSTART, SCN_DWELLEND + int ch; // SCN_CHARADDED, SCN_KEY + int modifiers; // SCN_KEY + int modificationType; // SCN_MODIFIED + const char *text; // SCN_MODIFIED, SCN_USERLISTSELECTION, SCN_AUTOCSELECTION + int length; // SCN_MODIFIED + int linesAdded; // SCN_MODIFIED + int message; // SCN_MACRORECORD + uptr_t wParam; // SCN_MACRORECORD + sptr_t lParam; // SCN_MACRORECORD + int line; // SCN_MODIFIED + int foldLevelNow; // SCN_MODIFIED + int foldLevelPrev; // SCN_MODIFIED + int margin; // SCN_MARGINCLICK + int listType; // SCN_USERLISTSELECTION + int x; // SCN_DWELLSTART, SCN_DWELLEND + int y; // SCN_DWELLSTART, SCN_DWELLEND +}; + +struct SearchResultMarking { + long _start; + long _end; +}; + +struct SearchResultMarkings { + long _length; + SearchResultMarking *_markings; +}; + +#ifdef SCI_NAMESPACE +} +#endif + +// Deprecation section listing all API features that are deprecated and will +// will be removed completely in a future version. +// To enable these features define INCLUDE_DEPRECATED_FEATURES + +#ifdef INCLUDE_DEPRECATED_FEATURES + +#define SCI_SETCARETPOLICY 2369 +#define CARET_CENTER 0x02 +#define CARET_XEVEN 0x08 +#define CARET_XJUMPS 0x10 + +#define SCN_POSCHANGED 2012 +#define SCN_CHECKBRACE 2007 + +#endif + +#endif diff --git a/scintilla/include/Scintilla.iface b/scintilla/include/Scintilla.iface new file mode 100644 index 00000000..00853cd5 --- /dev/null +++ b/scintilla/include/Scintilla.iface @@ -0,0 +1,3340 @@ +## First line may be used for shbang + +## This file defines the interface to Scintilla + +## Copyright 2000-2003 by Neil Hodgson +## The License.txt file describes the conditions under which this software may be distributed. + +## A line starting with ## is a pure comment and should be stripped by readers. +## A line starting with #! is for future shbang use +## A line starting with # followed by a space is a documentation comment and refers +## to the next feature definition. + +## Each feature is defined by a line starting with fun, get, set, val or evt. +## cat -> start a category +## fun -> a function +## get -> a property get function +## set -> a property set function +## val -> definition of a constant +## evt -> an event +## enu -> associate an enumeration with a set of vals with a prefix +## lex -> associate a lexer with the lexical classes it produces +## +## All other feature names should be ignored. They may be defined in the future. +## A property may have a set function, a get function or both. Each will have +## "Get" or "Set" in their names and the corresponding name will have the obvious switch. +## A property may be subscripted, in which case the first parameter is the subscript. +## fun, get, and set features have a strict syntax: +## [=,) +## where stands for white space. +## param may be empty (null value) or is [=] +## Additional white space is allowed between elements. +## The syntax for evt is [=[,]*]) +## Feature names that contain an underscore are defined by Windows, so in these +## cases, using the Windows definition is preferred where available. +## The feature numbers are stable so features will not be renumbered. +## Features may be removed but they will go through a period of deprecation +## before removal which is signalled by moving them into the Deprecated category. +## +## enu has the syntax enu=[]* where all the val +## features in this file starting with a given are considered part of the +## enumeration. +## +## lex has the syntax lex=[]* +## where name is a reasonably capitalised (Python, XML) identifier or UI name, +## lexerVal is the val used to specify the lexer, and the list of prefixes is similar +## to enu. The name may not be the same as that used within the lexer so the lexerVal +## should be used to tie these entities together. + +## Types: +## void +## int +## bool -> integer, 1=true, 0=false +## position -> integer position in a document +## colour -> colour integer containing red, green and blue bytes. +## string -> pointer to const character +## stringresult -> pointer to character, NULL-> return size of result +## cells -> pointer to array of cells, each cell containing a style byte and character byte +## textrange -> range of a min and a max position with an output string +## findtext -> searchrange, text -> foundposition +## keymod -> integer containing key in low half and modifiers in high half +## formatrange +## Types no longer used: +## findtextex -> searchrange +## charrange -> range of a min and a max position +## charrangeresult -> like charrange, but output param +## countedstring +## point -> x,y +## pointresult -> like point, but output param +## rectangle -> left,top,right,bottom +## Client code should ignore definitions containing types it does not understand, except +## for possibly #defining the constants + +## Line numbers and positions start at 0. +## String arguments may contain NUL ('\0') characters where the calls provide a length +## argument and retrieve NUL characters. All retrieved strings except for those retrieved +## by GetLine also have a NUL appended but client code should calculate the size that +## will be returned rather than relying upon the NUL whenever possible. Allow for the +## extra NUL character when allocating buffers. The size to allocate for a stringresult +## can be determined by calling with a NULL (0) pointer. + +cat Basics + +################################################ +## For Scintilla.h +val INVALID_POSITION=-1 +# Define start of Scintilla messages to be greater than all Windows edit (EM_*) messages +# as many EM_ messages can be used although that use is deprecated. +val SCI_START=2000 +val SCI_OPTIONAL_START=3000 +val SCI_LEXER_START=4000 + +# Add text to the document at current position. +fun void AddText=2001(int length, string text) + +# Add array of cells to document. +fun void AddStyledText=2002(int length, cells c) + +# Insert string at a position. +fun void InsertText=2003(position pos, string text) + +# Delete all text in the document. +fun void ClearAll=2004(,) + +# Set all style bytes to 0, remove all folding information. +fun void ClearDocumentStyle=2005(,) + +# Returns the number of characters in the document. +get int GetLength=2006(,) + +# Returns the character byte at the position. +get int GetCharAt=2007(position pos,) + +# Returns the position of the caret. +get position GetCurrentPos=2008(,) + +# Returns the position of the opposite end of the selection to the caret. +get position GetAnchor=2009(,) + +# Returns the style byte at the position. +get int GetStyleAt=2010(position pos,) + +# Redoes the next action on the undo history. +fun void Redo=2011(,) + +# Choose between collecting actions into the undo +# history and discarding them. +set void SetUndoCollection=2012(bool collectUndo,) + +# Select all the text in the document. +fun void SelectAll=2013(,) + +# Remember the current position in the undo history as the position +# at which the document was saved. +fun void SetSavePoint=2014(,) + +# Retrieve a buffer of cells. +# Returns the number of bytes in the buffer not including terminating NULs. +fun int GetStyledText=2015(, textrange tr) + +# Are there any redoable actions in the undo history? +fun bool CanRedo=2016(,) + +# Retrieve the line number at which a particular marker is located. +fun int MarkerLineFromHandle=2017(int handle,) + +# Delete a marker. +fun void MarkerDeleteHandle=2018(int handle,) + +# Is undo history being collected? +get bool GetUndoCollection=2019(,) + +enu WhiteSpace=SCWS_ +val SCWS_INVISIBLE=0 +val SCWS_VISIBLEALWAYS=1 +val SCWS_VISIBLEAFTERINDENT=2 + +# Are white space characters currently visible? +# Returns one of SCWS_* constants. +get int GetViewWS=2020(,) + +# Make white space characters invisible, always visible or visible outside indentation. +set void SetViewWS=2021(int viewWS,) + +# Find the position from a point within the window. +fun position PositionFromPoint=2022(int x, int y) + +# Find the position from a point within the window but return +# INVALID_POSITION if not close to text. +fun position PositionFromPointClose=2023(int x, int y) + +# Set caret to start of a line and ensure it is visible. +fun void GotoLine=2024(int line,) + +# Set caret to a position and ensure it is visible. +fun void GotoPos=2025(position pos,) + +# Set the selection anchor to a position. The anchor is the opposite +# end of the selection from the caret. +set void SetAnchor=2026(position posAnchor,) + +# Retrieve the text of the line containing the caret. +# Returns the index of the caret on the line. +fun int GetCurLine=2027(int length, stringresult text) + +# Retrieve the position of the last correctly styled character. +get position GetEndStyled=2028(,) + +enu EndOfLine=SC_EOL_ +val SC_EOL_CRLF=0 +val SC_EOL_CR=1 +val SC_EOL_LF=2 + +# Convert all line endings in the document to one mode. +fun void ConvertEOLs=2029(int eolMode,) + +# Retrieve the current end of line mode - one of CRLF, CR, or LF. +get int GetEOLMode=2030(,) + +# Set the current end of line mode. +set void SetEOLMode=2031(int eolMode,) + +# Set the current styling position to pos and the styling mask to mask. +# The styling mask can be used to protect some bits in each styling byte from modification. +fun void StartStyling=2032(position pos, int mask) + +# Change style from current styling position for length characters to a style +# and move the current styling position to after this newly styled segment. +fun void SetStyling=2033(int length, int style) + +# Is drawing done first into a buffer or direct to the screen? +get bool GetBufferedDraw=2034(,) + +# If drawing is buffered then each line of text is drawn into a bitmap buffer +# before drawing it to the screen to avoid flicker. +set void SetBufferedDraw=2035(bool buffered,) + +# Change the visible size of a tab to be a multiple of the width of a space character. +set void SetTabWidth=2036(int tabWidth,) + +# Retrieve the visible size of a tab. +get int GetTabWidth=2121(,) + +# The SC_CP_UTF8 value can be used to enter Unicode mode. +# This is the same value as CP_UTF8 in Windows +val SC_CP_UTF8=65001 + +# The SC_CP_DBCS value can be used to indicate a DBCS mode for GTK+. +val SC_CP_DBCS=1 + +# Set the code page used to interpret the bytes of the document as characters. +# The SC_CP_UTF8 value can be used to enter Unicode mode. +set void SetCodePage=2037(int codePage,) + +# In palette mode, Scintilla uses the environment's palette calls to display +# more colours. This may lead to ugly displays. +set void SetUsePalette=2039(bool usePalette,) + +enu MarkerSymbol=SC_MARK_ +val MARKER_MAX=31 +val SC_MARK_CIRCLE=0 +val SC_MARK_ROUNDRECT=1 +val SC_MARK_ARROW=2 +val SC_MARK_SMALLRECT=3 +val SC_MARK_SHORTARROW=4 +val SC_MARK_EMPTY=5 +val SC_MARK_ARROWDOWN=6 +val SC_MARK_MINUS=7 +val SC_MARK_PLUS=8 + +# Shapes used for outlining column. +val SC_MARK_VLINE=9 +val SC_MARK_LCORNER=10 +val SC_MARK_TCORNER=11 +val SC_MARK_BOXPLUS=12 +val SC_MARK_BOXPLUSCONNECTED=13 +val SC_MARK_BOXMINUS=14 +val SC_MARK_BOXMINUSCONNECTED=15 +val SC_MARK_LCORNERCURVE=16 +val SC_MARK_TCORNERCURVE=17 +val SC_MARK_CIRCLEPLUS=18 +val SC_MARK_CIRCLEPLUSCONNECTED=19 +val SC_MARK_CIRCLEMINUS=20 +val SC_MARK_CIRCLEMINUSCONNECTED=21 + +# Invisible mark that only sets the line background color. +val SC_MARK_BACKGROUND=22 +val SC_MARK_DOTDOTDOT=23 +val SC_MARK_ARROWS=24 +val SC_MARK_PIXMAP=25 +val SC_MARK_FULLRECT=26 +val SC_MARK_LEFTRECT=27 + +val SC_MARK_CHARACTER=10000 + +enu MarkerOutline=SC_MARKNUM_ +# Markers used for outlining column. +val SC_MARKNUM_FOLDEREND=25 +val SC_MARKNUM_FOLDEROPENMID=26 +val SC_MARKNUM_FOLDERMIDTAIL=27 +val SC_MARKNUM_FOLDERTAIL=28 +val SC_MARKNUM_FOLDERSUB=29 +val SC_MARKNUM_FOLDER=30 +val SC_MARKNUM_FOLDEROPEN=31 + +val SC_MASK_FOLDERS=0xFE000000 + +# Set the symbol used for a particular marker number. +fun void MarkerDefine=2040(int markerNumber, int markerSymbol) + +# Set the foreground colour used for a particular marker number. +fun void MarkerSetFore=2041(int markerNumber, colour fore) + +# Set the background colour used for a particular marker number. +fun void MarkerSetBack=2042(int markerNumber, colour back) + +# Add a marker to a line, returning an ID which can be used to find or delete the marker. +fun int MarkerAdd=2043(int line, int markerNumber) + +# Delete a marker from a line. +fun void MarkerDelete=2044(int line, int markerNumber) + +# Delete all markers with a particular number from all lines. +fun void MarkerDeleteAll=2045(int markerNumber,) + +# Get a bit mask of all the markers set on a line. +fun int MarkerGet=2046(int line,) + +# Find the next line after lineStart that includes a marker in mask. +fun int MarkerNext=2047(int lineStart, int markerMask) + +# Find the previous line before lineStart that includes a marker in mask. +fun int MarkerPrevious=2048(int lineStart, int markerMask) + +# Define a marker from a pixmap. +fun void MarkerDefinePixmap=2049(int markerNumber, string pixmap) + +# Add a set of markers to a line. +fun void MarkerAddSet=2466(int line, int set) + +# Set the alpha used for a marker that is drawn in the text area, not the margin. +fun void MarkerSetAlpha=2476(int markerNumber, int alpha) + +enu MarginType=SC_MARGIN_ +val SC_MARGIN_SYMBOL=0 +val SC_MARGIN_NUMBER=1 +val SC_MARGIN_BACK=2 +val SC_MARGIN_FORE=3 + +# Set a margin to be either numeric or symbolic. +set void SetMarginTypeN=2240(int margin, int marginType) + +# Retrieve the type of a margin. +get int GetMarginTypeN=2241(int margin,) + +# Set the width of a margin to a width expressed in pixels. +set void SetMarginWidthN=2242(int margin, int pixelWidth) + +# Retrieve the width of a margin in pixels. +get int GetMarginWidthN=2243(int margin,) + +# Set a mask that determines which markers are displayed in a margin. +set void SetMarginMaskN=2244(int margin, int mask) + +# Retrieve the marker mask of a margin. +get int GetMarginMaskN=2245(int margin,) + +# Make a margin sensitive or insensitive to mouse clicks. +set void SetMarginSensitiveN=2246(int margin, bool sensitive) + +# Retrieve the mouse click sensitivity of a margin. +get bool GetMarginSensitiveN=2247(int margin,) + +# Styles in range 32..38 are predefined for parts of the UI and are not used as normal styles. +# Style 39 is for future use. +enu StylesCommon=STYLE_ +val STYLE_DEFAULT=32 +val STYLE_LINENUMBER=33 +val STYLE_BRACELIGHT=34 +val STYLE_BRACEBAD=35 +val STYLE_CONTROLCHAR=36 +val STYLE_INDENTGUIDE=37 +val STYLE_CALLTIP=38 +val STYLE_LASTPREDEFINED=39 +val STYLE_MAX=255 + +# Character set identifiers are used in StyleSetCharacterSet. +# The values are the same as the Windows *_CHARSET values. +enu CharacterSet=SC_CHARSET_ +val SC_CHARSET_ANSI=0 +val SC_CHARSET_DEFAULT=1 +val SC_CHARSET_BALTIC=186 +val SC_CHARSET_CHINESEBIG5=136 +val SC_CHARSET_EASTEUROPE=238 +val SC_CHARSET_GB2312=134 +val SC_CHARSET_GREEK=161 +val SC_CHARSET_HANGUL=129 +val SC_CHARSET_MAC=77 +val SC_CHARSET_OEM=255 +val SC_CHARSET_RUSSIAN=204 +val SC_CHARSET_CYRILLIC=1251 +val SC_CHARSET_SHIFTJIS=128 +val SC_CHARSET_SYMBOL=2 +val SC_CHARSET_TURKISH=162 +val SC_CHARSET_JOHAB=130 +val SC_CHARSET_HEBREW=177 +val SC_CHARSET_ARABIC=178 +val SC_CHARSET_VIETNAMESE=163 +val SC_CHARSET_THAI=222 +val SC_CHARSET_8859_15=1000 + +# Clear all the styles and make equivalent to the global default style. +set void StyleClearAll=2050(,) + +# Set the foreground colour of a style. +set void StyleSetFore=2051(int style, colour fore) + +# Set the background colour of a style. +set void StyleSetBack=2052(int style, colour back) + +# Set a style to be bold or not. +set void StyleSetBold=2053(int style, bool bold) + +# Set a style to be italic or not. +set void StyleSetItalic=2054(int style, bool italic) + +# Set the size of characters of a style. +set void StyleSetSize=2055(int style, int sizePoints) + +# Set the font of a style. +set void StyleSetFont=2056(int style, string fontName) + +# Set a style to have its end of line filled or not. +set void StyleSetEOLFilled=2057(int style, bool filled) + +# Reset the default style to its state at startup +fun void StyleResetDefault=2058(,) + +# Set a style to be underlined or not. +set void StyleSetUnderline=2059(int style, bool underline) + +enu CaseVisible=SC_CASE_ +val SC_CASE_MIXED=0 +val SC_CASE_UPPER=1 +val SC_CASE_LOWER=2 + +# Get the foreground colour of a style. +get colour StyleGetFore=2481(int style,) + +# Get the background colour of a style. +get colour StyleGetBack=2482(int style,) + +# Get is a style bold or not. +get bool StyleGetBold=2483(int style,) + +# Get is a style italic or not. +get bool StyleGetItalic=2484(int style,) + +# Get the size of characters of a style. +get int StyleGetSize=2485(int style,) + +# Get the font of a style. +# Returns the length of the fontName +fun int StyleGetFont=2486(int style, stringresult fontName) + +# Get is a style to have its end of line filled or not. +get bool StyleGetEOLFilled=2487(int style,) + +# Get is a style underlined or not. +get bool StyleGetUnderline=2488(int style,) + +# Get is a style mixed case, or to force upper or lower case. +get int StyleGetCase=2489(int style,) + +# Get the character get of the font in a style. +get int StyleGetCharacterSet=2490(int style,) + +# Get is a style visible or not. +get bool StyleGetVisible=2491(int style,) + +# Get is a style changeable or not (read only). +# Experimental feature, currently buggy. +get bool StyleGetChangeable=2492(int style,) + +# Get is a style a hotspot or not. +get bool StyleGetHotSpot=2493(int style,) + +# Set a style to be mixed case, or to force upper or lower case. +set void StyleSetCase=2060(int style, int caseForce) + +# Set the character set of the font in a style. +set void StyleSetCharacterSet=2066(int style, int characterSet) + +# Set a style to be a hotspot or not. +set void StyleSetHotSpot=2409(int style, bool hotspot) + +# Set the foreground colour of the selection and whether to use this setting. +fun void SetSelFore=2067(bool useSetting, colour fore) + +# Set the background colour of the selection and whether to use this setting. +fun void SetSelBack=2068(bool useSetting, colour back) + +# Get the alpha of the selection. +get int GetSelAlpha=2477(,) + +# Set the alpha of the selection. +set void SetSelAlpha=2478(int alpha,) + +# Is the selection end of line filled? +get bool GetSelEOLFilled=2479(,) + +# Set the selection to have its end of line filled or not. +set void SetSelEOLFilled=2480(bool filled,) + +# Set the foreground colour of the caret. +set void SetCaretFore=2069(colour fore,) + +# When key+modifier combination km is pressed perform msg. +fun void AssignCmdKey=2070(keymod km, int msg) + +# When key+modifier combination km is pressed do nothing. +fun void ClearCmdKey=2071(keymod km,) + +# Drop all key mappings. +fun void ClearAllCmdKeys=2072(,) + +# Set the styles for a segment of the document. +fun void SetStylingEx=2073(int length, string styles) + +# Set a style to be visible or not. +set void StyleSetVisible=2074(int style, bool visible) + +# Get the time in milliseconds that the caret is on and off. +get int GetCaretPeriod=2075(,) + +# Get the time in milliseconds that the caret is on and off. 0 = steady on. +set void SetCaretPeriod=2076(int periodMilliseconds,) + +# Set the set of characters making up words for when moving or selecting by word. +# First sets deaults like SetCharsDefault. +set void SetWordChars=2077(, string characters) + +# Start a sequence of actions that is undone and redone as a unit. +# May be nested. +fun void BeginUndoAction=2078(,) + +# End a sequence of actions that is undone and redone as a unit. +fun void EndUndoAction=2079(,) + +# Indicator style enumeration and some constants +enu IndicatorStyle=INDIC_ +val INDIC_PLAIN=0 +val INDIC_SQUIGGLE=1 +val INDIC_TT=2 +val INDIC_DIAGONAL=3 +val INDIC_STRIKE=4 +val INDIC_HIDDEN=5 +val INDIC_BOX=6 +val INDIC_ROUNDBOX=7 +val INDIC_MAX=31 +val INDIC_CONTAINER=8 +val INDIC0_MASK=0x20 +val INDIC1_MASK=0x40 +val INDIC2_MASK=0x80 +val INDICS_MASK=0xE0 + +# Set an indicator to plain, squiggle or TT. +set void IndicSetStyle=2080(int indic, int style) + +# Retrieve the style of an indicator. +get int IndicGetStyle=2081(int indic,) + +# Set the foreground colour of an indicator. +set void IndicSetFore=2082(int indic, colour fore) + +# Retrieve the foreground colour of an indicator. +get colour IndicGetFore=2083(int indic,) + +# Set an indicator to draw under text or over(default). +set void IndicSetUnder=2510(int indic, bool under) + +# Retrieve whether indicator drawn under or over text. +get bool IndicGetUnder=2511(int indic,) + +# Set the foreground colour of all whitespace and whether to use this setting. +fun void SetWhitespaceFore=2084(bool useSetting, colour fore) + +# Set the background colour of all whitespace and whether to use this setting. +fun void SetWhitespaceBack=2085(bool useSetting, colour back) + +# Divide each styling byte into lexical class bits (default: 5) and indicator +# bits (default: 3). If a lexer requires more than 32 lexical states, then this +# is used to expand the possible states. +set void SetStyleBits=2090(int bits,) + +# Retrieve number of bits in style bytes used to hold the lexical state. +get int GetStyleBits=2091(,) + +# Used to hold extra styling information for each line. +set void SetLineState=2092(int line, int state) + +# Retrieve the extra styling information for a line. +get int GetLineState=2093(int line,) + +# Retrieve the last line number that has line state. +get int GetMaxLineState=2094(,) + +# Is the background of the line containing the caret in a different colour? +get bool GetCaretLineVisible=2095(,) + +# Display the background of the line containing the caret in a different colour. +set void SetCaretLineVisible=2096(bool show,) + +# Get the colour of the background of the line containing the caret. +get colour GetCaretLineBack=2097(,) + +# Set the colour of the background of the line containing the caret. +set void SetCaretLineBack=2098(colour back,) + +# Set a style to be changeable or not (read only). +# Experimental feature, currently buggy. +set void StyleSetChangeable=2099(int style, bool changeable) + +# Display a auto-completion list. +# The lenEntered parameter indicates how many characters before +# the caret should be used to provide context. +fun void AutoCShow=2100(int lenEntered, string itemList) + +# Remove the auto-completion list from the screen. +fun void AutoCCancel=2101(,) + +# Is there an auto-completion list visible? +fun bool AutoCActive=2102(,) + +# Retrieve the position of the caret when the auto-completion list was displayed. +fun position AutoCPosStart=2103(,) + +# User has selected an item so remove the list and insert the selection. +fun void AutoCComplete=2104(,) + +# Define a set of character that when typed cancel the auto-completion list. +fun void AutoCStops=2105(, string characterSet) + +# Change the separator character in the string setting up an auto-completion list. +# Default is space but can be changed if items contain space. +set void AutoCSetSeparator=2106(int separatorCharacter,) + +# Retrieve the auto-completion list separator character. +get int AutoCGetSeparator=2107(,) + +# Select the item in the auto-completion list that starts with a string. +fun void AutoCSelect=2108(, string text) + +# Should the auto-completion list be cancelled if the user backspaces to a +# position before where the box was created. +set void AutoCSetCancelAtStart=2110(bool cancel,) + +# Retrieve whether auto-completion cancelled by backspacing before start. +get bool AutoCGetCancelAtStart=2111(,) + +# Define a set of characters that when typed will cause the autocompletion to +# choose the selected item. +set void AutoCSetFillUps=2112(, string characterSet) + +# Should a single item auto-completion list automatically choose the item. +set void AutoCSetChooseSingle=2113(bool chooseSingle,) + +# Retrieve whether a single item auto-completion list automatically choose the item. +get bool AutoCGetChooseSingle=2114(,) + +# Set whether case is significant when performing auto-completion searches. +set void AutoCSetIgnoreCase=2115(bool ignoreCase,) + +# Retrieve state of ignore case flag. +get bool AutoCGetIgnoreCase=2116(,) + +# Display a list of strings and send notification when user chooses one. +fun void UserListShow=2117(int listType, string itemList) + +# Set whether or not autocompletion is hidden automatically when nothing matches. +set void AutoCSetAutoHide=2118(bool autoHide,) + +# Retrieve whether or not autocompletion is hidden automatically when nothing matches. +get bool AutoCGetAutoHide=2119(,) + +# Set whether or not autocompletion deletes any word characters +# after the inserted text upon completion. +set void AutoCSetDropRestOfWord=2270(bool dropRestOfWord,) + +# Retrieve whether or not autocompletion deletes any word characters +# after the inserted text upon completion. +get bool AutoCGetDropRestOfWord=2271(,) + +# Register an XPM image for use in autocompletion lists. +fun void RegisterImage=2405(int type, string xpmData) + +# Clear all the registered XPM images. +fun void ClearRegisteredImages=2408(,) + +# Retrieve the auto-completion list type-separator character. +get int AutoCGetTypeSeparator=2285(,) + +# Change the type-separator character in the string setting up an auto-completion list. +# Default is '?' but can be changed if items contain '?'. +set void AutoCSetTypeSeparator=2286(int separatorCharacter,) + +# Set the maximum width, in characters, of auto-completion and user lists. +# Set to 0 to autosize to fit longest item, which is the default. +set void AutoCSetMaxWidth=2208(int characterCount,) + +# Get the maximum width, in characters, of auto-completion and user lists. +get int AutoCGetMaxWidth=2209(,) + +# Set the maximum height, in rows, of auto-completion and user lists. +# The default is 5 rows. +set void AutoCSetMaxHeight=2210(int rowCount,) + +# Set the maximum height, in rows, of auto-completion and user lists. +get int AutoCGetMaxHeight=2211(,) + +# Set the number of spaces used for one level of indentation. +set void SetIndent=2122(int indentSize,) + +# Retrieve indentation size. +get int GetIndent=2123(,) + +# Indentation will only use space characters if useTabs is false, otherwise +# it will use a combination of tabs and spaces. +set void SetUseTabs=2124(bool useTabs,) + +# Retrieve whether tabs will be used in indentation. +get bool GetUseTabs=2125(,) + +# Change the indentation of a line to a number of columns. +set void SetLineIndentation=2126(int line, int indentSize) + +# Retrieve the number of columns that a line is indented. +get int GetLineIndentation=2127(int line,) + +# Retrieve the position before the first non indentation character on a line. +get position GetLineIndentPosition=2128(int line,) + +# Retrieve the column number of a position, taking tab width into account. +get int GetColumn=2129(position pos,) + +# Show or hide the horizontal scroll bar. +set void SetHScrollBar=2130(bool show,) + +# Is the horizontal scroll bar visible? +get bool GetHScrollBar=2131(,) + +enu IndentView=SC_IV_ +val SC_IV_NONE=0 +val SC_IV_REAL=1 +val SC_IV_LOOKFORWARD=2 +val SC_IV_LOOKBOTH=3 + +# Show or hide indentation guides. +set void SetIndentationGuides=2132(int indentView,) + +# Are the indentation guides visible? +get int GetIndentationGuides=2133(,) + +# Set the highlighted indentation guide column. +# 0 = no highlighted guide. +set void SetHighlightGuide=2134(int column,) + +# Get the highlighted indentation guide column. +get int GetHighlightGuide=2135(,) + +# Get the position after the last visible characters on a line. +get int GetLineEndPosition=2136(int line,) + +# Get the code page used to interpret the bytes of the document as characters. +get int GetCodePage=2137(,) + +# Get the foreground colour of the caret. +get colour GetCaretFore=2138(,) + +# In palette mode? +get bool GetUsePalette=2139(,) + +# In read-only mode? +get bool GetReadOnly=2140(,) + +# Sets the position of the caret. +set void SetCurrentPos=2141(position pos,) + +# Sets the position that starts the selection - this becomes the anchor. +set void SetSelectionStart=2142(position pos,) + +# Returns the position at the start of the selection. +get position GetSelectionStart=2143(,) + +# Sets the position that ends the selection - this becomes the currentPosition. +set void SetSelectionEnd=2144(position pos,) + +# Returns the position at the end of the selection. +get position GetSelectionEnd=2145(,) + +# Sets the print magnification added to the point size of each style for printing. +set void SetPrintMagnification=2146(int magnification,) + +# Returns the print magnification. +get int GetPrintMagnification=2147(,) + +enu PrintOption=SC_PRINT_ +# PrintColourMode - use same colours as screen. +val SC_PRINT_NORMAL=0 +# PrintColourMode - invert the light value of each style for printing. +val SC_PRINT_INVERTLIGHT=1 +# PrintColourMode - force black text on white background for printing. +val SC_PRINT_BLACKONWHITE=2 +# PrintColourMode - text stays coloured, but all background is forced to be white for printing. +val SC_PRINT_COLOURONWHITE=3 +# PrintColourMode - only the default-background is forced to be white for printing. +val SC_PRINT_COLOURONWHITEDEFAULTBG=4 + +# Modify colours when printing for clearer printed text. +set void SetPrintColourMode=2148(int mode,) + +# Returns the print colour mode. +get int GetPrintColourMode=2149(,) + +enu FindOption=SCFIND_ +val SCFIND_WHOLEWORD=2 +val SCFIND_MATCHCASE=4 +val SCFIND_WORDSTART=0x00100000 +val SCFIND_REGEXP=0x00200000 +val SCFIND_POSIX=0x00400000 + +# Find some text in the document. +fun position FindText=2150(int flags, findtext ft) + +# On Windows, will draw the document into a display context such as a printer. +fun position FormatRange=2151(bool draw, formatrange fr) + +# Retrieve the display line at the top of the display. +get int GetFirstVisibleLine=2152(,) + +# Retrieve the contents of a line. +# Returns the length of the line. +fun int GetLine=2153(int line, stringresult text) + +# Returns the number of lines in the document. There is always at least one. +get int GetLineCount=2154(,) + +# Sets the size in pixels of the left margin. +set void SetMarginLeft=2155(, int pixelWidth) + +# Returns the size in pixels of the left margin. +get int GetMarginLeft=2156(,) + +# Sets the size in pixels of the right margin. +set void SetMarginRight=2157(, int pixelWidth) + +# Returns the size in pixels of the right margin. +get int GetMarginRight=2158(,) + +# Is the document different from when it was last saved? +get bool GetModify=2159(,) + +# Select a range of text. +fun void SetSel=2160(position start, position end) + +# Retrieve the selected text. +# Return the length of the text. +fun int GetSelText=2161(, stringresult text) + +# Retrieve a range of text. +# Return the length of the text. +fun int GetTextRange=2162(, textrange tr) + +# Draw the selection in normal style or with selection highlighted. +fun void HideSelection=2163(bool normal,) + +# Retrieve the x value of the point in the window where a position is displayed. +fun int PointXFromPosition=2164(, position pos) + +# Retrieve the y value of the point in the window where a position is displayed. +fun int PointYFromPosition=2165(, position pos) + +# Retrieve the line containing a position. +fun int LineFromPosition=2166(position pos,) + +# Retrieve the position at the start of a line. +fun position PositionFromLine=2167(int line,) + +# Scroll horizontally and vertically. +fun void LineScroll=2168(int columns, int lines) + +# Ensure the caret is visible. +fun void ScrollCaret=2169(,) + +# Replace the selected text with the argument text. +fun void ReplaceSel=2170(, string text) + +# Set to read only or read write. +set void SetReadOnly=2171(bool readOnly,) + +# Null operation. +fun void Null=2172(,) + +# Will a paste succeed? +fun bool CanPaste=2173(,) + +# Are there any undoable actions in the undo history? +fun bool CanUndo=2174(,) + +# Delete the undo history. +fun void EmptyUndoBuffer=2175(,) + +# Undo one action in the undo history. +fun void Undo=2176(,) + +# Cut the selection to the clipboard. +fun void Cut=2177(,) + +# Copy the selection to the clipboard. +fun void Copy=2178(,) + +# Paste the contents of the clipboard into the document replacing the selection. +fun void Paste=2179(,) + +# Clear the selection. +fun void Clear=2180(,) + +# Replace the contents of the document with the argument text. +fun void SetText=2181(, string text) + +# Retrieve all the text in the document. +# Returns number of characters retrieved. +fun int GetText=2182(int length, stringresult text) + +# Retrieve the number of characters in the document. +get int GetTextLength=2183(,) + +# Retrieve a pointer to a function that processes messages for this Scintilla. +get int GetDirectFunction=2184(,) + +# Retrieve a pointer value to use as the first argument when calling +# the function returned by GetDirectFunction. +get int GetDirectPointer=2185(,) + +# Set to overtype (true) or insert mode. +set void SetOvertype=2186(bool overtype,) + +# Returns true if overtype mode is active otherwise false is returned. +get bool GetOvertype=2187(,) + +# Set the width of the insert mode caret. +set void SetCaretWidth=2188(int pixelWidth,) + +# Returns the width of the insert mode caret. +get int GetCaretWidth=2189(,) + +# Sets the position that starts the target which is used for updating the +# document without affecting the scroll position. +set void SetTargetStart=2190(position pos,) + +# Get the position that starts the target. +get position GetTargetStart=2191(,) + +# Sets the position that ends the target which is used for updating the +# document without affecting the scroll position. +set void SetTargetEnd=2192(position pos,) + +# Get the position that ends the target. +get position GetTargetEnd=2193(,) + +# Replace the target text with the argument text. +# Text is counted so it can contain NULs. +# Returns the length of the replacement text. +fun int ReplaceTarget=2194(int length, string text) + +# Replace the target text with the argument text after \d processing. +# Text is counted so it can contain NULs. +# Looks for \d where d is between 1 and 9 and replaces these with the strings +# matched in the last search operation which were surrounded by \( and \). +# Returns the length of the replacement text including any change +# caused by processing the \d patterns. +fun int ReplaceTargetRE=2195(int length, string text) + +# Search for a counted string in the target and set the target to the found +# range. Text is counted so it can contain NULs. +# Returns length of range or -1 for failure in which case target is not moved. +fun int SearchInTarget=2197(int length, string text) + +# Set the search flags used by SearchInTarget. +set void SetSearchFlags=2198(int flags,) + +# Get the search flags used by SearchInTarget. +get int GetSearchFlags=2199(,) + +# Show a call tip containing a definition near position pos. +fun void CallTipShow=2200(position pos, string definition) + +# Remove the call tip from the screen. +fun void CallTipCancel=2201(,) + +# Is there an active call tip? +fun bool CallTipActive=2202(,) + +# Retrieve the position where the caret was before displaying the call tip. +fun position CallTipPosStart=2203(,) + +# Highlight a segment of the definition. +fun void CallTipSetHlt=2204(int start, int end) + +# Set the background colour for the call tip. +set void CallTipSetBack=2205(colour back,) + +# Set the foreground colour for the call tip. +set void CallTipSetFore=2206(colour fore,) + +# Set the foreground colour for the highlighted part of the call tip. +set void CallTipSetForeHlt=2207(colour fore,) + +# Enable use of STYLE_CALLTIP and set call tip tab size in pixels. +set void CallTipUseStyle=2212(int tabSize,) + +# Find the display line of a document line taking hidden lines into account. +fun int VisibleFromDocLine=2220(int line,) + +# Find the document line of a display line taking hidden lines into account. +fun int DocLineFromVisible=2221(int lineDisplay,) + +# The number of display lines needed to wrap a document line +fun int WrapCount=2235(int line,) + +enu FoldLevel=SC_FOLDLEVEL +val SC_FOLDLEVELBASE=0x400 +val SC_FOLDLEVELWHITEFLAG=0x1000 +val SC_FOLDLEVELHEADERFLAG=0x2000 +val SC_FOLDLEVELBOXHEADERFLAG=0x4000 +val SC_FOLDLEVELBOXFOOTERFLAG=0x8000 +val SC_FOLDLEVELCONTRACTED=0x10000 +val SC_FOLDLEVELUNINDENT=0x20000 +val SC_FOLDLEVELNUMBERMASK=0x0FFF + +# Set the fold level of a line. +# This encodes an integer level along with flags indicating whether the +# line is a header and whether it is effectively white space. +set void SetFoldLevel=2222(int line, int level) + +# Retrieve the fold level of a line. +get int GetFoldLevel=2223(int line,) + +# Find the last child line of a header line. +get int GetLastChild=2224(int line, int level) + +# Find the parent line of a child line. +get int GetFoldParent=2225(int line,) + +# Make a range of lines visible. +fun void ShowLines=2226(int lineStart, int lineEnd) + +# Make a range of lines invisible. +fun void HideLines=2227(int lineStart, int lineEnd) + +# Is a line visible? +get bool GetLineVisible=2228(int line,) + +# Show the children of a header line. +set void SetFoldExpanded=2229(int line, bool expanded) + +# Is a header line expanded? +get bool GetFoldExpanded=2230(int line,) + +# Switch a header line between expanded and contracted. +fun void ToggleFold=2231(int line,) + +# Ensure a particular line is visible by expanding any header line hiding it. +fun void EnsureVisible=2232(int line,) + +enu FoldFlag=SC_FOLDFLAG_ +val SC_FOLDFLAG_LINEBEFORE_EXPANDED=0x0002 +val SC_FOLDFLAG_LINEBEFORE_CONTRACTED=0x0004 +val SC_FOLDFLAG_LINEAFTER_EXPANDED=0x0008 +val SC_FOLDFLAG_LINEAFTER_CONTRACTED=0x0010 +val SC_FOLDFLAG_LEVELNUMBERS=0x0040 +val SC_FOLDFLAG_BOX=0x0001 + +# Set some style options for folding. +fun void SetFoldFlags=2233(int flags,) + +# Ensure a particular line is visible by expanding any header line hiding it. +# Use the currently set visibility policy to determine which range to display. +fun void EnsureVisibleEnforcePolicy=2234(int line,) + +# Sets whether a tab pressed when caret is within indentation indents. +set void SetTabIndents=2260(bool tabIndents,) + +# Does a tab pressed when caret is within indentation indent? +get bool GetTabIndents=2261(,) + +# Sets whether a backspace pressed when caret is within indentation unindents. +set void SetBackSpaceUnIndents=2262(bool bsUnIndents,) + +# Does a backspace pressed when caret is within indentation unindent? +get bool GetBackSpaceUnIndents=2263(,) + +val SC_TIME_FOREVER=10000000 + +# Sets the time the mouse must sit still to generate a mouse dwell event. +set void SetMouseDwellTime=2264(int periodMilliseconds,) + +# Retrieve the time the mouse must sit still to generate a mouse dwell event. +get int GetMouseDwellTime=2265(,) + +# Get position of start of word. +fun int WordStartPosition=2266(position pos, bool onlyWordCharacters) + +# Get position of end of word. +fun int WordEndPosition=2267(position pos, bool onlyWordCharacters) + +enu Wrap=SC_WRAP_ +val SC_WRAP_NONE=0 +val SC_WRAP_WORD=1 +val SC_WRAP_CHAR=2 + +# Sets whether text is word wrapped. +set void SetWrapMode=2268(int mode,) + +# Retrieve whether text is word wrapped. +get int GetWrapMode=2269(,) + +enu WrapVisualFlag=SC_WRAPVISUALFLAG_ +val SC_WRAPVISUALFLAG_NONE=0x0000 +val SC_WRAPVISUALFLAG_END=0x0001 +val SC_WRAPVISUALFLAG_START=0x0002 + +# Set the display mode of visual flags for wrapped lines. +set void SetWrapVisualFlags=2460(int wrapVisualFlags,) + +# Retrive the display mode of visual flags for wrapped lines. +get int GetWrapVisualFlags=2461(,) + +enu WrapVisualLocation=SC_WRAPVISUALFLAGLOC_ +val SC_WRAPVISUALFLAGLOC_DEFAULT=0x0000 +val SC_WRAPVISUALFLAGLOC_END_BY_TEXT=0x0001 +val SC_WRAPVISUALFLAGLOC_START_BY_TEXT=0x0002 + +# Set the location of visual flags for wrapped lines. +set void SetWrapVisualFlagsLocation=2462(int wrapVisualFlagsLocation,) + +# Retrive the location of visual flags for wrapped lines. +get int GetWrapVisualFlagsLocation=2463(,) + +# Set the start indent for wrapped lines. +set void SetWrapStartIndent=2464(int indent,) + +# Retrive the start indent for wrapped lines. +get int GetWrapStartIndent=2465(,) + +enu LineCache=SC_CACHE_ +val SC_CACHE_NONE=0 +val SC_CACHE_CARET=1 +val SC_CACHE_PAGE=2 +val SC_CACHE_DOCUMENT=3 + +# Sets the degree of caching of layout information. +set void SetLayoutCache=2272(int mode,) + +# Retrieve the degree of caching of layout information. +get int GetLayoutCache=2273(,) + +# Sets the document width assumed for scrolling. +set void SetScrollWidth=2274(int pixelWidth,) + +# Retrieve the document width assumed for scrolling. +get int GetScrollWidth=2275(,) + +# Sets whether the maximum width line displayed is used to set scroll width. +set void SetScrollWidthTracking=2516(bool tracking,) + +# Retrieve whether the scroll width tracks wide lines. +get bool GetScrollWidthTracking=2517(,) + +# Measure the pixel width of some text in a particular style. +# NUL terminated text argument. +# Does not handle tab or control characters. +fun int TextWidth=2276(int style, string text) + +# Sets the scroll range so that maximum scroll position has +# the last line at the bottom of the view (default). +# Setting this to false allows scrolling one page below the last line. +set void SetEndAtLastLine=2277(bool endAtLastLine,) + +# Retrieve whether the maximum scroll position has the last +# line at the bottom of the view. +get bool GetEndAtLastLine=2278(,) + +# Retrieve the height of a particular line of text in pixels. +fun int TextHeight=2279(int line,) + +# Show or hide the vertical scroll bar. +set void SetVScrollBar=2280(bool show,) + +# Is the vertical scroll bar visible? +get bool GetVScrollBar=2281(,) + +# Append a string to the end of the document without changing the selection. +fun void AppendText=2282(int length, string text) + +# Is drawing done in two phases with backgrounds drawn before faoregrounds? +get bool GetTwoPhaseDraw=2283(,) + +# In twoPhaseDraw mode, drawing is performed in two phases, first the background +# and then the foreground. This avoids chopping off characters that overlap the next run. +set void SetTwoPhaseDraw=2284(bool twoPhase,) + +# Make the target range start and end be the same as the selection range start and end. +fun void TargetFromSelection=2287(,) + +# Join the lines in the target. +fun void LinesJoin=2288(,) + +# Split the lines in the target into lines that are less wide than pixelWidth +# where possible. +fun void LinesSplit=2289(int pixelWidth,) + +# Set the colours used as a chequerboard pattern in the fold margin +fun void SetFoldMarginColour=2290(bool useSetting, colour back) +fun void SetFoldMarginHiColour=2291(bool useSetting, colour fore) + +## New messages go here + +## Start of key messages +# Move caret down one line. +fun void LineDown=2300(,) + +# Move caret down one line extending selection to new caret position. +fun void LineDownExtend=2301(,) + +# Move caret up one line. +fun void LineUp=2302(,) + +# Move caret up one line extending selection to new caret position. +fun void LineUpExtend=2303(,) + +# Move caret left one character. +fun void CharLeft=2304(,) + +# Move caret left one character extending selection to new caret position. +fun void CharLeftExtend=2305(,) + +# Move caret right one character. +fun void CharRight=2306(,) + +# Move caret right one character extending selection to new caret position. +fun void CharRightExtend=2307(,) + +# Move caret left one word. +fun void WordLeft=2308(,) + +# Move caret left one word extending selection to new caret position. +fun void WordLeftExtend=2309(,) + +# Move caret right one word. +fun void WordRight=2310(,) + +# Move caret right one word extending selection to new caret position. +fun void WordRightExtend=2311(,) + +# Move caret to first position on line. +fun void Home=2312(,) + +# Move caret to first position on line extending selection to new caret position. +fun void HomeExtend=2313(,) + +# Move caret to last position on line. +fun void LineEnd=2314(,) + +# Move caret to last position on line extending selection to new caret position. +fun void LineEndExtend=2315(,) + +# Move caret to first position in document. +fun void DocumentStart=2316(,) + +# Move caret to first position in document extending selection to new caret position. +fun void DocumentStartExtend=2317(,) + +# Move caret to last position in document. +fun void DocumentEnd=2318(,) + +# Move caret to last position in document extending selection to new caret position. +fun void DocumentEndExtend=2319(,) + +# Move caret one page up. +fun void PageUp=2320(,) + +# Move caret one page up extending selection to new caret position. +fun void PageUpExtend=2321(,) + +# Move caret one page down. +fun void PageDown=2322(,) + +# Move caret one page down extending selection to new caret position. +fun void PageDownExtend=2323(,) + +# Switch from insert to overtype mode or the reverse. +fun void EditToggleOvertype=2324(,) + +# Cancel any modes such as call tip or auto-completion list display. +fun void Cancel=2325(,) + +# Delete the selection or if no selection, the character before the caret. +fun void DeleteBack=2326(,) + +# If selection is empty or all on one line replace the selection with a tab character. +# If more than one line selected, indent the lines. +fun void Tab=2327(,) + +# Dedent the selected lines. +fun void BackTab=2328(,) + +# Insert a new line, may use a CRLF, CR or LF depending on EOL mode. +fun void NewLine=2329(,) + +# Insert a Form Feed character. +fun void FormFeed=2330(,) + +# Move caret to before first visible character on line. +# If already there move to first character on line. +fun void VCHome=2331(,) + +# Like VCHome but extending selection to new caret position. +fun void VCHomeExtend=2332(,) + +# Magnify the displayed text by increasing the sizes by 1 point. +fun void ZoomIn=2333(,) + +# Make the displayed text smaller by decreasing the sizes by 1 point. +fun void ZoomOut=2334(,) + +# Delete the word to the left of the caret. +fun void DelWordLeft=2335(,) + +# Delete the word to the right of the caret. +fun void DelWordRight=2336(,) + +# Delete the word to the right of the caret, but not the trailing non-word characters. +fun void DelWordRightEnd=2518(,) + +# Cut the line containing the caret. +fun void LineCut=2337(,) + +# Delete the line containing the caret. +fun void LineDelete=2338(,) + +# Switch the current line with the previous. +fun void LineTranspose=2339(,) + +# Duplicate the current line. +fun void LineDuplicate=2404(,) + +# Transform the selection to lower case. +fun void LowerCase=2340(,) + +# Transform the selection to upper case. +fun void UpperCase=2341(,) + +# Scroll the document down, keeping the caret visible. +fun void LineScrollDown=2342(,) + +# Scroll the document up, keeping the caret visible. +fun void LineScrollUp=2343(,) + +# Delete the selection or if no selection, the character before the caret. +# Will not delete the character before at the start of a line. +fun void DeleteBackNotLine=2344(,) + +# Move caret to first position on display line. +fun void HomeDisplay=2345(,) + +# Move caret to first position on display line extending selection to +# new caret position. +fun void HomeDisplayExtend=2346(,) + +# Move caret to last position on display line. +fun void LineEndDisplay=2347(,) + +# Move caret to last position on display line extending selection to new +# caret position. +fun void LineEndDisplayExtend=2348(,) + +# These are like their namesakes Home(Extend)?, LineEnd(Extend)?, VCHome(Extend)? +# except they behave differently when word-wrap is enabled: +# They go first to the start / end of the display line, like (Home|LineEnd)Display +# The difference is that, the cursor is already at the point, it goes on to the start +# or end of the document line, as appropriate for (Home|LineEnd|VCHome)(Extend)?. + +fun void HomeWrap=2349(,) +fun void HomeWrapExtend=2450(,) +fun void LineEndWrap=2451(,) +fun void LineEndWrapExtend=2452(,) +fun void VCHomeWrap=2453(,) +fun void VCHomeWrapExtend=2454(,) + +# Copy the line containing the caret. +fun void LineCopy=2455(,) + +# Move the caret inside current view if it's not there already. +fun void MoveCaretInsideView=2401(,) + +# How many characters are on a line, including end of line characters? +fun int LineLength=2350(int line,) + +# Highlight the characters at two positions. +fun void BraceHighlight=2351(position pos1, position pos2) + +# Highlight the character at a position indicating there is no matching brace. +fun void BraceBadLight=2352(position pos,) + +# Find the position of a matching brace or INVALID_POSITION if no match. +fun position BraceMatch=2353(position pos,) + +# Are the end of line characters visible? +get bool GetViewEOL=2355(,) + +# Make the end of line characters visible or invisible. +set void SetViewEOL=2356(bool visible,) + +# Retrieve a pointer to the document object. +get int GetDocPointer=2357(,) + +# Change the document object used. +set void SetDocPointer=2358(, int pointer) + +# Set which document modification events are sent to the container. +set void SetModEventMask=2359(int mask,) + +enu EdgeVisualStyle=EDGE_ +val EDGE_NONE=0 +val EDGE_LINE=1 +val EDGE_BACKGROUND=2 + +# Retrieve the column number which text should be kept within. +get int GetEdgeColumn=2360(,) + +# Set the column number of the edge. +# If text goes past the edge then it is highlighted. +set void SetEdgeColumn=2361(int column,) + +# Retrieve the edge highlight mode. +get int GetEdgeMode=2362(,) + +# The edge may be displayed by a line (EDGE_LINE) or by highlighting text that +# goes beyond it (EDGE_BACKGROUND) or not displayed at all (EDGE_NONE). +set void SetEdgeMode=2363(int mode,) + +# Retrieve the colour used in edge indication. +get colour GetEdgeColour=2364(,) + +# Change the colour used in edge indication. +set void SetEdgeColour=2365(colour edgeColour,) + +# Sets the current caret position to be the search anchor. +fun void SearchAnchor=2366(,) + +# Find some text starting at the search anchor. +# Does not ensure the selection is visible. +fun int SearchNext=2367(int flags, string text) + +# Find some text starting at the search anchor and moving backwards. +# Does not ensure the selection is visible. +fun int SearchPrev=2368(int flags, string text) + +# Retrieves the number of lines completely visible. +get int LinesOnScreen=2370(,) + +# Set whether a pop up menu is displayed automatically when the user presses +# the wrong mouse button. +fun void UsePopUp=2371(bool allowPopUp,) + +# Is the selection rectangular? The alternative is the more common stream selection. +get bool SelectionIsRectangle=2372(,) + +# Set the zoom level. This number of points is added to the size of all fonts. +# It may be positive to magnify or negative to reduce. +set void SetZoom=2373(int zoom,) +# Retrieve the zoom level. +get int GetZoom=2374(,) + +# Create a new document object. +# Starts with reference count of 1 and not selected into editor. +fun int CreateDocument=2375(,) +# Extend life of document. +fun void AddRefDocument=2376(, int doc) +# Release a reference to the document, deleting document if it fades to black. +fun void ReleaseDocument=2377(, int doc) + +# Get which document modification events are sent to the container. +get int GetModEventMask=2378(,) + +# Change internal focus flag. +set void SetFocus=2380(bool focus,) +# Get internal focus flag. +get bool GetFocus=2381(,) + +# Change error status - 0 = OK. +set void SetStatus=2382(int statusCode,) +# Get error status. +get int GetStatus=2383(,) + +# Set whether the mouse is captured when its button is pressed. +set void SetMouseDownCaptures=2384(bool captures,) +# Get whether mouse gets captured. +get bool GetMouseDownCaptures=2385(,) + +enu CursorShape=SC_CURSOR +val SC_CURSORNORMAL=-1 +val SC_CURSORWAIT=4 +# Sets the cursor to one of the SC_CURSOR* values. +set void SetCursor=2386(int cursorType,) +# Get cursor type. +get int GetCursor=2387(,) + +# Change the way control characters are displayed: +# If symbol is < 32, keep the drawn way, else, use the given character. +set void SetControlCharSymbol=2388(int symbol,) +# Get the way control characters are displayed. +get int GetControlCharSymbol=2389(,) + +# Move to the previous change in capitalisation. +fun void WordPartLeft=2390(,) +# Move to the previous change in capitalisation extending selection +# to new caret position. +fun void WordPartLeftExtend=2391(,) +# Move to the change next in capitalisation. +fun void WordPartRight=2392(,) +# Move to the next change in capitalisation extending selection +# to new caret position. +fun void WordPartRightExtend=2393(,) + +# Constants for use with SetVisiblePolicy, similar to SetCaretPolicy. +val VISIBLE_SLOP=0x01 +val VISIBLE_STRICT=0x04 +# Set the way the display area is determined when a particular line +# is to be moved to by Find, FindNext, GotoLine, etc. +fun void SetVisiblePolicy=2394(int visiblePolicy, int visibleSlop) + +# Delete back from the current position to the start of the line. +fun void DelLineLeft=2395(,) + +# Delete forwards from the current position to the end of the line. +fun void DelLineRight=2396(,) + +# Get and Set the xOffset (ie, horizonal scroll position). +set void SetXOffset=2397(int newOffset,) +get int GetXOffset=2398(,) + +# Set the last x chosen value to be the caret x position. +fun void ChooseCaretX=2399(,) + +# Set the focus to this Scintilla widget. +fun void GrabFocus=2400(,) + +enu CaretPolicy = CARET_ +# Caret policy, used by SetXCaretPolicy and SetYCaretPolicy. +# If CARET_SLOP is set, we can define a slop value: caretSlop. +# This value defines an unwanted zone (UZ) where the caret is... unwanted. +# This zone is defined as a number of pixels near the vertical margins, +# and as a number of lines near the horizontal margins. +# By keeping the caret away from the edges, it is seen within its context, +# so it is likely that the identifier that the caret is on can be completely seen, +# and that the current line is seen with some of the lines following it which are +# often dependent on that line. +val CARET_SLOP=0x01 +# If CARET_STRICT is set, the policy is enforced... strictly. +# The caret is centred on the display if slop is not set, +# and cannot go in the UZ if slop is set. +val CARET_STRICT=0x04 +# If CARET_JUMPS is set, the display is moved more energetically +# so the caret can move in the same direction longer before the policy is applied again. +val CARET_JUMPS=0x10 +# If CARET_EVEN is not set, instead of having symmetrical UZs, +# the left and bottom UZs are extended up to right and top UZs respectively. +# This way, we favour the displaying of useful information: the begining of lines, +# where most code reside, and the lines after the caret, eg. the body of a function. +val CARET_EVEN=0x08 + +# Set the way the caret is kept visible when going sideway. +# The exclusion zone is given in pixels. +fun void SetXCaretPolicy=2402(int caretPolicy, int caretSlop) + +# Set the way the line the caret is on is kept visible. +# The exclusion zone is given in lines. +fun void SetYCaretPolicy=2403(int caretPolicy, int caretSlop) + +# Set printing to line wrapped (SC_WRAP_WORD) or not line wrapped (SC_WRAP_NONE). +set void SetPrintWrapMode=2406(int mode,) + +# Is printing line wrapped? +get int GetPrintWrapMode=2407(,) + +# Set a fore colour for active hotspots. +set void SetHotspotActiveFore=2410(bool useSetting, colour fore) + +# Get the fore colour for active hotspots. +get colour GetHotspotActiveFore=2494(,) + +# Set a back colour for active hotspots. +set void SetHotspotActiveBack=2411(bool useSetting, colour back) + +# Get the back colour for active hotspots. +get colour GetHotspotActiveBack=2495(,) + +# Enable / Disable underlining active hotspots. +set void SetHotspotActiveUnderline=2412(bool underline,) + +# Get whether underlining for active hotspots. +get bool GetHotspotActiveUnderline=2496(,) + +# Limit hotspots to single line so hotspots on two lines don't merge. +set void SetHotspotSingleLine=2421(bool singleLine,) + +# Get the HotspotSingleLine property +get bool GetHotspotSingleLine=2497(,) + +# Move caret between paragraphs (delimited by empty lines). +fun void ParaDown=2413(,) +fun void ParaDownExtend=2414(,) +fun void ParaUp=2415(,) +fun void ParaUpExtend=2416(,) + +# Given a valid document position, return the previous position taking code +# page into account. Returns 0 if passed 0. +fun position PositionBefore=2417(position pos,) + +# Given a valid document position, return the next position taking code +# page into account. Maximum value returned is the last position in the document. +fun position PositionAfter=2418(position pos,) + +# Copy a range of text to the clipboard. Positions are clipped into the document. +fun void CopyRange=2419(position start, position end) + +# Copy argument text to the clipboard. +fun void CopyText=2420(int length, string text) + +enu SelectionMode=SC_SEL_ +val SC_SEL_STREAM=0 +val SC_SEL_RECTANGLE=1 +val SC_SEL_LINES=2 + +# Set the selection mode to stream (SC_SEL_STREAM) or rectangular (SC_SEL_RECTANGLE) or +# by lines (SC_SEL_LINES). +set void SetSelectionMode=2422(int mode,) + +# Get the mode of the current selection. +get int GetSelectionMode=2423(,) + +# Retrieve the position of the start of the selection at the given line (INVALID_POSITION if no selection on this line). +fun position GetLineSelStartPosition=2424(int line,) + +# Retrieve the position of the end of the selection at the given line (INVALID_POSITION if no selection on this line). +fun position GetLineSelEndPosition=2425(int line,) + +## RectExtended rectangular selection moves +# Move caret down one line, extending rectangular selection to new caret position. +fun void LineDownRectExtend=2426(,) + +# Move caret up one line, extending rectangular selection to new caret position. +fun void LineUpRectExtend=2427(,) + +# Move caret left one character, extending rectangular selection to new caret position. +fun void CharLeftRectExtend=2428(,) + +# Move caret right one character, extending rectangular selection to new caret position. +fun void CharRightRectExtend=2429(,) + +# Move caret to first position on line, extending rectangular selection to new caret position. +fun void HomeRectExtend=2430(,) + +# Move caret to before first visible character on line. +# If already there move to first character on line. +# In either case, extend rectangular selection to new caret position. +fun void VCHomeRectExtend=2431(,) + +# Move caret to last position on line, extending rectangular selection to new caret position. +fun void LineEndRectExtend=2432(,) + +# Move caret one page up, extending rectangular selection to new caret position. +fun void PageUpRectExtend=2433(,) + +# Move caret one page down, extending rectangular selection to new caret position. +fun void PageDownRectExtend=2434(,) + + +# Move caret to top of page, or one page up if already at top of page. +fun void StutteredPageUp=2435(,) + +# Move caret to top of page, or one page up if already at top of page, extending selection to new caret position. +fun void StutteredPageUpExtend=2436(,) + +# Move caret to bottom of page, or one page down if already at bottom of page. +fun void StutteredPageDown=2437(,) + +# Move caret to bottom of page, or one page down if already at bottom of page, extending selection to new caret position. +fun void StutteredPageDownExtend=2438(,) + + +# Move caret left one word, position cursor at end of word. +fun void WordLeftEnd=2439(,) + +# Move caret left one word, position cursor at end of word, extending selection to new caret position. +fun void WordLeftEndExtend=2440(,) + +# Move caret right one word, position cursor at end of word. +fun void WordRightEnd=2441(,) + +# Move caret right one word, position cursor at end of word, extending selection to new caret position. +fun void WordRightEndExtend=2442(,) + +# Set the set of characters making up whitespace for when moving or selecting by word. +# Should be called after SetWordChars. +set void SetWhitespaceChars=2443(, string characters) + +# Reset the set of characters for whitespace and word characters to the defaults. +fun void SetCharsDefault=2444(,) + +# Get currently selected item position in the auto-completion list +fun int AutoCGetCurrent=2445(,) + +# Enlarge the document to a particular size of text bytes. +fun void Allocate=2446(int bytes,) + +# Returns the target converted to UTF8. +# Return the length in bytes. +fun int TargetAsUTF8=2447(, stringresult s) + +# Set the length of the utf8 argument for calling EncodedFromUTF8. +# Set to -1 and the string will be measured to the first nul. +fun void SetLengthForEncode=2448(int bytes,) + +# Translates a UTF8 string into the document encoding. +# Return the length of the result in bytes. +# On error return 0. +fun int EncodedFromUTF8=2449(string utf8, stringresult encoded) + +# Find the position of a column on a line taking into account tabs and +# multi-byte characters. If beyond end of line, return line end position. +fun int FindColumn=2456(int line, int column) + +# Can the caret preferred x position only be changed by explicit movement commands? +get bool GetCaretSticky=2457(,) + +# Stop the caret preferred x position changing when the user types. +set void SetCaretSticky=2458(bool useCaretStickyBehaviour,) + +# Switch between sticky and non-sticky: meant to be bound to a key. +fun void ToggleCaretSticky=2459(,) + +# Enable/Disable convert-on-paste for line endings +set void SetPasteConvertEndings=2467(bool convert,) + +# Get convert-on-paste setting +get bool GetPasteConvertEndings=2468(,) + +# Duplicate the selection. If selection empty duplicate the line containing the caret. +fun void SelectionDuplicate=2469(,) + +val SC_ALPHA_TRANSPARENT=0 +val SC_ALPHA_OPAQUE=255 +val SC_ALPHA_NOALPHA=256 + +# Set background alpha of the caret line. +set void SetCaretLineBackAlpha=2470(int alpha,) + +# Get the background alpha of the caret line. +get int GetCaretLineBackAlpha=2471(,) + +enu CaretStyle=CARETSTYLE_ +val CARETSTYLE_INVISIBLE=0 +val CARETSTYLE_LINE=1 +val CARETSTYLE_BLOCK=2 + +# Set the style of the caret to be drawn. +set void SetCaretStyle=2512(int caretStyle,) + +# Returns the current style of the caret. +get int GetCaretStyle=2513(,) + +# Set the indicator used for IndicatorFillRange and IndicatorClearRange +set void SetIndicatorCurrent=2500(int indicator,) + +# Get the current indicator +get int GetIndicatorCurrent=2501(,) + +# Set the value used for IndicatorFillRange +set void SetIndicatorValue=2502(int value,) + +# Get the current indicator vaue +get int GetIndicatorValue=2503(,) + +# Turn a indicator on over a range. +fun void IndicatorFillRange=2504(int position, int fillLength) + +# Turn a indicator off over a range. +fun void IndicatorClearRange=2505(int position, int clearLength) + +# Are any indicators present at position? +fun int IndicatorAllOnFor=2506(int position,) + +# What value does a particular indicator have at at a position? +fun int IndicatorValueAt=2507(int indicator, int position) + +# Where does a particular indicator start? +fun int IndicatorStart=2508(int indicator, int position) + +# Where does a particular indicator end? +fun int IndicatorEnd=2509(int indicator, int position) + +# Set number of entries in position cache +set void SetPositionCache=2514(int size,) + +# How many entries are allocated to the position cache? +get int GetPositionCache=2515(,) + +# Copy the selection, if selection empty copy the line with the caret +fun void CopyAllowLine=2519(,) + +# Start notifying the container of all key presses and commands. +fun void StartRecord=3001(,) + +# Stop notifying the container of all key presses and commands. +fun void StopRecord=3002(,) + +# Set the lexing language of the document. +set void SetLexer=4001(int lexer,) + +# Retrieve the lexing language of the document. +get int GetLexer=4002(,) + +# Colourise a segment of the document using the current lexing language. +fun void Colourise=4003(position start, position end) + +# Set up a value that may be used by a lexer for some optional feature. +set void SetProperty=4004(string key, string value) + +# Maximum value of keywordSet parameter of SetKeyWords. +val KEYWORDSET_MAX=8 + +# Set up the key words used by the lexer. +set void SetKeyWords=4005(int keywordSet, string keyWords) + +# Set the lexing language of the document based on string name. +set void SetLexerLanguage=4006(, string language) + +# Load a lexer library (dll / so). +fun void LoadLexerLibrary=4007(, string path) + +# Retrieve a "property" value previously set with SetProperty. +fun int GetProperty=4008(string key, stringresult buf) + +# Retrieve a "property" value previously set with SetProperty, +# with "$()" variable replacement on returned buffer. +fun int GetPropertyExpanded=4009(string key, stringresult buf) + +# Retrieve a "property" value previously set with SetProperty, +# interpreted as an int AFTER any "$()" variable replacement. +get int GetPropertyInt=4010(string key,) + +# Retrieve the number of bits the current lexer needs for styling. +get int GetStyleBitsNeeded=4011(,) + +# Notifications +# Type of modification and the action which caused the modification. +# These are defined as a bit mask to make it easy to specify which notifications are wanted. +# One bit is set from each of SC_MOD_* and SC_PERFORMED_*. +enu ModificationFlags=SC_MOD_ SC_PERFORMED_ SC_LAST +val SC_MOD_INSERTTEXT=0x1 +val SC_MOD_DELETETEXT=0x2 +val SC_MOD_CHANGESTYLE=0x4 +val SC_MOD_CHANGEFOLD=0x8 +val SC_PERFORMED_USER=0x10 +val SC_PERFORMED_UNDO=0x20 +val SC_PERFORMED_REDO=0x40 +val SC_MULTISTEPUNDOREDO=0x80 +val SC_LASTSTEPINUNDOREDO=0x100 +val SC_MOD_CHANGEMARKER=0x200 +val SC_MOD_BEFOREINSERT=0x400 +val SC_MOD_BEFOREDELETE=0x800 +val SC_MULTILINEUNDOREDO=0x1000 +val SC_STARTACTION=0x2000 +val SC_MOD_CHANGEINDICATOR=0x4000 +val SC_MOD_CHANGELINESTATE=0x8000 +val SC_MODEVENTMASKALL=0xFFFF + +# For compatibility, these go through the COMMAND notification rather than NOTIFY +# and should have had exactly the same values as the EN_* constants. +# Unfortunately the SETFOCUS and KILLFOCUS are flipped over from EN_* +# As clients depend on these constants, this will not be changed. +val SCEN_CHANGE=768 +val SCEN_SETFOCUS=512 +val SCEN_KILLFOCUS=256 + +# Symbolic key codes and modifier flags. +# ASCII and other printable characters below 256. +# Extended keys above 300. + +enu Keys=SCK_ +val SCK_DOWN=300 +val SCK_UP=301 +val SCK_LEFT=302 +val SCK_RIGHT=303 +val SCK_HOME=304 +val SCK_END=305 +val SCK_PRIOR=306 +val SCK_NEXT=307 +val SCK_DELETE=308 +val SCK_INSERT=309 +val SCK_ESCAPE=7 +val SCK_BACK=8 +val SCK_TAB=9 +val SCK_RETURN=13 +val SCK_ADD=310 +val SCK_SUBTRACT=311 +val SCK_DIVIDE=312 +val SCK_WIN=313 +val SCK_RWIN=314 +val SCK_MENU=315 + +enu KeyMod=SCMOD_ +val SCMOD_NORM=0 +val SCMOD_SHIFT=1 +val SCMOD_CTRL=2 +val SCMOD_ALT=4 + +################################################ +# For SciLexer.h +enu Lexer=SCLEX_ +val SCLEX_CONTAINER=0 +val SCLEX_NULL=1 +val SCLEX_PYTHON=2 +val SCLEX_CPP=3 +val SCLEX_HTML=4 +val SCLEX_XML=5 +val SCLEX_PERL=6 +val SCLEX_SQL=7 +val SCLEX_VB=8 +val SCLEX_PROPERTIES=9 +val SCLEX_ERRORLIST=10 +val SCLEX_MAKEFILE=11 +val SCLEX_BATCH=12 +val SCLEX_XCODE=13 +val SCLEX_LATEX=14 +val SCLEX_LUA=15 +val SCLEX_DIFF=16 +val SCLEX_CONF=17 +val SCLEX_PASCAL=18 +val SCLEX_AVE=19 +val SCLEX_ADA=20 +val SCLEX_LISP=21 +val SCLEX_RUBY=22 +val SCLEX_EIFFEL=23 +val SCLEX_EIFFELKW=24 +val SCLEX_TCL=25 +val SCLEX_NNCRONTAB=26 +val SCLEX_BULLANT=27 +val SCLEX_VBSCRIPT=28 +val SCLEX_BAAN=31 +val SCLEX_MATLAB=32 +val SCLEX_SCRIPTOL=33 +val SCLEX_ASM=34 +val SCLEX_CPPNOCASE=35 +val SCLEX_FORTRAN=36 +val SCLEX_F77=37 +val SCLEX_CSS=38 +val SCLEX_POV=39 +val SCLEX_LOUT=40 +val SCLEX_ESCRIPT=41 +val SCLEX_PS=42 +val SCLEX_NSIS=43 +val SCLEX_MMIXAL=44 +val SCLEX_CLW=45 +val SCLEX_CLWNOCASE=46 +val SCLEX_LOT=47 +val SCLEX_YAML=48 +val SCLEX_TEX=49 +val SCLEX_METAPOST=50 +val SCLEX_POWERBASIC=51 +val SCLEX_FORTH=52 +val SCLEX_ERLANG=53 +val SCLEX_OCTAVE=54 +val SCLEX_MSSQL=55 +val SCLEX_VERILOG=56 +val SCLEX_KIX=57 +val SCLEX_GUI4CLI=58 +val SCLEX_SPECMAN=59 +val SCLEX_AU3=60 +val SCLEX_APDL=61 +val SCLEX_BASH=62 +val SCLEX_ASN1=63 +val SCLEX_VHDL=64 +val SCLEX_CAML=65 +val SCLEX_BLITZBASIC=66 +val SCLEX_PUREBASIC=67 +val SCLEX_HASKELL=68 +val SCLEX_PHPSCRIPT=69 +val SCLEX_TADS3=70 +val SCLEX_REBOL=71 +val SCLEX_SMALLTALK=72 +val SCLEX_FLAGSHIP=73 +val SCLEX_CSOUND=74 +val SCLEX_FREEBASIC=75 +val SCLEX_INNOSETUP=76 +val SCLEX_OPAL=77 +val SCLEX_SPICE=78 +val SCLEX_D=79 +val SCLEX_CMAKE=80 +val SCLEX_GAP=81 +val SCLEX_PLM=82 +val SCLEX_PROGRESS=83 +val SCLEX_ABAQUS=84 +val SCLEX_ASYMPTOTE=85 +val SCLEX_R=86 +val SCLEX_MAGIK=87 +val SCLEX_POWERSHELL=88 + +# When a lexer specifies its language as SCLEX_AUTOMATIC it receives a +# value assigned in sequence from SCLEX_AUTOMATIC+1. +val SCLEX_AUTOMATIC=1000 +# Lexical states for SCLEX_PYTHON +lex Python=SCLEX_PYTHON SCE_P_ +val SCE_P_DEFAULT=0 +val SCE_P_COMMENTLINE=1 +val SCE_P_NUMBER=2 +val SCE_P_STRING=3 +val SCE_P_CHARACTER=4 +val SCE_P_WORD=5 +val SCE_P_TRIPLE=6 +val SCE_P_TRIPLEDOUBLE=7 +val SCE_P_CLASSNAME=8 +val SCE_P_DEFNAME=9 +val SCE_P_OPERATOR=10 +val SCE_P_IDENTIFIER=11 +val SCE_P_COMMENTBLOCK=12 +val SCE_P_STRINGEOL=13 +val SCE_P_WORD2=14 +val SCE_P_DECORATOR=15 +# Lexical states for SCLEX_CPP +lex Cpp=SCLEX_CPP SCE_C_ +lex Pascal=SCLEX_PASCAL SCE_C_ +lex BullAnt=SCLEX_BULLANT SCE_C_ +val SCE_C_DEFAULT=0 +val SCE_C_COMMENT=1 +val SCE_C_COMMENTLINE=2 +val SCE_C_COMMENTDOC=3 +val SCE_C_NUMBER=4 +val SCE_C_WORD=5 +val SCE_C_STRING=6 +val SCE_C_CHARACTER=7 +val SCE_C_UUID=8 +val SCE_C_PREPROCESSOR=9 +val SCE_C_OPERATOR=10 +val SCE_C_IDENTIFIER=11 +val SCE_C_STRINGEOL=12 +val SCE_C_VERBATIM=13 +val SCE_C_REGEX=14 +val SCE_C_COMMENTLINEDOC=15 +val SCE_C_WORD2=16 +val SCE_C_COMMENTDOCKEYWORD=17 +val SCE_C_COMMENTDOCKEYWORDERROR=18 +val SCE_C_GLOBALCLASS=19 +# Lexical states for SCLEX_D +lex D=SCLEX_D SCE_D_ +val SCE_D_DEFAULT=0 +val SCE_D_COMMENT=1 +val SCE_D_COMMENTLINE=2 +val SCE_D_COMMENTDOC=3 +val SCE_D_COMMENTNESTED=4 +val SCE_D_NUMBER=5 +val SCE_D_WORD=6 +val SCE_D_WORD2=7 +val SCE_D_WORD3=8 +val SCE_D_TYPEDEF=9 +val SCE_D_STRING=10 +val SCE_D_STRINGEOL=11 +val SCE_D_CHARACTER=12 +val SCE_D_OPERATOR=13 +val SCE_D_IDENTIFIER=14 +val SCE_D_COMMENTLINEDOC=15 +val SCE_D_COMMENTDOCKEYWORD=16 +val SCE_D_COMMENTDOCKEYWORDERROR=17 +# Lexical states for SCLEX_TCL +lex TCL=SCLEX_TCL SCE_TCL_ +val SCE_TCL_DEFAULT=0 +val SCE_TCL_COMMENT=1 +val SCE_TCL_COMMENTLINE=2 +val SCE_TCL_NUMBER=3 +val SCE_TCL_WORD_IN_QUOTE=4 +val SCE_TCL_IN_QUOTE=5 +val SCE_TCL_OPERATOR=6 +val SCE_TCL_IDENTIFIER=7 +val SCE_TCL_SUBSTITUTION=8 +val SCE_TCL_SUB_BRACE=9 +val SCE_TCL_MODIFIER=10 +val SCE_TCL_EXPAND=11 +val SCE_TCL_WORD=12 +val SCE_TCL_WORD2=13 +val SCE_TCL_WORD3=14 +val SCE_TCL_WORD4=15 +val SCE_TCL_WORD5=16 +val SCE_TCL_WORD6=17 +val SCE_TCL_WORD7=18 +val SCE_TCL_WORD8=19 +val SCE_TCL_COMMENT_BOX=20 +val SCE_TCL_BLOCK_COMMENT=21 +# Lexical states for SCLEX_HTML, SCLEX_XML +lex HTML=SCLEX_HTML SCE_H +lex XML=SCLEX_XML SCE_H +lex ASP=SCLEX_ASP SCE_H +lex PHP=SCLEX_PHP SCE_H +val SCE_H_DEFAULT=0 +val SCE_H_TAG=1 +val SCE_H_TAGUNKNOWN=2 +val SCE_H_ATTRIBUTE=3 +val SCE_H_ATTRIBUTEUNKNOWN=4 +val SCE_H_NUMBER=5 +val SCE_H_DOUBLESTRING=6 +val SCE_H_SINGLESTRING=7 +val SCE_H_OTHER=8 +val SCE_H_COMMENT=9 +val SCE_H_ENTITY=10 +# XML and ASP +val SCE_H_TAGEND=11 +val SCE_H_XMLSTART=12 +val SCE_H_XMLEND=13 +val SCE_H_SCRIPT=14 +val SCE_H_ASP=15 +val SCE_H_ASPAT=16 +val SCE_H_CDATA=17 +val SCE_H_QUESTION=18 +# More HTML +val SCE_H_VALUE=19 +# X-Code +val SCE_H_XCCOMMENT=20 +# SGML +val SCE_H_SGML_DEFAULT=21 +val SCE_H_SGML_COMMAND=22 +val SCE_H_SGML_1ST_PARAM=23 +val SCE_H_SGML_DOUBLESTRING=24 +val SCE_H_SGML_SIMPLESTRING=25 +val SCE_H_SGML_ERROR=26 +val SCE_H_SGML_SPECIAL=27 +val SCE_H_SGML_ENTITY=28 +val SCE_H_SGML_COMMENT=29 +val SCE_H_SGML_1ST_PARAM_COMMENT=30 +val SCE_H_SGML_BLOCK_DEFAULT=31 +# Embedded Javascript +val SCE_HJ_START=40 +val SCE_HJ_DEFAULT=41 +val SCE_HJ_COMMENT=42 +val SCE_HJ_COMMENTLINE=43 +val SCE_HJ_COMMENTDOC=44 +val SCE_HJ_NUMBER=45 +val SCE_HJ_WORD=46 +val SCE_HJ_KEYWORD=47 +val SCE_HJ_DOUBLESTRING=48 +val SCE_HJ_SINGLESTRING=49 +val SCE_HJ_SYMBOLS=50 +val SCE_HJ_STRINGEOL=51 +val SCE_HJ_REGEX=52 +# ASP Javascript +val SCE_HJA_START=55 +val SCE_HJA_DEFAULT=56 +val SCE_HJA_COMMENT=57 +val SCE_HJA_COMMENTLINE=58 +val SCE_HJA_COMMENTDOC=59 +val SCE_HJA_NUMBER=60 +val SCE_HJA_WORD=61 +val SCE_HJA_KEYWORD=62 +val SCE_HJA_DOUBLESTRING=63 +val SCE_HJA_SINGLESTRING=64 +val SCE_HJA_SYMBOLS=65 +val SCE_HJA_STRINGEOL=66 +val SCE_HJA_REGEX=67 +# Embedded VBScript +val SCE_HB_START=70 +val SCE_HB_DEFAULT=71 +val SCE_HB_COMMENTLINE=72 +val SCE_HB_NUMBER=73 +val SCE_HB_WORD=74 +val SCE_HB_STRING=75 +val SCE_HB_IDENTIFIER=76 +val SCE_HB_STRINGEOL=77 +# ASP VBScript +val SCE_HBA_START=80 +val SCE_HBA_DEFAULT=81 +val SCE_HBA_COMMENTLINE=82 +val SCE_HBA_NUMBER=83 +val SCE_HBA_WORD=84 +val SCE_HBA_STRING=85 +val SCE_HBA_IDENTIFIER=86 +val SCE_HBA_STRINGEOL=87 +# Embedded Python +val SCE_HP_START=90 +val SCE_HP_DEFAULT=91 +val SCE_HP_COMMENTLINE=92 +val SCE_HP_NUMBER=93 +val SCE_HP_STRING=94 +val SCE_HP_CHARACTER=95 +val SCE_HP_WORD=96 +val SCE_HP_TRIPLE=97 +val SCE_HP_TRIPLEDOUBLE=98 +val SCE_HP_CLASSNAME=99 +val SCE_HP_DEFNAME=100 +val SCE_HP_OPERATOR=101 +val SCE_HP_IDENTIFIER=102 +# PHP +val SCE_HPHP_COMPLEX_VARIABLE=104 +# ASP Python +val SCE_HPA_START=105 +val SCE_HPA_DEFAULT=106 +val SCE_HPA_COMMENTLINE=107 +val SCE_HPA_NUMBER=108 +val SCE_HPA_STRING=109 +val SCE_HPA_CHARACTER=110 +val SCE_HPA_WORD=111 +val SCE_HPA_TRIPLE=112 +val SCE_HPA_TRIPLEDOUBLE=113 +val SCE_HPA_CLASSNAME=114 +val SCE_HPA_DEFNAME=115 +val SCE_HPA_OPERATOR=116 +val SCE_HPA_IDENTIFIER=117 +# PHP +val SCE_HPHP_DEFAULT=118 +val SCE_HPHP_HSTRING=119 +val SCE_HPHP_SIMPLESTRING=120 +val SCE_HPHP_WORD=121 +val SCE_HPHP_NUMBER=122 +val SCE_HPHP_VARIABLE=123 +val SCE_HPHP_COMMENT=124 +val SCE_HPHP_COMMENTLINE=125 +val SCE_HPHP_HSTRING_VARIABLE=126 +val SCE_HPHP_OPERATOR=127 +# Lexical states for SCLEX_PERL +lex Perl=SCLEX_PERL SCE_PL_ +val SCE_PL_DEFAULT=0 +val SCE_PL_ERROR=1 +val SCE_PL_COMMENTLINE=2 +val SCE_PL_POD=3 +val SCE_PL_NUMBER=4 +val SCE_PL_WORD=5 +val SCE_PL_STRING=6 +val SCE_PL_CHARACTER=7 +val SCE_PL_PUNCTUATION=8 +val SCE_PL_PREPROCESSOR=9 +val SCE_PL_OPERATOR=10 +val SCE_PL_IDENTIFIER=11 +val SCE_PL_SCALAR=12 +val SCE_PL_ARRAY=13 +val SCE_PL_HASH=14 +val SCE_PL_SYMBOLTABLE=15 +val SCE_PL_VARIABLE_INDEXER=16 +val SCE_PL_REGEX=17 +val SCE_PL_REGSUBST=18 +val SCE_PL_LONGQUOTE=19 +val SCE_PL_BACKTICKS=20 +val SCE_PL_DATASECTION=21 +val SCE_PL_HERE_DELIM=22 +val SCE_PL_HERE_Q=23 +val SCE_PL_HERE_QQ=24 +val SCE_PL_HERE_QX=25 +val SCE_PL_STRING_Q=26 +val SCE_PL_STRING_QQ=27 +val SCE_PL_STRING_QX=28 +val SCE_PL_STRING_QR=29 +val SCE_PL_STRING_QW=30 +val SCE_PL_POD_VERB=31 +val SCE_PL_SUB_PROTOTYPE=40 +val SCE_PL_FORMAT_IDENT=41 +val SCE_PL_FORMAT=42 +# Lexical states for SCLEX_RUBY +lex Ruby=SCLEX_RUBY SCE_RB_ +val SCE_RB_DEFAULT=0 +val SCE_RB_ERROR=1 +val SCE_RB_COMMENTLINE=2 +val SCE_RB_POD=3 +val SCE_RB_NUMBER=4 +val SCE_RB_WORD=5 +val SCE_RB_STRING=6 +val SCE_RB_CHARACTER=7 +val SCE_RB_CLASSNAME=8 +val SCE_RB_DEFNAME=9 +val SCE_RB_OPERATOR=10 +val SCE_RB_IDENTIFIER=11 +val SCE_RB_REGEX=12 +val SCE_RB_GLOBAL=13 +val SCE_RB_SYMBOL=14 +val SCE_RB_MODULE_NAME=15 +val SCE_RB_INSTANCE_VAR=16 +val SCE_RB_CLASS_VAR=17 +val SCE_RB_BACKTICKS=18 +val SCE_RB_DATASECTION=19 +val SCE_RB_HERE_DELIM=20 +val SCE_RB_HERE_Q=21 +val SCE_RB_HERE_QQ=22 +val SCE_RB_HERE_QX=23 +val SCE_RB_STRING_Q=24 +val SCE_RB_STRING_QQ=25 +val SCE_RB_STRING_QX=26 +val SCE_RB_STRING_QR=27 +val SCE_RB_STRING_QW=28 +val SCE_RB_WORD_DEMOTED=29 +val SCE_RB_STDIN=30 +val SCE_RB_STDOUT=31 +val SCE_RB_STDERR=40 +val SCE_RB_UPPER_BOUND=41 +# Lexical states for SCLEX_VB, SCLEX_VBSCRIPT, SCLEX_POWERBASIC +lex VB=SCLEX_VB SCE_B_ +lex VBScript=SCLEX_VBSCRIPT SCE_B_ +lex PowerBasic=SCLEX_POWERBASIC SCE_B_ +val SCE_B_DEFAULT=0 +val SCE_B_COMMENT=1 +val SCE_B_NUMBER=2 +val SCE_B_KEYWORD=3 +val SCE_B_STRING=4 +val SCE_B_PREPROCESSOR=5 +val SCE_B_OPERATOR=6 +val SCE_B_IDENTIFIER=7 +val SCE_B_DATE=8 +val SCE_B_STRINGEOL=9 +val SCE_B_KEYWORD2=10 +val SCE_B_KEYWORD3=11 +val SCE_B_KEYWORD4=12 +val SCE_B_CONSTANT=13 +val SCE_B_ASM=14 +val SCE_B_LABEL=15 +val SCE_B_ERROR=16 +val SCE_B_HEXNUMBER=17 +val SCE_B_BINNUMBER=18 +# Lexical states for SCLEX_PROPERTIES +lex Properties=SCLEX_PROPERTIES SCE_PROPS_ +val SCE_PROPS_DEFAULT=0 +val SCE_PROPS_COMMENT=1 +val SCE_PROPS_SECTION=2 +val SCE_PROPS_ASSIGNMENT=3 +val SCE_PROPS_DEFVAL=4 +val SCE_PROPS_KEY=5 +# Lexical states for SCLEX_LATEX +lex LaTeX=SCLEX_LATEX SCE_L_ +val SCE_L_DEFAULT=0 +val SCE_L_COMMAND=1 +val SCE_L_TAG=2 +val SCE_L_MATH=3 +val SCE_L_COMMENT=4 +# Lexical states for SCLEX_LUA +lex Lua=SCLEX_LUA SCE_LUA_ +val SCE_LUA_DEFAULT=0 +val SCE_LUA_COMMENT=1 +val SCE_LUA_COMMENTLINE=2 +val SCE_LUA_COMMENTDOC=3 +val SCE_LUA_NUMBER=4 +val SCE_LUA_WORD=5 +val SCE_LUA_STRING=6 +val SCE_LUA_CHARACTER=7 +val SCE_LUA_LITERALSTRING=8 +val SCE_LUA_PREPROCESSOR=9 +val SCE_LUA_OPERATOR=10 +val SCE_LUA_IDENTIFIER=11 +val SCE_LUA_STRINGEOL=12 +val SCE_LUA_WORD2=13 +val SCE_LUA_WORD3=14 +val SCE_LUA_WORD4=15 +val SCE_LUA_WORD5=16 +val SCE_LUA_WORD6=17 +val SCE_LUA_WORD7=18 +val SCE_LUA_WORD8=19 +# Lexical states for SCLEX_ERRORLIST +lex ErrorList=SCLEX_ERRORLIST SCE_ERR_ +val SCE_ERR_DEFAULT=0 +val SCE_ERR_PYTHON=1 +val SCE_ERR_GCC=2 +val SCE_ERR_MS=3 +val SCE_ERR_CMD=4 +val SCE_ERR_BORLAND=5 +val SCE_ERR_PERL=6 +val SCE_ERR_NET=7 +val SCE_ERR_LUA=8 +val SCE_ERR_CTAG=9 +val SCE_ERR_DIFF_CHANGED=10 +val SCE_ERR_DIFF_ADDITION=11 +val SCE_ERR_DIFF_DELETION=12 +val SCE_ERR_DIFF_MESSAGE=13 +val SCE_ERR_PHP=14 +val SCE_ERR_ELF=15 +val SCE_ERR_IFC=16 +val SCE_ERR_IFORT=17 +val SCE_ERR_ABSF=18 +val SCE_ERR_TIDY=19 +val SCE_ERR_JAVA_STACK=20 +val SCE_ERR_VALUE=21 +# Lexical states for SCLEX_BATCH +lex Batch=SCLEX_BATCH SCE_BAT_ +val SCE_BAT_DEFAULT=0 +val SCE_BAT_COMMENT=1 +val SCE_BAT_WORD=2 +val SCE_BAT_LABEL=3 +val SCE_BAT_HIDE=4 +val SCE_BAT_COMMAND=5 +val SCE_BAT_IDENTIFIER=6 +val SCE_BAT_OPERATOR=7 +# Lexical states for SCLEX_MAKEFILE +lex MakeFile=SCLEX_MAKEFILE SCE_MAKE_ +val SCE_MAKE_DEFAULT=0 +val SCE_MAKE_COMMENT=1 +val SCE_MAKE_PREPROCESSOR=2 +val SCE_MAKE_IDENTIFIER=3 +val SCE_MAKE_OPERATOR=4 +val SCE_MAKE_TARGET=5 +val SCE_MAKE_IDEOL=9 +# Lexical states for SCLEX_DIFF +lex Diff=SCLEX_DIFF SCE_DIFF_ +val SCE_DIFF_DEFAULT=0 +val SCE_DIFF_COMMENT=1 +val SCE_DIFF_COMMAND=2 +val SCE_DIFF_HEADER=3 +val SCE_DIFF_POSITION=4 +val SCE_DIFF_DELETED=5 +val SCE_DIFF_ADDED=6 +# Lexical states for SCLEX_CONF (Apache Configuration Files Lexer) +lex Conf=SCLEX_CONF SCE_CONF_ +val SCE_CONF_DEFAULT=0 +val SCE_CONF_COMMENT=1 +val SCE_CONF_NUMBER=2 +val SCE_CONF_IDENTIFIER=3 +val SCE_CONF_EXTENSION=4 +val SCE_CONF_PARAMETER=5 +val SCE_CONF_STRING=6 +val SCE_CONF_OPERATOR=7 +val SCE_CONF_IP=8 +val SCE_CONF_DIRECTIVE=9 +# Lexical states for SCLEX_AVE, Avenue +lex Avenue=SCLEX_AVE SCE_AVE_ +val SCE_AVE_DEFAULT=0 +val SCE_AVE_COMMENT=1 +val SCE_AVE_NUMBER=2 +val SCE_AVE_WORD=3 +val SCE_AVE_STRING=6 +val SCE_AVE_ENUM=7 +val SCE_AVE_STRINGEOL=8 +val SCE_AVE_IDENTIFIER=9 +val SCE_AVE_OPERATOR=10 +val SCE_AVE_WORD1=11 +val SCE_AVE_WORD2=12 +val SCE_AVE_WORD3=13 +val SCE_AVE_WORD4=14 +val SCE_AVE_WORD5=15 +val SCE_AVE_WORD6=16 +# Lexical states for SCLEX_ADA +lex Ada=SCLEX_ADA SCE_ADA_ +val SCE_ADA_DEFAULT=0 +val SCE_ADA_WORD=1 +val SCE_ADA_IDENTIFIER=2 +val SCE_ADA_NUMBER=3 +val SCE_ADA_DELIMITER=4 +val SCE_ADA_CHARACTER=5 +val SCE_ADA_CHARACTEREOL=6 +val SCE_ADA_STRING=7 +val SCE_ADA_STRINGEOL=8 +val SCE_ADA_LABEL=9 +val SCE_ADA_COMMENTLINE=10 +val SCE_ADA_ILLEGAL=11 +# Lexical states for SCLEX_BAAN +lex Baan=SCLEX_BAAN SCE_BAAN_ +val SCE_BAAN_DEFAULT=0 +val SCE_BAAN_COMMENT=1 +val SCE_BAAN_COMMENTDOC=2 +val SCE_BAAN_NUMBER=3 +val SCE_BAAN_WORD=4 +val SCE_BAAN_STRING=5 +val SCE_BAAN_PREPROCESSOR=6 +val SCE_BAAN_OPERATOR=7 +val SCE_BAAN_IDENTIFIER=8 +val SCE_BAAN_STRINGEOL=9 +val SCE_BAAN_WORD2=10 +# Lexical states for SCLEX_LISP +lex Lisp=SCLEX_LISP SCE_LISP_ +val SCE_LISP_DEFAULT=0 +val SCE_LISP_COMMENT=1 +val SCE_LISP_NUMBER=2 +val SCE_LISP_KEYWORD=3 +val SCE_LISP_KEYWORD_KW=4 +val SCE_LISP_SYMBOL=5 +val SCE_LISP_STRING=6 +val SCE_LISP_STRINGEOL=8 +val SCE_LISP_IDENTIFIER=9 +val SCE_LISP_OPERATOR=10 +val SCE_LISP_SPECIAL=11 +val SCE_LISP_MULTI_COMMENT=12 +# Lexical states for SCLEX_EIFFEL and SCLEX_EIFFELKW +lex Eiffel=SCLEX_EIFFEL SCE_EIFFEL_ +lex EiffelKW=SCLEX_EIFFELKW SCE_EIFFEL_ +val SCE_EIFFEL_DEFAULT=0 +val SCE_EIFFEL_COMMENTLINE=1 +val SCE_EIFFEL_NUMBER=2 +val SCE_EIFFEL_WORD=3 +val SCE_EIFFEL_STRING=4 +val SCE_EIFFEL_CHARACTER=5 +val SCE_EIFFEL_OPERATOR=6 +val SCE_EIFFEL_IDENTIFIER=7 +val SCE_EIFFEL_STRINGEOL=8 +# Lexical states for SCLEX_NNCRONTAB (nnCron crontab Lexer) +lex NNCronTab=SCLEX_NNCRONTAB SCE_NNCRONTAB_ +val SCE_NNCRONTAB_DEFAULT=0 +val SCE_NNCRONTAB_COMMENT=1 +val SCE_NNCRONTAB_TASK=2 +val SCE_NNCRONTAB_SECTION=3 +val SCE_NNCRONTAB_KEYWORD=4 +val SCE_NNCRONTAB_MODIFIER=5 +val SCE_NNCRONTAB_ASTERISK=6 +val SCE_NNCRONTAB_NUMBER=7 +val SCE_NNCRONTAB_STRING=8 +val SCE_NNCRONTAB_ENVIRONMENT=9 +val SCE_NNCRONTAB_IDENTIFIER=10 +# Lexical states for SCLEX_FORTH (Forth Lexer) +lex Forth=SCLEX_FORTH SCE_FORTH_ +val SCE_FORTH_DEFAULT=0 +val SCE_FORTH_COMMENT=1 +val SCE_FORTH_COMMENT_ML=2 +val SCE_FORTH_IDENTIFIER=3 +val SCE_FORTH_CONTROL=4 +val SCE_FORTH_KEYWORD=5 +val SCE_FORTH_DEFWORD=6 +val SCE_FORTH_PREWORD1=7 +val SCE_FORTH_PREWORD2=8 +val SCE_FORTH_NUMBER=9 +val SCE_FORTH_STRING=10 +val SCE_FORTH_LOCALE=11 +# Lexical states for SCLEX_MATLAB +lex MatLab=SCLEX_MATLAB SCE_MATLAB_ +val SCE_MATLAB_DEFAULT=0 +val SCE_MATLAB_COMMENT=1 +val SCE_MATLAB_COMMAND=2 +val SCE_MATLAB_NUMBER=3 +val SCE_MATLAB_KEYWORD=4 +# single quoted string +val SCE_MATLAB_STRING=5 +val SCE_MATLAB_OPERATOR=6 +val SCE_MATLAB_IDENTIFIER=7 +val SCE_MATLAB_DOUBLEQUOTESTRING=8 +# Lexical states for SCLEX_SCRIPTOL +lex Sol=SCLEX_SCRIPTOL SCE_SCRIPTOL_ +val SCE_SCRIPTOL_DEFAULT=0 +val SCE_SCRIPTOL_WHITE=1 +val SCE_SCRIPTOL_COMMENTLINE=2 +val SCE_SCRIPTOL_PERSISTENT=3 +val SCE_SCRIPTOL_CSTYLE=4 +val SCE_SCRIPTOL_COMMENTBLOCK=5 +val SCE_SCRIPTOL_NUMBER=6 +val SCE_SCRIPTOL_STRING=7 +val SCE_SCRIPTOL_CHARACTER=8 +val SCE_SCRIPTOL_STRINGEOL=9 +val SCE_SCRIPTOL_KEYWORD=10 +val SCE_SCRIPTOL_OPERATOR=11 +val SCE_SCRIPTOL_IDENTIFIER=12 +val SCE_SCRIPTOL_TRIPLE=13 +val SCE_SCRIPTOL_CLASSNAME=14 +val SCE_SCRIPTOL_PREPROCESSOR=15 +# Lexical states for SCLEX_ASM +lex Asm=SCLEX_ASM SCE_ASM_ +val SCE_ASM_DEFAULT=0 +val SCE_ASM_COMMENT=1 +val SCE_ASM_NUMBER=2 +val SCE_ASM_STRING=3 +val SCE_ASM_OPERATOR=4 +val SCE_ASM_IDENTIFIER=5 +val SCE_ASM_CPUINSTRUCTION=6 +val SCE_ASM_MATHINSTRUCTION=7 +val SCE_ASM_REGISTER=8 +val SCE_ASM_DIRECTIVE=9 +val SCE_ASM_DIRECTIVEOPERAND=10 +val SCE_ASM_COMMENTBLOCK=11 +val SCE_ASM_CHARACTER=12 +val SCE_ASM_STRINGEOL=13 +val SCE_ASM_EXTINSTRUCTION=14 +# Lexical states for SCLEX_FORTRAN +lex Fortran=SCLEX_FORTRAN SCE_F_ +lex F77=SCLEX_F77 SCE_F_ +val SCE_F_DEFAULT=0 +val SCE_F_COMMENT=1 +val SCE_F_NUMBER=2 +val SCE_F_STRING1=3 +val SCE_F_STRING2=4 +val SCE_F_STRINGEOL=5 +val SCE_F_OPERATOR=6 +val SCE_F_IDENTIFIER=7 +val SCE_F_WORD=8 +val SCE_F_WORD2=9 +val SCE_F_WORD3=10 +val SCE_F_PREPROCESSOR=11 +val SCE_F_OPERATOR2=12 +val SCE_F_LABEL=13 +val SCE_F_CONTINUATION=14 +# Lexical states for SCLEX_CSS +lex CSS=SCLEX_CSS SCE_CSS_ +val SCE_CSS_DEFAULT=0 +val SCE_CSS_TAG=1 +val SCE_CSS_CLASS=2 +val SCE_CSS_PSEUDOCLASS=3 +val SCE_CSS_UNKNOWN_PSEUDOCLASS=4 +val SCE_CSS_OPERATOR=5 +val SCE_CSS_IDENTIFIER=6 +val SCE_CSS_UNKNOWN_IDENTIFIER=7 +val SCE_CSS_VALUE=8 +val SCE_CSS_COMMENT=9 +val SCE_CSS_ID=10 +val SCE_CSS_IMPORTANT=11 +val SCE_CSS_DIRECTIVE=12 +val SCE_CSS_DOUBLESTRING=13 +val SCE_CSS_SINGLESTRING=14 +val SCE_CSS_IDENTIFIER2=15 +val SCE_CSS_ATTRIBUTE=16 +# Lexical states for SCLEX_POV +lex POV=SCLEX_POV SCE_POV_ +val SCE_POV_DEFAULT=0 +val SCE_POV_COMMENT=1 +val SCE_POV_COMMENTLINE=2 +val SCE_POV_NUMBER=3 +val SCE_POV_OPERATOR=4 +val SCE_POV_IDENTIFIER=5 +val SCE_POV_STRING=6 +val SCE_POV_STRINGEOL=7 +val SCE_POV_DIRECTIVE=8 +val SCE_POV_BADDIRECTIVE=9 +val SCE_POV_WORD2=10 +val SCE_POV_WORD3=11 +val SCE_POV_WORD4=12 +val SCE_POV_WORD5=13 +val SCE_POV_WORD6=14 +val SCE_POV_WORD7=15 +val SCE_POV_WORD8=16 +# Lexical states for SCLEX_LOUT +lex LOUT=SCLEX_LOUT SCE_LOUT_ +val SCE_LOUT_DEFAULT=0 +val SCE_LOUT_COMMENT=1 +val SCE_LOUT_NUMBER=2 +val SCE_LOUT_WORD=3 +val SCE_LOUT_WORD2=4 +val SCE_LOUT_WORD3=5 +val SCE_LOUT_WORD4=6 +val SCE_LOUT_STRING=7 +val SCE_LOUT_OPERATOR=8 +val SCE_LOUT_IDENTIFIER=9 +val SCE_LOUT_STRINGEOL=10 +# Lexical states for SCLEX_ESCRIPT +lex ESCRIPT=SCLEX_ESCRIPT SCE_ESCRIPT_ +val SCE_ESCRIPT_DEFAULT=0 +val SCE_ESCRIPT_COMMENT=1 +val SCE_ESCRIPT_COMMENTLINE=2 +val SCE_ESCRIPT_COMMENTDOC=3 +val SCE_ESCRIPT_NUMBER=4 +val SCE_ESCRIPT_WORD=5 +val SCE_ESCRIPT_STRING=6 +val SCE_ESCRIPT_OPERATOR=7 +val SCE_ESCRIPT_IDENTIFIER=8 +val SCE_ESCRIPT_BRACE=9 +val SCE_ESCRIPT_WORD2=10 +val SCE_ESCRIPT_WORD3=11 +# Lexical states for SCLEX_PS +lex PS=SCLEX_PS SCE_PS_ +val SCE_PS_DEFAULT=0 +val SCE_PS_COMMENT=1 +val SCE_PS_DSC_COMMENT=2 +val SCE_PS_DSC_VALUE=3 +val SCE_PS_NUMBER=4 +val SCE_PS_NAME=5 +val SCE_PS_KEYWORD=6 +val SCE_PS_LITERAL=7 +val SCE_PS_IMMEVAL=8 +val SCE_PS_PAREN_ARRAY=9 +val SCE_PS_PAREN_DICT=10 +val SCE_PS_PAREN_PROC=11 +val SCE_PS_TEXT=12 +val SCE_PS_HEXSTRING=13 +val SCE_PS_BASE85STRING=14 +val SCE_PS_BADSTRINGCHAR=15 +# Lexical states for SCLEX_NSIS +lex NSIS=SCLEX_NSIS SCE_NSIS_ +val SCE_NSIS_DEFAULT=0 +val SCE_NSIS_COMMENT=1 +val SCE_NSIS_STRINGDQ=2 +val SCE_NSIS_STRINGLQ=3 +val SCE_NSIS_STRINGRQ=4 +val SCE_NSIS_FUNCTION=5 +val SCE_NSIS_VARIABLE=6 +val SCE_NSIS_LABEL=7 +val SCE_NSIS_USERDEFINED=8 +val SCE_NSIS_SECTIONDEF=9 +val SCE_NSIS_SUBSECTIONDEF=10 +val SCE_NSIS_IFDEFINEDEF=11 +val SCE_NSIS_MACRODEF=12 +val SCE_NSIS_STRINGVAR=13 +val SCE_NSIS_NUMBER=14 +val SCE_NSIS_SECTIONGROUP=15 +val SCE_NSIS_PAGEEX=16 +val SCE_NSIS_FUNCTIONDEF=17 +val SCE_NSIS_COMMENTBOX=18 +# Lexical states for SCLEX_MMIXAL +lex MMIXAL=SCLEX_MMIXAL SCE_MMIXAL_ +val SCE_MMIXAL_LEADWS=0 +val SCE_MMIXAL_COMMENT=1 +val SCE_MMIXAL_LABEL=2 +val SCE_MMIXAL_OPCODE=3 +val SCE_MMIXAL_OPCODE_PRE=4 +val SCE_MMIXAL_OPCODE_VALID=5 +val SCE_MMIXAL_OPCODE_UNKNOWN=6 +val SCE_MMIXAL_OPCODE_POST=7 +val SCE_MMIXAL_OPERANDS=8 +val SCE_MMIXAL_NUMBER=9 +val SCE_MMIXAL_REF=10 +val SCE_MMIXAL_CHAR=11 +val SCE_MMIXAL_STRING=12 +val SCE_MMIXAL_REGISTER=13 +val SCE_MMIXAL_HEX=14 +val SCE_MMIXAL_OPERATOR=15 +val SCE_MMIXAL_SYMBOL=16 +val SCE_MMIXAL_INCLUDE=17 +# Lexical states for SCLEX_CLW +lex Clarion=SCLEX_CLW SCE_CLW_ +val SCE_CLW_DEFAULT=0 +val SCE_CLW_LABEL=1 +val SCE_CLW_COMMENT=2 +val SCE_CLW_STRING=3 +val SCE_CLW_USER_IDENTIFIER=4 +val SCE_CLW_INTEGER_CONSTANT=5 +val SCE_CLW_REAL_CONSTANT=6 +val SCE_CLW_PICTURE_STRING=7 +val SCE_CLW_KEYWORD=8 +val SCE_CLW_COMPILER_DIRECTIVE=9 +val SCE_CLW_RUNTIME_EXPRESSIONS=10 +val SCE_CLW_BUILTIN_PROCEDURES_FUNCTION=11 +val SCE_CLW_STRUCTURE_DATA_TYPE=12 +val SCE_CLW_ATTRIBUTE=13 +val SCE_CLW_STANDARD_EQUATE=14 +val SCE_CLW_ERROR=15 +val SCE_CLW_DEPRECATED=16 +# Lexical states for SCLEX_LOT +lex LOT=SCLEX_LOT SCE_LOT_ +val SCE_LOT_DEFAULT=0 +val SCE_LOT_HEADER=1 +val SCE_LOT_BREAK=2 +val SCE_LOT_SET=3 +val SCE_LOT_PASS=4 +val SCE_LOT_FAIL=5 +val SCE_LOT_ABORT=6 +# Lexical states for SCLEX_YAML +lex YAML=SCLEX_YAML SCE_YAML_ +val SCE_YAML_DEFAULT=0 +val SCE_YAML_COMMENT=1 +val SCE_YAML_IDENTIFIER=2 +val SCE_YAML_KEYWORD=3 +val SCE_YAML_NUMBER=4 +val SCE_YAML_REFERENCE=5 +val SCE_YAML_DOCUMENT=6 +val SCE_YAML_TEXT=7 +val SCE_YAML_ERROR=8 +val SCE_YAML_OPERATOR=9 +# Lexical states for SCLEX_TEX +lex TeX=SCLEX_TEX SCE_TEX_ +val SCE_TEX_DEFAULT=0 +val SCE_TEX_SPECIAL=1 +val SCE_TEX_GROUP=2 +val SCE_TEX_SYMBOL=3 +val SCE_TEX_COMMAND=4 +val SCE_TEX_TEXT=5 +lex Metapost=SCLEX_METAPOST SCE_METAPOST_ +val SCE_METAPOST_DEFAULT=0 +val SCE_METAPOST_SPECIAL=1 +val SCE_METAPOST_GROUP=2 +val SCE_METAPOST_SYMBOL=3 +val SCE_METAPOST_COMMAND=4 +val SCE_METAPOST_TEXT=5 +val SCE_METAPOST_EXTRA=6 +# Lexical states for SCLEX_ERLANG +lex Erlang=SCLEX_ERLANG SCE_ERLANG_ +val SCE_ERLANG_DEFAULT=0 +val SCE_ERLANG_COMMENT=1 +val SCE_ERLANG_VARIABLE=2 +val SCE_ERLANG_NUMBER=3 +val SCE_ERLANG_KEYWORD=4 +val SCE_ERLANG_STRING=5 +val SCE_ERLANG_OPERATOR=6 +val SCE_ERLANG_ATOM=7 +val SCE_ERLANG_FUNCTION_NAME=8 +val SCE_ERLANG_CHARACTER=9 +val SCE_ERLANG_MACRO=10 +val SCE_ERLANG_RECORD=11 +val SCE_ERLANG_SEPARATOR=12 +val SCE_ERLANG_NODE_NAME=13 +val SCE_ERLANG_UNKNOWN=31 +# Lexical states for SCLEX_OCTAVE are identical to MatLab +lex Octave=SCLEX_OCTAVE SCE_MATLAB_ +# Lexical states for SCLEX_MSSQL +lex MSSQL=SCLEX_MSSQL SCE_MSSQL_ +val SCE_MSSQL_DEFAULT=0 +val SCE_MSSQL_COMMENT=1 +val SCE_MSSQL_LINE_COMMENT=2 +val SCE_MSSQL_NUMBER=3 +val SCE_MSSQL_STRING=4 +val SCE_MSSQL_OPERATOR=5 +val SCE_MSSQL_IDENTIFIER=6 +val SCE_MSSQL_VARIABLE=7 +val SCE_MSSQL_COLUMN_NAME=8 +val SCE_MSSQL_STATEMENT=9 +val SCE_MSSQL_DATATYPE=10 +val SCE_MSSQL_SYSTABLE=11 +val SCE_MSSQL_GLOBAL_VARIABLE=12 +val SCE_MSSQL_FUNCTION=13 +val SCE_MSSQL_STORED_PROCEDURE=14 +val SCE_MSSQL_DEFAULT_PREF_DATATYPE=15 +val SCE_MSSQL_COLUMN_NAME_2=16 +# Lexical states for SCLEX_VERILOG +lex Verilog=SCLEX_VERILOG SCE_V_ +val SCE_V_DEFAULT=0 +val SCE_V_COMMENT=1 +val SCE_V_COMMENTLINE=2 +val SCE_V_COMMENTLINEBANG=3 +val SCE_V_NUMBER=4 +val SCE_V_WORD=5 +val SCE_V_STRING=6 +val SCE_V_WORD2=7 +val SCE_V_WORD3=8 +val SCE_V_PREPROCESSOR=9 +val SCE_V_OPERATOR=10 +val SCE_V_IDENTIFIER=11 +val SCE_V_STRINGEOL=12 +val SCE_V_USER=19 +# Lexical states for SCLEX_KIX +lex Kix=SCLEX_KIX SCE_KIX_ +val SCE_KIX_DEFAULT=0 +val SCE_KIX_COMMENT=1 +val SCE_KIX_STRING1=2 +val SCE_KIX_STRING2=3 +val SCE_KIX_NUMBER=4 +val SCE_KIX_VAR=5 +val SCE_KIX_MACRO=6 +val SCE_KIX_KEYWORD=7 +val SCE_KIX_FUNCTIONS=8 +val SCE_KIX_OPERATOR=9 +val SCE_KIX_IDENTIFIER=31 +# Lexical states for SCLEX_GUI4CLI +val SCE_GC_DEFAULT=0 +val SCE_GC_COMMENTLINE=1 +val SCE_GC_COMMENTBLOCK=2 +val SCE_GC_GLOBAL=3 +val SCE_GC_EVENT=4 +val SCE_GC_ATTRIBUTE=5 +val SCE_GC_CONTROL=6 +val SCE_GC_COMMAND=7 +val SCE_GC_STRING=8 +val SCE_GC_OPERATOR=9 +# Lexical states for SCLEX_SPECMAN +lex Specman=SCLEX_SPECMAN SCE_SN_ +val SCE_SN_DEFAULT=0 +val SCE_SN_CODE=1 +val SCE_SN_COMMENTLINE=2 +val SCE_SN_COMMENTLINEBANG=3 +val SCE_SN_NUMBER=4 +val SCE_SN_WORD=5 +val SCE_SN_STRING=6 +val SCE_SN_WORD2=7 +val SCE_SN_WORD3=8 +val SCE_SN_PREPROCESSOR=9 +val SCE_SN_OPERATOR=10 +val SCE_SN_IDENTIFIER=11 +val SCE_SN_STRINGEOL=12 +val SCE_SN_REGEXTAG=13 +val SCE_SN_SIGNAL=14 +val SCE_SN_USER=19 +# Lexical states for SCLEX_AU3 +lex Au3=SCLEX_AU3 SCE_AU3_ +val SCE_AU3_DEFAULT=0 +val SCE_AU3_COMMENT=1 +val SCE_AU3_COMMENTBLOCK=2 +val SCE_AU3_NUMBER=3 +val SCE_AU3_FUNCTION=4 +val SCE_AU3_KEYWORD=5 +val SCE_AU3_MACRO=6 +val SCE_AU3_STRING=7 +val SCE_AU3_OPERATOR=8 +val SCE_AU3_VARIABLE=9 +val SCE_AU3_SENT=10 +val SCE_AU3_PREPROCESSOR=11 +val SCE_AU3_SPECIAL=12 +val SCE_AU3_EXPAND=13 +val SCE_AU3_COMOBJ=14 +val SCE_AU3_UDF=15 +# Lexical states for SCLEX_APDL +lex APDL=SCLEX_APDL SCE_APDL_ +val SCE_APDL_DEFAULT=0 +val SCE_APDL_COMMENT=1 +val SCE_APDL_COMMENTBLOCK=2 +val SCE_APDL_NUMBER=3 +val SCE_APDL_STRING=4 +val SCE_APDL_OPERATOR=5 +val SCE_APDL_WORD=6 +val SCE_APDL_PROCESSOR=7 +val SCE_APDL_COMMAND=8 +val SCE_APDL_SLASHCOMMAND=9 +val SCE_APDL_STARCOMMAND=10 +val SCE_APDL_ARGUMENT=11 +val SCE_APDL_FUNCTION=12 +# Lexical states for SCLEX_BASH +lex Bash=SCLEX_BASH SCE_SH_ +val SCE_SH_DEFAULT=0 +val SCE_SH_ERROR=1 +val SCE_SH_COMMENTLINE=2 +val SCE_SH_NUMBER=3 +val SCE_SH_WORD=4 +val SCE_SH_STRING=5 +val SCE_SH_CHARACTER=6 +val SCE_SH_OPERATOR=7 +val SCE_SH_IDENTIFIER=8 +val SCE_SH_SCALAR=9 +val SCE_SH_PARAM=10 +val SCE_SH_BACKTICKS=11 +val SCE_SH_HERE_DELIM=12 +val SCE_SH_HERE_Q=13 +# Lexical states for SCLEX_ASN1 +lex Asn1=SCLEX_ASN1 SCE_ASN1_ +val SCE_ASN1_DEFAULT=0 +val SCE_ASN1_COMMENT=1 +val SCE_ASN1_IDENTIFIER=2 +val SCE_ASN1_STRING=3 +val SCE_ASN1_OID=4 +val SCE_ASN1_SCALAR=5 +val SCE_ASN1_KEYWORD=6 +val SCE_ASN1_ATTRIBUTE=7 +val SCE_ASN1_DESCRIPTOR=8 +val SCE_ASN1_TYPE=9 +val SCE_ASN1_OPERATOR=10 +# Lexical states for SCLEX_VHDL +lex VHDL=SCLEX_VHDL SCE_VHDL_ +val SCE_VHDL_DEFAULT=0 +val SCE_VHDL_COMMENT=1 +val SCE_VHDL_COMMENTLINEBANG=2 +val SCE_VHDL_NUMBER=3 +val SCE_VHDL_STRING=4 +val SCE_VHDL_OPERATOR=5 +val SCE_VHDL_IDENTIFIER=6 +val SCE_VHDL_STRINGEOL=7 +val SCE_VHDL_KEYWORD=8 +val SCE_VHDL_STDOPERATOR=9 +val SCE_VHDL_ATTRIBUTE=10 +val SCE_VHDL_STDFUNCTION=11 +val SCE_VHDL_STDPACKAGE=12 +val SCE_VHDL_STDTYPE=13 +val SCE_VHDL_USERWORD=14 +# Lexical states for SCLEX_CAML +lex Caml=SCLEX_CAML SCE_CAML_ +val SCE_CAML_DEFAULT=0 +val SCE_CAML_IDENTIFIER=1 +val SCE_CAML_TAGNAME=2 +val SCE_CAML_KEYWORD=3 +val SCE_CAML_KEYWORD2=4 +val SCE_CAML_KEYWORD3=5 +val SCE_CAML_LINENUM=6 +val SCE_CAML_OPERATOR=7 +val SCE_CAML_NUMBER=8 +val SCE_CAML_CHAR=9 +val SCE_CAML_STRING=11 +val SCE_CAML_COMMENT=12 +val SCE_CAML_COMMENT1=13 +val SCE_CAML_COMMENT2=14 +val SCE_CAML_COMMENT3=15 +# Lexical states for SCLEX_HASKELL +lex Haskell=SCLEX_HASKELL SCE_HA_ +val SCE_HA_DEFAULT=0 +val SCE_HA_IDENTIFIER=1 +val SCE_HA_KEYWORD=2 +val SCE_HA_NUMBER=3 +val SCE_HA_STRING=4 +val SCE_HA_CHARACTER=5 +val SCE_HA_CLASS=6 +val SCE_HA_MODULE=7 +val SCE_HA_CAPITAL=8 +val SCE_HA_DATA=9 +val SCE_HA_IMPORT=10 +val SCE_HA_OPERATOR=11 +val SCE_HA_INSTANCE=12 +val SCE_HA_COMMENTLINE=13 +val SCE_HA_COMMENTBLOCK=14 +val SCE_HA_COMMENTBLOCK2=15 +val SCE_HA_COMMENTBLOCK3=16 +# Lexical states of SCLEX_TADS3 +lex TADS3=SCLEX_TADS3 SCE_T3_ +val SCE_T3_DEFAULT=0 +val SCE_T3_X_DEFAULT=1 +val SCE_T3_PREPROCESSOR=2 +val SCE_T3_BLOCK_COMMENT=3 +val SCE_T3_LINE_COMMENT=4 +val SCE_T3_OPERATOR=5 +val SCE_T3_KEYWORD=6 +val SCE_T3_NUMBER=7 +val SCE_T3_IDENTIFIER=8 +val SCE_T3_S_STRING=9 +val SCE_T3_D_STRING=10 +val SCE_T3_X_STRING=11 +val SCE_T3_LIB_DIRECTIVE=12 +val SCE_T3_MSG_PARAM=13 +val SCE_T3_HTML_TAG=14 +val SCE_T3_HTML_DEFAULT=15 +val SCE_T3_HTML_STRING=16 +val SCE_T3_USER1=17 +val SCE_T3_USER2=18 +val SCE_T3_USER3=19 +val SCE_T3_BRACE=20 +# Lexical states for SCLEX_REBOL +lex Rebol=SCLEX_REBOL SCE_REBOL_ +val SCE_REBOL_DEFAULT=0 +val SCE_REBOL_COMMENTLINE=1 +val SCE_REBOL_COMMENTBLOCK=2 +val SCE_REBOL_PREFACE=3 +val SCE_REBOL_OPERATOR=4 +val SCE_REBOL_CHARACTER=5 +val SCE_REBOL_QUOTEDSTRING=6 +val SCE_REBOL_BRACEDSTRING=7 +val SCE_REBOL_NUMBER=8 +val SCE_REBOL_PAIR=9 +val SCE_REBOL_TUPLE=10 +val SCE_REBOL_BINARY=11 +val SCE_REBOL_MONEY=12 +val SCE_REBOL_ISSUE=13 +val SCE_REBOL_TAG=14 +val SCE_REBOL_FILE=15 +val SCE_REBOL_EMAIL=16 +val SCE_REBOL_URL=17 +val SCE_REBOL_DATE=18 +val SCE_REBOL_TIME=19 +val SCE_REBOL_IDENTIFIER=20 +val SCE_REBOL_WORD=21 +val SCE_REBOL_WORD2=22 +val SCE_REBOL_WORD3=23 +val SCE_REBOL_WORD4=24 +val SCE_REBOL_WORD5=25 +val SCE_REBOL_WORD6=26 +val SCE_REBOL_WORD7=27 +val SCE_REBOL_WORD8=28 +# Lexical states for SCLEX_SQL +lex SQL=SCLEX_SQL SCE_SQL_ +val SCE_SQL_DEFAULT=0 +val SCE_SQL_COMMENT=1 +val SCE_SQL_COMMENTLINE=2 +val SCE_SQL_COMMENTDOC=3 +val SCE_SQL_NUMBER=4 +val SCE_SQL_WORD=5 +val SCE_SQL_STRING=6 +val SCE_SQL_CHARACTER=7 +val SCE_SQL_SQLPLUS=8 +val SCE_SQL_SQLPLUS_PROMPT=9 +val SCE_SQL_OPERATOR=10 +val SCE_SQL_IDENTIFIER=11 +val SCE_SQL_SQLPLUS_COMMENT=13 +val SCE_SQL_COMMENTLINEDOC=15 +val SCE_SQL_WORD2=16 +val SCE_SQL_COMMENTDOCKEYWORD=17 +val SCE_SQL_COMMENTDOCKEYWORDERROR=18 +val SCE_SQL_USER1=19 +val SCE_SQL_USER2=20 +val SCE_SQL_USER3=21 +val SCE_SQL_USER4=22 +val SCE_SQL_QUOTEDIDENTIFIER=23 +# Lexical states for SCLEX_SMALLTALK +lex Smalltalk=SCLEX_SMALLTALK SCE_ST_ +val SCE_ST_DEFAULT=0 +val SCE_ST_STRING=1 +val SCE_ST_NUMBER=2 +val SCE_ST_COMMENT=3 +val SCE_ST_SYMBOL=4 +val SCE_ST_BINARY=5 +val SCE_ST_BOOL=6 +val SCE_ST_SELF=7 +val SCE_ST_SUPER=8 +val SCE_ST_NIL=9 +val SCE_ST_GLOBAL=10 +val SCE_ST_RETURN=11 +val SCE_ST_SPECIAL=12 +val SCE_ST_KWSEND=13 +val SCE_ST_ASSIGN=14 +val SCE_ST_CHARACTER=15 +val SCE_ST_SPEC_SEL=16 +# Lexical states for SCLEX_FLAGSHIP (clipper) +lex FlagShip=SCLEX_FLAGSHIP SCE_B_ +val SCE_FS_DEFAULT=0 +val SCE_FS_COMMENT=1 +val SCE_FS_COMMENTLINE=2 +val SCE_FS_COMMENTDOC=3 +val SCE_FS_COMMENTLINEDOC=4 +val SCE_FS_COMMENTDOCKEYWORD=5 +val SCE_FS_COMMENTDOCKEYWORDERROR=6 +val SCE_FS_KEYWORD=7 +val SCE_FS_KEYWORD2=8 +val SCE_FS_KEYWORD3=9 +val SCE_FS_KEYWORD4=10 +val SCE_FS_NUMBER=11 +val SCE_FS_STRING=12 +val SCE_FS_PREPROCESSOR=13 +val SCE_FS_OPERATOR=14 +val SCE_FS_IDENTIFIER=15 +val SCE_FS_DATE=16 +val SCE_FS_STRINGEOL=17 +val SCE_FS_CONSTANT=18 +val SCE_FS_ASM=19 +val SCE_FS_LABEL=20 +val SCE_FS_ERROR=21 +val SCE_FS_HEXNUMBER=22 +val SCE_FS_BINNUMBER=23 +# Lexical states for SCLEX_CSOUND +lex Csound=SCLEX_CSOUND SCE_CSOUND_ +val SCE_CSOUND_DEFAULT=0 +val SCE_CSOUND_COMMENT=1 +val SCE_CSOUND_NUMBER=2 +val SCE_CSOUND_OPERATOR=3 +val SCE_CSOUND_INSTR=4 +val SCE_CSOUND_IDENTIFIER=5 +val SCE_CSOUND_OPCODE=6 +val SCE_CSOUND_HEADERSTMT=7 +val SCE_CSOUND_USERKEYWORD=8 +val SCE_CSOUND_COMMENTBLOCK=9 +val SCE_CSOUND_PARAM=10 +val SCE_CSOUND_ARATE_VAR=11 +val SCE_CSOUND_KRATE_VAR=12 +val SCE_CSOUND_IRATE_VAR=13 +val SCE_CSOUND_GLOBAL_VAR=14 +val SCE_CSOUND_STRINGEOL=15 +# Lexical states for SCLEX_INNOSETUP +lex Inno=SCLEX_INNOSETUP SCE_INNO_ +val SCE_INNO_DEFAULT=0 +val SCE_INNO_COMMENT=1 +val SCE_INNO_KEYWORD=2 +val SCE_INNO_PARAMETER=3 +val SCE_INNO_SECTION=4 +val SCE_INNO_PREPROC=5 +val SCE_INNO_PREPROC_INLINE=6 +val SCE_INNO_COMMENT_PASCAL=7 +val SCE_INNO_KEYWORD_PASCAL=8 +val SCE_INNO_KEYWORD_USER=9 +val SCE_INNO_STRING_DOUBLE=10 +val SCE_INNO_STRING_SINGLE=11 +val SCE_INNO_IDENTIFIER=12 +# Lexical states for SCLEX_OPAL +lex Opal=SCLEX_OPAL SCE_OPAL_ +val SCE_OPAL_SPACE=0 +val SCE_OPAL_COMMENT_BLOCK=1 +val SCE_OPAL_COMMENT_LINE=2 +val SCE_OPAL_INTEGER=3 +val SCE_OPAL_KEYWORD=4 +val SCE_OPAL_SORT=5 +val SCE_OPAL_STRING=6 +val SCE_OPAL_PAR=7 +val SCE_OPAL_BOOL_CONST=8 +val SCE_OPAL_DEFAULT=32 +# Lexical states for SCLEX_SPICE +lex Spice=SCLEX_SPICE SCE_SPICE_ +val SCE_SPICE_DEFAULT=0 +val SCE_SPICE_IDENTIFIER=1 +val SCE_SPICE_KEYWORD=2 +val SCE_SPICE_KEYWORD2=3 +val SCE_SPICE_KEYWORD3=4 +val SCE_SPICE_NUMBER=5 +val SCE_SPICE_DELIMITER=6 +val SCE_SPICE_VALUE=7 +val SCE_SPICE_COMMENTLINE=8 +# Lexical states for SCLEX_CMAKE +lex CMAKE=SCLEX_CMAKE SCE_CMAKE_ +val SCE_CMAKE_DEFAULT=0 +val SCE_CMAKE_COMMENT=1 +val SCE_CMAKE_STRINGDQ=2 +val SCE_CMAKE_STRINGLQ=3 +val SCE_CMAKE_STRINGRQ=4 +val SCE_CMAKE_COMMANDS=5 +val SCE_CMAKE_PARAMETERS=6 +val SCE_CMAKE_VARIABLE=7 +val SCE_CMAKE_USERDEFINED=8 +val SCE_CMAKE_WHILEDEF=9 +val SCE_CMAKE_FOREACHDEF=10 +val SCE_CMAKE_IFDEFINEDEF=11 +val SCE_CMAKE_MACRODEF=12 +val SCE_CMAKE_STRINGVAR=13 +val SCE_CMAKE_NUMBER=14 +# Lexical states for SCLEX_GAP +lex Gap=SCLEX_GAP SCE_GAP_ +val SCE_GAP_DEFAULT=0 +val SCE_GAP_IDENTIFIER=1 +val SCE_GAP_KEYWORD=2 +val SCE_GAP_KEYWORD2=3 +val SCE_GAP_KEYWORD3=4 +val SCE_GAP_KEYWORD4=5 +val SCE_GAP_STRING=6 +val SCE_GAP_CHAR=7 +val SCE_GAP_OPERATOR=8 +val SCE_GAP_COMMENT=9 +val SCE_GAP_NUMBER=10 +val SCE_GAP_STRINGEOL=11 +# Lexical state for SCLEX_PLM +lex PLM=SCLEX_PLM SCE_PLM_ +val SCE_PLM_DEFAULT=0 +val SCE_PLM_COMMENT=1 +val SCE_PLM_STRING=2 +val SCE_PLM_NUMBER=3 +val SCE_PLM_IDENTIFIER=4 +val SCE_PLM_OPERATOR=5 +val SCE_PLM_CONTROL=6 +val SCE_PLM_KEYWORD=7 +# Lexical state for SCLEX_PROGRESS +lex Progress=SCLEX_PROGRESS SCE_4GL_ +val SCE_4GL_DEFAULT=0 +val SCE_4GL_NUMBER=1 +val SCE_4GL_WORD=2 +val SCE_4GL_STRING=3 +val SCE_4GL_CHARACTER=4 +val SCE_4GL_PREPROCESSOR=5 +val SCE_4GL_OPERATOR=6 +val SCE_4GL_IDENTIFIER=7 +val SCE_4GL_BLOCK=8 +val SCE_4GL_END=9 +val SCE_4GL_COMMENT1=10 +val SCE_4GL_COMMENT2=11 +val SCE_4GL_COMMENT3=12 +val SCE_4GL_COMMENT4=13 +val SCE_4GL_COMMENT5=14 +val SCE_4GL_COMMENT6=15 +val SCE_4GL_DEFAULT_=16 +val SCE_4GL_NUMBER_=17 +val SCE_4GL_WORD_=18 +val SCE_4GL_STRING_=19 +val SCE_4GL_CHARACTER_=20 +val SCE_4GL_PREPROCESSOR_=21 +val SCE_4GL_OPERATOR_=22 +val SCE_4GL_IDENTIFIER_=23 +val SCE_4GL_BLOCK_=24 +val SCE_4GL_END_=25 +val SCE_4GL_COMMENT1_=26 +val SCE_4GL_COMMENT2_=27 +val SCE_4GL_COMMENT3_=28 +val SCE_4GL_COMMENT4_=29 +val SCE_4GL_COMMENT5_=30 +val SCE_4GL_COMMENT6_=31 +# Lexical states for SCLEX_ABAQUS +lex ABAQUS=SCLEX_ABAQUS SCE_ABAQUS_ +val SCE_ABAQUS_DEFAULT=0 +val SCE_ABAQUS_COMMENT=1 +val SCE_ABAQUS_COMMENTBLOCK=2 +val SCE_ABAQUS_NUMBER=3 +val SCE_ABAQUS_STRING=4 +val SCE_ABAQUS_OPERATOR=5 +val SCE_ABAQUS_WORD=6 +val SCE_ABAQUS_PROCESSOR=7 +val SCE_ABAQUS_COMMAND=8 +val SCE_ABAQUS_SLASHCOMMAND=9 +val SCE_ABAQUS_STARCOMMAND=10 +val SCE_ABAQUS_ARGUMENT=11 +val SCE_ABAQUS_FUNCTION=12 +# Lexical states for SCLEX_ASYMPTOTE +lex Asymptote=SCLEX_ASYMPTOTE SCE_ASY_ +val SCE_ASY_DEFAULT=0 +val SCE_ASY_COMMENT=1 +val SCE_ASY_COMMENTLINE=2 +val SCE_ASY_NUMBER=3 +val SCE_ASY_WORD=4 +val SCE_ASY_STRING=5 +val SCE_ASY_CHARACTER=6 +val SCE_ASY_OPERATOR=7 +val SCE_ASY_IDENTIFIER=8 +val SCE_ASY_STRINGEOL=9 +val SCE_ASY_COMMENTLINEDOC=10 +val SCE_ASY_WORD2=11 +# Lexical states for SCLEX_R +lex R=SCLEX_R SCE_R_ +val SCE_R_DEFAULT=0 +val SCE_R_COMMENT=1 +val SCE_R_KWORD=2 +val SCE_R_BASEKWORD=3 +val SCE_R_OTHERKWORD=4 +val SCE_R_NUMBER=5 +val SCE_R_STRING=6 +val SCE_R_STRING2=7 +val SCE_R_OPERATOR=8 +val SCE_R_IDENTIFIER=9 +val SCE_R_INFIX=10 +val SCE_R_INFIXEOL=11 +# Lexical state for SCLEX_MAGIKSF +lex MagikSF=SCLEX_MAGIKSF SCE_MAGIK_ +val SCE_MAGIK_DEFAULT=0 +val SCE_MAGIK_COMMENT=1 +val SCE_MAGIK_HYPER_COMMENT=16 +val SCE_MAGIK_STRING=2 +val SCE_MAGIK_CHARACTER=3 +val SCE_MAGIK_NUMBER=4 +val SCE_MAGIK_IDENTIFIER=5 +val SCE_MAGIK_OPERATOR=6 +val SCE_MAGIK_FLOW=7 +val SCE_MAGIK_CONTAINER=8 +val SCE_MAGIK_BRACKET_BLOCK=9 +val SCE_MAGIK_BRACE_BLOCK=10 +val SCE_MAGIK_SQBRACKET_BLOCK=11 +val SCE_MAGIK_UNKNOWN_KEYWORD=12 +val SCE_MAGIK_KEYWORD=13 +val SCE_MAGIK_PRAGMA=14 +val SCE_MAGIK_SYMBOL=15 +# Lexical state for SCLEX_POWERSHELL +lex PowerShell=SCLEX_POWERSHELL SCE_POWERSHELL_ +val SCE_POWERSHELL_DEFAULT=0 +val SCE_POWERSHELL_COMMENT=1 +val SCE_POWERSHELL_STRING=2 +val SCE_POWERSHELL_CHARACTER=3 +val SCE_POWERSHELL_NUMBER=4 +val SCE_POWERSHELL_VARIABLE=5 +val SCE_POWERSHELL_OPERATOR=6 +val SCE_POWERSHELL_IDENTIFIER=7 +val SCE_POWERSHELL_KEYWORD=8 +val SCE_POWERSHELL_CMDLET=9 +val SCE_POWERSHELL_ALIAS=10 + +# Events + +evt void StyleNeeded=2000(int position) +evt void CharAdded=2001(int ch) +evt void SavePointReached=2002(void) +evt void SavePointLeft=2003(void) +evt void ModifyAttemptRO=2004(void) +# GTK+ Specific to work around focus and accelerator problems: +evt void Key=2005(int ch, int modifiers) +evt void DoubleClick=2006(void) +evt void UpdateUI=2007(void) +evt void Modified=2008(int position, int modificationType, string text, int length, int linesAdded, int line, int foldLevelNow, int foldLevelPrev) +evt void MacroRecord=2009(int message, int wParam, int lParam) +evt void MarginClick=2010(int modifiers, int position, int margin) +evt void NeedShown=2011(int position, int length) +evt void Painted=2013(void) +evt void UserListSelection=2014(int listType, string text) +evt void URIDropped=2015(string text) +evt void DwellStart=2016(int position) +evt void DwellEnd=2017(int position) +evt void Zoom=2018(void) +evt void HotSpotClick=2019(int modifiers, int position) +evt void HotSpotDoubleClick=2020(int modifiers, int position) +evt void CallTipClick=2021(int position) +evt void AutoCSelection=2022(string text) +evt void IndicatorClick=2023(int modifiers, int position) +evt void IndicatorRelease=2024(int modifiers, int position) + +cat Deprecated + +# CARET_POLICY changed in 1.47 +fun void SetCaretPolicy=2369(int caretPolicy, int caretSlop) +val CARET_CENTER=0x02 +val CARET_XEVEN=0x08 +val CARET_XJUMPS=0x10 + +# The old name for SCN_UPDATEUI +val SCN_CHECKBRACE=2007 +evt void PosChanged=2012(int position) + +# SCLEX_HTML should be used in preference to these. +val SCLEX_ASP=29 +val SCLEX_PHP=30 diff --git a/scintilla/include/ScintillaWidget.h b/scintilla/include/ScintillaWidget.h new file mode 100644 index 00000000..d9909524 --- /dev/null +++ b/scintilla/include/ScintillaWidget.h @@ -0,0 +1,59 @@ +// Scintilla source code edit control +/** @file ScintillaWidget.h + ** Definition of Scintilla widget for GTK+. + ** Only needed by GTK+ code but is harmless on other platforms. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef SCINTILLAWIDGET_H +#define SCINTILLAWIDGET_H + +#if PLAT_GTK + +#ifdef __cplusplus +extern "C" { +#endif + +#define SCINTILLA(obj) GTK_CHECK_CAST (obj, scintilla_get_type (), ScintillaObject) +#define SCINTILLA_CLASS(klass) GTK_CHECK_CLASS_CAST (klass, scintilla_get_type (), ScintillaClass) +#define IS_SCINTILLA(obj) GTK_CHECK_TYPE (obj, scintilla_get_type ()) + +typedef struct _ScintillaObject ScintillaObject; +typedef struct _ScintillaClass ScintillaClass; + +struct _ScintillaObject { + GtkContainer cont; + void *pscin; +}; + +struct _ScintillaClass { + GtkContainerClass parent_class; + + void (* command) (ScintillaObject *ttt); + void (* notify) (ScintillaObject *ttt); +}; + +#if GLIB_MAJOR_VERSION < 2 +GtkType scintilla_get_type (void); +#else +GType scintilla_get_type (void); +#endif +GtkWidget* scintilla_new (void); +void scintilla_set_id (ScintillaObject *sci, uptr_t id); +sptr_t scintilla_send_message (ScintillaObject *sci,unsigned int iMessage, uptr_t wParam, sptr_t lParam); +void scintilla_release_resources(void); + +#if GTK_MAJOR_VERSION < 2 +#define SCINTILLA_NOTIFY "notify" +#else +#define SCINTILLA_NOTIFY "sci-notify" +#endif + +#ifdef __cplusplus +} +#endif + +#endif + +#endif diff --git a/scintilla/include/WindowAccessor.h b/scintilla/include/WindowAccessor.h new file mode 100644 index 00000000..6724e841 --- /dev/null +++ b/scintilla/include/WindowAccessor.h @@ -0,0 +1,66 @@ +// Scintilla source code edit control +/** @file WindowAccessor.h + ** Implementation of BufferAccess and StylingAccess on a Scintilla + ** rapid easy access to contents of a Scintilla. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +/** + */ +class WindowAccessor : public Accessor { + // Private so WindowAccessor objects can not be copied + WindowAccessor(const WindowAccessor &source) : Accessor(), props(source.props) {} + WindowAccessor &operator=(const WindowAccessor &) { return *this; } +protected: + WindowID id; + PropSet &props; + int lenDoc; + + char styleBuf[bufferSize]; + int validLen; + char chFlags; + char chWhile; + unsigned int startSeg; + + bool InternalIsLeadByte(char ch); + void Fill(int position); +public: + WindowAccessor(WindowID id_, PropSet &props_) : + Accessor(), id(id_), props(props_), + lenDoc(-1), validLen(0), chFlags(0), chWhile(0) { + } + ~WindowAccessor(); + bool Match(int pos, const char *s); + char StyleAt(int position); + int GetLine(int position); + int LineStart(int line); + int LevelAt(int line); + int Length(); + void Flush(); + int GetLineState(int line); + int SetLineState(int line, int state); + int GetPropertyInt(const char *key, int defaultValue=0) { + return props.GetInt(key, defaultValue); + } + char *GetProperties() { + return props.ToString(); + } + + void StartAt(unsigned int start, char chMask=31); + void SetFlags(char chFlags_, char chWhile_) {chFlags = chFlags_; chWhile = chWhile_; }; + unsigned int GetStartSegment() { return startSeg; } + void StartSegment(unsigned int pos); + void ColourTo(unsigned int pos, int chAttr); + void SetLevel(int line, int level); + int IndentAmount(int line, int *flags, PFNIsCommentLeader pfnIsCommentLeader = 0); + void IndicatorFill(int start, int end, int indicator, int value); +}; + +#ifdef SCI_NAMESPACE +} +#endif diff --git a/scintilla/src/AutoComplete.cxx b/scintilla/src/AutoComplete.cxx new file mode 100644 index 00000000..eff2b1e1 --- /dev/null +++ b/scintilla/src/AutoComplete.cxx @@ -0,0 +1,179 @@ +// Scintilla source code edit control +/** @file AutoComplete.cxx + ** Defines the auto completion list box. + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "AutoComplete.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +AutoComplete::AutoComplete() : + active(false), + separator(' '), + typesep('?'), + ignoreCase(false), + chooseSingle(false), + lb(0), + posStart(0), + startLen(0), + cancelAtStartPos(true), + autoHide(true), + dropRestOfWord(false) { + lb = ListBox::Allocate(); + stopChars[0] = '\0'; + fillUpChars[0] = '\0'; +} + +AutoComplete::~AutoComplete() { + if (lb) { + lb->Destroy(); + delete lb; + lb = 0; + } +} + +bool AutoComplete::Active() { + return active; +} + +void AutoComplete::Start(Window &parent, int ctrlID, + int position, Point location, int startLen_, + int lineHeight, bool unicodeMode) { + if (active) { + Cancel(); + } + lb->Create(parent, ctrlID, location, lineHeight, unicodeMode); + lb->Clear(); + active = true; + startLen = startLen_; + posStart = position; +} + +void AutoComplete::SetStopChars(const char *stopChars_) { + strncpy(stopChars, stopChars_, sizeof(stopChars)); + stopChars[sizeof(stopChars) - 1] = '\0'; +} + +bool AutoComplete::IsStopChar(char ch) { + return ch && strchr(stopChars, ch); +} + +void AutoComplete::SetFillUpChars(const char *fillUpChars_) { + strncpy(fillUpChars, fillUpChars_, sizeof(fillUpChars)); + fillUpChars[sizeof(fillUpChars) - 1] = '\0'; +} + +bool AutoComplete::IsFillUpChar(char ch) { + return ch && strchr(fillUpChars, ch); +} + +void AutoComplete::SetSeparator(char separator_) { + separator = separator_; +} + +char AutoComplete::GetSeparator() { + return separator; +} + +void AutoComplete::SetTypesep(char separator_) { + typesep = separator_; +} + +char AutoComplete::GetTypesep() { + return typesep; +} + +void AutoComplete::SetList(const char *list) { + lb->SetList(list, separator, typesep); +} + +void AutoComplete::Show(bool show) { + lb->Show(show); + if (show) + lb->Select(0); +} + +void AutoComplete::Cancel() { + if (lb->Created()) { + lb->Clear(); + lb->Destroy(); + active = false; + } +} + + +void AutoComplete::Move(int delta) { + int count = lb->Length(); + int current = lb->GetSelection(); + current += delta; + if (current >= count) + current = count - 1; + if (current < 0) + current = 0; + lb->Select(current); +} + +void AutoComplete::Select(const char *word) { + size_t lenWord = strlen(word); + int location = -1; + const int maxItemLen=1000; + char item[maxItemLen]; + int start = 0; // lower bound of the api array block to search + int end = lb->Length() - 1; // upper bound of the api array block to search + while ((start <= end) && (location == -1)) { // Binary searching loop + int pivot = (start + end) / 2; + lb->GetValue(pivot, item, maxItemLen); + int cond; + if (ignoreCase) + cond = CompareNCaseInsensitive(word, item, lenWord); + else + cond = strncmp(word, item, lenWord); + if (!cond) { + // Find first match + while (pivot > start) { + lb->GetValue(pivot-1, item, maxItemLen); + if (ignoreCase) + cond = CompareNCaseInsensitive(word, item, lenWord); + else + cond = strncmp(word, item, lenWord); + if (0 != cond) + break; + --pivot; + } + location = pivot; + if (ignoreCase) { + // Check for exact-case match + for (; pivot <= end; pivot++) { + lb->GetValue(pivot, item, maxItemLen); + if (!strncmp(word, item, lenWord)) { + location = pivot; + break; + } + if (CompareNCaseInsensitive(word, item, lenWord)) + break; + } + } + } else if (cond < 0) { + end = pivot - 1; + } else if (cond > 0) { + start = pivot + 1; + } + } + if (location == -1 && autoHide) + Cancel(); + else + lb->Select(location); +} + + diff --git a/scintilla/src/AutoComplete.h b/scintilla/src/AutoComplete.h new file mode 100644 index 00000000..0a38d80e --- /dev/null +++ b/scintilla/src/AutoComplete.h @@ -0,0 +1,78 @@ +// Scintilla source code edit control +/** @file AutoComplete.h + ** Defines the auto completion list box. + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef AUTOCOMPLETE_H +#define AUTOCOMPLETE_H + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +/** + */ +class AutoComplete { + bool active; + char stopChars[256]; + char fillUpChars[256]; + char separator; + char typesep; // Type seperator + +public: + bool ignoreCase; + bool chooseSingle; + ListBox *lb; + int posStart; + int startLen; + /// Should autocompletion be canceled if editor's currentPos <= startPos? + bool cancelAtStartPos; + bool autoHide; + bool dropRestOfWord; + + AutoComplete(); + ~AutoComplete(); + + /// Is the auto completion list displayed? + bool Active(); + + /// Display the auto completion list positioned to be near a character position + void Start(Window &parent, int ctrlID, int position, Point location, + int startLen_, int lineHeight, bool unicodeMode); + + /// The stop chars are characters which, when typed, cause the auto completion list to disappear + void SetStopChars(const char *stopChars_); + bool IsStopChar(char ch); + + /// The fillup chars are characters which, when typed, fill up the selected word + void SetFillUpChars(const char *fillUpChars_); + bool IsFillUpChar(char ch); + + /// The separator character is used when interpreting the list in SetList + void SetSeparator(char separator_); + char GetSeparator(); + + /// The typesep character is used for seperating the word from the type + void SetTypesep(char separator_); + char GetTypesep(); + + /// The list string contains a sequence of words separated by the separator character + void SetList(const char *list); + + void Show(bool show); + void Cancel(); + + /// Move the current list element by delta, scrolling appropriately + void Move(int delta); + + /// Select a list element that starts with word as the current element + void Select(const char *word); +}; + +#ifdef SCI_NAMESPACE +} +#endif + +#endif diff --git a/scintilla/src/CallTip.cxx b/scintilla/src/CallTip.cxx new file mode 100644 index 00000000..bfbd8db5 --- /dev/null +++ b/scintilla/src/CallTip.cxx @@ -0,0 +1,329 @@ +// Scintilla source code edit control +/** @file CallTip.cxx + ** Code for displaying call tips. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include + +#include "Platform.h" + +#include "Scintilla.h" +#include "CallTip.h" +#include + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static const int insetX = 5; // text inset in x from calltip border +static const int widthArrow = 14; + +CallTip::CallTip() { + wCallTip = 0; + inCallTipMode = false; + posStartCallTip = 0; + val = 0; + rectUp = PRectangle(0,0,0,0); + rectDown = PRectangle(0,0,0,0); + lineHeight = 1; + startHighlight = 0; + endHighlight = 0; + tabSize = 0; + useStyleCallTip = false; // for backwards compatibility + +#ifdef __APPLE__ + // proper apple colours for the default + colourBG.desired = ColourDesired(0xff, 0xff, 0xc6); + colourUnSel.desired = ColourDesired(0, 0, 0); +#else + colourBG.desired = ColourDesired(0xff, 0xff, 0xff); + colourUnSel.desired = ColourDesired(0x80, 0x80, 0x80); +#endif + colourSel.desired = ColourDesired(0, 0, 0x80); + colourShade.desired = ColourDesired(0, 0, 0); + colourLight.desired = ColourDesired(0xc0, 0xc0, 0xc0); +} + +CallTip::~CallTip() { + font.Release(); + wCallTip.Destroy(); + delete []val; + val = 0; +} + +void CallTip::RefreshColourPalette(Palette &pal, bool want) { + pal.WantFind(colourBG, want); + pal.WantFind(colourUnSel, want); + pal.WantFind(colourSel, want); + pal.WantFind(colourShade, want); + pal.WantFind(colourLight, want); +} + +// Although this test includes 0, we should never see a \0 character. +static bool IsArrowCharacter(char ch) { + return (ch == 0) || (ch == '\001') || (ch == '\002'); +} + +// We ignore tabs unless a tab width has been set. +bool CallTip::IsTabCharacter(char ch) { + return (tabSize > 0) && (ch == '\t'); +} + +int CallTip::NextTabPos(int x) { + if (tabSize > 0) { // paranoia... not called unless this is true + x -= insetX; // position relative to text + x = (x + tabSize) / tabSize; // tab "number" + return tabSize*x + insetX; // position of next tab + } else { + return x + 1; // arbitrary + } +} + +// Draw a section of the call tip that does not include \n in one colour. +// The text may include up to numEnds tabs or arrow characters. +void CallTip::DrawChunk(Surface *surface, int &x, const char *s, + int posStart, int posEnd, int ytext, PRectangle rcClient, + bool highlight, bool draw) { + s += posStart; + int len = posEnd - posStart; + + // Divide the text into sections that are all text, or that are + // single arrows or single tab characters (if tabSize > 0). + int maxEnd = 0; + const int numEnds = 10; + int ends[numEnds + 2]; + for (int i=0;i 0) + ends[maxEnd++] = i; + ends[maxEnd++] = i+1; + } + } + ends[maxEnd++] = len; + int startSeg = 0; + int xEnd; + for (int seg = 0; seg startSeg) { + if (IsArrowCharacter(s[startSeg])) { + bool upArrow = s[startSeg] == '\001'; + rcClient.left = x; + rcClient.right = rcClient.left + widthArrow; + if (draw) { + const int halfWidth = widthArrow / 2 - 3; + const int centreX = rcClient.left + widthArrow / 2 - 1; + const int centreY = (rcClient.top + rcClient.bottom) / 2; + surface->FillRectangle(rcClient, colourBG.allocated); + PRectangle rcClientInner(rcClient.left + 1, rcClient.top + 1, + rcClient.right - 2, rcClient.bottom - 1); + surface->FillRectangle(rcClientInner, colourUnSel.allocated); + + if (upArrow) { // Up arrow + Point pts[] = { + Point(centreX - halfWidth, centreY + halfWidth / 2), + Point(centreX + halfWidth, centreY + halfWidth / 2), + Point(centreX, centreY - halfWidth + halfWidth / 2), + }; + surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), + colourBG.allocated, colourBG.allocated); + } else { // Down arrow + Point pts[] = { + Point(centreX - halfWidth, centreY - halfWidth / 2), + Point(centreX + halfWidth, centreY - halfWidth / 2), + Point(centreX, centreY + halfWidth - halfWidth / 2), + }; + surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), + colourBG.allocated, colourBG.allocated); + } + } + xEnd = rcClient.right; + offsetMain = xEnd; + if (upArrow) { + rectUp = rcClient; + } else { + rectDown = rcClient; + } + } else if (IsTabCharacter(s[startSeg])) { + xEnd = NextTabPos(x); + } else { + xEnd = x + surface->WidthText(font, s + startSeg, endSeg - startSeg); + if (draw) { + rcClient.left = x; + rcClient.right = xEnd; + surface->DrawTextTransparent(rcClient, font, ytext, + s+startSeg, endSeg - startSeg, + highlight ? colourSel.allocated : colourUnSel.allocated); + } + } + x = xEnd; + startSeg = endSeg; + } + } +} + +int CallTip::PaintContents(Surface *surfaceWindow, bool draw) { + PRectangle rcClientPos = wCallTip.GetClientPosition(); + PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, + rcClientPos.bottom - rcClientPos.top); + PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); + + // To make a nice small call tip window, it is only sized to fit most normal characters without accents + int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font); + + // For each line... + // Draw the definition in three parts: before highlight, highlighted, after highlight + int ytext = rcClient.top + ascent + 1; + rcClient.bottom = ytext + surfaceWindow->Descent(font) + 1; + char *chunkVal = val; + bool moreChunks = true; + int maxWidth = 0; + + while (moreChunks) { + char *chunkEnd = strchr(chunkVal, '\n'); + if (chunkEnd == NULL) { + chunkEnd = chunkVal + strlen(chunkVal); + moreChunks = false; + } + int chunkOffset = chunkVal - val; + int chunkLength = chunkEnd - chunkVal; + int chunkEndOffset = chunkOffset + chunkLength; + int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset); + thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset); + thisStartHighlight -= chunkOffset; + int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset); + thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset); + thisEndHighlight -= chunkOffset; + rcClient.top = ytext - ascent - 1; + + int x = insetX; // start each line at this inset + + DrawChunk(surfaceWindow, x, chunkVal, 0, thisStartHighlight, + ytext, rcClient, false, draw); + DrawChunk(surfaceWindow, x, chunkVal, thisStartHighlight, thisEndHighlight, + ytext, rcClient, true, draw); + DrawChunk(surfaceWindow, x, chunkVal, thisEndHighlight, chunkLength, + ytext, rcClient, false, draw); + + chunkVal = chunkEnd + 1; + ytext += lineHeight; + rcClient.bottom += lineHeight; + maxWidth = Platform::Maximum(maxWidth, x); + } + return maxWidth; +} + +void CallTip::PaintCT(Surface *surfaceWindow) { + if (!val) + return; + PRectangle rcClientPos = wCallTip.GetClientPosition(); + PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, + rcClientPos.bottom - rcClientPos.top); + PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); + + surfaceWindow->FillRectangle(rcClient, colourBG.allocated); + + offsetMain = insetX; // initial alignment assuming no arrows + PaintContents(surfaceWindow, true); + +#ifndef __APPLE__ + // OSX doesn't put borders on "help tags" + // Draw a raised border around the edges of the window + surfaceWindow->MoveTo(0, rcClientSize.bottom - 1); + surfaceWindow->PenColour(colourShade.allocated); + surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1); + surfaceWindow->LineTo(rcClientSize.right - 1, 0); + surfaceWindow->PenColour(colourLight.allocated); + surfaceWindow->LineTo(0, 0); + surfaceWindow->LineTo(0, rcClientSize.bottom - 1); +#endif +} + +void CallTip::MouseClick(Point pt) { + clickPlace = 0; + if (rectUp.Contains(pt)) + clickPlace = 1; + if (rectDown.Contains(pt)) + clickPlace = 2; +} + +PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn, + const char *faceName, int size, + int codePage_, int characterSet, Window &wParent) { + clickPlace = 0; + if (val) + delete []val; + val = new char[strlen(defn) + 1]; + if (!val) + return PRectangle(); + strcpy(val, defn); + codePage = codePage_; + Surface *surfaceMeasure = Surface::Allocate(); + if (!surfaceMeasure) + return PRectangle(); + surfaceMeasure->Init(wParent.GetID()); + surfaceMeasure->SetUnicodeMode(SC_CP_UTF8 == codePage); + surfaceMeasure->SetDBCSMode(codePage); + startHighlight = 0; + endHighlight = 0; + inCallTipMode = true; + posStartCallTip = pos; + int deviceHeight = surfaceMeasure->DeviceHeightFont(size); + font.Create(faceName, characterSet, deviceHeight, false, false); + // Look for multiple lines in the text + // Only support \n here - simply means container must avoid \r! + int numLines = 1; + const char *newline; + const char *look = val; + rectUp = PRectangle(0,0,0,0); + rectDown = PRectangle(0,0,0,0); + offsetMain = insetX; // changed to right edge of any arrows + int width = PaintContents(surfaceMeasure, false) + insetX; + while ((newline = strchr(look, '\n')) != NULL) { + look = newline + 1; + numLines++; + } + lineHeight = surfaceMeasure->Height(font); + + // Extra line for border and an empty line at top and bottom. The returned + // rectangle is aligned to the right edge of the last arrow encountered in + // the tip text, else to the tip text left edge. + int height = lineHeight * numLines - surfaceMeasure->InternalLeading(font) + 2 + 2; + delete surfaceMeasure; + return PRectangle(pt.x - offsetMain, pt.y + 1, pt.x + width - offsetMain, pt.y + 1 + height); +} + +void CallTip::CallTipCancel() { + inCallTipMode = false; + if (wCallTip.Created()) { + wCallTip.Destroy(); + } +} + +void CallTip::SetHighlight(int start, int end) { + // Avoid flashing by checking something has really changed + if ((start != startHighlight) || (end != endHighlight)) { + startHighlight = start; + endHighlight = end; + if (wCallTip.Created()) { + wCallTip.InvalidateAll(); + } + } +} + +// Set the tab size (sizes > 0 enable the use of tabs). This also enables the +// use of the STYLE_CALLTIP. +void CallTip::SetTabSize(int tabSz) { + tabSize = tabSz; + useStyleCallTip = true; +} + +// It might be better to have two access functions for this and to use +// them for all settings of colours. +void CallTip::SetForeBack(const ColourPair &fore, const ColourPair &back) { + colourBG = back; + colourUnSel = fore; +} diff --git a/scintilla/src/CallTip.h b/scintilla/src/CallTip.h new file mode 100644 index 00000000..52fddd13 --- /dev/null +++ b/scintilla/src/CallTip.h @@ -0,0 +1,87 @@ +// Scintilla source code edit control +/** @file CallTip.h + ** Interface to the call tip control. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef CALLTIP_H +#define CALLTIP_H + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +/** + */ +class CallTip { + int startHighlight; // character offset to start and... + int endHighlight; // ...end of highlighted text + char *val; + Font font; + PRectangle rectUp; // rectangle of last up angle in the tip + PRectangle rectDown; // rectangle of last down arrow in the tip + int lineHeight; // vertical line spacing + int offsetMain; // The alignment point of the call tip + int tabSize; // Tab size in pixels, <=0 no TAB expand + bool useStyleCallTip; // if true, STYLE_CALLTIP should be used + + // Private so CallTip objects can not be copied + CallTip(const CallTip &) {} + CallTip &operator=(const CallTip &) { return *this; } + void DrawChunk(Surface *surface, int &x, const char *s, + int posStart, int posEnd, int ytext, PRectangle rcClient, + bool highlight, bool draw); + int PaintContents(Surface *surfaceWindow, bool draw); + bool IsTabCharacter(char c); + int NextTabPos(int x); + +public: + Window wCallTip; + Window wDraw; + bool inCallTipMode; + int posStartCallTip; + ColourPair colourBG; + ColourPair colourUnSel; + ColourPair colourSel; + ColourPair colourShade; + ColourPair colourLight; + int codePage; + int clickPlace; + + CallTip(); + ~CallTip(); + + /// Claim or accept palette entries for the colours required to paint a calltip. + void RefreshColourPalette(Palette &pal, bool want); + + void PaintCT(Surface *surfaceWindow); + + void MouseClick(Point pt); + + /// Setup the calltip and return a rectangle of the area required. + PRectangle CallTipStart(int pos, Point pt, const char *defn, + const char *faceName, int size, int codePage_, + int characterSet, Window &wParent); + + void CallTipCancel(); + + /// Set a range of characters to be displayed in a highlight style. + /// Commonly used to highlight the current parameter. + void SetHighlight(int start, int end); + + /// Set the tab size in pixels for the call tip. 0 or -ve means no tab expand. + void SetTabSize(int tabSz); + + /// Used to determine which STYLE_xxxx to use for call tip information + bool UseStyleCallTip() const { return useStyleCallTip;} + + // Modify foreground and background colours + void SetForeBack(const ColourPair &fore, const ColourPair &back); +}; + +#ifdef SCI_NAMESPACE +} +#endif + +#endif diff --git a/scintilla/src/CellBuffer.cxx b/scintilla/src/CellBuffer.cxx new file mode 100644 index 00000000..15ff9d20 --- /dev/null +++ b/scintilla/src/CellBuffer.cxx @@ -0,0 +1,935 @@ +// Scintilla source code edit control +/** @file CellBuffer.cxx + ** Manages a buffer of cells. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include + +#include "Platform.h" + +#include "Scintilla.h" +#include "SplitVector.h" +#include "Partitioning.h" +#include "CellBuffer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +MarkerHandleSet::MarkerHandleSet() { + root = 0; +} + +MarkerHandleSet::~MarkerHandleSet() { + MarkerHandleNumber *mhn = root; + while (mhn) { + MarkerHandleNumber *mhnToFree = mhn; + mhn = mhn->next; + delete mhnToFree; + } + root = 0; +} + +int MarkerHandleSet::Length() const { + int c = 0; + MarkerHandleNumber *mhn = root; + while (mhn) { + c++; + mhn = mhn->next; + } + return c; +} + +int MarkerHandleSet::NumberFromHandle(int handle) const { + MarkerHandleNumber *mhn = root; + while (mhn) { + if (mhn->handle == handle) { + return mhn->number; + } + mhn = mhn->next; + } + return - 1; +} + +int MarkerHandleSet::MarkValue() const { + unsigned int m = 0; + MarkerHandleNumber *mhn = root; + while (mhn) { + m |= (1 << mhn->number); + mhn = mhn->next; + } + return m; +} + +bool MarkerHandleSet::Contains(int handle) const { + MarkerHandleNumber *mhn = root; + while (mhn) { + if (mhn->handle == handle) { + return true; + } + mhn = mhn->next; + } + return false; +} + +bool MarkerHandleSet::InsertHandle(int handle, int markerNum) { + MarkerHandleNumber *mhn = new MarkerHandleNumber; + if (!mhn) + return false; + mhn->handle = handle; + mhn->number = markerNum; + mhn->next = root; + root = mhn; + return true; +} + +void MarkerHandleSet::RemoveHandle(int handle) { + MarkerHandleNumber **pmhn = &root; + while (*pmhn) { + MarkerHandleNumber *mhn = *pmhn; + if (mhn->handle == handle) { + *pmhn = mhn->next; + delete mhn; + return; + } + pmhn = &((*pmhn)->next); + } +} + +bool MarkerHandleSet::RemoveNumber(int markerNum) { + bool performedDeletion = false; + MarkerHandleNumber **pmhn = &root; + while (*pmhn) { + MarkerHandleNumber *mhn = *pmhn; + if (mhn->number == markerNum) { + *pmhn = mhn->next; + delete mhn; + performedDeletion = true; + } else { + pmhn = &((*pmhn)->next); + } + } + return performedDeletion; +} + +void MarkerHandleSet::CombineWith(MarkerHandleSet *other) { + MarkerHandleNumber **pmhn = &root; + while (*pmhn) { + pmhn = &((*pmhn)->next); + } + *pmhn = other->root; + other->root = 0; +} + +LineVector::LineVector() : starts(256) { + handleCurrent = 1; + + Init(); +} + +LineVector::~LineVector() { + starts.DeleteAll(); + for (int line = 0; line < markers.Length(); line++) { + delete markers[line]; + markers[line] = 0; + } + markers.DeleteAll(); + levels.DeleteAll(); +} + +void LineVector::Init() { + starts.DeleteAll(); + for (int line = 0; line < markers.Length(); line++) { + delete markers[line]; + markers[line] = 0; + } + markers.DeleteAll(); + levels.DeleteAll(); +} + +void LineVector::ExpandLevels(int sizeNew) { + levels.InsertValue(levels.Length(), sizeNew - levels.Length(), SC_FOLDLEVELBASE); +} + +void LineVector::ClearLevels() { + levels.DeleteAll(); +} + +int LineVector::SetLevel(int line, int level) { + int prev = 0; + if ((line >= 0) && (line < Lines())) { + if (!levels.Length()) { + ExpandLevels(Lines() + 1); + } + prev = levels[line]; + if (prev != level) { + levels[line] = level; + } + } + return prev; +} + +int LineVector::GetLevel(int line) { + if (levels.Length() && (line >= 0) && (line < Lines())) { + return levels[line]; + } else { + return SC_FOLDLEVELBASE; + } +} + +void LineVector::InsertText(int line, int delta) { + starts.InsertText(line, delta); +} + +void LineVector::InsertLine(int line, int position) { + starts.InsertPartition(line, position); + if (markers.Length()) { + markers.Insert(line, 0); + } + if (levels.Length()) { + int level = SC_FOLDLEVELBASE; + if ((line > 0) && (line < Lines())) { + level = levels[line-1] & ~SC_FOLDLEVELWHITEFLAG; + } + levels.InsertValue(line, 1, level); + } +} + +void LineVector::SetLineStart(int line, int position) { + starts.SetPartitionStartPosition(line, position); +} + +void LineVector::RemoveLine(int line) { + starts.RemovePartition(line); + // Retain the markers from the deleted line by oring them into the previous line + if (markers.Length()) { + if (line > 0) { + MergeMarkers(line - 1); + } + markers.Delete(line); + } + if (levels.Length()) { + // Move up following lines but merge header flag from this line + // to line before to avoid a temporary disappearence causing expansion. + int firstHeader = levels[line] & SC_FOLDLEVELHEADERFLAG; + levels.Delete(line); + if (line > 0) + levels[line-1] |= firstHeader; + } +} + +int LineVector::LineFromPosition(int pos) { + return starts.PartitionFromPosition(pos); +} + +int LineVector::MarkValue(int line) { + if (markers.Length() && markers[line]) + return markers[line]->MarkValue(); + else + return 0; +} + +int LineVector::AddMark(int line, int markerNum) { + handleCurrent++; + if (!markers.Length()) { + // No existing markers so allocate one element per line + markers.InsertValue(0, Lines(), 0); + } + if (!markers[line]) { + // Need new structure to hold marker handle + markers[line] = new MarkerHandleSet(); + if (!markers[line]) + return - 1; + } + markers[line]->InsertHandle(handleCurrent, markerNum); + + return handleCurrent; +} + +void LineVector::MergeMarkers(int pos) { + if (markers[pos + 1] != NULL) { + if (markers[pos] == NULL) + markers[pos] = new MarkerHandleSet; + markers[pos]->CombineWith(markers[pos + 1]); + delete markers[pos + 1]; + markers[pos + 1] = NULL; + } +} + +void LineVector::DeleteMark(int line, int markerNum, bool all) { + if (markers.Length() && markers[line]) { + if (markerNum == -1) { + delete markers[line]; + markers[line] = NULL; + } else { + bool performedDeletion = markers[line]->RemoveNumber(markerNum); + while (all && performedDeletion) { + performedDeletion = markers[line]->RemoveNumber(markerNum); + } + if (markers[line]->Length() == 0) { + delete markers[line]; + markers[line] = NULL; + } + } + } +} + +void LineVector::DeleteMarkFromHandle(int markerHandle) { + int line = LineFromHandle(markerHandle); + if (line >= 0) { + markers[line]->RemoveHandle(markerHandle); + if (markers[line]->Length() == 0) { + delete markers[line]; + markers[line] = NULL; + } + } +} + +int LineVector::LineFromHandle(int markerHandle) { + if (markers.Length()) { + for (int line = 0; line < Lines(); line++) { + if (markers[line]) { + if (markers[line]->Contains(markerHandle)) { + return line; + } + } + } + } + return -1; +} + +Action::Action() { + at = startAction; + position = 0; + data = 0; + lenData = 0; +} + +Action::~Action() { + Destroy(); +} + +void Action::Create(actionType at_, int position_, char *data_, int lenData_, bool mayCoalesce_) { + delete []data; + position = position_; + at = at_; + data = data_; + lenData = lenData_; + mayCoalesce = mayCoalesce_; +} + +void Action::Destroy() { + delete []data; + data = 0; +} + +void Action::Grab(Action *source) { + delete []data; + + position = source->position; + at = source->at; + data = source->data; + lenData = source->lenData; + mayCoalesce = source->mayCoalesce; + + // Ownership of source data transferred to this + source->position = 0; + source->at = startAction; + source->data = 0; + source->lenData = 0; + source->mayCoalesce = true; +} + +// The undo history stores a sequence of user operations that represent the user's view of the +// commands executed on the text. +// Each user operation contains a sequence of text insertion and text deletion actions. +// All the user operations are stored in a list of individual actions with 'start' actions used +// as delimiters between user operations. +// Initially there is one start action in the history. +// As each action is performed, it is recorded in the history. The action may either become +// part of the current user operation or may start a new user operation. If it is to be part of the +// current operation, then it overwrites the current last action. If it is to be part of a new +// operation, it is appended after the current last action. +// After writing the new action, a new start action is appended at the end of the history. +// The decision of whether to start a new user operation is based upon two factors. If a +// compound operation has been explicitly started by calling BeginUndoAction and no matching +// EndUndoAction (these calls nest) has been called, then the action is coalesced into the current +// operation. If there is no outstanding BeginUndoAction call then a new operation is started +// unless it looks as if the new action is caused by the user typing or deleting a stream of text. +// Sequences that look like typing or deletion are coalesced into a single user operation. + +UndoHistory::UndoHistory() { + + lenActions = 100; + actions = new Action[lenActions]; + maxAction = 0; + currentAction = 0; + undoSequenceDepth = 0; + savePoint = 0; + + actions[currentAction].Create(startAction); +} + +UndoHistory::~UndoHistory() { + delete []actions; + actions = 0; +} + +void UndoHistory::EnsureUndoRoom() { + // Have to test that there is room for 2 more actions in the array + // as two actions may be created by the calling function + if (currentAction >= (lenActions - 2)) { + // Run out of undo nodes so extend the array + int lenActionsNew = lenActions * 2; + Action *actionsNew = new Action[lenActionsNew]; + if (!actionsNew) + return; + for (int act = 0; act <= currentAction; act++) + actionsNew[act].Grab(&actions[act]); + delete []actions; + lenActions = lenActionsNew; + actions = actionsNew; + } +} + +void UndoHistory::AppendAction(actionType at, int position, char *data, int lengthData, + bool &startSequence) { + EnsureUndoRoom(); + //Platform::DebugPrintf("%% %d action %d %d %d\n", at, position, lengthData, currentAction); + //Platform::DebugPrintf("^ %d action %d %d\n", actions[currentAction - 1].at, + // actions[currentAction - 1].position, actions[currentAction - 1].lenData); + if (currentAction < savePoint) { + savePoint = -1; + } + int oldCurrentAction = currentAction; + if (currentAction >= 1) { + if (0 == undoSequenceDepth) { + // Top level actions may not always be coalesced + Action &actPrevious = actions[currentAction - 1]; + // See if current action can be coalesced into previous action + // Will work if both are inserts or deletes and position is same + if (at != actPrevious.at) { + currentAction++; + } else if (currentAction == savePoint) { + currentAction++; + } else if ((at == insertAction) && + (position != (actPrevious.position + actPrevious.lenData))) { + // Insertions must be immediately after to coalesce + currentAction++; + } else if (!actions[currentAction].mayCoalesce) { + // Not allowed to coalesce if this set + currentAction++; + } else if (at == removeAction) { + if ((lengthData == 1) || (lengthData == 2)){ + if ((position + lengthData) == actPrevious.position) { + ; // Backspace -> OK + } else if (position == actPrevious.position) { + ; // Delete -> OK + } else { + // Removals must be at same position to coalesce + currentAction++; + } + } else { + // Removals must be of one character to coalesce + currentAction++; + } + } else { + // Action coalesced. + } + + } else { + // Actions not at top level are always coalesced unless this is after return to top level + if (!actions[currentAction].mayCoalesce) + currentAction++; + } + } else { + currentAction++; + } + startSequence = oldCurrentAction != currentAction; + actions[currentAction].Create(at, position, data, lengthData); + currentAction++; + actions[currentAction].Create(startAction); + maxAction = currentAction; +} + +void UndoHistory::BeginUndoAction() { + EnsureUndoRoom(); + if (undoSequenceDepth == 0) { + if (actions[currentAction].at != startAction) { + currentAction++; + actions[currentAction].Create(startAction); + maxAction = currentAction; + } + actions[currentAction].mayCoalesce = false; + } + undoSequenceDepth++; +} + +void UndoHistory::EndUndoAction() { + PLATFORM_ASSERT(undoSequenceDepth > 0); + EnsureUndoRoom(); + undoSequenceDepth--; + if (0 == undoSequenceDepth) { + if (actions[currentAction].at != startAction) { + currentAction++; + actions[currentAction].Create(startAction); + maxAction = currentAction; + } + actions[currentAction].mayCoalesce = false; + } +} + +void UndoHistory::DropUndoSequence() { + undoSequenceDepth = 0; +} + +void UndoHistory::DeleteUndoHistory() { + for (int i = 1; i < maxAction; i++) + actions[i].Destroy(); + maxAction = 0; + currentAction = 0; + actions[currentAction].Create(startAction); + savePoint = 0; +} + +void UndoHistory::SetSavePoint() { + savePoint = currentAction; +} + +bool UndoHistory::IsSavePoint() const { + return savePoint == currentAction; +} + +bool UndoHistory::CanUndo() const { + return (currentAction > 0) && (maxAction > 0); +} + +int UndoHistory::StartUndo() { + // Drop any trailing startAction + if (actions[currentAction].at == startAction && currentAction > 0) + currentAction--; + + // Count the steps in this action + int act = currentAction; + while (actions[act].at != startAction && act > 0) { + act--; + } + return currentAction - act; +} + +const Action &UndoHistory::GetUndoStep() const { + return actions[currentAction]; +} + +void UndoHistory::CompletedUndoStep() { + currentAction--; +} + +bool UndoHistory::CanRedo() const { + return maxAction > currentAction; +} + +int UndoHistory::StartRedo() { + // Drop any leading startAction + if (actions[currentAction].at == startAction && currentAction < maxAction) + currentAction++; + + // Count the steps in this action + int act = currentAction; + while (actions[act].at != startAction && act < maxAction) { + act++; + } + return act - currentAction; +} + +const Action &UndoHistory::GetRedoStep() const { + return actions[currentAction]; +} + +void UndoHistory::CompletedRedoStep() { + currentAction++; +} + +CellBuffer::CellBuffer() { + readOnly = false; + collectingUndo = true; +} + +CellBuffer::~CellBuffer() { +} + +char CellBuffer::CharAt(int position) const { + return substance.ValueAt(position); +} + +void CellBuffer::GetCharRange(char *buffer, int position, int lengthRetrieve) { + if (lengthRetrieve < 0) + return; + if (position < 0) + return; + if ((position + lengthRetrieve) > substance.Length()) { + Platform::DebugPrintf("Bad GetCharRange %d for %d of %d\n", position, + lengthRetrieve, substance.Length()); + return; + } + + for (int i=0; i((curVal & ~mask) | styleValue)); + return true; + } else { + return false; + } +} + +bool CellBuffer::SetStyleFor(int position, int lengthStyle, char styleValue, char mask) { + bool changed = false; + PLATFORM_ASSERT(lengthStyle == 0 || + (lengthStyle > 0 && lengthStyle + position <= style.Length())); + while (lengthStyle--) { + char curVal = style.ValueAt(position); + if ((curVal & mask) != styleValue) { + style.SetValueAt(position, static_cast((curVal & ~mask) | styleValue)); + changed = true; + } + position++; + } + return changed; +} + +// The char* returned is to an allocation owned by the undo history +const char *CellBuffer::DeleteChars(int position, int deleteLength, bool &startSequence) { + // InsertString and DeleteChars are the bottleneck though which all changes occur + PLATFORM_ASSERT(deleteLength > 0); + char *data = 0; + if (!readOnly) { + if (collectingUndo) { + // Save into the undo/redo stack, but only the characters - not the formatting + data = new char[deleteLength]; + for (int i = 0; i < deleteLength; i++) { + data[i] = substance.ValueAt(position + i); + } + uh.AppendAction(removeAction, position, data, deleteLength, startSequence); + } + + BasicDeleteChars(position, deleteLength); + } + return data; +} + +int CellBuffer::Length() const { + return substance.Length(); +} + +void CellBuffer::Allocate(int newSize) { + substance.ReAllocate(newSize); + style.ReAllocate(newSize); +} + +int CellBuffer::Lines() const { + return lv.Lines(); +} + +int CellBuffer::LineStart(int line) const { + if (line < 0) + return 0; + else if (line >= Lines()) + return Length(); + else + return lv.LineStart(line); +} + +bool CellBuffer::IsReadOnly() { + return readOnly; +} + +void CellBuffer::SetReadOnly(bool set) { + readOnly = set; +} + +void CellBuffer::SetSavePoint() { + uh.SetSavePoint(); +} + +bool CellBuffer::IsSavePoint() { + return uh.IsSavePoint(); +} + +int CellBuffer::AddMark(int line, int markerNum) { + if ((line >= 0) && (line < Lines())) { + return lv.AddMark(line, markerNum); + } + return - 1; +} + +void CellBuffer::DeleteMark(int line, int markerNum) { + if ((line >= 0) && (line < Lines())) { + lv.DeleteMark(line, markerNum, false); + } +} + +void CellBuffer::DeleteMarkFromHandle(int markerHandle) { + lv.DeleteMarkFromHandle(markerHandle); +} + +int CellBuffer::GetMark(int line) { + if ((line >= 0) && (line < Lines())) + return lv.MarkValue(line); + return 0; +} + +void CellBuffer::DeleteAllMarks(int markerNum) { + for (int line = 0; line < Lines(); line++) { + lv.DeleteMark(line, markerNum, true); + } +} + +int CellBuffer::LineFromHandle(int markerHandle) { + return lv.LineFromHandle(markerHandle); +} + +// Without undo + +void CellBuffer::InsertLine(int line, int position) { + lv.InsertLine(line, position); + if (lineStates.Length()) { + lineStates.EnsureLength(line); + lineStates.Insert(line, 0); + } +} + +void CellBuffer::RemoveLine(int line) { + lv.RemoveLine(line); + if (lineStates.Length() > line) { + lineStates.Delete(line); + } +} + +void CellBuffer::BasicInsertString(int position, const char *s, int insertLength) { + if (insertLength == 0) + return; + PLATFORM_ASSERT(insertLength > 0); + + substance.InsertFromArray(position, s, 0, insertLength); + style.InsertValue(position, insertLength, 0); + + int lineInsert = lv.LineFromPosition(position) + 1; + // Point all the lines after the insertion point further along in the buffer + lv.InsertText(lineInsert-1, insertLength); + char chPrev = substance.ValueAt(position - 1); + char chAfter = substance.ValueAt(position + insertLength); + if (chPrev == '\r' && chAfter == '\n') { + // Splitting up a crlf pair at position + InsertLine(lineInsert, position); + lineInsert++; + } + char ch = ' '; + for (int i = 0; i < insertLength; i++) { + ch = s[i]; + if (ch == '\r') { + InsertLine(lineInsert, (position + i) + 1); + lineInsert++; + } else if (ch == '\n') { + if (chPrev == '\r') { + // Patch up what was end of line + lv.SetLineStart(lineInsert - 1, (position + i) + 1); + } else { + InsertLine(lineInsert, (position + i) + 1); + lineInsert++; + } + } + chPrev = ch; + } + // Joining two lines where last insertion is cr and following substance starts with lf + if (chAfter == '\n') { + if (ch == '\r') { + // End of line already in buffer so drop the newly created one + RemoveLine(lineInsert - 1); + } + } +} + +void CellBuffer::BasicDeleteChars(int position, int deleteLength) { + if (deleteLength == 0) + return; + + if ((position == 0) && (deleteLength == substance.Length())) { + // If whole buffer is being deleted, faster to reinitialise lines data + // than to delete each line. + lv.Init(); + } else { + // Have to fix up line positions before doing deletion as looking at text in buffer + // to work out which lines have been removed + + int lineRemove = lv.LineFromPosition(position) + 1; + lv.InsertText(lineRemove-1, - (deleteLength)); + char chPrev = substance.ValueAt(position - 1); + char chBefore = chPrev; + char chNext = substance.ValueAt(position); + bool ignoreNL = false; + if (chPrev == '\r' && chNext == '\n') { + // Move back one + lv.SetLineStart(lineRemove, position); + lineRemove++; + ignoreNL = true; // First \n is not real deletion + } + + char ch = chNext; + for (int i = 0; i < deleteLength; i++) { + chNext = substance.ValueAt(position + i + 1); + if (ch == '\r') { + if (chNext != '\n') { + RemoveLine(lineRemove); + } + } else if (ch == '\n') { + if (ignoreNL) { + ignoreNL = false; // Further \n are real deletions + } else { + RemoveLine(lineRemove); + } + } + + ch = chNext; + } + // May have to fix up end if last deletion causes cr to be next to lf + // or removes one of a crlf pair + char chAfter = substance.ValueAt(position + deleteLength); + if (chBefore == '\r' && chAfter == '\n') { + // Using lineRemove-1 as cr ended line before start of deletion + RemoveLine(lineRemove - 1); + lv.SetLineStart(lineRemove - 1, position + 1); + } + } + substance.DeleteRange(position, deleteLength); + style.DeleteRange(position, deleteLength); +} + +bool CellBuffer::SetUndoCollection(bool collectUndo) { + collectingUndo = collectUndo; + uh.DropUndoSequence(); + return collectingUndo; +} + +bool CellBuffer::IsCollectingUndo() { + return collectingUndo; +} + +void CellBuffer::BeginUndoAction() { + uh.BeginUndoAction(); +} + +void CellBuffer::EndUndoAction() { + uh.EndUndoAction(); +} + +void CellBuffer::DeleteUndoHistory() { + uh.DeleteUndoHistory(); +} + +bool CellBuffer::CanUndo() { + return uh.CanUndo(); +} + +int CellBuffer::StartUndo() { + return uh.StartUndo(); +} + +const Action &CellBuffer::GetUndoStep() const { + return uh.GetUndoStep(); +} + +void CellBuffer::PerformUndoStep() { + const Action &actionStep = uh.GetUndoStep(); + if (actionStep.at == insertAction) { + BasicDeleteChars(actionStep.position, actionStep.lenData); + } else if (actionStep.at == removeAction) { + BasicInsertString(actionStep.position, actionStep.data, actionStep.lenData); + } + uh.CompletedUndoStep(); +} + +bool CellBuffer::CanRedo() { + return uh.CanRedo(); +} + +int CellBuffer::StartRedo() { + return uh.StartRedo(); +} + +const Action &CellBuffer::GetRedoStep() const { + return uh.GetRedoStep(); +} + +void CellBuffer::PerformRedoStep() { + const Action &actionStep = uh.GetRedoStep(); + if (actionStep.at == insertAction) { + BasicInsertString(actionStep.position, actionStep.data, actionStep.lenData); + } else if (actionStep.at == removeAction) { + BasicDeleteChars(actionStep.position, actionStep.lenData); + } + uh.CompletedRedoStep(); +} + +int CellBuffer::SetLineState(int line, int state) { + lineStates.EnsureLength(line + 1); + int stateOld = lineStates[line]; + lineStates[line] = state; + return stateOld; +} + +int CellBuffer::GetLineState(int line) { + lineStates.EnsureLength(line + 1); + return lineStates[line]; +} + +int CellBuffer::GetMaxLineState() { + return lineStates.Length(); +} + +int CellBuffer::SetLevel(int line, int level) { + return lv.SetLevel(line, level); +} + +int CellBuffer::GetLevel(int line) { + return lv.GetLevel(line); +} + +void CellBuffer::ClearLevels() { + lv.ClearLevels(); +} diff --git a/scintilla/src/CellBuffer.h b/scintilla/src/CellBuffer.h new file mode 100644 index 00000000..2a303868 --- /dev/null +++ b/scintilla/src/CellBuffer.h @@ -0,0 +1,241 @@ +// Scintilla source code edit control +/** @file CellBuffer.h + ** Manages the text of the document. + **/ +// Copyright 1998-2004 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef CELLBUFFER_H +#define CELLBUFFER_H + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +/** + * This holds the marker identifier and the marker type to display. + * MarkerHandleNumbers are members of lists. + */ +struct MarkerHandleNumber { + int handle; + int number; + MarkerHandleNumber *next; +}; + +/** + * A marker handle set contains any number of MarkerHandleNumbers. + */ +class MarkerHandleSet { + MarkerHandleNumber *root; + +public: + MarkerHandleSet(); + ~MarkerHandleSet(); + int Length() const; + int NumberFromHandle(int handle) const; + int MarkValue() const; ///< Bit set of marker numbers. + bool Contains(int handle) const; + bool InsertHandle(int handle, int markerNum); + void RemoveHandle(int handle); + bool RemoveNumber(int markerNum); + void CombineWith(MarkerHandleSet *other); +}; + +/** + * The line vector contains information about each of the lines in a cell buffer. + */ +class LineVector { + + Partitioning starts; + SplitVector markers; + SplitVector levels; + /// Handles are allocated sequentially and should never have to be reused as 32 bit ints are very big. + int handleCurrent; + +public: + + LineVector(); + ~LineVector(); + void Init(); + + void ExpandLevels(int sizeNew=-1); + void ClearLevels(); + int SetLevel(int line, int level); + int GetLevel(int line); + + void InsertText(int line, int delta); + void InsertLine(int line, int position); + void SetLineStart(int line, int position); + void RemoveLine(int line); + int Lines() const { + return starts.Partitions(); + } + int LineFromPosition(int pos); + int LineStart(int line) const { + return starts.PositionFromPartition(line); + } + + int MarkValue(int line); + int AddMark(int line, int marker); + void MergeMarkers(int pos); + void DeleteMark(int line, int markerNum, bool all); + void DeleteMarkFromHandle(int markerHandle); + int LineFromHandle(int markerHandle); +}; + +enum actionType { insertAction, removeAction, startAction }; + +/** + * Actions are used to store all the information required to perform one undo/redo step. + */ +class Action { +public: + actionType at; + int position; + char *data; + int lenData; + bool mayCoalesce; + + Action(); + ~Action(); + void Create(actionType at_, int position_=0, char *data_=0, int lenData_=0, bool mayCoalesce_=true); + void Destroy(); + void Grab(Action *source); +}; + +/** + * + */ +class UndoHistory { + Action *actions; + int lenActions; + int maxAction; + int currentAction; + int undoSequenceDepth; + int savePoint; + + void EnsureUndoRoom(); + +public: + UndoHistory(); + ~UndoHistory(); + + void AppendAction(actionType at, int position, char *data, int length, bool &startSequence); + + void BeginUndoAction(); + void EndUndoAction(); + void DropUndoSequence(); + void DeleteUndoHistory(); + + /// The save point is a marker in the undo stack where the container has stated that + /// the buffer was saved. Undo and redo can move over the save point. + void SetSavePoint(); + bool IsSavePoint() const; + + /// To perform an undo, StartUndo is called to retrieve the number of steps, then UndoStep is + /// called that many times. Similarly for redo. + bool CanUndo() const; + int StartUndo(); + const Action &GetUndoStep() const; + void CompletedUndoStep(); + bool CanRedo() const; + int StartRedo(); + const Action &GetRedoStep() const; + void CompletedRedoStep(); +}; + +/** + * Holder for an expandable array of characters that supports undo and line markers. + * Based on article "Data Structures in a Bit-Mapped Text Editor" + * by Wilfred J. Hansen, Byte January 1987, page 183. + */ +class CellBuffer { +private: + SplitVector substance; + SplitVector style; + bool readOnly; + + bool collectingUndo; + UndoHistory uh; + + LineVector lv; + + SplitVector lineStates; + +public: + + CellBuffer(); + ~CellBuffer(); + + /// Retrieving positions outside the range of the buffer works and returns 0 + char CharAt(int position) const; + void GetCharRange(char *buffer, int position, int lengthRetrieve); + char StyleAt(int position); + + int Length() const; + void Allocate(int newSize); + int Lines() const; + int LineStart(int line) const; + int LineFromPosition(int pos) { return lv.LineFromPosition(pos); } + void InsertLine(int line, int position); + void RemoveLine(int line); + const char *InsertString(int position, const char *s, int insertLength, bool &startSequence); + + /// Setting styles for positions outside the range of the buffer is safe and has no effect. + /// @return true if the style of a character is changed. + bool SetStyleAt(int position, char styleValue, char mask='\377'); + bool SetStyleFor(int position, int length, char styleValue, char mask); + + const char *DeleteChars(int position, int deleteLength, bool &startSequence); + + bool IsReadOnly(); + void SetReadOnly(bool set); + + /// The save point is a marker in the undo stack where the container has stated that + /// the buffer was saved. Undo and redo can move over the save point. + void SetSavePoint(); + bool IsSavePoint(); + + /// Line marker functions + int AddMark(int line, int markerNum); + void DeleteMark(int line, int markerNum); + void DeleteMarkFromHandle(int markerHandle); + int GetMark(int line); + void DeleteAllMarks(int markerNum); + int LineFromHandle(int markerHandle); + + /// Actions without undo + void BasicInsertString(int position, const char *s, int insertLength); + void BasicDeleteChars(int position, int deleteLength); + + bool SetUndoCollection(bool collectUndo); + bool IsCollectingUndo(); + void BeginUndoAction(); + void EndUndoAction(); + void DeleteUndoHistory(); + + /// To perform an undo, StartUndo is called to retrieve the number of steps, then UndoStep is + /// called that many times. Similarly for redo. + bool CanUndo(); + int StartUndo(); + const Action &GetUndoStep() const; + void PerformUndoStep(); + bool CanRedo(); + int StartRedo(); + const Action &GetRedoStep() const; + void PerformRedoStep(); + + int SetLineState(int line, int state); + int GetLineState(int line); + int GetMaxLineState(); + + int SetLevel(int line, int level); + int GetLevel(int line); + void ClearLevels(); +}; + +#ifdef SCI_NAMESPACE +} +#endif + +#endif diff --git a/scintilla/src/CharClassify.cxx b/scintilla/src/CharClassify.cxx new file mode 100644 index 00000000..76eb905c --- /dev/null +++ b/scintilla/src/CharClassify.cxx @@ -0,0 +1,43 @@ +// Scintilla source code edit control +/** @file CharClassify.cxx + ** Character classifications used by Document and RESearch. + **/ +// Copyright 2006 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include + +#include "CharClassify.h" + +// Shut up annoying Visual C++ warnings: +#ifdef _MSC_VER +#pragma warning(disable: 4514) +#endif + +CharClassify::CharClassify() { + SetDefaultCharClasses(true); +} + +void CharClassify::SetDefaultCharClasses(bool includeWordClass) { + // Initialize all char classes to default values + for (int ch = 0; ch < 256; ch++) { + if (ch == '\r' || ch == '\n') + charClass[ch] = ccNewLine; + else if (ch < 0x20 || ch == ' ') + charClass[ch] = ccSpace; + else if (includeWordClass && (ch >= 0x80 || isalnum(ch) || ch == '_')) + charClass[ch] = ccWord; + else + charClass[ch] = ccPunctuation; + } +} + +void CharClassify::SetCharClasses(const unsigned char *chars, cc newCharClass) { + // Apply the newCharClass to the specifed chars + if (chars) { + while (*chars) { + charClass[*chars] = static_cast(newCharClass); + chars++; + } + } +} diff --git a/scintilla/src/CharClassify.h b/scintilla/src/CharClassify.h new file mode 100644 index 00000000..d26f4b34 --- /dev/null +++ b/scintilla/src/CharClassify.h @@ -0,0 +1,25 @@ +// Scintilla source code edit control +/** @file CharClassify.h + ** Character classifications used by Document and RESearch. + **/ +// Copyright 2006 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef CHARCLASSIFY_H +#define CHARCLASSIFY_H + +class CharClassify { +public: + CharClassify(); + + enum cc { ccSpace, ccNewLine, ccWord, ccPunctuation }; + void SetDefaultCharClasses(bool includeWordClass); + void SetCharClasses(const unsigned char *chars, cc newCharClass); + cc GetClass(unsigned char ch) const { return static_cast(charClass[ch]);} + bool IsWord(unsigned char ch) const { return static_cast(charClass[ch]) == ccWord;} + +private: + enum { maxChar=256 }; + unsigned char charClass[maxChar]; // not type cc to save space +}; +#endif diff --git a/scintilla/src/CharacterSet.h b/scintilla/src/CharacterSet.h new file mode 100644 index 00000000..764ee642 --- /dev/null +++ b/scintilla/src/CharacterSet.h @@ -0,0 +1,58 @@ +// Scintilla source code edit control +/** @file CharacterSet.h + ** Encapsulates a set of characters. Used to test if a character is within a set. + **/ +// Copyright 2007 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +class CharacterSet { + int size; + bool valueAfter; + bool *bset; +public: + enum setBase { + setNone=0, + setLower=1, + setUpper=2, + setDigits=4, + setAlpha=setLower|setUpper, + setAlphaNum=setAlpha|setDigits + }; + CharacterSet(setBase base=setNone, const char *initialSet="", int size_=0x80, bool valueAfter_=false) { + size = size_; + valueAfter = valueAfter_; + bset = new bool[size]; + for (int i=0; i < size; i++) { + bset[i] = false; + } + AddString(initialSet); + if (base & setLower) + AddString("abcdefghijklmnopqrstuvwxyz"); + if (base & setUpper) + AddString("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); + if (base & setDigits) + AddString("0123456789"); + } + ~CharacterSet() { + delete []bset; + bset = 0; + size = 0; + } + void Add(int val) { + PLATFORM_ASSERT(val >= 0); + PLATFORM_ASSERT(val < size); + bset[val] = true; + } + void AddString(const char *CharacterSet) { + for (const char *cp=CharacterSet; *cp; cp++) { + int val = static_cast(*cp); + PLATFORM_ASSERT(val >= 0); + PLATFORM_ASSERT(val < size); + bset[val] = true; + } + } + bool Contains(int val) const { + PLATFORM_ASSERT(val >= 0); + return (val < size) ? bset[val] : valueAfter; + } +}; diff --git a/scintilla/src/ContractionState.cxx b/scintilla/src/ContractionState.cxx new file mode 100644 index 00000000..d6a6be4b --- /dev/null +++ b/scintilla/src/ContractionState.cxx @@ -0,0 +1,251 @@ +// Scintilla source code edit control +/** @file ContractionState.cxx + ** Manages visibility of lines for folding and wrapping. + **/ +// Copyright 1998-2007 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include + +#include "Platform.h" + +#include "SplitVector.h" +#include "Partitioning.h" +#include "RunStyles.h" +#include "ContractionState.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +ContractionState::ContractionState() : visible(0), expanded(0), heights(0), displayLines(0), linesInDocument(1) { + //InsertLine(0); +} + +ContractionState::~ContractionState() { + Clear(); +} + +void ContractionState::EnsureData() { + if (OneToOne()) { + visible = new RunStyles(); + expanded = new RunStyles(); + heights = new RunStyles(); + displayLines = new Partitioning(4); + InsertLines(0, linesInDocument); + } +} + +void ContractionState::Clear() { + delete visible; + visible = 0; + delete expanded; + expanded = 0; + delete heights; + heights = 0; + delete displayLines; + displayLines = 0; + linesInDocument = 1; +} + +int ContractionState::LinesInDoc() const { + if (OneToOne()) { + return linesInDocument; + } else { + return displayLines->Partitions() - 1; + } +} + +int ContractionState::LinesDisplayed() const { + if (OneToOne()) { + return linesInDocument; + } else { + return displayLines->PositionFromPartition(LinesInDoc()); + } +} + +int ContractionState::DisplayFromDoc(int lineDoc) const { + if (OneToOne()) { + return lineDoc; + } else { + if (lineDoc > displayLines->Partitions()) + lineDoc = displayLines->Partitions(); + return displayLines->PositionFromPartition(lineDoc); + } +} + +int ContractionState::DocFromDisplay(int lineDisplay) const { + if (OneToOne()) { + return lineDisplay; + } else { + if (lineDisplay <= 0) { + return 0; + } + if (lineDisplay > LinesDisplayed()) { + return displayLines->PartitionFromPosition(LinesDisplayed()); + } + int lineDoc = displayLines->PartitionFromPosition(lineDisplay); + PLATFORM_ASSERT(GetVisible(lineDoc)); + return lineDoc; + } +} + +void ContractionState::InsertLine(int lineDoc) { + if (OneToOne()) { + linesInDocument++; + } else { + visible->InsertSpace(lineDoc, 1); + visible->SetValueAt(lineDoc, 1); + expanded->InsertSpace(lineDoc, 1); + expanded->SetValueAt(lineDoc, 1); + heights->InsertSpace(lineDoc, 1); + heights->SetValueAt(lineDoc, 1); + int lineDisplay = DisplayFromDoc(lineDoc); + displayLines->InsertPartition(lineDoc, lineDisplay); + displayLines->InsertText(lineDoc, 1); + } +} + +void ContractionState::InsertLines(int lineDoc, int lineCount) { + for (int l = 0; l < lineCount; l++) { + InsertLine(lineDoc + l); + } + Check(); +} + +void ContractionState::DeleteLine(int lineDoc) { + if (OneToOne()) { + linesInDocument--; + } else { + if (GetVisible(lineDoc)) { + displayLines->InsertText(lineDoc, -heights->ValueAt(lineDoc)); + } + displayLines->RemovePartition(lineDoc); + visible->DeleteRange(lineDoc, 1); + expanded->DeleteRange(lineDoc, 1); + heights->DeleteRange(lineDoc, 1); + } +} + +void ContractionState::DeleteLines(int lineDoc, int lineCount) { + for (int l = 0; l < lineCount; l++) { + DeleteLine(lineDoc); + } + Check(); +} + +bool ContractionState::GetVisible(int lineDoc) const { + if (OneToOne()) { + return true; + } else { + if (lineDoc >= visible->Length()) + return true; + return visible->ValueAt(lineDoc) == 1; + } +} + +bool ContractionState::SetVisible(int lineDocStart, int lineDocEnd, bool visible_) { + if (OneToOne() && visible_) { + return false; + } else { + EnsureData(); + int delta = 0; + Check(); + if ((lineDocStart <= lineDocEnd) && (lineDocStart >= 0) && (lineDocEnd < LinesInDoc())) { + for (int line = lineDocStart; line <= lineDocEnd; line++) { + if (GetVisible(line) != visible_) { + int difference = visible_ ? heights->ValueAt(line) : -heights->ValueAt(line); + visible->SetValueAt(line, visible_ ? 1 : 0); + displayLines->InsertText(line, difference); + delta += difference; + } + } + } else { + return false; + } + Check(); + return delta != 0; + } +} + +bool ContractionState::GetExpanded(int lineDoc) const { + if (OneToOne()) { + return true; + } else { + Check(); + return expanded->ValueAt(lineDoc) == 1; + } +} + +bool ContractionState::SetExpanded(int lineDoc, bool expanded_) { + if (OneToOne() && expanded_) { + return false; + } else { + EnsureData(); + if (expanded_ != (expanded->ValueAt(lineDoc) == 1)) { + expanded->SetValueAt(lineDoc, expanded_ ? 1 : 0); + Check(); + return true; + } else { + Check(); + return false; + } + } +} + +int ContractionState::GetHeight(int lineDoc) const { + if (OneToOne()) { + return 1; + } else { + return heights->ValueAt(lineDoc); + } +} + +// Set the number of display lines needed for this line. +// Return true if this is a change. +bool ContractionState::SetHeight(int lineDoc, int height) { + if (OneToOne() && (height == 1)) { + return false; + } else { + EnsureData(); + if (GetHeight(lineDoc) != height) { + if (GetVisible(lineDoc)) { + displayLines->InsertText(lineDoc, height - GetHeight(lineDoc)); + } + heights->SetValueAt(lineDoc, height); + Check(); + return true; + } else { + Check(); + return false; + } + } +} + +void ContractionState::ShowAll() { + int lines = LinesInDoc(); + Clear(); + linesInDocument = lines; +} + +// Debugging checks + +void ContractionState::Check() const { +#ifdef CHECK_CORRECTNESS + for (int vline = 0;vline < LinesDisplayed(); vline++) { + const int lineDoc = DocFromDisplay(vline); + PLATFORM_ASSERT(GetVisible(lineDoc)); + } + for (int lineDoc = 0;lineDoc < LinesInDoc(); lineDoc++) { + const int displayThis = DisplayFromDoc(lineDoc); + const int displayNext = DisplayFromDoc(lineDoc + 1); + const int height = displayNext - displayThis; + PLATFORM_ASSERT(height >= 0); + if (GetVisible(lineDoc)) { + PLATFORM_ASSERT(GetHeight(lineDoc) == height); + } else { + PLATFORM_ASSERT(0 == height); + } + } +#endif +} diff --git a/scintilla/src/ContractionState.h b/scintilla/src/ContractionState.h new file mode 100644 index 00000000..20a98564 --- /dev/null +++ b/scintilla/src/ContractionState.h @@ -0,0 +1,66 @@ +// Scintilla source code edit control +/** @file ContractionState.h + ** Manages visibility of lines for folding and wrapping. + **/ +// Copyright 1998-2007 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef CONTRACTIONSTATE_H +#define CONTRACTIONSTATE_H + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +/** + */ +class ContractionState { + // These contain 1 element for every document line. + RunStyles *visible; + RunStyles *expanded; + RunStyles *heights; + Partitioning *displayLines; + int linesInDocument; + + void EnsureData(); + + bool OneToOne() const { + // True when each document line is exactly one display line so need for + // complex data structures. + return visible == 0; + } + +public: + ContractionState(); + virtual ~ContractionState(); + + void Clear(); + + int LinesInDoc() const; + int LinesDisplayed() const; + int DisplayFromDoc(int lineDoc) const; + int DocFromDisplay(int lineDisplay) const; + + void InsertLine(int lineDoc); + void InsertLines(int lineDoc, int lineCount); + void DeleteLine(int lineDoc); + void DeleteLines(int lineDoc, int lineCount); + + bool GetVisible(int lineDoc) const; + bool SetVisible(int lineDocStart, int lineDocEnd, bool visible); + + bool GetExpanded(int lineDoc) const; + bool SetExpanded(int lineDoc, bool expanded); + + int GetHeight(int lineDoc) const; + bool SetHeight(int lineDoc, int height); + + void ShowAll(); + void Check() const; +}; + +#ifdef SCI_NAMESPACE +} +#endif + +#endif diff --git a/scintilla/src/Decoration.cxx b/scintilla/src/Decoration.cxx new file mode 100644 index 00000000..cb84e26d --- /dev/null +++ b/scintilla/src/Decoration.cxx @@ -0,0 +1,188 @@ +/** @file Decoration.cxx + ** Visual elements added over text. + **/ +// Copyright 1998-2007 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include + +#include "Platform.h" + +#include "Scintilla.h" +#include "SplitVector.h" +#include "Partitioning.h" +#include "RunStyles.h" +#include "Decoration.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +Decoration::Decoration(int indicator_) : next(0), indicator(indicator_) { +} + +Decoration::~Decoration() { +} + +bool Decoration::Empty() { + return rs.starts->Partitions() == 1; +} + +DecorationList::DecorationList() : currentIndicator(0), currentValue(1), current(0), + lengthDocument(0), root(0), clickNotified(false) { +} + +DecorationList::~DecorationList() { + Decoration *deco = root; + while (deco) { + Decoration *decoNext = deco->next; + delete deco; + deco = decoNext; + } + root = 0; + current = 0; +} + +Decoration *DecorationList::DecorationFromIndicator(int indicator) { + for (Decoration *deco=root; deco; deco = deco->next) { + if (deco->indicator == indicator) { + return deco; + } + } + return 0; +} + +Decoration *DecorationList::Create(int indicator, int length) { + currentIndicator = indicator; + Decoration *decoNew = new Decoration(indicator); + decoNew->rs.InsertSpace(0, length); + + Decoration *decoPrev = 0; + Decoration *deco = root; + + while (deco && (deco->indicator < indicator)) { + decoPrev = deco; + deco = deco->next; + } + if (decoPrev == 0) { + decoNew->next = root; + root = decoNew; + } else { + decoNew->next = deco; + decoPrev->next = decoNew; + } + return decoNew; +} + +void DecorationList::Delete(int indicator) { + Decoration *decoToDelete = 0; + if (root) { + if (root->indicator == indicator) { + decoToDelete = root; + root = root->next; + } else { + Decoration *deco=root; + while (deco->next && !decoToDelete) { + if (deco->next && deco->next->indicator == indicator) { + decoToDelete = deco->next; + deco->next = decoToDelete->next; + } else { + deco = deco->next; + } + } + } + } + if (decoToDelete) { + delete decoToDelete; + current = 0; + } +} + +void DecorationList::SetCurrentIndicator(int indicator) { + currentIndicator = indicator; + current = DecorationFromIndicator(indicator); + currentValue = 1; +} + +void DecorationList::SetCurrentValue(int value) { + currentValue = value ? value : 1; +} + +bool DecorationList::FillRange(int &position, int value, int &fillLength) { + if (!current) { + current = DecorationFromIndicator(currentIndicator); + if (!current) { + current = Create(currentIndicator, lengthDocument); + } + } + bool changed = current->rs.FillRange(position, value, fillLength); + if (current->Empty()) { + Delete(currentIndicator); + } + return changed; +} + +void DecorationList::InsertSpace(int position, int insertLength) { + lengthDocument += insertLength; + for (Decoration *deco=root; deco; deco = deco->next) { + deco->rs.InsertSpace(position, insertLength); + } +} + +void DecorationList::DeleteRange(int position, int deleteLength) { + lengthDocument -= deleteLength; + Decoration *deco; + for (deco=root; deco; deco = deco->next) { + deco->rs.DeleteRange(position, deleteLength); + } + DeleteAnyEmpty(); +} + +void DecorationList::DeleteAnyEmpty() { + Decoration *deco = root; + while (deco) { + if (deco->Empty()) { + Delete(deco->indicator); + deco = root; + } else { + deco = deco->next; + } + } +} + +int DecorationList::AllOnFor(int position) { + int mask = 0; + for (Decoration *deco=root; deco; deco = deco->next) { + if (deco->rs.ValueAt(position)) { + mask |= 1 << deco->indicator; + } + } + return mask; +} + +int DecorationList::ValueAt(int indicator, int position) { + Decoration *deco = DecorationFromIndicator(indicator); + if (deco) { + return deco->rs.ValueAt(position); + } + return 0; +} + +int DecorationList::Start(int indicator, int position) { + Decoration *deco = DecorationFromIndicator(indicator); + if (deco) { + return deco->rs.StartRun(position); + } + return 0; +} + +int DecorationList::End(int indicator, int position) { + Decoration *deco = DecorationFromIndicator(indicator); + if (deco) { + return deco->rs.EndRun(position); + } + return 0; +} diff --git a/scintilla/src/Decoration.h b/scintilla/src/Decoration.h new file mode 100644 index 00000000..25c28e5c --- /dev/null +++ b/scintilla/src/Decoration.h @@ -0,0 +1,64 @@ +/** @file Decoration.h + ** Visual elements added over text. + **/ +// Copyright 1998-2007 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef DECORATION_H +#define DECORATION_H + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +class Decoration { +public: + Decoration *next; + RunStyles rs; + int indicator; + + Decoration(int indicator_); + ~Decoration(); + + bool Empty(); +}; + +class DecorationList { + int currentIndicator; + int currentValue; + Decoration *current; + int lengthDocument; + Decoration *DecorationFromIndicator(int indicator); + Decoration *Create(int indicator, int length); + void Delete(int indicator); + void DeleteAnyEmpty(); +public: + Decoration *root; + bool clickNotified; + + DecorationList(); + ~DecorationList(); + + void SetCurrentIndicator(int indicator); + int GetCurrentIndicator() { return currentIndicator; } + + void SetCurrentValue(int value); + int GetCurrentValue() { return currentValue; } + + // Returns true if some values may have changed + bool FillRange(int &position, int value, int &fillLength); + + void InsertSpace(int position, int insertLength); + void DeleteRange(int position, int deleteLength); + + int AllOnFor(int position); + int ValueAt(int indicator, int position); + int Start(int indicator, int position); + int End(int indicator, int position); +}; + +#ifdef SCI_NAMESPACE +} +#endif + +#endif diff --git a/scintilla/src/Document.cxx b/scintilla/src/Document.cxx new file mode 100644 index 00000000..3df5f809 --- /dev/null +++ b/scintilla/src/Document.cxx @@ -0,0 +1,1830 @@ +// Scintilla source code edit control +/** @file Document.cxx + ** Text document that handles notifications, DBCS, styling, words and end of line. + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include + +#include "Platform.h" + +#include "Scintilla.h" +#include "SplitVector.h" +#include "Partitioning.h" +#include "RunStyles.h" +#include "CellBuffer.h" +#include "CharClassify.h" +#include "Decoration.h" +#include "Document.h" +#include "RESearch.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +//Vitaliy +#include "UniConversion.h" + +// Win32 only !!! +static bool IsMustDie9x(void) +{ + OSVERSIONINFO osver; + osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + if ( GetVersionEx( &osver ) ) + { + if ( (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) && + (osver.dwMajorVersion == 4) ) + { + //MessageBox(NULL, "MustDie9x == true", "Test", MB_OK); + return true; + } + } + //MessageBox(NULL, "MustDie9x == false", "Test", MB_OK); + return false; +} + +static inline void Platform_MakeUpperW(wchar_t* wstr, unsigned int len) { + // TODO: Add platform-specific function here + + // Win32 example: + static bool bIsMustDie9x = IsMustDie9x(); + + if ( !bIsMustDie9x ) + { + ::CharUpperW(wstr); + } + else + { + char* str = new char[len + 1]; + if ( str ) + { + ::WideCharToMultiByte(CP_ACP, 0, wstr, len, str, len, NULL, NULL); + str[len] = 0; + ::CharUpperA(str); + ::MultiByteToWideChar(CP_ACP, 0, str, len, wstr, len); + wstr[len] = 0; + delete [] str; + } + } +} + +static inline char Platform_MakeUpperChar(char ch) { + // TODO: Add platform-specific function here + + // Win32 example: + char str[2] = {ch, 0}; + ::CharUpperA(str); + ch = str[0]; + + // default: no conversion + return ch; +} + +static inline char Platform_MakeLowerChar(char ch) { + // TODO: Add platform-specific function here + + // Win32 example: + char str[2] = {ch, 0}; + ::CharLowerA(str); + ch = str[0]; + + // default: no conversion + return ch; +} +// yilatiV + +// This is ASCII specific but is safe with chars >= 0x80 +static inline bool isspacechar(unsigned char ch) { + return (ch == ' ') || ((ch >= 0x09) && (ch <= 0x0d)); +} + +static inline bool IsPunctuation(char ch) { + return isascii(ch) && ispunct(ch); +} + +static inline bool IsADigit(char ch) { + return isascii(ch) && isdigit(ch); +} + +static inline bool IsLowerCase(char ch) { + return isascii(ch) && islower(ch); +} + +static inline bool IsUpperCase(char ch) { + return isascii(ch) && isupper(ch); +} + +Document::Document() { + refCount = 0; +#ifdef unix + eolMode = SC_EOL_LF; +#else + eolMode = SC_EOL_CRLF; +#endif + dbcsCodePage = 0; + stylingBits = 5; + stylingBitsMask = 0x1F; + stylingMask = 0; + endStyled = 0; + styleClock = 0; + enteredModification = 0; + enteredStyling = 0; + enteredReadOnlyCount = 0; + tabInChars = 8; + indentInChars = 0; + actualIndentInChars = 8; + useTabs = true; + tabIndents = true; + backspaceUnindents = false; + watchers = 0; + lenWatchers = 0; + + matchesValid = false; + pre = 0; + substituted = 0; +} + +Document::~Document() { + for (int i = 0; i < lenWatchers; i++) { + watchers[i].watcher->NotifyDeleted(this, watchers[i].userData); + } + delete []watchers; + watchers = 0; + lenWatchers = 0; + delete pre; + pre = 0; + delete []substituted; + substituted = 0; +} + +// Increase reference count and return its previous value. +int Document::AddRef() { + return refCount++; +} + +// Decrease reference count and return its previous value. +// Delete the document if reference count reaches zero. +int Document::Release() { + int curRefCount = --refCount; + if (curRefCount == 0) + delete this; + return curRefCount; +} + +void Document::SetSavePoint() { + cb.SetSavePoint(); + NotifySavePoint(true); +} + +int Document::AddMark(int line, int markerNum) { + int prev = cb.AddMark(line, markerNum); + DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line); + NotifyModified(mh); + return prev; +} + +void Document::AddMarkSet(int line, int valueSet) { + unsigned int m = valueSet; + for (int i = 0; m; i++, m >>= 1) + if (m & 1) + cb.AddMark(line, i); + DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line); + NotifyModified(mh); +} + +void Document::DeleteMark(int line, int markerNum) { + cb.DeleteMark(line, markerNum); + DocModification mh(SC_MOD_CHANGEMARKER, LineStart(line), 0, 0, 0, line); + NotifyModified(mh); +} + +void Document::DeleteMarkFromHandle(int markerHandle) { + cb.DeleteMarkFromHandle(markerHandle); + DocModification mh(SC_MOD_CHANGEMARKER, 0, 0, 0, 0); + mh.line = -1; + NotifyModified(mh); +} + +void Document::DeleteAllMarks(int markerNum) { + cb.DeleteAllMarks(markerNum); + DocModification mh(SC_MOD_CHANGEMARKER, 0, 0, 0, 0); + mh.line = -1; + NotifyModified(mh); +} + +int Document::LineStart(int line) const { + return cb.LineStart(line); +} + +int Document::LineEnd(int line) const { + if (line == LinesTotal() - 1) { + return LineStart(line + 1); + } else { + int position = LineStart(line + 1) - 1; + // When line terminator is CR+LF, may need to go back one more + if ((position > LineStart(line)) && (cb.CharAt(position - 1) == '\r')) { + position--; + } + return position; + } +} + +int Document::LineFromPosition(int pos) { + return cb.LineFromPosition(pos); +} + +int Document::LineEndPosition(int position) { + return LineEnd(LineFromPosition(position)); +} + +int Document::VCHomePosition(int position) { + int line = LineFromPosition(position); + int startPosition = LineStart(line); + int endLine = LineStart(line + 1) - 1; + int startText = startPosition; + while (startText < endLine && (cb.CharAt(startText) == ' ' || cb.CharAt(startText) == '\t' ) ) + startText++; + if (position == startText) + return startPosition; + else + return startText; +} + +int Document::SetLevel(int line, int level) { + int prev = cb.SetLevel(line, level); + if (prev != level) { + DocModification mh(SC_MOD_CHANGEFOLD | SC_MOD_CHANGEMARKER, + LineStart(line), 0, 0, 0, line); + mh.foldLevelNow = level; + mh.foldLevelPrev = prev; + NotifyModified(mh); + } + return prev; +} + +static bool IsSubordinate(int levelStart, int levelTry) { + if (levelTry & SC_FOLDLEVELWHITEFLAG) + return true; + else + return (levelStart & SC_FOLDLEVELNUMBERMASK) < (levelTry & SC_FOLDLEVELNUMBERMASK); +} + +int Document::GetLastChild(int lineParent, int level) { + if (level == -1) + level = GetLevel(lineParent) & SC_FOLDLEVELNUMBERMASK; + int maxLine = LinesTotal(); + int lineMaxSubord = lineParent; + while (lineMaxSubord < maxLine - 1) { + EnsureStyledTo(LineStart(lineMaxSubord + 2)); + if (!IsSubordinate(level, GetLevel(lineMaxSubord + 1))) + break; + lineMaxSubord++; + } + if (lineMaxSubord > lineParent) { + if (level > (GetLevel(lineMaxSubord + 1) & SC_FOLDLEVELNUMBERMASK)) { + // Have chewed up some whitespace that belongs to a parent so seek back + if (GetLevel(lineMaxSubord) & SC_FOLDLEVELWHITEFLAG) { + lineMaxSubord--; + } + } + } + return lineMaxSubord; +} + +int Document::GetFoldParent(int line) { + int level = GetLevel(line) & SC_FOLDLEVELNUMBERMASK; + int lineLook = line - 1; + while ((lineLook > 0) && ( + (!(GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG)) || + ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) >= level)) + ) { + lineLook--; + } + if ((GetLevel(lineLook) & SC_FOLDLEVELHEADERFLAG) && + ((GetLevel(lineLook) & SC_FOLDLEVELNUMBERMASK) < level)) { + return lineLook; + } else { + return -1; + } +} + +int Document::ClampPositionIntoDocument(int pos) { + return Platform::Clamp(pos, 0, Length()); +} + +bool Document::IsCrLf(int pos) { + if (pos < 0) + return false; + if (pos >= (Length() - 1)) + return false; + return (cb.CharAt(pos) == '\r') && (cb.CharAt(pos + 1) == '\n'); +} + +static const int maxBytesInDBCSCharacter=5; + +int Document::LenChar(int pos) { + if (pos < 0) { + return 1; + } else if (IsCrLf(pos)) { + return 2; + } else if (SC_CP_UTF8 == dbcsCodePage) { + unsigned char ch = static_cast(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; + int lengthDoc = Length(); + if ((pos + len) > lengthDoc) + return lengthDoc -pos; + else + return len; + } else if (dbcsCodePage) { + char mbstr[maxBytesInDBCSCharacter+1]; + int i; + for (i=0; i= 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) { + int lead = pos; + while ((lead>0) && (pos-lead < 4) && IsTrailByte(static_cast(cb.CharAt(lead-1)))) + lead--; + start = 0; + if (lead > 0) { + start = lead-1; + } + int leadByte = static_cast(cb.CharAt(start)); + int bytes = BytesFromLead(leadByte); + if (bytes == 0) { + return false; + } else { + int trailBytes = bytes - 1; + int len = pos - lead + 1; + 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(cb.CharAt(trail)))) { + return false; + } + trail++; + } + end = start + bytes; + return true; + } +} + +// Normalise a position so that it is not halfway through a two byte character. +// This can occur in two situations - +// When lines are terminated with \r\n pairs which should be treated as one character. +// When displaying DBCS text such as Japanese. +// If moving, move the position in the indicated direction. +int Document::MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd) { + //Platform::DebugPrintf("NoCRLF %d %d\n", pos, moveDir); + // If out of range, just return minimum/maximum value. + if (pos <= 0) + return 0; + if (pos >= Length()) + return Length(); + + // PLATFORM_ASSERT(pos > 0 && pos < Length()); + if (checkLineEnd && IsCrLf(pos - 1)) { + if (moveDir > 0) + return pos + 1; + else + return pos - 1; + } + + // Not between CR and LF + + if (dbcsCodePage) { + if (SC_CP_UTF8 == dbcsCodePage) { + unsigned char ch = static_cast(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; + } + } else { + // Anchor DBCS calculations at start of line because start of line can + // not be a DBCS trail byte. + int posCheck = LineStart(LineFromPosition(pos)); + while (posCheck < pos) { + char mbstr[maxBytesInDBCSCharacter+1]; + int i; + for(i=0;i pos) { + if (moveDir > 0) { + return posCheck + mbsize; + } else { + return posCheck; + } + } + posCheck += mbsize; + } + } + } + + return pos; +} + +void Document::ModifiedAt(int pos) { + if (endStyled > pos) + endStyled = pos; +} + +void Document::CheckReadOnly() { + if (cb.IsReadOnly() && enteredReadOnlyCount == 0) { + enteredReadOnlyCount++; + NotifyModifyAttempt(); + enteredReadOnlyCount--; + } +} + +// Document only modified by gateways DeleteChars, InsertString, Undo, Redo, and SetStyleAt. +// SetStyleAt does not change the persistent state of a document + +bool Document::DeleteChars(int pos, int len) { + if (len == 0) + return false; + if ((pos + len) > Length()) + return false; + CheckReadOnly(); + if (enteredModification != 0) { + return false; + } else { + enteredModification++; + if (!cb.IsReadOnly()) { + NotifyModified( + DocModification( + SC_MOD_BEFOREDELETE | SC_PERFORMED_USER, + pos, len, + 0, 0)); + int prevLinesTotal = LinesTotal(); + bool startSavePoint = cb.IsSavePoint(); + bool startSequence = false; + const char *text = cb.DeleteChars(pos, len, startSequence); + if (startSavePoint && cb.IsCollectingUndo()) + NotifySavePoint(!startSavePoint); + if ((pos < Length()) || (pos == 0)) + ModifiedAt(pos); + else + ModifiedAt(pos-1); + NotifyModified( + DocModification( + SC_MOD_DELETETEXT | SC_PERFORMED_USER | (startSequence?SC_STARTACTION:0), + pos, len, + LinesTotal() - prevLinesTotal, text)); + } + enteredModification--; + } + return !cb.IsReadOnly(); +} + +/** + * Insert a string with a length. + */ +bool Document::InsertString(int position, const char *s, int insertLength) { + if (insertLength <= 0) { + return false; + } + CheckReadOnly(); + if (enteredModification != 0) { + return false; + } else { + enteredModification++; + if (!cb.IsReadOnly()) { + NotifyModified( + DocModification( + SC_MOD_BEFOREINSERT | SC_PERFORMED_USER, + position, insertLength, + 0, s)); + int prevLinesTotal = LinesTotal(); + bool startSavePoint = cb.IsSavePoint(); + bool startSequence = false; + const char *text = cb.InsertString(position, s, insertLength, startSequence); + if (startSavePoint && cb.IsCollectingUndo()) + NotifySavePoint(!startSavePoint); + ModifiedAt(position); + NotifyModified( + DocModification( + SC_MOD_INSERTTEXT | SC_PERFORMED_USER | (startSequence?SC_STARTACTION:0), + position, insertLength, + LinesTotal() - prevLinesTotal, text)); + } + enteredModification--; + } + return !cb.IsReadOnly(); +} + +int Document::Undo() { + int newPos = -1; + CheckReadOnly(); + if (enteredModification == 0) { + enteredModification++; + if (!cb.IsReadOnly()) { + bool startSavePoint = cb.IsSavePoint(); + bool multiLine = false; + int steps = cb.StartUndo(); + //Platform::DebugPrintf("Steps=%d\n", steps); + for (int step = 0; step < steps; step++) { + const int prevLinesTotal = LinesTotal(); + const Action &action = cb.GetUndoStep(); + if (action.at == removeAction) { + NotifyModified(DocModification( + SC_MOD_BEFOREINSERT | SC_PERFORMED_UNDO, action)); + } else { + NotifyModified(DocModification( + SC_MOD_BEFOREDELETE | SC_PERFORMED_UNDO, action)); + } + cb.PerformUndoStep(); + int cellPosition = action.position; + ModifiedAt(cellPosition); + newPos = cellPosition; + + int modFlags = SC_PERFORMED_UNDO; + // With undo, an insertion action becomes a deletion notification + if (action.at == removeAction) { + newPos += action.lenData; + modFlags |= SC_MOD_INSERTTEXT; + } else { + modFlags |= SC_MOD_DELETETEXT; + } + if (steps > 1) + modFlags |= SC_MULTISTEPUNDOREDO; + const int linesAdded = LinesTotal() - prevLinesTotal; + if (linesAdded != 0) + multiLine = true; + if (step == steps - 1) { + modFlags |= SC_LASTSTEPINUNDOREDO; + if (multiLine) + modFlags |= SC_MULTILINEUNDOREDO; + } + NotifyModified(DocModification(modFlags, cellPosition, action.lenData, + linesAdded, action.data)); + } + + bool endSavePoint = cb.IsSavePoint(); + if (startSavePoint != endSavePoint) + NotifySavePoint(endSavePoint); + } + enteredModification--; + } + return newPos; +} + +int Document::Redo() { + int newPos = -1; + CheckReadOnly(); + if (enteredModification == 0) { + enteredModification++; + if (!cb.IsReadOnly()) { + bool startSavePoint = cb.IsSavePoint(); + bool multiLine = false; + int steps = cb.StartRedo(); + for (int step = 0; step < steps; step++) { + const int prevLinesTotal = LinesTotal(); + const Action &action = cb.GetRedoStep(); + if (action.at == insertAction) { + NotifyModified(DocModification( + SC_MOD_BEFOREINSERT | SC_PERFORMED_REDO, action)); + } else { + NotifyModified(DocModification( + SC_MOD_BEFOREDELETE | SC_PERFORMED_REDO, action)); + } + cb.PerformRedoStep(); + ModifiedAt(action.position); + newPos = action.position; + + int modFlags = SC_PERFORMED_REDO; + if (action.at == insertAction) { + newPos += action.lenData; + modFlags |= SC_MOD_INSERTTEXT; + } else { + modFlags |= SC_MOD_DELETETEXT; + } + if (steps > 1) + modFlags |= SC_MULTISTEPUNDOREDO; + const int linesAdded = LinesTotal() - prevLinesTotal; + if (linesAdded != 0) + multiLine = true; + if (step == steps - 1) { + modFlags |= SC_LASTSTEPINUNDOREDO; + if (multiLine) + modFlags |= SC_MULTILINEUNDOREDO; + } + NotifyModified( + DocModification(modFlags, action.position, action.lenData, + linesAdded, action.data)); + } + + bool endSavePoint = cb.IsSavePoint(); + if (startSavePoint != endSavePoint) + NotifySavePoint(endSavePoint); + } + enteredModification--; + } + return newPos; +} + +/** + * Insert a single character. + */ +bool Document::InsertChar(int pos, char ch) { + char chs[1]; + chs[0] = ch; + return InsertString(pos, chs, 1); +} + +/** + * Insert a null terminated string. + */ +bool Document::InsertCString(int position, const char *s) { + return InsertString(position, s, strlen(s)); +} + +void Document::ChangeChar(int pos, char ch) { + DeleteChars(pos, 1); + InsertChar(pos, ch); +} + +void Document::DelChar(int pos) { + DeleteChars(pos, LenChar(pos)); +} + +void Document::DelCharBack(int pos) { + if (pos <= 0) { + return; + } else if (IsCrLf(pos - 2)) { + DeleteChars(pos - 2, 2); + } else if (dbcsCodePage) { + int startChar = MovePositionOutsideChar(pos - 1, -1, false); + DeleteChars(startChar, pos - startChar); + } else { + DeleteChars(pos - 1, 1); + } +} + +static bool isindentchar(char ch) { + return (ch == ' ') || (ch == '\t'); +} + +static int NextTab(int pos, int tabSize) { + return ((pos / tabSize) + 1) * tabSize; +} + +static void CreateIndentation(char *linebuf, int length, int indent, int tabSize, bool insertSpaces) { + length--; // ensure space for \0 + if (!insertSpaces) { + while ((indent >= tabSize) && (length > 0)) { + *linebuf++ = '\t'; + indent -= tabSize; + length--; + } + } + while ((indent > 0) && (length > 0)) { + *linebuf++ = ' '; + indent--; + length--; + } + *linebuf = '\0'; +} + +int Document::GetLineIndentation(int line) { + int indent = 0; + if ((line >= 0) && (line < LinesTotal())) { + int lineStart = LineStart(line); + int length = Length(); + for (int i = lineStart;i < length;i++) { + char ch = cb.CharAt(i); + if (ch == ' ') + indent++; + else if (ch == '\t') + indent = NextTab(indent, tabInChars); + else + return indent; + } + } + return indent; +} + +void Document::SetLineIndentation(int line, int indent) { + int indentOfLine = GetLineIndentation(line); + if (indent < 0) + indent = 0; + if (indent != indentOfLine) { + char linebuf[1000]; + CreateIndentation(linebuf, sizeof(linebuf), indent, tabInChars, !useTabs); + int thisLineStart = LineStart(line); + int indentPos = GetLineIndentPosition(line); + BeginUndoAction(); + DeleteChars(thisLineStart, indentPos - thisLineStart); + InsertCString(thisLineStart, linebuf); + EndUndoAction(); + } +} + +int Document::GetLineIndentPosition(int line) const { + if (line < 0) + return 0; + int pos = LineStart(line); + int length = Length(); + while ((pos < length) && isindentchar(cb.CharAt(pos))) { + pos++; + } + return pos; +} + +int Document::GetColumn(int pos) { + int column = 0; + int line = LineFromPosition(pos); + if ((line >= 0) && (line < LinesTotal())) { + for (int i = LineStart(line);i < pos;) { + char ch = cb.CharAt(i); + if (ch == '\t') { + column = NextTab(column, tabInChars); + i++; + } else if (ch == '\r') { + return column; + } else if (ch == '\n') { + return column; + } else if (i >= Length()) { + return column; + } else { + column++; + i = MovePositionOutsideChar(i + 1, 1, false); + } + } + } + return column; +} + +int Document::FindColumn(int line, int column) { + int position = LineStart(line); + int columnCurrent = 0; + if ((line >= 0) && (line < LinesTotal())) { + while ((columnCurrent < column) && (position < Length())) { + char ch = cb.CharAt(position); + if (ch == '\t') { + columnCurrent = NextTab(columnCurrent, tabInChars); + position++; + } else if (ch == '\r') { + return position; + } else if (ch == '\n') { + return position; + } else { + columnCurrent++; + position = MovePositionOutsideChar(position + 1, 1, false); + } + } + } + return position; +} + +void Document::Indent(bool forwards, int lineBottom, int lineTop) { + // Dedent - suck white space off the front of the line to dedent by equivalent of a tab + for (int line = lineBottom; line >= lineTop; line--) { + int indentOfLine = GetLineIndentation(line); + if (forwards) { + if (LineStart(line) < LineEnd(line)) { + SetLineIndentation(line, indentOfLine + IndentSize()); + } + } else { + SetLineIndentation(line, indentOfLine - IndentSize()); + } + } +} + +// Convert line endings for a piece of text to a particular mode. +// Stop at len or when a NUL is found. +// Caller must delete the returned pointer. +char *Document::TransformLineEnds(int *pLenOut, const char *s, size_t len, int eolMode) { + char *dest = new char[2 * len + 1]; + const char *sptr = s; + char *dptr = dest; + for (size_t i = 0; (i < len) && (*sptr != '\0'); i++) { + if (*sptr == '\n' || *sptr == '\r') { + if (eolMode == SC_EOL_CR) { + *dptr++ = '\r'; + } else if (eolMode == SC_EOL_LF) { + *dptr++ = '\n'; + } else { // eolMode == SC_EOL_CRLF + *dptr++ = '\r'; + *dptr++ = '\n'; + } + if ((*sptr == '\r') && (i+1 < len) && (*(sptr+1) == '\n')) { + i++; + sptr++; + } + sptr++; + } else { + *dptr++ = *sptr++; + } + } + *dptr++ = '\0'; + *pLenOut = (dptr - dest) - 1; + return dest; +} + +void Document::ConvertLineEnds(int eolModeSet) { + BeginUndoAction(); + + for (int pos = 0; pos < Length(); pos++) { + if (cb.CharAt(pos) == '\r') { + if (cb.CharAt(pos + 1) == '\n') { + // CRLF + if (eolModeSet == SC_EOL_CR) { + DeleteChars(pos + 1, 1); // Delete the LF + } else if (eolModeSet == SC_EOL_LF) { + DeleteChars(pos, 1); // Delete the CR + } else { + pos++; + } + } else { + // CR + if (eolModeSet == SC_EOL_CRLF) { + InsertString(pos + 1, "\n", 1); // Insert LF + pos++; + } else if (eolModeSet == SC_EOL_LF) { + InsertString(pos, "\n", 1); // Insert LF + DeleteChars(pos + 1, 1); // Delete CR + } + } + } else if (cb.CharAt(pos) == '\n') { + // LF + if (eolModeSet == SC_EOL_CRLF) { + InsertString(pos, "\r", 1); // Insert CR + pos++; + } else if (eolModeSet == SC_EOL_CR) { + InsertString(pos, "\r", 1); // Insert CR + DeleteChars(pos + 1, 1); // Delete LF + } + } + } + + EndUndoAction(); +} + +bool Document::IsWhiteLine(int line) const { + int currentChar = LineStart(line); + int endLine = LineEnd(line); + while (currentChar < endLine) { + if (cb.CharAt(currentChar) != ' ' && cb.CharAt(currentChar) != '\t') { + return false; + } + ++currentChar; + } + return true; +} + +int Document::ParaUp(int pos) { + int line = LineFromPosition(pos); + line--; + while (line >= 0 && IsWhiteLine(line)) { // skip empty lines + line--; + } + while (line >= 0 && !IsWhiteLine(line)) { // skip non-empty lines + line--; + } + line++; + return LineStart(line); +} + +int Document::ParaDown(int pos) { + int line = LineFromPosition(pos); + while (line < LinesTotal() && !IsWhiteLine(line)) { // skip non-empty lines + line++; + } + while (line < LinesTotal() && IsWhiteLine(line)) { // skip empty lines + line++; + } + if (line < LinesTotal()) + return LineStart(line); + else // end of a document + return LineEnd(line-1); +} + +CharClassify::cc Document::WordCharClass(unsigned char ch) { + if ((SC_CP_UTF8 == dbcsCodePage) && (ch >= 0x80)) + return CharClassify::ccWord; + return charClass.GetClass(ch); +} + +/** + * Used by commmands that want to select whole words. + * Finds the start of word at pos when delta < 0 or the end of the word when delta >= 0. + */ +int Document::ExtendWordSelect(int pos, int delta, bool onlyWordCharacters) { + CharClassify::cc ccStart = CharClassify::ccWord; + if (delta < 0) { + if (!onlyWordCharacters) + ccStart = WordCharClass(cb.CharAt(pos-1)); + while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == ccStart)) + pos--; + } else { + if (!onlyWordCharacters && pos < Length()) + ccStart = WordCharClass(cb.CharAt(pos)); + while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == ccStart)) + pos++; + } + return MovePositionOutsideChar(pos, delta); +} + +/** + * Find the start of the next word in either a forward (delta >= 0) or backwards direction + * (delta < 0). + * This is looking for a transition between character classes although there is also some + * additional movement to transit white space. + * Used by cursor movement by word commands. + */ +int Document::NextWordStart(int pos, int delta) { + if (delta < 0) { + while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == CharClassify::ccSpace)) + pos--; + if (pos > 0) { + CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos-1)); + while (pos > 0 && (WordCharClass(cb.CharAt(pos - 1)) == ccStart)) { + pos--; + } + } + } else { + CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos)); + while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == ccStart)) + pos++; + while (pos < (Length()) && (WordCharClass(cb.CharAt(pos)) == CharClassify::ccSpace)) + pos++; + } + return pos; +} + +/** + * Find the end of the next word in either a forward (delta >= 0) or backwards direction + * (delta < 0). + * This is looking for a transition between character classes although there is also some + * additional movement to transit white space. + * Used by cursor movement by word commands. + */ +int Document::NextWordEnd(int pos, int delta) { + if (delta < 0) { + if (pos > 0) { + CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos-1)); + if (ccStart != CharClassify::ccSpace) { + while (pos > 0 && WordCharClass(cb.CharAt(pos - 1)) == ccStart) { + pos--; + } + } + while (pos > 0 && WordCharClass(cb.CharAt(pos - 1)) == CharClassify::ccSpace) { + pos--; + } + } + } else { + while (pos < Length() && WordCharClass(cb.CharAt(pos)) == CharClassify::ccSpace) { + pos++; + } + if (pos < Length()) { + CharClassify::cc ccStart = WordCharClass(cb.CharAt(pos)); + while (pos < Length() && WordCharClass(cb.CharAt(pos)) == ccStart) { + pos++; + } + } + } + return pos; +} + +/** + * Check that the character at the given position is a word or punctuation character and that + * the previous character is of a different character class. + */ +bool Document::IsWordStartAt(int pos) { + if (pos > 0) { + CharClassify::cc ccPos = WordCharClass(CharAt(pos)); + return (ccPos == CharClassify::ccWord || ccPos == CharClassify::ccPunctuation) && + (ccPos != WordCharClass(CharAt(pos - 1))); + } + return true; +} + +/** + * Check that the character at the given position is a word or punctuation character and that + * the next character is of a different character class. + */ +bool Document::IsWordEndAt(int pos) { + if (pos < Length()) { + CharClassify::cc ccPrev = WordCharClass(CharAt(pos-1)); + return (ccPrev == CharClassify::ccWord || ccPrev == CharClassify::ccPunctuation) && + (ccPrev != WordCharClass(CharAt(pos))); + } + return true; +} + +/** + * Check that the given range is has transitions between character classes at both + * ends and where the characters on the inside are word or punctuation characters. + */ +bool Document::IsWordAt(int start, int end) { + return IsWordStartAt(start) && IsWordEndAt(end); +} + +// The comparison and case changing functions here assume ASCII +// or extended ASCII such as the normal Windows code page. + +//Vitaliy +// NOTE: this function is called for non-Unicode characters only! +// ( i.e. when (!dbcsCodePage || isascii(ch)) ) +static inline char MakeUpperCase(char ch) { + if (ch >= 'A' && ch <= 'Z') + return ch; + else if (ch >= 'a' && ch <= 'z') + return static_cast(ch - 'a' + 'A'); + else + return Platform_MakeUpperChar(ch); +} + + + +// NOTE: this function is called for non-Unicode characters only! +// ( i.e. when (!dbcsCodePage || isascii(ch)) ) +static inline char MakeLowerCase(char ch) { + if (ch >= 'a' && ch <= 'z') + return ch; + else if (ch >= 'A' && ch <= 'Z') + return static_cast(ch - 'A' + 'a'); + else + return Platform_MakeLowerChar(ch); +} +//yilatiV + +// Define a way for the Regular Expression code to access the document +class DocumentIndexer : public CharacterIndexer { + Document *pdoc; + int end; +public: + DocumentIndexer(Document *pdoc_, int end_) : + pdoc(pdoc_), end(end_) { + } + + virtual ~DocumentIndexer() { + } + + virtual char CharAt(int index) { + if (index < 0 || index >= end) + return 0; + else + return pdoc->CharAt(index); + } +}; + +/** + * Find text in document, supporting both forward and backward + * searches (just pass minPos > maxPos to do a backward search) + * Has not been tested with backwards DBCS searches yet. + */ +long Document::FindText(int minPos, int maxPos, const char *s, + bool caseSensitive, bool word, bool wordStart, bool regExp, bool posix, + int *length) { + if (regExp) { + if (!pre) + pre = new RESearch(&charClass); + if (!pre) + return -1; + + int increment = (minPos <= maxPos) ? 1 : -1; + + int startPos = minPos; + int endPos = maxPos; + + // Range endpoints should not be inside DBCS characters, but just in case, move them. + startPos = MovePositionOutsideChar(startPos, 1, false); + endPos = MovePositionOutsideChar(endPos, 1, false); + + const char *errmsg = pre->Compile(s, *length, caseSensitive, posix); + if (errmsg) { + return -1; + } + // Find a variable in a property file: \$(\([A-Za-z0-9_.]+\)) + // Replace first '.' with '-' in each property file variable reference: + // Search: \$(\([A-Za-z0-9_-]+\)\.\([A-Za-z0-9_.]+\)) + // Replace: $(\1-\2) + int lineRangeStart = LineFromPosition(startPos); + int lineRangeEnd = LineFromPosition(endPos); + if ((increment == 1) && + (startPos >= LineEnd(lineRangeStart)) && + (lineRangeStart < lineRangeEnd)) { + // the start position is at end of line or between line end characters. + lineRangeStart++; + startPos = LineStart(lineRangeStart); + } + int pos = -1; + int lenRet = 0; + char searchEnd = s[*length - 1]; + int lineRangeBreak = lineRangeEnd + increment; + for (int line = lineRangeStart; line != lineRangeBreak; line += increment) { + int startOfLine = LineStart(line); + int endOfLine = LineEnd(line); + if (increment == 1) { + if (line == lineRangeStart) { + if ((startPos != startOfLine) && (s[0] == '^')) + continue; // Can't match start of line if start position after start of line + startOfLine = startPos; + } + if (line == lineRangeEnd) { + if ((endPos != endOfLine) && (searchEnd == '$')) + continue; // Can't match end of line if end position before end of line + endOfLine = endPos; + } + } else { + if (line == lineRangeEnd) { + if ((endPos != startOfLine) && (s[0] == '^')) + continue; // Can't match start of line if end position after start of line + startOfLine = endPos; + } + if (line == lineRangeStart) { + if ((startPos != endOfLine) && (searchEnd == '$')) + continue; // Can't match end of line if start position before end of line + endOfLine = startPos; + } + } + + DocumentIndexer di(this, endOfLine); + int success = pre->Execute(di, startOfLine, endOfLine); + if (success) { + pos = pre->bopat[0]; + lenRet = pre->eopat[0] - pre->bopat[0]; + if (increment == -1) { + // Check for the last match on this line. + int repetitions = 1000; // Break out of infinite loop + while (success && (pre->eopat[0] <= endOfLine) && (repetitions--)) { + success = pre->Execute(di, pos+1, endOfLine); + if (success) { + if (pre->eopat[0] <= minPos) { + pos = pre->bopat[0]; + lenRet = pre->eopat[0] - pre->bopat[0]; + } else { + success = 0; + } + } + } + } + break; + } + } + *length = lenRet; + return pos; + + } else { + + bool forward = minPos <= maxPos; + int increment = forward ? 1 : -1; + + // Range endpoints should not be inside DBCS characters, but just in case, move them. + int startPos = MovePositionOutsideChar(minPos, increment, false); + int endPos = MovePositionOutsideChar(maxPos, increment, false); + + // Compute actual search ranges needed + int lengthFind = *length; + if (lengthFind == -1) + lengthFind = static_cast(strlen(s)); + int endSearch = endPos; + if (startPos <= endPos) { + endSearch = endPos - lengthFind + 1; + } + //Platform::DebugPrintf("Find %d %d %s %d\n", startPos, endPos, ft->lpstrText, lengthFind); + char firstChar = s[0]; + wchar_t* ws_upr = NULL; + int ws_len = 0; + char str[8]; + wchar_t wstr[4]; + if (!caseSensitive && !dbcsCodePage) + firstChar = static_cast(MakeUpperCase(firstChar)); + int pos = forward ? startPos : (startPos - 1); + if (dbcsCodePage) { + if (!caseSensitive && dbcsCodePage == SC_CP_UTF8) { + ws_len = (int) UTF16Length(s, lengthFind); + if (ws_len != lengthFind) { + int ws_size = (((ws_len + 1) >> 4) + 1) << 4; // 16-chars alignment + ws_upr = new wchar_t[ws_size]; + if (ws_upr != NULL) { + UTF16FromUTF8(s, lengthFind, ws_upr, ws_size); + ws_upr[ws_len] = 0; + Platform_MakeUpperW(ws_upr, ws_len); + // now ws_upr is UCS2 s in upper-case + } + } + } + if (!caseSensitive && ws_upr == NULL) { + // the text is Latin i.e. one character is one byte + // ws_upr is NULL + // BUT !!! ws_upr can be NULL if dbcsCodePage != SC_CP_UTF8 + // (also ws_upr = new wchar_t[ws_size] can be NULL) + + // for latin characters in non-UTF8 Unicode text + // (thanks to Airix Z) + if (isascii(firstChar)) + firstChar = static_cast(MakeUpperCase(firstChar)); + } + if (pos >= 0) + pos = MovePositionOutsideChar(pos, increment, false); + } + while (forward ? (pos < endSearch) : (pos >= endSearch)) { + char ch = CharAt(pos); + if (caseSensitive) { + if (ch == firstChar) { + bool found = true; + if (pos + lengthFind > Platform::Maximum(startPos, endPos)) found = false; + for (int posMatch = 1; posMatch < lengthFind && found; posMatch++) { + ch = CharAt(pos + posMatch); + if (ch != s[posMatch]) + found = false; + } + if (found) { + if ((!word && !wordStart) || + word && IsWordAt(pos, pos + lengthFind) || + wordStart && IsWordStartAt(pos)) + return pos; + } + } + } else { + bool bMatch = false; + int charLen = 0; + + if (!dbcsCodePage) { + bMatch = (MakeUpperCase(ch) == firstChar); + } + else if (ws_upr == NULL) { + // for latin characters in non-UTF8 Unicode text + // (thanks to Airix Z) + + if (isascii(ch)) + bMatch = (MakeUpperCase(ch) == firstChar); + else + bMatch = (ch == firstChar); + } + else { + // LenChar returns 2 for "\r\n" + // this is wrong for UTF8 because "\r\n" + // is not one character with length=2 + charLen = IsCrLf(pos) ? 1 : LenChar(pos); + for (int i = 0; i < charLen; i++) { + str[i] = CharAt(pos+i); + } + str[charLen] = 0; + UTF16FromUTF8(str, charLen, wstr, 2); + wstr[1] = 0; + Platform_MakeUpperW(wstr, 1); + bMatch = (ws_upr[0] == wstr[0]); + + /* + if (bMatch) + MessageBoxA(NULL, "MatchCaseInsensitive is true!!!", "", 0); + // OK + */ + } + if (bMatch) { + bool found = true; + if (pos + lengthFind > Platform::Maximum(startPos, endPos)) found = false; + if (!dbcsCodePage || ws_upr == NULL) { + /* + MessageBoxA(NULL, "Text is Latin (ws_upr == NULL)", "First character matched", 0); + */ + for (int posMatch = 1; posMatch < lengthFind && found; posMatch++) { + ch = CharAt(pos + posMatch); + char ch2 = s[posMatch]; + // for latin characters in non-UTF8 Unicode text + // (thanks to Airix Z) + if (!dbcsCodePage || (isascii(ch) && isascii(ch2))) { + if (MakeUpperCase(ch) != MakeUpperCase(ch2)) + found = false; + } else { + if (ch != ch2) + found = false; + } + } + } + else { + int i1, i2; + + /* + MessageBoxA(NULL, "first matched!!!", "", 0); + // OK + */ + i1 = 1; + i2 = pos + charLen; + while (found && i1 < ws_len) { + // LenChar returns 2 for "\r\n" + // this is wrong for UTF8 because "\r\n" + // is not one character with length=2 + charLen = IsCrLf(i2) ? 1 : LenChar(i2); + for (int i = 0; i < charLen; i++) { + str[i] = CharAt(i2+i); + } + str[charLen] = 0; + UTF16FromUTF8(str, charLen, wstr, 2); + wstr[1] = 0; + Platform_MakeUpperW(wstr, 1); + found = (ws_upr[i1] == wstr[0]); + i1++; + i2 += charLen; + } + } + if (found) { + if ((!word && !wordStart) || + word && IsWordAt(pos, pos + lengthFind) || + wordStart && IsWordStartAt(pos)) { + if (ws_upr != NULL) { + delete [] ws_upr; + ws_upr = NULL; + } + return pos; + } + } + } + } + pos += increment; + if (dbcsCodePage && (pos >= 0)) { + // Ensure trying to match from start of character + pos = MovePositionOutsideChar(pos, increment, false); + } + } + if (ws_upr != NULL) { + delete [] ws_upr; + ws_upr = NULL; + } + } + //Platform::DebugPrintf("Not found\n"); + return -1; +} + +const char *Document::SubstituteByPosition(const char *text, int *length) { + if (!pre) + return 0; + delete []substituted; + substituted = 0; + DocumentIndexer di(this, Length()); + if (!pre->GrabMatches(di)) + return 0; + unsigned int lenResult = 0; + for (int i = 0; i < *length; i++) { + if (text[i] == '\\') { + if (text[i + 1] >= '1' && text[i + 1] <= '9') { + unsigned int patNum = text[i + 1] - '0'; + lenResult += pre->eopat[patNum] - pre->bopat[patNum]; + i++; + } else { + switch (text[i + 1]) { + case 'a': + case 'b': + case 'f': + case 'n': + case 'r': + case 't': + case 'v': + i++; + } + lenResult++; + } + } else { + lenResult++; + } + } + substituted = new char[lenResult + 1]; + if (!substituted) + return 0; + char *o = substituted; + for (int j = 0; j < *length; j++) { + if (text[j] == '\\') { + if (text[j + 1] >= '1' && text[j + 1] <= '9') { + unsigned int patNum = text[j + 1] - '0'; + unsigned int len = pre->eopat[patNum] - pre->bopat[patNum]; + if (pre->pat[patNum]) // Will be null if try for a match that did not occur + memcpy(o, pre->pat[patNum], len); + o += len; + j++; + } else { + j++; + switch (text[j]) { + case 'a': + *o++ = '\a'; + break; + case 'b': + *o++ = '\b'; + break; + case 'f': + *o++ = '\f'; + break; + case 'n': + *o++ = '\n'; + break; + case 'r': + *o++ = '\r'; + break; + case 't': + *o++ = '\t'; + break; + case 'v': + *o++ = '\v'; + break; + default: + *o++ = '\\'; + j--; + } + } + } else { + *o++ = text[j]; + } + } + *o = '\0'; + *length = lenResult; + return substituted; +} + +int Document::LinesTotal() const { + return cb.Lines(); +} + +void Document::ChangeCase(Range r, bool makeUpperCase) { + for (int pos = r.start; pos < r.end;) { + int len = LenChar(pos); + if (len == 1) { + char ch = CharAt(pos); + if (makeUpperCase) { + if (IsLowerCase(ch)) { + ChangeChar(pos, static_cast(MakeUpperCase(ch))); + } + } else { + if (IsUpperCase(ch)) { + ChangeChar(pos, static_cast(MakeLowerCase(ch))); + } + } + } + pos += len; + } +} + +void Document::SetDefaultCharClasses(bool includeWordClass) { + charClass.SetDefaultCharClasses(includeWordClass); +} + +void Document::SetCharClasses(const unsigned char *chars, CharClassify::cc newCharClass) { + charClass.SetCharClasses(chars, newCharClass); +} + +void Document::SetStylingBits(int bits) { + stylingBits = bits; + stylingBitsMask = (1 << stylingBits) - 1; +} + +void Document::StartStyling(int position, char mask) { + stylingMask = mask; + endStyled = position; +} + +bool Document::SetStyleFor(int length, char style) { + if (enteredStyling != 0) { + return false; + } else { + enteredStyling++; + style &= stylingMask; + int prevEndStyled = endStyled; + if (cb.SetStyleFor(endStyled, length, style, stylingMask)) { + DocModification mh(SC_MOD_CHANGESTYLE | SC_PERFORMED_USER, + prevEndStyled, length); + NotifyModified(mh); + } + endStyled += length; + enteredStyling--; + return true; + } +} + +bool Document::SetStyles(int length, char *styles) { + if (enteredStyling != 0) { + return false; + } else { + enteredStyling++; + bool didChange = false; + int startMod = 0; + int endMod = 0; + for (int iPos = 0; iPos < length; iPos++, endStyled++) { + PLATFORM_ASSERT(endStyled < Length()); + if (cb.SetStyleAt(endStyled, styles[iPos], stylingMask)) { + if (!didChange) { + startMod = endStyled; + } + didChange = true; + endMod = endStyled; + } + } + if (didChange) { + DocModification mh(SC_MOD_CHANGESTYLE | SC_PERFORMED_USER, + startMod, endMod - startMod + 1); + NotifyModified(mh); + } + enteredStyling--; + return true; + } +} + +void Document::EnsureStyledTo(int pos) { + if ((enteredStyling == 0) && (pos > GetEndStyled())) { + IncrementStyleClock(); + // Ask the watchers to style, and stop as soon as one responds. + for (int i = 0; pos > GetEndStyled() && i < lenWatchers; i++) { + watchers[i].watcher->NotifyStyleNeeded(this, watchers[i].userData, pos); + } + } +} + +int Document::SetLineState(int line, int state) { + int statePrevious = cb.SetLineState(line, state); + if (state != statePrevious) { + DocModification mh(SC_MOD_CHANGELINESTATE, 0, 0, 0, 0, line); + NotifyModified(mh); + } + return statePrevious; +} + +void Document::IncrementStyleClock() { + styleClock = (styleClock + 1) % 0x100000; +} + +void Document::DecorationFillRange(int position, int value, int fillLength) { + if (decorations.FillRange(position, value, fillLength)) { + DocModification mh(SC_MOD_CHANGEINDICATOR | SC_PERFORMED_USER, + position, fillLength); + NotifyModified(mh); + } +} + +bool Document::AddWatcher(DocWatcher *watcher, void *userData) { + for (int i = 0; i < lenWatchers; i++) { + if ((watchers[i].watcher == watcher) && + (watchers[i].userData == userData)) + return false; + } + WatcherWithUserData *pwNew = new WatcherWithUserData[lenWatchers + 1]; + if (!pwNew) + return false; + for (int j = 0; j < lenWatchers; j++) + pwNew[j] = watchers[j]; + pwNew[lenWatchers].watcher = watcher; + pwNew[lenWatchers].userData = userData; + delete []watchers; + watchers = pwNew; + lenWatchers++; + return true; +} + +bool Document::RemoveWatcher(DocWatcher *watcher, void *userData) { + for (int i = 0; i < lenWatchers; i++) { + if ((watchers[i].watcher == watcher) && + (watchers[i].userData == userData)) { + if (lenWatchers == 1) { + delete []watchers; + watchers = 0; + lenWatchers = 0; + } else { + WatcherWithUserData *pwNew = new WatcherWithUserData[lenWatchers]; + if (!pwNew) + return false; + for (int j = 0; j < lenWatchers - 1; j++) { + pwNew[j] = (j < i) ? watchers[j] : watchers[j + 1]; + } + delete []watchers; + watchers = pwNew; + lenWatchers--; + } + return true; + } + } + return false; +} + +void Document::NotifyModifyAttempt() { + for (int i = 0; i < lenWatchers; i++) { + watchers[i].watcher->NotifyModifyAttempt(this, watchers[i].userData); + } +} + +void Document::NotifySavePoint(bool atSavePoint) { + for (int i = 0; i < lenWatchers; i++) { + watchers[i].watcher->NotifySavePoint(this, watchers[i].userData, atSavePoint); + } +} + +void Document::NotifyModified(DocModification mh) { + if (mh.modificationType & SC_MOD_INSERTTEXT) { + decorations.InsertSpace(mh.position, mh.length); + } else if (mh.modificationType & SC_MOD_DELETETEXT) { + decorations.DeleteRange(mh.position, mh.length); + } + for (int i = 0; i < lenWatchers; i++) { + watchers[i].watcher->NotifyModified(this, mh, watchers[i].userData); + } +} + +bool Document::IsWordPartSeparator(char ch) { + return (WordCharClass(ch) == CharClassify::ccWord) && IsPunctuation(ch); +} + +int Document::WordPartLeft(int pos) { + if (pos > 0) { + --pos; + char startChar = cb.CharAt(pos); + if (IsWordPartSeparator(startChar)) { + while (pos > 0 && IsWordPartSeparator(cb.CharAt(pos))) { + --pos; + } + } + if (pos > 0) { + startChar = cb.CharAt(pos); + --pos; + if (IsLowerCase(startChar)) { + while (pos > 0 && IsLowerCase(cb.CharAt(pos))) + --pos; + if (!IsUpperCase(cb.CharAt(pos)) && !IsLowerCase(cb.CharAt(pos))) + ++pos; + } else if (IsUpperCase(startChar)) { + while (pos > 0 && IsUpperCase(cb.CharAt(pos))) + --pos; + if (!IsUpperCase(cb.CharAt(pos))) + ++pos; + } else if (IsADigit(startChar)) { + while (pos > 0 && IsADigit(cb.CharAt(pos))) + --pos; + if (!IsADigit(cb.CharAt(pos))) + ++pos; + } else if (IsPunctuation(startChar)) { + while (pos > 0 && IsPunctuation(cb.CharAt(pos))) + --pos; + if (!IsPunctuation(cb.CharAt(pos))) + ++pos; + } else if (isspacechar(startChar)) { + while (pos > 0 && isspacechar(cb.CharAt(pos))) + --pos; + if (!isspacechar(cb.CharAt(pos))) + ++pos; + } else if (!isascii(startChar)) { + while (pos > 0 && !isascii(cb.CharAt(pos))) + --pos; + if (isascii(cb.CharAt(pos))) + ++pos; + } else { + ++pos; + } + } + } + return pos; +} + +int Document::WordPartRight(int pos) { + char startChar = cb.CharAt(pos); + int length = Length(); + if (IsWordPartSeparator(startChar)) { + while (pos < length && IsWordPartSeparator(cb.CharAt(pos))) + ++pos; + startChar = cb.CharAt(pos); + } + if (!isascii(startChar)) { + while (pos < length && !isascii(cb.CharAt(pos))) + ++pos; + } else if (IsLowerCase(startChar)) { + while (pos < length && IsLowerCase(cb.CharAt(pos))) + ++pos; + } else if (IsUpperCase(startChar)) { + if (IsLowerCase(cb.CharAt(pos + 1))) { + ++pos; + while (pos < length && IsLowerCase(cb.CharAt(pos))) + ++pos; + } else { + while (pos < length && IsUpperCase(cb.CharAt(pos))) + ++pos; + } + if (IsLowerCase(cb.CharAt(pos)) && IsUpperCase(cb.CharAt(pos - 1))) + --pos; + } else if (IsADigit(startChar)) { + while (pos < length && IsADigit(cb.CharAt(pos))) + ++pos; + } else if (IsPunctuation(startChar)) { + while (pos < length && IsPunctuation(cb.CharAt(pos))) + ++pos; + } else if (isspacechar(startChar)) { + while (pos < length && isspacechar(cb.CharAt(pos))) + ++pos; + } else { + ++pos; + } + return pos; +} + +bool IsLineEndChar(char c) { + return (c == '\n' || c == '\r'); +} + +int Document::ExtendStyleRange(int pos, int delta, bool singleLine) { + int sStart = cb.StyleAt(pos); + if (delta < 0) { + while (pos > 0 && (cb.StyleAt(pos) == sStart) && (!singleLine || !IsLineEndChar(cb.CharAt(pos))) ) + pos--; + pos++; + } else { + while (pos < (Length()) && (cb.StyleAt(pos) == sStart) && (!singleLine || !IsLineEndChar(cb.CharAt(pos))) ) + pos++; + } + return pos; +} + +static char BraceOpposite(char ch) { + switch (ch) { + case '(': + return ')'; + case ')': + return '('; + case '[': + return ']'; + case ']': + return '['; + case '{': + return '}'; + case '}': + return '{'; + case '<': + return '>'; + case '>': + return '<'; + default: + return '\0'; + } +} + +// TODO: should be able to extend styled region to find matching brace +int Document::BraceMatch(int position, int /*maxReStyle*/) { + char chBrace = CharAt(position); + char chSeek = BraceOpposite(chBrace); + if (chSeek == '\0') + return - 1; + char styBrace = static_cast(StyleAt(position) & stylingBitsMask); + int direction = -1; + if (chBrace == '(' || chBrace == '[' || chBrace == '{' || chBrace == '<') + direction = 1; + int depth = 1; + position = position + direction; + while ((position >= 0) && (position < Length())) { + position = MovePositionOutsideChar(position, direction); + char chAtPos = CharAt(position); + char styAtPos = static_cast(StyleAt(position) & stylingBitsMask); + if ((position > GetEndStyled()) || (styAtPos == styBrace)) { + if (chAtPos == chBrace) + depth++; + if (chAtPos == chSeek) + depth--; + if (depth == 0) + return position; + } + position = position + direction; + } + return - 1; +} diff --git a/scintilla/src/Document.h b/scintilla/src/Document.h new file mode 100644 index 00000000..00433eda --- /dev/null +++ b/scintilla/src/Document.h @@ -0,0 +1,316 @@ +// Scintilla source code edit control +/** @file Document.h + ** Text document that handles notifications, DBCS, styling, words and end of line. + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef DOCUMENT_H +#define DOCUMENT_H + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +/** + * A Position is a position within a document between two characters or at the beginning or end. + * Sometimes used as a character index where it identifies the character after the position. + */ +typedef int Position; +const Position invalidPosition = -1; + +/** + * The range class represents a range of text in a document. + * The two values are not sorted as one end may be more significant than the other + * as is the case for the selection where the end position is the position of the caret. + * If either position is invalidPosition then the range is invalid and most operations will fail. + */ +class Range { +public: + Position start; + Position end; + + Range(Position pos=0) : + start(pos), end(pos) { + }; + Range(Position start_, Position end_) : + start(start_), end(end_) { + }; + + bool Valid() const { + return (start != invalidPosition) && (end != invalidPosition); + } + + // Is the position within the range? + bool Contains(Position pos) const { + if (start < end) { + return (pos >= start && pos <= end); + } else { + return (pos <= start && pos >= end); + } + } + + // Is the character after pos within the range? + bool ContainsCharacter(Position pos) const { + if (start < end) { + return (pos >= start && pos < end); + } else { + return (pos < start && pos >= end); + } + } + + bool Contains(Range other) const { + return Contains(other.start) && Contains(other.end); + } + + bool Overlaps(Range other) const { + return + Contains(other.start) || + Contains(other.end) || + other.Contains(start) || + other.Contains(end); + } +}; + +class DocWatcher; +class DocModification; +class RESearch; + +/** + */ +class Document { + +public: + /** Used to pair watcher pointer with user data. */ + class WatcherWithUserData { + public: + DocWatcher *watcher; + void *userData; + WatcherWithUserData() { + watcher = 0; + userData = 0; + } + }; + + enum charClassification { ccSpace, ccNewLine, ccWord, ccPunctuation }; + +private: + int refCount; + CellBuffer cb; + CharClassify charClass; + char stylingMask; + int endStyled; + int styleClock; + int enteredModification; + int enteredStyling; + int enteredReadOnlyCount; + + WatcherWithUserData *watchers; + int lenWatchers; + + bool matchesValid; + RESearch *pre; + char *substituted; + +public: + int stylingBits; + int stylingBitsMask; + + int eolMode; + /// Can also be SC_CP_UTF8 to enable UTF-8 mode + int dbcsCodePage; + int tabInChars; + int indentInChars; + int actualIndentInChars; + bool useTabs; + bool tabIndents; + bool backspaceUnindents; + + DecorationList decorations; + + Document(); + virtual ~Document(); + + int AddRef(); + int Release(); + + int LineFromPosition(int pos); + int ClampPositionIntoDocument(int pos); + bool IsCrLf(int pos); + int LenChar(int pos); + bool InGoodUTF8(int pos, int &start, int &end); + int MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd=true); + + // Gateways to modifying document + void ModifiedAt(int pos); + void CheckReadOnly(); + bool DeleteChars(int pos, int len); + bool InsertString(int position, const char *s, int insertLength); + int Undo(); + int Redo(); + bool CanUndo() { return cb.CanUndo(); } + bool CanRedo() { return cb.CanRedo(); } + void DeleteUndoHistory() { cb.DeleteUndoHistory(); } + bool SetUndoCollection(bool collectUndo) { + return cb.SetUndoCollection(collectUndo); + } + bool IsCollectingUndo() { return cb.IsCollectingUndo(); } + void BeginUndoAction() { cb.BeginUndoAction(); } + void EndUndoAction() { cb.EndUndoAction(); } + void SetSavePoint(); + bool IsSavePoint() { return cb.IsSavePoint(); } + + int GetLineIndentation(int line); + void SetLineIndentation(int line, int indent); + int GetLineIndentPosition(int line) const; + int GetColumn(int position); + int FindColumn(int line, int column); + void Indent(bool forwards, int lineBottom, int lineTop); + static char *TransformLineEnds(int *pLenOut, const char *s, size_t len, int eolMode); + void ConvertLineEnds(int eolModeSet); + void SetReadOnly(bool set) { cb.SetReadOnly(set); } + bool IsReadOnly() { return cb.IsReadOnly(); } + + bool InsertChar(int pos, char ch); + bool InsertCString(int position, const char *s); + void ChangeChar(int pos, char ch); + void DelChar(int pos); + void DelCharBack(int pos); + + char CharAt(int position) { return cb.CharAt(position); } + void GetCharRange(char *buffer, int position, int lengthRetrieve) { + cb.GetCharRange(buffer, position, lengthRetrieve); + } + char StyleAt(int position) { return cb.StyleAt(position); } + int GetMark(int line) { return cb.GetMark(line); } + int AddMark(int line, int markerNum); + void AddMarkSet(int line, int valueSet); + void DeleteMark(int line, int markerNum); + void DeleteMarkFromHandle(int markerHandle); + void DeleteAllMarks(int markerNum); + int LineFromHandle(int markerHandle) { return cb.LineFromHandle(markerHandle); } + int LineStart(int line) const; + int LineEnd(int line) const; + int LineEndPosition(int position); + int VCHomePosition(int position); + + int SetLevel(int line, int level); + int GetLevel(int line) { return cb.GetLevel(line); } + void ClearLevels() { cb.ClearLevels(); } + int GetLastChild(int lineParent, int level=-1); + int GetFoldParent(int line); + + void Indent(bool forwards); + int ExtendWordSelect(int pos, int delta, bool onlyWordCharacters=false); + int NextWordStart(int pos, int delta); + int NextWordEnd(int pos, int delta); + int Length() const { return cb.Length(); } + void Allocate(int newSize) { cb.Allocate(newSize); } + long FindText(int minPos, int maxPos, const char *s, + bool caseSensitive, bool word, bool wordStart, bool regExp, bool posix, int *length); + long FindText(int iMessage, unsigned long wParam, long lParam); + const char *SubstituteByPosition(const char *text, int *length); + int LinesTotal() const; + + void ChangeCase(Range r, bool makeUpperCase); + + void SetDefaultCharClasses(bool includeWordClass); + void SetCharClasses(const unsigned char *chars, CharClassify::cc newCharClass); + void SetStylingBits(int bits); + void StartStyling(int position, char mask); + bool SetStyleFor(int length, char style); + bool SetStyles(int length, char *styles); + int GetEndStyled() { return endStyled; } + void EnsureStyledTo(int pos); + int GetStyleClock() { return styleClock; } + void IncrementStyleClock(); + void DecorationFillRange(int position, int value, int fillLength); + + int SetLineState(int line, int state); + int GetLineState(int line) { return cb.GetLineState(line); } + int GetMaxLineState() { return cb.GetMaxLineState(); } + + bool AddWatcher(DocWatcher *watcher, void *userData); + bool RemoveWatcher(DocWatcher *watcher, void *userData); + const WatcherWithUserData *GetWatchers() const { return watchers; } + int GetLenWatchers() const { return lenWatchers; } + + bool IsWordPartSeparator(char ch); + int WordPartLeft(int pos); + int WordPartRight(int pos); + int ExtendStyleRange(int pos, int delta, bool singleLine = false); + bool IsWhiteLine(int line) const; + int ParaUp(int pos); + int ParaDown(int pos); + int IndentSize() { return actualIndentInChars; } + int BraceMatch(int position, int maxReStyle); + +private: + CharClassify::cc WordCharClass(unsigned char ch); + bool IsWordStartAt(int pos); + bool IsWordEndAt(int pos); + bool IsWordAt(int start, int end); + + void NotifyModifyAttempt(); + void NotifySavePoint(bool atSavePoint); + void NotifyModified(DocModification mh); +}; + +/** + * To optimise processing of document modifications by DocWatchers, a hint is passed indicating the + * scope of the change. + * If the DocWatcher is a document view then this can be used to optimise screen updating. + */ +class DocModification { +public: + int modificationType; + int position; + int length; + int linesAdded; /**< Negative if lines deleted. */ + const char *text; /**< Only valid for changes to text, not for changes to style. */ + int line; + int foldLevelNow; + int foldLevelPrev; + + DocModification(int modificationType_, int position_=0, int length_=0, + int linesAdded_=0, const char *text_=0, int line_=0) : + modificationType(modificationType_), + position(position_), + length(length_), + linesAdded(linesAdded_), + text(text_), + line(line_), + foldLevelNow(0), + foldLevelPrev(0) {} + + DocModification(int modificationType_, const Action &act, int linesAdded_=0) : + modificationType(modificationType_), + position(act.position), + length(act.lenData), + linesAdded(linesAdded_), + text(act.data), + line(0), + foldLevelNow(0), + foldLevelPrev(0) {} +}; + +/** + * A class that wants to receive notifications from a Document must be derived from DocWatcher + * and implement the notification methods. It can then be added to the watcher list with AddWatcher. + */ +class DocWatcher { +public: + virtual ~DocWatcher() {} + + virtual void NotifyModifyAttempt(Document *doc, void *userData) = 0; + virtual void NotifySavePoint(Document *doc, void *userData, bool atSavePoint) = 0; + virtual void NotifyModified(Document *doc, DocModification mh, void *userData) = 0; + virtual void NotifyDeleted(Document *doc, void *userData) = 0; + virtual void NotifyStyleNeeded(Document *doc, void *userData, int endPos) = 0; +}; + +#ifdef SCI_NAMESPACE +} +#endif + +#endif diff --git a/scintilla/src/DocumentAccessor.cxx b/scintilla/src/DocumentAccessor.cxx new file mode 100644 index 00000000..2ef741e9 --- /dev/null +++ b/scintilla/src/DocumentAccessor.cxx @@ -0,0 +1,200 @@ +// Scintilla source code edit control +/** @file DocumentAccessor.cxx + ** Rapid easy access to contents of a Scintilla. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "DocumentAccessor.h" +#include "SplitVector.h" +#include "Partitioning.h" +#include "RunStyles.h" +#include "CellBuffer.h" +#include "Scintilla.h" +#include "CharClassify.h" +#include "Decoration.h" +#include "Document.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +DocumentAccessor::~DocumentAccessor() { +} + +bool DocumentAccessor::InternalIsLeadByte(char ch) { + if (SC_CP_UTF8 == codePage) + // For lexing, all characters >= 0x80 are treated the + // same so none is considered a lead byte. + return false; + else + return Platform::IsDBCSLeadByte(codePage, ch); +} + +void DocumentAccessor::Fill(int position) { + if (lenDoc == -1) + lenDoc = pdoc->Length(); + startPos = position - slopSize; + if (startPos + bufferSize > lenDoc) + startPos = lenDoc - bufferSize; + if (startPos < 0) + startPos = 0; + endPos = startPos + bufferSize; + if (endPos > lenDoc) + endPos = lenDoc; + + pdoc->GetCharRange(buf, startPos, endPos-startPos); + buf[endPos-startPos] = '\0'; +} + +bool DocumentAccessor::Match(int pos, const char *s) { + for (int i=0; *s; i++) { + if (*s != SafeGetCharAt(pos+i)) + return false; + s++; + } + return true; +} + +char DocumentAccessor::StyleAt(int position) { + // Mask off all bits which aren't in the 'mask'. + return static_cast(pdoc->StyleAt(position) & mask); +} + +int DocumentAccessor::GetLine(int position) { + return pdoc->LineFromPosition(position); +} + +int DocumentAccessor::LineStart(int line) { + return pdoc->LineStart(line); +} + +int DocumentAccessor::LevelAt(int line) { + return pdoc->GetLevel(line); +} + +int DocumentAccessor::Length() { + if (lenDoc == -1) + lenDoc = pdoc->Length(); + return lenDoc; +} + +int DocumentAccessor::GetLineState(int line) { + return pdoc->GetLineState(line); +} + +int DocumentAccessor::SetLineState(int line, int state) { + return pdoc->SetLineState(line, state); +} + +void DocumentAccessor::StartAt(unsigned int start, char chMask) { + // Store the mask specified for use with StyleAt. + mask = chMask; + pdoc->StartStyling(start, chMask); + startPosStyling = start; +} + +void DocumentAccessor::StartSegment(unsigned int pos) { + startSeg = pos; +} + +void DocumentAccessor::ColourTo(unsigned int pos, int chAttr) { + // Only perform styling if non empty range + if (pos != startSeg - 1) { + PLATFORM_ASSERT(pos >= startSeg); + if (pos < startSeg) { + return; + } + + if (validLen + (pos - startSeg + 1) >= bufferSize) + Flush(); + if (validLen + (pos - startSeg + 1) >= bufferSize) { + // Too big for buffer so send directly + pdoc->SetStyleFor(pos - startSeg + 1, static_cast(chAttr)); + } else { + if (chAttr != chWhile) + chFlags = 0; + chAttr |= chFlags; + for (unsigned int i = startSeg; i <= pos; i++) { + PLATFORM_ASSERT((startPosStyling + validLen) < Length()); + styleBuf[validLen++] = static_cast(chAttr); + } + } + } + startSeg = pos+1; +} + +void DocumentAccessor::SetLevel(int line, int level) { + pdoc->SetLevel(line, level); +} + +void DocumentAccessor::Flush() { + startPos = extremePosition; + lenDoc = -1; + if (validLen > 0) { + pdoc->SetStyles(validLen, styleBuf); + startPosStyling += validLen; + validLen = 0; + } +} + +int DocumentAccessor::IndentAmount(int line, int *flags, PFNIsCommentLeader pfnIsCommentLeader) { + int end = Length(); + int spaceFlags = 0; + + // Determines the indentation level of the current line and also checks for consistent + // indentation compared to the previous line. + // Indentation is judged consistent when the indentation whitespace of each line lines + // the same or the indentation of one line is a prefix of the other. + + int pos = LineStart(line); + char ch = (*this)[pos]; + int indent = 0; + bool inPrevPrefix = line > 0; + int posPrev = inPrevPrefix ? LineStart(line-1) : 0; + while ((ch == ' ' || ch == '\t') && (pos < end)) { + if (inPrevPrefix) { + char chPrev = (*this)[posPrev++]; + if (chPrev == ' ' || chPrev == '\t') { + if (chPrev != ch) + spaceFlags |= wsInconsistent; + } else { + inPrevPrefix = false; + } + } + if (ch == ' ') { + spaceFlags |= wsSpace; + indent++; + } else { // Tab + spaceFlags |= wsTab; + if (spaceFlags & wsSpace) + spaceFlags |= wsSpaceTab; + indent = (indent / 8 + 1) * 8; + } + ch = (*this)[++pos]; + } + + *flags = spaceFlags; + indent += SC_FOLDLEVELBASE; + // if completely empty line or the start of a comment... + if ((ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') || + (pfnIsCommentLeader && (*pfnIsCommentLeader)(*this, pos, end-pos)) ) + return indent | SC_FOLDLEVELWHITEFLAG; + else + return indent; +} + +void DocumentAccessor::IndicatorFill(int start, int end, int indicator, int value) { + pdoc->decorations.SetCurrentIndicator(indicator); + pdoc->DecorationFillRange(start, value, end - start); +} + diff --git a/scintilla/src/DocumentAccessor.h b/scintilla/src/DocumentAccessor.h new file mode 100644 index 00000000..6f1ce541 --- /dev/null +++ b/scintilla/src/DocumentAccessor.h @@ -0,0 +1,76 @@ +// Scintilla source code edit control +/** @file DocumentAccessor.h + ** Implementation of BufferAccess and StylingAccess on a Scintilla + ** rapid easy access to contents of a Scintilla. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +class Document; + +/** + */ +class DocumentAccessor : public Accessor { + // Private so DocumentAccessor objects can not be copied + DocumentAccessor(const DocumentAccessor &source) : Accessor(), props(source.props) {} + DocumentAccessor &operator=(const DocumentAccessor &) { return *this; } + +protected: + Document *pdoc; + PropSet &props; + WindowID id; + int lenDoc; + + char styleBuf[bufferSize]; + int validLen; + char chFlags; + char chWhile; + unsigned int startSeg; + int startPosStyling; + int mask; + + bool InternalIsLeadByte(char ch); + void Fill(int position); + +public: + DocumentAccessor(Document *pdoc_, PropSet &props_, WindowID id_=0) : + Accessor(), pdoc(pdoc_), props(props_), id(id_), + lenDoc(-1), validLen(0), chFlags(0), chWhile(0), + startSeg(0), startPosStyling(0), + mask(127) { // Initialize the mask to be big enough for any lexer. + } + ~DocumentAccessor(); + bool Match(int pos, const char *s); + char StyleAt(int position); + int GetLine(int position); + int LineStart(int line); + int LevelAt(int line); + int Length(); + void Flush(); + int GetLineState(int line); + int SetLineState(int line, int state); + int GetPropertyInt(const char *key, int defaultValue=0) { + return props.GetInt(key, defaultValue); + } + char *GetProperties() { + return props.ToString(); + } + WindowID GetWindow() { return id; } + + void StartAt(unsigned int start, char chMask=31); + void SetFlags(char chFlags_, char chWhile_) {chFlags = chFlags_; chWhile = chWhile_; }; + unsigned int GetStartSegment() { return startSeg; } + void StartSegment(unsigned int pos); + void ColourTo(unsigned int pos, int chAttr); + void SetLevel(int line, int level); + int IndentAmount(int line, int *flags, PFNIsCommentLeader pfnIsCommentLeader = 0); + void IndicatorFill(int start, int end, int indicator, int value); +}; + +#ifdef SCI_NAMESPACE +} +#endif diff --git a/scintilla/src/Editor.cxx b/scintilla/src/Editor.cxx new file mode 100644 index 00000000..908d0b31 --- /dev/null +++ b/scintilla/src/Editor.cxx @@ -0,0 +1,7627 @@ +// Scintilla source code edit control +/** @file Editor.cxx + ** Main code for the edit control. + **/ +// Copyright 1998-2004 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include + +#include "Platform.h" + +#ifndef PLAT_QT +#define INCLUDE_DEPRECATED_FEATURES +#endif +#include "Scintilla.h" + +#include "SplitVector.h" +#include "Partitioning.h" +#include "RunStyles.h" +#include "ContractionState.h" +#include "CellBuffer.h" +#include "KeyMap.h" +#include "Indicator.h" +#include "XPM.h" +#include "LineMarker.h" +#include "Style.h" +#include "ViewStyle.h" +#include "CharClassify.h" +#include "Decoration.h" +#include "Document.h" +#include "PositionCache.h" +#include "Editor.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +/* + return whether this modification represents an operation that + may reasonably be deferred (not done now OR [possibly] at all) +*/ +static bool CanDeferToLastStep(const DocModification& mh) { + if (mh.modificationType & (SC_MOD_BEFOREINSERT | SC_MOD_BEFOREDELETE)) + return true; // CAN skip + if (!(mh.modificationType & (SC_PERFORMED_UNDO | SC_PERFORMED_REDO))) + return false; // MUST do + if (mh.modificationType & SC_MULTISTEPUNDOREDO) + return true; // CAN skip + return false; // PRESUMABLY must do +} + +static bool CanEliminate(const DocModification& mh) { + return + (mh.modificationType & (SC_MOD_BEFOREINSERT | SC_MOD_BEFOREDELETE)) != 0; +} + +/* + return whether this modification represents the FINAL step + in a [possibly lengthy] multi-step Undo/Redo sequence +*/ +static bool IsLastStep(const DocModification& mh) { + return + (mh.modificationType & (SC_PERFORMED_UNDO | SC_PERFORMED_REDO)) != 0 + && (mh.modificationType & SC_MULTISTEPUNDOREDO) != 0 + && (mh.modificationType & SC_LASTSTEPINUNDOREDO) != 0 + && (mh.modificationType & SC_MULTILINEUNDOREDO) != 0; +} + +Caret::Caret() : + active(false), on(false), period(500) {} + +Timer::Timer() : + ticking(false), ticksToWait(0), tickerID(0) {} + +Idler::Idler() : + state(false), idlerID(0) {} + +static inline bool IsControlCharacter(int ch) { + // iscntrl returns true for lots of chars > 127 which are displayable + return ch >= 0 && ch < ' '; +} + +Editor::Editor() { + ctrlID = 0; + + stylesValid = false; + + printMagnification = 0; + printColourMode = SC_PRINT_NORMAL; + printWrapState = eWrapWord; + cursorMode = SC_CURSORNORMAL; + controlCharSymbol = 0; /* Draw the control characters */ + + hasFocus = false; + hideSelection = false; + inOverstrike = false; + errorStatus = 0; + mouseDownCaptures = true; + + bufferedDraw = true; + twoPhaseDraw = true; + + lastClickTime = 0; + dwellDelay = SC_TIME_FOREVER; + ticksToDwell = SC_TIME_FOREVER; + dwelling = false; + ptMouseLast.x = 0; + ptMouseLast.y = 0; + inDragDrop = ddNone; + dropWentOutside = false; + posDrag = invalidPosition; + posDrop = invalidPosition; + selectionType = selChar; + + lastXChosen = 0; + lineAnchor = 0; + originalAnchorPos = 0; + + selType = selStream; + moveExtendsSelection = false; + xStartSelect = 0; + xEndSelect = 0; + primarySelection = true; + + caretXPolicy = CARET_SLOP | CARET_EVEN; + caretXSlop = 50; + + caretYPolicy = CARET_EVEN; + caretYSlop = 0; + + searchAnchor = 0; + + xOffset = 0; + xCaretMargin = 50; + horizontalScrollBarVisible = true; + scrollWidth = 2000; + trackLineWidth = false; + lineWidthMaxSeen = 0; + verticalScrollBarVisible = true; + endAtLastLine = true; + caretSticky = false; + + pixmapLine = Surface::Allocate(); + pixmapSelMargin = Surface::Allocate(); + pixmapSelPattern = Surface::Allocate(); + pixmapIndentGuide = Surface::Allocate(); + pixmapIndentGuideHighlight = Surface::Allocate(); + + currentPos = 0; + anchor = 0; + + targetStart = 0; + targetEnd = 0; + searchFlags = 0; + + topLine = 0; + posTopLine = 0; + + lengthForEncode = -1; + + needUpdateUI = true; + braces[0] = invalidPosition; + braces[1] = invalidPosition; + bracesMatchStyle = STYLE_BRACEBAD; + highlightGuideColumn = 0; + + theEdge = 0; + + paintState = notPainting; + + modEventMask = SC_MODEVENTMASKALL; + + pdoc = new Document(); + pdoc->AddRef(); + pdoc->AddWatcher(this, 0); + + recordingMacro = false; + foldFlags = 0; + + wrapState = eWrapNone; + wrapWidth = LineLayout::wrapWidthInfinite; + wrapStart = wrapLineLarge; + wrapEnd = wrapLineLarge; + wrapVisualFlags = 0; + wrapVisualFlagsLocation = 0; + wrapVisualStartIndent = 0; + actualWrapVisualStartIndent = 0; + + convertPastes = true; + + hsStart = -1; + hsEnd = -1; + + llc.SetLevel(LineLayoutCache::llcCaret); + posCache.SetSize(0x400); +} + +Editor::~Editor() { + pdoc->RemoveWatcher(this, 0); + pdoc->Release(); + pdoc = 0; + DropGraphics(); + delete pixmapLine; + delete pixmapSelMargin; + delete pixmapSelPattern; + delete pixmapIndentGuide; + delete pixmapIndentGuideHighlight; +} + +void Editor::Finalise() { + SetIdle(false); + CancelModes(); +} + +void Editor::DropGraphics() { + pixmapLine->Release(); + pixmapSelMargin->Release(); + pixmapSelPattern->Release(); + pixmapIndentGuide->Release(); + pixmapIndentGuideHighlight->Release(); +} + +void Editor::InvalidateStyleData() { + stylesValid = false; + DropGraphics(); + palette.Release(); + llc.Invalidate(LineLayout::llInvalid); + posCache.Clear(); + if (selType == selRectangle) { + xStartSelect = XFromPosition(anchor); + xEndSelect = XFromPosition(currentPos); + } +} + +void Editor::InvalidateStyleRedraw() { + NeedWrapping(); + InvalidateStyleData(); + Redraw(); +} + +void Editor::RefreshColourPalette(Palette &pal, bool want) { + vs.RefreshColourPalette(pal, want); +} + +void Editor::RefreshStyleData() { + if (!stylesValid) { + stylesValid = true; + AutoSurface surface(this); + if (surface) { + vs.Refresh(*surface); + RefreshColourPalette(palette, true); + palette.Allocate(wMain); + RefreshColourPalette(palette, false); + } + SetScrollBars(); + } +} + +PRectangle Editor::GetClientRectangle() { + return wMain.GetClientPosition(); +} + +PRectangle Editor::GetTextRectangle() { + PRectangle rc = GetClientRectangle(); + rc.left += vs.fixedColumnWidth; + rc.right -= vs.rightMarginWidth; + return rc; +} + +int Editor::LinesOnScreen() { + PRectangle rcClient = GetClientRectangle(); + int htClient = rcClient.bottom - rcClient.top; + //Platform::DebugPrintf("lines on screen = %d\n", htClient / lineHeight + 1); + return htClient / vs.lineHeight; +} + +int Editor::LinesToScroll() { + int retVal = LinesOnScreen() - 1; + if (retVal < 1) + return 1; + else + return retVal; +} + +int Editor::MaxScrollPos() { + //Platform::DebugPrintf("Lines %d screen = %d maxScroll = %d\n", + //LinesTotal(), LinesOnScreen(), LinesTotal() - LinesOnScreen() + 1); + int retVal = cs.LinesDisplayed(); + if (endAtLastLine) { + retVal -= LinesOnScreen(); + } else { + retVal--; + } + if (retVal < 0) { + return 0; + } else { + return retVal; + } +} + +const char *ControlCharacterString(unsigned char ch) { + const char *reps[] = { + "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", + "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI", + "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", + "CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US" + }; + if (ch < (sizeof(reps) / sizeof(reps[0]))) { + return reps[ch]; + } else { + return "BAD"; + } +} + +/** + * Convenience class to ensure LineLayout objects are always disposed. + */ +class AutoLineLayout { + LineLayoutCache &llc; + LineLayout *ll; + AutoLineLayout &operator=(const AutoLineLayout &) { return * this; } +public: + AutoLineLayout(LineLayoutCache &llc_, LineLayout *ll_) : llc(llc_), ll(ll_) {} + ~AutoLineLayout() { + llc.Dispose(ll); + ll = 0; + } + LineLayout *operator->() const { + return ll; + } + operator LineLayout *() const { + return ll; + } + void Set(LineLayout *ll_) { + llc.Dispose(ll); + ll = ll_; + } +}; + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +/** + * Allows to iterate through the lines of a selection. + * Althought it can be called for a stream selection, in most cases + * it is inefficient and it should be used only for + * a rectangular or a line selection. + */ +class SelectionLineIterator { +private: + Editor *ed; + int line; ///< Current line within the iteration. + bool forward; ///< True if iterating by increasing line number, false otherwise. + int selStart, selEnd; ///< Positions of the start and end of the selection relative to the start of the document. + int minX, maxX; ///< Left and right of selection rectangle. + +public: + int lineStart, lineEnd; ///< Line numbers, first and last lines of the selection. + int startPos, endPos; ///< Positions of the beginning and end of the selection on the current line. + + void Reset() { + if (forward) { + line = lineStart; + } else { + line = lineEnd; + } + } + + SelectionLineIterator(Editor *ed_, bool forward_ = true) : line(0), startPos(0), endPos(0) { + ed = ed_; + forward = forward_; + selStart = ed->SelectionStart(); + selEnd = ed->SelectionEnd(); + lineStart = ed->pdoc->LineFromPosition(selStart); + lineEnd = ed->pdoc->LineFromPosition(selEnd); + // Left of rectangle + minX = Platform::Minimum(ed->xStartSelect, ed->xEndSelect); + // Right of rectangle + maxX = Platform::Maximum(ed->xStartSelect, ed->xEndSelect); + Reset(); + } + ~SelectionLineIterator() {} + + void SetAt(int line) { + if (line < lineStart || line > lineEnd) { + startPos = endPos = INVALID_POSITION; + } else { + if (ed->selType == ed->selRectangle) { + // Measure line and return character closest to minX + startPos = ed->PositionFromLineX(line, minX); + // Measure line and return character closest to maxX + endPos = ed->PositionFromLineX(line, maxX); + } else if (ed->selType == ed->selLines) { + startPos = ed->pdoc->LineStart(line); + endPos = ed->pdoc->LineStart(line + 1); + } else { // Stream selection, here only for completion + if (line == lineStart) { + startPos = selStart; + } else { + startPos = ed->pdoc->LineStart(line); + } + if (line == lineEnd) { + endPos = selEnd; + } else { + endPos = ed->pdoc->LineStart(line + 1); + } + } + } + } + bool Iterate() { + SetAt(line); + if (forward) { + line++; + } else { + line--; + } + return startPos != INVALID_POSITION; + } +}; + +#ifdef SCI_NAMESPACE +} +#endif + +Point Editor::LocationFromPosition(int pos) { + Point pt; + RefreshStyleData(); + if (pos == INVALID_POSITION) + return pt; + int line = pdoc->LineFromPosition(pos); + int lineVisible = cs.DisplayFromDoc(line); + //Platform::DebugPrintf("line=%d\n", line); + AutoSurface surface(this); + AutoLineLayout ll(llc, RetrieveLineLayout(line)); + if (surface && ll) { + // -1 because of adding in for visible lines in following loop. + pt.y = (lineVisible - topLine - 1) * vs.lineHeight; + pt.x = 0; + unsigned int posLineStart = pdoc->LineStart(line); + LayoutLine(line, surface, vs, ll, wrapWidth); + int posInLine = pos - posLineStart; + // In case of very long line put x at arbitrary large position + if (posInLine > ll->maxLineLength) { + pt.x = ll->positions[ll->maxLineLength] - ll->positions[ll->LineStart(ll->lines)]; + } + + for (int subLine = 0; subLine < ll->lines; subLine++) { + if ((posInLine >= ll->LineStart(subLine)) && (posInLine <= ll->LineStart(subLine + 1))) { + pt.x = ll->positions[posInLine] - ll->positions[ll->LineStart(subLine)]; + if (actualWrapVisualStartIndent != 0) { + int lineStart = ll->LineStart(subLine); + if (lineStart != 0) // Wrapped + pt.x += actualWrapVisualStartIndent * vs.aveCharWidth; + } + } + if (posInLine >= ll->LineStart(subLine)) { + pt.y += vs.lineHeight; + } + } + pt.x += vs.fixedColumnWidth - xOffset; + } + return pt; +} + +int Editor::XFromPosition(int pos) { + Point pt = LocationFromPosition(pos); + return pt.x - vs.fixedColumnWidth + xOffset; +} + +int Editor::LineFromLocation(Point pt) { + return cs.DocFromDisplay(pt.y / vs.lineHeight + topLine); +} + +void Editor::SetTopLine(int topLineNew) { + topLine = topLineNew; + posTopLine = pdoc->LineStart(cs.DocFromDisplay(topLine)); +} + +int Editor::PositionFromLocation(Point pt) { + RefreshStyleData(); + 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; + } + if (visibleLine < 0) + visibleLine = 0; + int lineDoc = cs.DocFromDisplay(visibleLine); + if (lineDoc >= pdoc->LinesTotal()) + return pdoc->Length(); + unsigned int posLineStart = pdoc->LineStart(lineDoc); + int retVal = posLineStart; + AutoSurface surface(this); + AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc)); + if (surface && ll) { + LayoutLine(lineDoc, surface, vs, ll, wrapWidth); + int lineStartSet = cs.DisplayFromDoc(lineDoc); + int subLine = visibleLine - lineStartSet; + if (subLine < ll->lines) { + int lineStart = ll->LineStart(subLine); + int lineEnd = ll->LineLastVisible(subLine); + int subLineStart = ll->positions[lineStart]; + + if (actualWrapVisualStartIndent != 0) { + if (lineStart != 0) // Wrapped + pt.x -= actualWrapVisualStartIndent * vs.aveCharWidth; + } + int i = ll->FindBefore(pt.x + subLineStart, lineStart, lineEnd); + while (i < lineEnd) { + if ((pt.x + subLineStart) < ((ll->positions[i] + ll->positions[i + 1]) / 2)) { + return pdoc->MovePositionOutsideChar(i + posLineStart, 1); + } + i++; + } + return lineEnd + posLineStart; + } + retVal = ll->numCharsInLine + posLineStart; + } + return retVal; +} + +// Like PositionFromLocation but INVALID_POSITION returned when not near any text. +int Editor::PositionFromLocationClose(Point pt) { + RefreshStyleData(); + PRectangle rcClient = GetTextRectangle(); + if (!rcClient.Contains(pt)) + return INVALID_POSITION; + if (pt.x < vs.fixedColumnWidth) + return INVALID_POSITION; + if (pt.y < 0) + return INVALID_POSITION; + 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; + } + int lineDoc = cs.DocFromDisplay(visibleLine); + if (lineDoc < 0) + return INVALID_POSITION; + if (lineDoc >= pdoc->LinesTotal()) + return INVALID_POSITION; + AutoSurface surface(this); + AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc)); + if (surface && ll) { + LayoutLine(lineDoc, surface, vs, ll, wrapWidth); + unsigned int posLineStart = pdoc->LineStart(lineDoc); + int lineStartSet = cs.DisplayFromDoc(lineDoc); + int subLine = visibleLine - lineStartSet; + if (subLine < ll->lines) { + int lineStart = ll->LineStart(subLine); + int lineEnd = ll->LineLastVisible(subLine); + int subLineStart = ll->positions[lineStart]; + + if (actualWrapVisualStartIndent != 0) { + if (lineStart != 0) // Wrapped + pt.x -= actualWrapVisualStartIndent * vs.aveCharWidth; + } + int i = ll->FindBefore(pt.x + subLineStart, lineStart, lineEnd); + while (i < lineEnd) { + if ((pt.x + subLineStart) < ((ll->positions[i] + ll->positions[i + 1]) / 2)) { + return pdoc->MovePositionOutsideChar(i + posLineStart, 1); + } + i++; + } + if (pt.x < (ll->positions[lineEnd] - subLineStart)) { + return pdoc->MovePositionOutsideChar(lineEnd + posLineStart, 1); + } + } + } + + return INVALID_POSITION; +} + +/** + * Find the document position corresponding to an x coordinate on a particular document line. + * Ensure is between whole characters when document is in multi-byte or UTF-8 mode. + */ +int Editor::PositionFromLineX(int lineDoc, int x) { + RefreshStyleData(); + if (lineDoc >= pdoc->LinesTotal()) + return pdoc->Length(); + //Platform::DebugPrintf("Position of (%d,%d) line = %d top=%d\n", pt.x, pt.y, line, topLine); + AutoSurface surface(this); + AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc)); + int retVal = 0; + if (surface && ll) { + unsigned int posLineStart = pdoc->LineStart(lineDoc); + LayoutLine(lineDoc, surface, vs, ll, wrapWidth); + retVal = ll->numCharsInLine + posLineStart; + int subLine = 0; + int lineStart = ll->LineStart(subLine); + int lineEnd = ll->LineLastVisible(subLine); + int subLineStart = ll->positions[lineStart]; + + if (actualWrapVisualStartIndent != 0) { + if (lineStart != 0) // Wrapped + x -= actualWrapVisualStartIndent * vs.aveCharWidth; + } + int i = ll->FindBefore(x + subLineStart, lineStart, lineEnd); + while (i < lineEnd) { + if ((x + subLineStart) < ((ll->positions[i] + ll->positions[i + 1]) / 2)) { + retVal = pdoc->MovePositionOutsideChar(i + posLineStart, 1); + break; + } + i++; + } + } + return retVal; +} + +/** + * If painting then abandon the painting because a wider redraw is needed. + * @return true if calling code should stop drawing. + */ +bool Editor::AbandonPaint() { + if ((paintState == painting) && !paintingAllText) { + paintState = paintAbandoned; + } + return paintState == paintAbandoned; +} + +void Editor::RedrawRect(PRectangle rc) { + //Platform::DebugPrintf("Redraw %0d,%0d - %0d,%0d\n", rc.left, rc.top, rc.right, rc.bottom); + + // Clip the redraw rectangle into the client area + PRectangle rcClient = GetClientRectangle(); + if (rc.top < rcClient.top) + rc.top = rcClient.top; + if (rc.bottom > rcClient.bottom) + rc.bottom = rcClient.bottom; + if (rc.left < rcClient.left) + rc.left = rcClient.left; + if (rc.right > rcClient.right) + rc.right = rcClient.right; + + if ((rc.bottom > rc.top) && (rc.right > rc.left)) { + wMain.InvalidateRectangle(rc); + } +} + +void Editor::Redraw() { + //Platform::DebugPrintf("Redraw all\n"); + PRectangle rcClient = GetClientRectangle(); + wMain.InvalidateRectangle(rcClient); + //wMain.InvalidateAll(); +} + +void Editor::RedrawSelMargin(int line) { + if (!AbandonPaint()) { + if (vs.maskInLine) { + Redraw(); + } else { + PRectangle rcSelMargin = GetClientRectangle(); + rcSelMargin.right = vs.fixedColumnWidth; + if (line != -1) { + int position = pdoc->LineStart(line); + PRectangle rcLine = RectangleFromRange(position, position); + rcSelMargin.top = rcLine.top; + rcSelMargin.bottom = rcLine.bottom; + } + wMain.InvalidateRectangle(rcSelMargin); + } + } +} + +PRectangle Editor::RectangleFromRange(int start, int end) { + int minPos = start; + if (minPos > end) + minPos = end; + int maxPos = start; + if (maxPos < end) + maxPos = end; + int minLine = cs.DisplayFromDoc(pdoc->LineFromPosition(minPos)); + int lineDocMax = pdoc->LineFromPosition(maxPos); + int maxLine = cs.DisplayFromDoc(lineDocMax) + cs.GetHeight(lineDocMax) - 1; + PRectangle rcClient = GetTextRectangle(); + PRectangle rc; + rc.left = vs.fixedColumnWidth; + rc.top = (minLine - topLine) * vs.lineHeight; + if (rc.top < 0) + rc.top = 0; + rc.right = rcClient.right; + rc.bottom = (maxLine - topLine + 1) * vs.lineHeight; + // Ensure PRectangle is within 16 bit space + rc.top = Platform::Clamp(rc.top, -32000, 32000); + rc.bottom = Platform::Clamp(rc.bottom, -32000, 32000); + + return rc; +} + +void Editor::InvalidateRange(int start, int end) { + RedrawRect(RectangleFromRange(start, end)); +} + +int Editor::CurrentPosition() { + return currentPos; +} + +bool Editor::SelectionEmpty() { + return anchor == currentPos; +} + +int Editor::SelectionStart() { + return Platform::Minimum(currentPos, anchor); +} + +int Editor::SelectionEnd() { + return Platform::Maximum(currentPos, anchor); +} + +void Editor::SetRectangularRange() { + if (selType == selRectangle) { + xStartSelect = XFromPosition(anchor); + xEndSelect = XFromPosition(currentPos); + } +} + +void Editor::InvalidateSelection(int currentPos_, int anchor_, bool invalidateWholeSelection) { + if (anchor != anchor_ || selType == selRectangle) { + invalidateWholeSelection = true; + } + int firstAffected = currentPos; + if (invalidateWholeSelection) { + if (firstAffected > anchor) + firstAffected = anchor; + if (firstAffected > anchor_) + firstAffected = anchor_; + } + if (firstAffected > currentPos_) + firstAffected = currentPos_; + int lastAffected = currentPos; + if (invalidateWholeSelection) { + if (lastAffected < anchor) + lastAffected = anchor; + if (lastAffected < anchor_) + lastAffected = anchor_; + } + if (lastAffected < (currentPos_ + 1)) // +1 ensures caret repainted + lastAffected = (currentPos_ + 1); + needUpdateUI = true; + InvalidateRange(firstAffected, lastAffected); +} + +void Editor::SetSelection(int currentPos_, int anchor_) { + currentPos_ = pdoc->ClampPositionIntoDocument(currentPos_); + anchor_ = pdoc->ClampPositionIntoDocument(anchor_); + if ((currentPos != currentPos_) || (anchor != anchor_)) { + InvalidateSelection(currentPos_, anchor_, true); + currentPos = currentPos_; + anchor = anchor_; + } + SetRectangularRange(); + ClaimSelection(); +} + +void Editor::SetSelection(int currentPos_) { + currentPos_ = pdoc->ClampPositionIntoDocument(currentPos_); + if (currentPos != currentPos_) { + InvalidateSelection(currentPos_, anchor, false); + currentPos = currentPos_; + } + SetRectangularRange(); + ClaimSelection(); +} + +void Editor::SetEmptySelection(int currentPos_) { + selType = selStream; + moveExtendsSelection = false; + SetSelection(currentPos_, currentPos_); +} + +bool Editor::RangeContainsProtected(int start, int end) const { + if (vs.ProtectionActive()) { + if (start > end) { + int t = start; + start = end; + end = t; + } + int mask = pdoc->stylingBitsMask; + for (int pos = start; pos < end; pos++) { + if (vs.styles[pdoc->StyleAt(pos) & mask].IsProtected()) + return true; + } + } + return false; +} + +bool Editor::SelectionContainsProtected() { + // DONE, but untested...: make support rectangular selection + bool scp = false; + if (selType == selStream) { + scp = RangeContainsProtected(anchor, currentPos); + } else { + SelectionLineIterator lineIterator(this); + while (lineIterator.Iterate()) { + if (RangeContainsProtected(lineIterator.startPos, lineIterator.endPos)) { + scp = true; + break; + } + } + } + return scp; +} + +/** + * Asks document to find a good position and then moves out of any invisible positions. + */ +int Editor::MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd) { + pos = pdoc->MovePositionOutsideChar(pos, moveDir, checkLineEnd); + if (vs.ProtectionActive()) { + int mask = pdoc->stylingBitsMask; + if (moveDir > 0) { + if ((pos > 0) && vs.styles[pdoc->StyleAt(pos - 1) & mask].IsProtected()) { + while ((pos < pdoc->Length()) && + (vs.styles[pdoc->StyleAt(pos) & mask].IsProtected())) + pos++; + } + } else if (moveDir < 0) { + if (vs.styles[pdoc->StyleAt(pos) & mask].IsProtected()) { + while ((pos > 0) && + (vs.styles[pdoc->StyleAt(pos - 1) & mask].IsProtected())) + pos--; + } + } + } + return pos; +} + +int Editor::MovePositionTo(int newPos, selTypes sel, bool ensureVisible) { + int delta = newPos - currentPos; + newPos = pdoc->ClampPositionIntoDocument(newPos); + newPos = MovePositionOutsideChar(newPos, delta); + if (sel != noSel) { + selType = sel; + } + if (sel != noSel || moveExtendsSelection) { + SetSelection(newPos); + } else { + SetEmptySelection(newPos); + } + ShowCaretAtCurrentPosition(); + if (ensureVisible) { + EnsureCaretVisible(); + } + NotifyMove(newPos); + return 0; +} + +int Editor::MovePositionSoVisible(int pos, int moveDir) { + pos = pdoc->ClampPositionIntoDocument(pos); + pos = MovePositionOutsideChar(pos, moveDir); + int lineDoc = pdoc->LineFromPosition(pos); + if (cs.GetVisible(lineDoc)) { + return pos; + } else { + int lineDisplay = cs.DisplayFromDoc(lineDoc); + if (moveDir > 0) { + // lineDisplay is already line before fold as lines in fold use display line of line after fold + lineDisplay = Platform::Clamp(lineDisplay, 0, cs.LinesDisplayed()); + return pdoc->LineStart(cs.DocFromDisplay(lineDisplay)); + } else { + lineDisplay = Platform::Clamp(lineDisplay - 1, 0, cs.LinesDisplayed()); + return pdoc->LineEnd(cs.DocFromDisplay(lineDisplay)); + } + } +} + +/** + * Choose the x position that the caret will try to stick to + * as it moves up and down. + */ +void Editor::SetLastXChosen() { + Point pt = LocationFromPosition(currentPos); + lastXChosen = pt.x; +} + +void Editor::ScrollTo(int line, bool moveThumb) { + int topLineNew = Platform::Clamp(line, 0, MaxScrollPos()); + if (topLineNew != topLine) { + // Try to optimise small scrolls + int linesToMove = topLine - topLineNew; + SetTopLine(topLineNew); + ShowCaretAtCurrentPosition(); + // Perform redraw rather than scroll if many lines would be redrawn anyway. +#ifndef UNDER_CE + if ((abs(linesToMove) <= 10) && (paintState == notPainting)) { + ScrollText(linesToMove); + } else { + Redraw(); + } +#else + Redraw(); +#endif + if (moveThumb) { + SetVerticalScrollPos(); + } + NotifyScrolled(); + } +} + +void Editor::ScrollText(int /* linesToMove */) { + //Platform::DebugPrintf("Editor::ScrollText %d\n", linesToMove); + Redraw(); +} + +void Editor::HorizontalScrollTo(int xPos) { + //Platform::DebugPrintf("HorizontalScroll %d\n", xPos); + if (xPos < 0) + xPos = 0; + if ((wrapState == eWrapNone) && (xOffset != xPos)) { + xOffset = xPos; + SetHorizontalScrollPos(); + RedrawRect(GetClientRectangle()); + } + + NotifyScrolled(); +} + +void Editor::MoveCaretInsideView(bool ensureVisible) { + PRectangle rcClient = GetTextRectangle(); + Point pt = LocationFromPosition(currentPos); + if (pt.y < rcClient.top) { + MovePositionTo(PositionFromLocation( + Point(lastXChosen, rcClient.top)), + noSel, ensureVisible); + } else if ((pt.y + vs.lineHeight - 1) > rcClient.bottom) { + int yOfLastLineFullyDisplayed = rcClient.top + (LinesOnScreen() - 1) * vs.lineHeight; + MovePositionTo(PositionFromLocation( + Point(lastXChosen, rcClient.top + yOfLastLineFullyDisplayed)), + noSel, ensureVisible); + } +} + +int Editor::DisplayFromPosition(int pos) { + int lineDoc = pdoc->LineFromPosition(pos); + int lineDisplay = cs.DisplayFromDoc(lineDoc); + AutoSurface surface(this); + AutoLineLayout ll(llc, RetrieveLineLayout(lineDoc)); + if (surface && ll) { + LayoutLine(lineDoc, surface, vs, ll, wrapWidth); + unsigned int posLineStart = pdoc->LineStart(lineDoc); + int posInLine = pos - posLineStart; + lineDisplay--; // To make up for first increment ahead. + for (int subLine = 0; subLine < ll->lines; subLine++) { + if (posInLine >= ll->LineStart(subLine)) { + lineDisplay++; + } + } + } + return lineDisplay; +} + +/** + * Ensure the caret is reasonably visible in context. + * +Caret policy in SciTE + +If slop is set, we can define a slop value. +This value defines an unwanted zone (UZ) where the caret is... unwanted. +This zone is defined as a number of pixels near the vertical margins, +and as a number of lines near the horizontal margins. +By keeping the caret away from the edges, it is seen within its context, +so it is likely that the identifier that the caret is on can be completely seen, +and that the current line is seen with some of the lines following it which are +often dependent on that line. + +If strict is set, the policy is enforced... strictly. +The caret is centred on the display if slop is not set, +and cannot go in the UZ if slop is set. + +If jumps is set, the display is moved more energetically +so the caret can move in the same direction longer before the policy is applied again. +'3UZ' notation is used to indicate three time the size of the UZ as a distance to the margin. + +If even is not set, instead of having symmetrical UZs, +the left and bottom UZs are extended up to right and top UZs respectively. +This way, we favour the displaying of useful information: the begining of lines, +where most code reside, and the lines after the caret, eg. the body of a function. + + | | | | | +slop | strict | jumps | even | Caret can go to the margin | When reaching limitÝ(caret going out of + | | | | | visibility or going into the UZ) display is... +-----+--------+-------+------+--------------------------------------------+-------------------------------------------------------------- + 0 | 0 | 0 | 0 | Yes | moved to put caret on top/on right + 0 | 0 | 0 | 1 | Yes | moved by one position + 0 | 0 | 1 | 0 | Yes | moved to put caret on top/on right + 0 | 0 | 1 | 1 | Yes | centred on the caret + 0 | 1 | - | 0 | Caret is always on top/on right of display | - + 0 | 1 | - | 1 | No, caret is always centred | - + 1 | 0 | 0 | 0 | Yes | moved to put caret out of the asymmetrical UZ + 1 | 0 | 0 | 1 | Yes | moved to put caret out of the UZ + 1 | 0 | 1 | 0 | Yes | moved to put caret at 3UZ of the top or right margin + 1 | 0 | 1 | 1 | Yes | moved to put caret at 3UZ of the margin + 1 | 1 | - | 0 | Caret is always at UZ of top/right margin | - + 1 | 1 | 0 | 1 | No, kept out of UZ | moved by one position + 1 | 1 | 1 | 1 | No, kept out of UZ | moved to put caret at 3UZ of the margin +*/ +void Editor::EnsureCaretVisible(bool useMargin, bool vert, bool horiz) { + //Platform::DebugPrintf("EnsureCaretVisible %d %s\n", xOffset, useMargin ? " margin" : " "); + PRectangle rcClient = GetTextRectangle(); + //int rcClientFullWidth = rcClient.Width(); + int posCaret = currentPos; + if (posDrag >= 0) { + posCaret = posDrag; + } + Point pt = LocationFromPosition(posCaret); + Point ptBottomCaret = pt; + ptBottomCaret.y += vs.lineHeight - 1; + int lineCaret = DisplayFromPosition(posCaret); + bool bSlop, bStrict, bJump, bEven; + + // Vertical positioning + if (vert && (pt.y < rcClient.top || ptBottomCaret.y > rcClient.bottom || (caretYPolicy & CARET_STRICT) != 0)) { + int linesOnScreen = LinesOnScreen(); + int halfScreen = Platform::Maximum(linesOnScreen - 1, 2) / 2; + int newTopLine = topLine; + bSlop = (caretYPolicy & CARET_SLOP) != 0; + bStrict = (caretYPolicy & CARET_STRICT) != 0; + bJump = (caretYPolicy & CARET_JUMPS) != 0; + bEven = (caretYPolicy & CARET_EVEN) != 0; + + // It should be possible to scroll the window to show the caret, + // but this fails to remove the caret on GTK+ + if (bSlop) { // A margin is defined + int yMoveT, yMoveB; + if (bStrict) { + int yMarginT, yMarginB; + if (!useMargin) { + // In drag mode, avoid moves + // otherwise, a double click will select several lines. + yMarginT = yMarginB = 0; + } else { + // yMarginT must equal to caretYSlop, with a minimum of 1 and + // a maximum of slightly less than half the heigth of the text area. + yMarginT = Platform::Clamp(caretYSlop, 1, halfScreen); + if (bEven) { + yMarginB = yMarginT; + } else { + yMarginB = linesOnScreen - yMarginT - 1; + } + } + yMoveT = yMarginT; + if (bEven) { + if (bJump) { + yMoveT = Platform::Clamp(caretYSlop * 3, 1, halfScreen); + } + yMoveB = yMoveT; + } else { + yMoveB = linesOnScreen - yMoveT - 1; + } + if (lineCaret < topLine + yMarginT) { + // Caret goes too high + newTopLine = lineCaret - yMoveT; + } else if (lineCaret > topLine + linesOnScreen - 1 - yMarginB) { + // Caret goes too low + newTopLine = lineCaret - linesOnScreen + 1 + yMoveB; + } + } else { // Not strict + yMoveT = bJump ? caretYSlop * 3 : caretYSlop; + yMoveT = Platform::Clamp(yMoveT, 1, halfScreen); + if (bEven) { + yMoveB = yMoveT; + } else { + yMoveB = linesOnScreen - yMoveT - 1; + } + if (lineCaret < topLine) { + // Caret goes too high + newTopLine = lineCaret - yMoveT; + } else if (lineCaret > topLine + linesOnScreen - 1) { + // Caret goes too low + newTopLine = lineCaret - linesOnScreen + 1 + yMoveB; + } + } + } else { // No slop + if (!bStrict && !bJump) { + // Minimal move + if (lineCaret < topLine) { + // Caret goes too high + newTopLine = lineCaret; + } else if (lineCaret > topLine + linesOnScreen - 1) { + // Caret goes too low + if (bEven) { + newTopLine = lineCaret - linesOnScreen + 1; + } else { + newTopLine = lineCaret; + } + } + } else { // Strict or going out of display + if (bEven) { + // Always center caret + newTopLine = lineCaret - halfScreen; + } else { + // Always put caret on top of display + newTopLine = lineCaret; + } + } + } + newTopLine = Platform::Clamp(newTopLine, 0, MaxScrollPos()); + if (newTopLine != topLine) { + Redraw(); + SetTopLine(newTopLine); + SetVerticalScrollPos(); + } + } + + // Horizontal positioning + if (horiz && (wrapState == eWrapNone)) { + int halfScreen = Platform::Maximum(rcClient.Width() - 4, 4) / 2; + int xOffsetNew = xOffset; + bSlop = (caretXPolicy & CARET_SLOP) != 0; + bStrict = (caretXPolicy & CARET_STRICT) != 0; + bJump = (caretXPolicy & CARET_JUMPS) != 0; + bEven = (caretXPolicy & CARET_EVEN) != 0; + + if (bSlop) { // A margin is defined + int xMoveL, xMoveR; + if (bStrict) { + int xMarginL, xMarginR; + if (!useMargin) { + // In drag mode, avoid moves unless very near of the margin + // otherwise, a simple click will select text. + xMarginL = xMarginR = 2; + } else { + // xMargin must equal to caretXSlop, with a minimum of 2 and + // a maximum of slightly less than half the width of the text area. + xMarginR = Platform::Clamp(caretXSlop, 2, halfScreen); + if (bEven) { + xMarginL = xMarginR; + } else { + xMarginL = rcClient.Width() - xMarginR - 4; + } + } + if (bJump && bEven) { + // Jump is used only in even mode + xMoveL = xMoveR = Platform::Clamp(caretXSlop * 3, 1, halfScreen); + } else { + xMoveL = xMoveR = 0; // Not used, avoid a warning + } + if (pt.x < rcClient.left + xMarginL) { + // Caret is on the left of the display + if (bJump && bEven) { + xOffsetNew -= xMoveL; + } else { + // Move just enough to allow to display the caret + xOffsetNew -= (rcClient.left + xMarginL) - pt.x; + } + } else if (pt.x >= rcClient.right - xMarginR) { + // Caret is on the right of the display + if (bJump && bEven) { + xOffsetNew += xMoveR; + } else { + // Move just enough to allow to display the caret + xOffsetNew += pt.x - (rcClient.right - xMarginR) + 1; + } + } + } else { // Not strict + xMoveR = bJump ? caretXSlop * 3 : caretXSlop; + xMoveR = Platform::Clamp(xMoveR, 1, halfScreen); + if (bEven) { + xMoveL = xMoveR; + } else { + xMoveL = rcClient.Width() - xMoveR - 4; + } + if (pt.x < rcClient.left) { + // Caret is on the left of the display + xOffsetNew -= xMoveL; + } else if (pt.x >= rcClient.right) { + // Caret is on the right of the display + xOffsetNew += xMoveR; + } + } + } else { // No slop + if (bStrict || + (bJump && (pt.x < rcClient.left || pt.x >= rcClient.right))) { + // Strict or going out of display + if (bEven) { + // Center caret + xOffsetNew += pt.x - rcClient.left - halfScreen; + } else { + // Put caret on right + xOffsetNew += pt.x - rcClient.right + 1; + } + } else { + // Move just enough to allow to display the caret + if (pt.x < rcClient.left) { + // Caret is on the left of the display + if (bEven) { + xOffsetNew -= rcClient.left - pt.x; + } else { + xOffsetNew += pt.x - rcClient.right + 1; + } + } else if (pt.x >= rcClient.right) { + // Caret is on the right of the display + xOffsetNew += pt.x - rcClient.right + 1; + } + } + } + // In case of a jump (find result) largely out of display, adjust the offset to display the caret + if (pt.x + xOffset < rcClient.left + xOffsetNew) { + xOffsetNew = pt.x + xOffset - rcClient.left; + } else if (pt.x + xOffset >= rcClient.right + xOffsetNew) { + xOffsetNew = pt.x + xOffset - rcClient.right + 1; + if (vs.caretStyle == CARETSTYLE_BLOCK) { + // Ensure we can see a good portion of the block caret + xOffsetNew += vs.aveCharWidth; + } + } + if (xOffsetNew < 0) { + xOffsetNew = 0; + } + if (xOffset != xOffsetNew) { + xOffset = xOffsetNew; + if (xOffsetNew > 0) { + PRectangle rcText = GetTextRectangle(); + if (horizontalScrollBarVisible && + rcText.Width() + xOffset > scrollWidth) { + scrollWidth = xOffset + rcText.Width(); + SetScrollBars(); + } + } + SetHorizontalScrollPos(); + Redraw(); + } + } + UpdateSystemCaret(); +} + +void Editor::ShowCaretAtCurrentPosition() { + if (hasFocus) { + caret.active = true; + caret.on = true; + SetTicking(true); + } else { + caret.active = false; + caret.on = false; + } + InvalidateCaret(); +} + +void Editor::DropCaret() { + caret.active = false; + InvalidateCaret(); +} + +void Editor::InvalidateCaret() { + if (posDrag >= 0) + InvalidateRange(posDrag, posDrag + 1); + else + InvalidateRange(currentPos, currentPos + 1); + UpdateSystemCaret(); +} + +void Editor::UpdateSystemCaret() { +} + +void Editor::NeedWrapping(int docLineStart, int docLineEnd) { + docLineStart = Platform::Clamp(docLineStart, 0, pdoc->LinesTotal()); + if (wrapStart > docLineStart) { + wrapStart = docLineStart; + llc.Invalidate(LineLayout::llPositions); + } + if (wrapEnd < docLineEnd) { + wrapEnd = docLineEnd; + } + wrapEnd = Platform::Clamp(wrapEnd, 0, pdoc->LinesTotal()); + // Wrap lines during idle. + if ((wrapState != eWrapNone) && (wrapEnd != wrapStart)) { + SetIdle(true); + } +} + +bool Editor::WrapOneLine(Surface *surface, int lineToWrap) { + AutoLineLayout ll(llc, RetrieveLineLayout(lineToWrap)); + int linesWrapped = 1; + if (ll) { + LayoutLine(lineToWrap, surface, vs, ll, wrapWidth); + linesWrapped = ll->lines; + } + return cs.SetHeight(lineToWrap, linesWrapped); +} + +// Check if wrapping needed and perform any needed wrapping. +// fullwrap: if true, all lines which need wrapping will be done, +// in this single call. +// priorityWrapLineStart: If greater than zero, all lines starting from +// here to 1 page + 100 lines past will be wrapped (even if there are +// more lines under wrapping process in idle). +// If it is neither fullwrap, nor priorityWrap, then 1 page + 100 lines will be +// wrapped, if there are any wrapping going on in idle. (Generally this +// condition is called only from idler). +// Return true if wrapping occurred. +bool Editor::WrapLines(bool fullWrap, int priorityWrapLineStart) { + // If there are any pending wraps, do them during idle if possible. + int linesInOneCall = LinesOnScreen() + 100; + if (wrapState != eWrapNone) { + if (wrapStart < wrapEnd) { + if (!SetIdle(true)) { + // Idle processing not supported so full wrap required. + fullWrap = true; + } + } + if (!fullWrap && priorityWrapLineStart >= 0 && + // .. and if the paint window is outside pending wraps + (((priorityWrapLineStart + linesInOneCall) < wrapStart) || + (priorityWrapLineStart > wrapEnd))) { + // No priority wrap pending + return false; + } + } + int goodTopLine = topLine; + bool wrapOccurred = false; + if (wrapStart <= pdoc->LinesTotal()) { + if (wrapState == eWrapNone) { + if (wrapWidth != LineLayout::wrapWidthInfinite) { + wrapWidth = LineLayout::wrapWidthInfinite; + for (int lineDoc = 0; lineDoc < pdoc->LinesTotal(); lineDoc++) { + cs.SetHeight(lineDoc, 1); + } + wrapOccurred = true; + } + wrapStart = wrapLineLarge; + wrapEnd = wrapLineLarge; + } else { + if (wrapEnd >= pdoc->LinesTotal()) + wrapEnd = pdoc->LinesTotal(); + //ElapsedTime et; + int lineDocTop = cs.DocFromDisplay(topLine); + int subLineTop = topLine - cs.DisplayFromDoc(lineDocTop); + PRectangle rcTextArea = GetClientRectangle(); + rcTextArea.left = vs.fixedColumnWidth; + rcTextArea.right -= vs.rightMarginWidth; + wrapWidth = rcTextArea.Width(); + // Ensure all of the document is styled. + pdoc->EnsureStyledTo(pdoc->Length()); + RefreshStyleData(); + AutoSurface surface(this); + if (surface) { + bool priorityWrap = false; + int lastLineToWrap = wrapEnd; + int lineToWrap = wrapStart; + if (!fullWrap) { + if (priorityWrapLineStart >= 0) { + // This is a priority wrap. + lineToWrap = priorityWrapLineStart; + lastLineToWrap = priorityWrapLineStart + linesInOneCall; + priorityWrap = true; + } else { + // This is idle wrap. + lastLineToWrap = wrapStart + linesInOneCall; + } + if (lastLineToWrap >= wrapEnd) + lastLineToWrap = wrapEnd; + } // else do a fullWrap. + + // Platform::DebugPrintf("Wraplines: full = %d, priorityStart = %d (wrapping: %d to %d)\n", fullWrap, priorityWrapLineStart, lineToWrap, lastLineToWrap); + // Platform::DebugPrintf("Pending wraps: %d to %d\n", wrapStart, wrapEnd); + while (lineToWrap < lastLineToWrap) { + if (WrapOneLine(surface, lineToWrap)) { + wrapOccurred = true; + } + lineToWrap++; + } + if (!priorityWrap) + wrapStart = lineToWrap; + // If wrapping is done, bring it to resting position + if (wrapStart >= wrapEnd) { + wrapStart = wrapLineLarge; + wrapEnd = wrapLineLarge; + } + } + goodTopLine = cs.DisplayFromDoc(lineDocTop); + if (subLineTop < cs.GetHeight(lineDocTop)) + goodTopLine += subLineTop; + else + goodTopLine += cs.GetHeight(lineDocTop); + //double durWrap = et.Duration(true); + //Platform::DebugPrintf("Wrap:%9.6g \n", durWrap); + } + } + if (wrapOccurred) { + SetScrollBars(); + SetTopLine(Platform::Clamp(goodTopLine, 0, MaxScrollPos())); + SetVerticalScrollPos(); + } + return wrapOccurred; +} + +void Editor::LinesJoin() { + if (!RangeContainsProtected(targetStart, targetEnd)) { + pdoc->BeginUndoAction(); + bool prevNonWS = true; + for (int pos = targetStart; pos < targetEnd; pos++) { + if (IsEOLChar(pdoc->CharAt(pos))) { + targetEnd -= pdoc->LenChar(pos); + pdoc->DelChar(pos); + if (prevNonWS) { + // Ensure at least one space separating previous lines + pdoc->InsertChar(pos, ' '); + targetEnd++; + } + } else { + prevNonWS = pdoc->CharAt(pos) != ' '; + } + } + pdoc->EndUndoAction(); + } +} + +const char *Editor::StringFromEOLMode(int eolMode) { + if (eolMode == SC_EOL_CRLF) { + return "\r\n"; + } else if (eolMode == SC_EOL_CR) { + return "\r"; + } else { + return "\n"; + } +} + +void Editor::LinesSplit(int pixelWidth) { + if (!RangeContainsProtected(targetStart, targetEnd)) { + if (pixelWidth == 0) { + PRectangle rcText = GetTextRectangle(); + pixelWidth = rcText.Width(); + } + int lineStart = pdoc->LineFromPosition(targetStart); + int lineEnd = pdoc->LineFromPosition(targetEnd); + const char *eol = StringFromEOLMode(pdoc->eolMode); + pdoc->BeginUndoAction(); + for (int line = lineStart; line <= lineEnd; line++) { + AutoSurface surface(this); + AutoLineLayout ll(llc, RetrieveLineLayout(line)); + if (surface && ll) { + unsigned int posLineStart = pdoc->LineStart(line); + LayoutLine(line, surface, vs, ll, pixelWidth); + for (int subLine = 1; subLine < ll->lines; subLine++) { + pdoc->InsertCString(posLineStart + (subLine - 1) * strlen(eol) + + ll->LineStart(subLine), eol); + targetEnd += static_cast(strlen(eol)); + } + } + lineEnd = pdoc->LineFromPosition(targetEnd); + } + pdoc->EndUndoAction(); + } +} + +int Editor::SubstituteMarkerIfEmpty(int markerCheck, int markerDefault) { + if (vs.markers[markerCheck].markType == SC_MARK_EMPTY) + return 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(strlen(s)); +} + +void Editor::PaintSelMargin(Surface *surfWindow, PRectangle &rc) { + if (vs.fixedColumnWidth == 0) + return; + + PRectangle rcMargin = GetClientRectangle(); + rcMargin.right = vs.fixedColumnWidth; + + if (!rc.Intersects(rcMargin)) + return; + + Surface *surface; + if (bufferedDraw) { + surface = pixmapSelMargin; + } else { + surface = surfWindow; + } + + PRectangle rcSelMargin = rcMargin; + rcSelMargin.right = rcMargin.left; + + for (int margin = 0; margin < vs.margins; margin++) { + if (vs.ms[margin].width > 0) { + + rcSelMargin.left = rcSelMargin.right; + rcSelMargin.right = rcSelMargin.left + vs.ms[margin].width; + + if (vs.ms[margin].style != SC_MARGIN_NUMBER) { + /* alternate scheme: + if (vs.ms[margin].mask & SC_MASK_FOLDERS) + surface->FillRectangle(rcSelMargin, vs.styles[STYLE_DEFAULT].back.allocated); + else + // Required because of special way brush is created for selection margin + surface->FillRectangle(rcSelMargin, pixmapSelPattern); + */ + if (vs.ms[margin].mask & SC_MASK_FOLDERS) + // Required because of special way brush is created for selection margin + surface->FillRectangle(rcSelMargin, *pixmapSelPattern); + else { + ColourAllocated colour; + switch (vs.ms[margin].style) { + case SC_MARGIN_BACK: + colour = vs.styles[STYLE_DEFAULT].back.allocated; + break; + case SC_MARGIN_FORE: + colour = vs.styles[STYLE_DEFAULT].fore.allocated; + break; + default: + colour = vs.styles[STYLE_LINENUMBER].back.allocated; + break; + } + surface->FillRectangle(rcSelMargin, colour); + } + } else { + surface->FillRectangle(rcSelMargin, vs.styles[STYLE_LINENUMBER].back.allocated); + } + + int visibleLine = topLine; + int yposScreen = 0; + + // Work out whether the top line is whitespace located after a + // lessening of fold level which implies a 'fold tail' but which should not + // be displayed until the last of a sequence of whitespace. + bool needWhiteClosure = false; + int level = pdoc->GetLevel(cs.DocFromDisplay(topLine)); + if (level & SC_FOLDLEVELWHITEFLAG) { + int lineBack = cs.DocFromDisplay(topLine); + int levelPrev = level; + while ((lineBack > 0) && (levelPrev & SC_FOLDLEVELWHITEFLAG)) { + lineBack--; + levelPrev = pdoc->GetLevel(lineBack); + } + if (!(levelPrev & SC_FOLDLEVELHEADERFLAG)) { + if ((level & SC_FOLDLEVELNUMBERMASK) < (levelPrev & SC_FOLDLEVELNUMBERMASK)) + needWhiteClosure = true; + } + } + + // Old code does not know about new markers needed to distinguish all cases + int folderOpenMid = SubstituteMarkerIfEmpty(SC_MARKNUM_FOLDEROPENMID, + SC_MARKNUM_FOLDEROPEN); + int folderEnd = SubstituteMarkerIfEmpty(SC_MARKNUM_FOLDEREND, + SC_MARKNUM_FOLDER); + + while ((visibleLine < cs.LinesDisplayed()) && yposScreen < rcMargin.bottom) { + + PLATFORM_ASSERT(visibleLine < cs.LinesDisplayed()); + + int lineDoc = cs.DocFromDisplay(visibleLine); + PLATFORM_ASSERT(cs.GetVisible(lineDoc)); + bool firstSubLine = visibleLine == cs.DisplayFromDoc(lineDoc); + + // Decide which fold indicator should be displayed + level = pdoc->GetLevel(lineDoc); + int levelNext = pdoc->GetLevel(lineDoc + 1); + int marks = pdoc->GetMark(lineDoc); + if (!firstSubLine) + marks = 0; + int levelNum = level & SC_FOLDLEVELNUMBERMASK; + int levelNextNum = levelNext & SC_FOLDLEVELNUMBERMASK; + if (level & SC_FOLDLEVELHEADERFLAG) { + if (firstSubLine) { + if (cs.GetExpanded(lineDoc)) { + if (levelNum == SC_FOLDLEVELBASE) + marks |= 1 << SC_MARKNUM_FOLDEROPEN; + else + marks |= 1 << folderOpenMid; + } else { + if (levelNum == SC_FOLDLEVELBASE) + marks |= 1 << SC_MARKNUM_FOLDER; + else + marks |= 1 << folderEnd; + } + } else { + marks |= 1 << SC_MARKNUM_FOLDERSUB; + } + needWhiteClosure = false; + } else if (level & SC_FOLDLEVELWHITEFLAG) { + if (needWhiteClosure) { + if (levelNext & SC_FOLDLEVELWHITEFLAG) { + marks |= 1 << SC_MARKNUM_FOLDERSUB; + } else if (levelNum > SC_FOLDLEVELBASE) { + marks |= 1 << SC_MARKNUM_FOLDERMIDTAIL; + needWhiteClosure = false; + } else { + marks |= 1 << SC_MARKNUM_FOLDERTAIL; + needWhiteClosure = false; + } + } else if (levelNum > SC_FOLDLEVELBASE) { + if (levelNextNum < levelNum) { + if (levelNextNum > SC_FOLDLEVELBASE) { + marks |= 1 << SC_MARKNUM_FOLDERMIDTAIL; + } else { + marks |= 1 << SC_MARKNUM_FOLDERTAIL; + } + } else { + marks |= 1 << SC_MARKNUM_FOLDERSUB; + } + } + } else if (levelNum > SC_FOLDLEVELBASE) { + if (levelNextNum < levelNum) { + needWhiteClosure = false; + if (levelNext & SC_FOLDLEVELWHITEFLAG) { + marks |= 1 << SC_MARKNUM_FOLDERSUB; + needWhiteClosure = true; + } else if (levelNextNum > SC_FOLDLEVELBASE) { + marks |= 1 << SC_MARKNUM_FOLDERMIDTAIL; + } else { + marks |= 1 << SC_MARKNUM_FOLDERTAIL; + } + } else { + marks |= 1 << SC_MARKNUM_FOLDERSUB; + } + } + + marks &= vs.ms[margin].mask; + PRectangle rcMarker = rcSelMargin; + rcMarker.top = yposScreen; + rcMarker.bottom = yposScreen + vs.lineHeight; + if (vs.ms[margin].style == SC_MARGIN_NUMBER) { + char number[100]; + number[0] = '\0'; + if (firstSubLine) + sprintf(number, "%d", lineDoc + 1); + if (foldFlags & SC_FOLDFLAG_LEVELNUMBERS) { + int lev = pdoc->GetLevel(lineDoc); + sprintf(number, "%c%c %03X %03X", + (lev & SC_FOLDLEVELHEADERFLAG) ? 'H' : '_', + (lev & SC_FOLDLEVELWHITEFLAG) ? 'W' : '_', + lev & SC_FOLDLEVELNUMBERMASK, + lev >> 16 + ); + } + PRectangle rcNumber = rcMarker; + // Right justify + 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.allocated, + vs.styles[STYLE_LINENUMBER].back.allocated); + } + + if (marks) { + for (int markBit = 0; (markBit < 32) && marks; markBit++) { + if (marks & 1) { + vs.markers[markBit].Draw(surface, rcMarker, vs.styles[STYLE_LINENUMBER].font); + } + marks >>= 1; + } + } + + visibleLine++; + yposScreen += vs.lineHeight; + } + } + } + + PRectangle rcBlankMargin = rcMargin; + rcBlankMargin.left = rcSelMargin.right; + surface->FillRectangle(rcBlankMargin, vs.styles[STYLE_DEFAULT].back.allocated); + + if (bufferedDraw) { + surfWindow->Copy(rcMargin, Point(), *pixmapSelMargin); + } +} + +void DrawTabArrow(Surface *surface, PRectangle rcTab, int ymid) { + int ydiff = (rcTab.bottom - rcTab.top) / 2; + int xhead = rcTab.right - 1 - ydiff; + if (xhead <= rcTab.left) { + ydiff -= rcTab.left - xhead - 1; + xhead = rcTab.left - 1; + } + if ((rcTab.left + 2) < (rcTab.right - 1)) + surface->MoveTo(rcTab.left + 2, ymid); + else + surface->MoveTo(rcTab.right - 1, ymid); + surface->LineTo(rcTab.right - 1, ymid); + surface->LineTo(xhead, ymid - ydiff); + surface->MoveTo(rcTab.right - 1, ymid); + surface->LineTo(xhead, ymid + ydiff); +} + +LineLayout *Editor::RetrieveLineLayout(int lineNumber) { + int posLineStart = pdoc->LineStart(lineNumber); + int posLineEnd = pdoc->LineStart(lineNumber + 1); + PLATFORM_ASSERT(posLineEnd >= posLineStart); + int lineCaret = pdoc->LineFromPosition(currentPos); + return llc.Retrieve(lineNumber, lineCaret, + posLineEnd - posLineStart, pdoc->GetStyleClock(), + LinesOnScreen() + 1, pdoc->LinesTotal()); +} + +static bool GoodTrailByte(int v) { + return (v >= 0x80) && (v < 0xc0); +} + +bool BadUTF(const char *s, int len, int &trailBytes) { + if (trailBytes) { + trailBytes--; + return false; + } + const unsigned char *us = reinterpret_cast(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])) { + 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])) { + 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 + return true; + } else { + // Trail byte + return true; + } +} + +/** + * Fill in the LineLayout data for the given line. + * Copy the given @a line and its styles from the document into local arrays. + * Also determine the x position at which each character starts. + */ +void Editor::LayoutLine(int line, Surface *surface, ViewStyle &vstyle, LineLayout *ll, int width) { + if (!ll) + return; + + PLATFORM_ASSERT(line < pdoc->LinesTotal()); + PLATFORM_ASSERT(ll->chars != NULL); + int posLineStart = pdoc->LineStart(line); + int posLineEnd = pdoc->LineStart(line + 1); + // If the line is very long, limit the treatment to a length that should fit in the viewport + if (posLineEnd > (posLineStart + ll->maxLineLength)) { + posLineEnd = posLineStart + ll->maxLineLength; + } + if (ll->validity == LineLayout::llCheckTextAndStyle) { + int lineLength = posLineEnd - posLineStart; + if (!vstyle.viewEOL) { + int cid = posLineEnd - 1; + while ((cid > posLineStart) && IsEOLChar(pdoc->CharAt(cid))) { + cid--; + lineLength--; + } + } + if (lineLength == ll->numCharsInLine) { + // See if chars, styles, indicators, are all the same + bool allSame = true; + const int styleMask = pdoc->stylingBitsMask; + // Check base line layout + char styleByte = 0; + int numCharsInLine = 0; + while (numCharsInLine < lineLength) { + int charInDoc = numCharsInLine + posLineStart; + char chDoc = pdoc->CharAt(charInDoc); + styleByte = pdoc->StyleAt(charInDoc); + allSame = allSame && + (ll->styles[numCharsInLine] == static_cast(styleByte & styleMask)); + allSame = allSame && + (ll->indicators[numCharsInLine] == static_cast(styleByte & ~styleMask)); + if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == Style::caseMixed) + allSame = allSame && + (ll->chars[numCharsInLine] == chDoc); + else if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == Style::caseLower) + allSame = allSame && + (ll->chars[numCharsInLine] == static_cast(tolower(chDoc))); + else // Style::caseUpper + allSame = allSame && + (ll->chars[numCharsInLine] == static_cast(toupper(chDoc))); + numCharsInLine++; + } + allSame = allSame && (ll->styles[numCharsInLine] == styleByte); // For eolFilled + if (allSame) { + ll->validity = LineLayout::llPositions; + } else { + ll->validity = LineLayout::llInvalid; + } + } else { + ll->validity = LineLayout::llInvalid; + } + } + if (ll->validity == LineLayout::llInvalid) { + ll->widthLine = LineLayout::wrapWidthInfinite; + ll->lines = 1; + int numCharsInLine = 0; + if (vstyle.edgeState == EDGE_BACKGROUND) { + ll->edgeColumn = pdoc->FindColumn(line, theEdge); + if (ll->edgeColumn >= posLineStart) { + ll->edgeColumn -= posLineStart; + } + } else { + ll->edgeColumn = -1; + } + + char styleByte = 0; + int styleMask = pdoc->stylingBitsMask; + ll->styleBitsSet = 0; + // Fill base line layout + for (int charInDoc = posLineStart; charInDoc < posLineEnd; charInDoc++) { + char chDoc = pdoc->CharAt(charInDoc); + styleByte = pdoc->StyleAt(charInDoc); + ll->styleBitsSet |= styleByte; + if (vstyle.viewEOL || (!IsEOLChar(chDoc))) { + ll->chars[numCharsInLine] = chDoc; + ll->styles[numCharsInLine] = static_cast(styleByte & styleMask); + ll->indicators[numCharsInLine] = static_cast(styleByte & ~styleMask); + if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == Style::caseUpper) + ll->chars[numCharsInLine] = static_cast(toupper(chDoc)); + else if (vstyle.styles[ll->styles[numCharsInLine]].caseForce == Style::caseLower) + ll->chars[numCharsInLine] = static_cast(tolower(chDoc)); + numCharsInLine++; + } + } + ll->xHighlightGuide = 0; + // Extra element at the end of the line to hold end x position and act as + ll->chars[numCharsInLine] = 0; // Also triggers processing in the loops as this is a control character + ll->styles[numCharsInLine] = styleByte; // For eolFilled + ll->indicators[numCharsInLine] = 0; + + // Layout the line, determining the position of each character, + // with an extra element at the end for the end of the line. + int startseg = 0; // Start of the current segment, in char. number + int startsegx = 0; // Start of the current segment, in pixels + ll->positions[0] = 0; + unsigned int tabWidth = vstyle.spaceWidth * pdoc->tabInChars; + bool lastSegItalics = false; + Font &ctrlCharsFont = vstyle.styles[STYLE_CONTROLCHAR].font; + + int ctrlCharWidth[32] = {0}; + bool isControlNext = IsControlCharacter(ll->chars[0]); + int trailBytes = 0; + bool isBadUTFNext = IsUnicodeMode() && BadUTF(ll->chars, numCharsInLine, trailBytes); + for (int charInLine = 0; charInLine < numCharsInLine; charInLine++) { + bool isControl = isControlNext; + isControlNext = IsControlCharacter(ll->chars[charInLine + 1]); + bool isBadUTF = isBadUTFNext; + isBadUTFNext = IsUnicodeMode() && BadUTF(ll->chars + charInLine + 1, numCharsInLine - charInLine - 1, trailBytes); + if ((ll->styles[charInLine] != ll->styles[charInLine + 1]) || + isControl || isControlNext || isBadUTF || isBadUTFNext) { + ll->positions[startseg] = 0; + if (vstyle.styles[ll->styles[charInLine]].visible) { + if (isControl) { + if (ll->chars[charInLine] == '\t') { + ll->positions[charInLine + 1] = ((((startsegx + 2) / + tabWidth) + 1) * tabWidth) - startsegx; + } else if (controlCharSymbol < 32) { + if (ctrlCharWidth[ll->chars[charInLine]] == 0) { + const char *ctrlChar = ControlCharacterString(ll->chars[charInLine]); + // +3 For a blank on front and rounded edge each side: + ctrlCharWidth[ll->chars[charInLine]] = + surface->WidthText(ctrlCharsFont, ctrlChar, istrlen(ctrlChar)) + 3; + } + ll->positions[charInLine + 1] = ctrlCharWidth[ll->chars[charInLine]]; + } else { + char cc[2] = { static_cast(controlCharSymbol), '\0' }; + surface->MeasureWidths(ctrlCharsFont, cc, 1, + ll->positions + startseg + 1); + } + lastSegItalics = false; + } else if (isBadUTF) { + char hexits[3]; + sprintf(hexits, "%2X", ll->chars[charInLine] & 0xff); + ll->positions[charInLine + 1] = + surface->WidthText(ctrlCharsFont, hexits, istrlen(hexits)) + 3; + } else { // Regular character + int lenSeg = charInLine - startseg + 1; + if ((lenSeg == 1) && (' ' == ll->chars[startseg])) { + lastSegItalics = false; + // Over half the segments are single characters and of these about half are space characters. + ll->positions[charInLine + 1] = vstyle.styles[ll->styles[charInLine]].spaceWidth; + } else { + lastSegItalics = vstyle.styles[ll->styles[charInLine]].italic; + posCache.MeasureWidths(surface, vstyle, ll->styles[charInLine], ll->chars + startseg, + lenSeg, ll->positions + startseg + 1); + } + } + } else { // invisible + for (int posToZero = startseg; posToZero <= (charInLine + 1); posToZero++) { + ll->positions[posToZero] = 0; + } + } + for (int posToIncrease = startseg; posToIncrease <= (charInLine + 1); posToIncrease++) { + ll->positions[posToIncrease] += startsegx; + } + startsegx = ll->positions[charInLine + 1]; + startseg = charInLine + 1; + } + } + // Small hack to make lines that end with italics not cut off the edge of the last character + if ((startseg > 0) && lastSegItalics) { + ll->positions[startseg] += 2; + } + ll->numCharsInLine = numCharsInLine; + ll->validity = LineLayout::llPositions; + } + // Hard to cope when too narrow, so just assume there is space + if (width < 20) { + width = 20; + } + if ((ll->validity == LineLayout::llPositions) || (ll->widthLine != width)) { + ll->widthLine = width; + if (width == LineLayout::wrapWidthInfinite) { + ll->lines = 1; + } else if (width > ll->positions[ll->numCharsInLine]) { + // Simple common case where line does not need wrapping. + ll->lines = 1; + } else { + if (wrapVisualFlags & SC_WRAPVISUALFLAG_END) { + width -= vstyle.aveCharWidth; // take into account the space for end wrap mark + } + ll->lines = 0; + // Calculate line start positions based upon width. + int lastGoodBreak = 0; + int lastLineStart = 0; + int startOffset = 0; + int p = 0; + while (p < ll->numCharsInLine) { + if ((ll->positions[p + 1] - startOffset) >= width) { + if (lastGoodBreak == lastLineStart) { + // Try moving to start of last character + if (p > 0) { + lastGoodBreak = pdoc->MovePositionOutsideChar(p + posLineStart, -1) + - posLineStart; + } + if (lastGoodBreak == lastLineStart) { + // Ensure at least one character on line. + lastGoodBreak = pdoc->MovePositionOutsideChar(lastGoodBreak + posLineStart + 1, 1) + - posLineStart; + } + } + lastLineStart = lastGoodBreak; + ll->lines++; + ll->SetLineStart(ll->lines, lastGoodBreak); + startOffset = ll->positions[lastGoodBreak]; + // take into account the space for start wrap mark and indent + startOffset -= actualWrapVisualStartIndent * vstyle.aveCharWidth; + p = lastGoodBreak + 1; + continue; + } + if (p > 0) { + if (wrapState == eWrapChar) { + lastGoodBreak = pdoc->MovePositionOutsideChar(p + posLineStart, -1) + - posLineStart; + p = pdoc->MovePositionOutsideChar(p + 1 + posLineStart, 1) - posLineStart; + continue; + } else if (ll->styles[p] != ll->styles[p - 1]) { + lastGoodBreak = p; + } else if (IsSpaceOrTab(ll->chars[p - 1]) && !IsSpaceOrTab(ll->chars[p])) { + lastGoodBreak = p; + } + } + p++; + } + ll->lines++; + } + ll->validity = LineLayout::llLines; + } +} + +ColourAllocated Editor::SelectionBackground(ViewStyle &vsDraw) { + return primarySelection ? vsDraw.selbackground.allocated : vsDraw.selbackground2.allocated; +} + +ColourAllocated Editor::TextBackground(ViewStyle &vsDraw, bool overrideBackground, + ColourAllocated background, bool inSelection, bool inHotspot, int styleMain, int i, LineLayout *ll) { + if (inSelection) { + if (vsDraw.selbackset && (vsDraw.selAlpha == SC_ALPHA_NOALPHA)) { + return SelectionBackground(vsDraw); + } + } else { + if ((vsDraw.edgeState == EDGE_BACKGROUND) && + (i >= ll->edgeColumn) && + !IsEOLChar(ll->chars[i])) + return vsDraw.edgecolour.allocated; + if (inHotspot && vsDraw.hotspotBackgroundSet) + return vsDraw.hotspotBackground.allocated; + if (overrideBackground && (((styleMain != STYLE_BRACELIGHT) && (styleMain != STYLE_BRACEBAD)) || + (vsDraw.styles[styleMain].back.allocated.AsLong() == vsDraw.styles[ll->bracePreviousStyles[0]].back.allocated.AsLong()))) + return background; + } + return vsDraw.styles[styleMain].back.allocated; +} + +void Editor::DrawIndentGuide(Surface *surface, int lineVisible, int lineHeight, int start, PRectangle rcSegment, bool highlight) { + Point from(0, ((lineVisible & 1) && (lineHeight & 1)) ? 1 : 0); + PRectangle rcCopyArea(start + 1, rcSegment.top, start + 2, rcSegment.bottom); + surface->Copy(rcCopyArea, from, + highlight ? *pixmapIndentGuideHighlight : *pixmapIndentGuide); +} + +void Editor::DrawWrapMarker(Surface *surface, PRectangle rcPlace, + bool isEndMarker, ColourAllocated wrapColour) { + surface->PenColour(wrapColour); + + enum { xa = 1 }; // gap before start + int w = rcPlace.right - rcPlace.left - xa - 1; + + bool xStraight = isEndMarker; // x-mirrored symbol for start marker + bool yStraight = true; + //bool yStraight= isEndMarker; // comment in for start marker y-mirrowed + + int x0 = xStraight ? rcPlace.left : rcPlace.right - 1; + int y0 = yStraight ? rcPlace.top : rcPlace.bottom - 1; + + int dy = (rcPlace.bottom - rcPlace.top) / 5; + int y = (rcPlace.bottom - rcPlace.top) / 2 + dy; + + struct Relative { + Surface *surface; + int xBase; + int xDir; + int yBase; + int yDir; + void MoveTo(int xRelative, int yRelative) { + surface->MoveTo(xBase + xDir * xRelative, yBase + yDir * yRelative); + } + void LineTo(int xRelative, int yRelative) { + surface->LineTo(xBase + xDir * xRelative, yBase + yDir * yRelative); + } + }; + Relative rel = {surface, x0, xStraight ? 1 : -1, y0, yStraight ? 1 : -1}; + + // arrow head + rel.MoveTo(xa, y); + rel.LineTo(xa + 2*w / 3, y - dy); + rel.MoveTo(xa, y); + rel.LineTo(xa + 2*w / 3, y + dy); + + // arrow body + rel.MoveTo(xa, y); + rel.LineTo(xa + w, y); + rel.LineTo(xa + w, y - 2 * dy); + rel.LineTo(xa - 1, // on windows lineto is exclusive endpoint, perhaps GTK not... + y - 2 * dy); +} + +static void SimpleAlphaRectangle(Surface *surface, PRectangle rc, ColourAllocated fill, int alpha) { + if (alpha != SC_ALPHA_NOALPHA) { + surface->AlphaRectangle(rc, 0, fill, alpha, fill, alpha, 0); + } +} + +void Editor::DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, LineLayout *ll, + int line, int lineEnd, int xStart, int subLine, int subLineStart, + bool overrideBackground, ColourAllocated background, + bool drawWrapMarkEnd, ColourAllocated wrapColour) { + + int styleMask = pdoc->stylingBitsMask; + PRectangle rcSegment = rcLine; + + // Fill in a PRectangle representing the end of line characters + int xEol = ll->positions[lineEnd] - subLineStart; + rcSegment.left = xEol + xStart; + rcSegment.right = xEol + vsDraw.aveCharWidth + xStart; + int posLineEnd = pdoc->LineStart(line + 1); + bool eolInSelection = (subLine == (ll->lines - 1)) && + (posLineEnd > ll->selStart) && (posLineEnd <= ll->selEnd) && (ll->selStart != ll->selEnd); + + if (eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (vsDraw.selAlpha == SC_ALPHA_NOALPHA)) { + surface->FillRectangle(rcSegment, SelectionBackground(vsDraw)); + } else { + if (overrideBackground) { + surface->FillRectangle(rcSegment, background); + } else { + surface->FillRectangle(rcSegment, vsDraw.styles[ll->styles[ll->numCharsInLine] & styleMask].back.allocated); + } + if (eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (vsDraw.selAlpha != SC_ALPHA_NOALPHA)) { + SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw), vsDraw.selAlpha); + } + } + + rcSegment.left = xEol + vsDraw.aveCharWidth + xStart; + rcSegment.right = rcLine.right; + if (overrideBackground) { + surface->FillRectangle(rcSegment, background); + } else if (vsDraw.styles[ll->styles[ll->numCharsInLine] & styleMask].eolFilled) { + surface->FillRectangle(rcSegment, vsDraw.styles[ll->styles[ll->numCharsInLine] & styleMask].back.allocated); + } else { + surface->FillRectangle(rcSegment, vsDraw.styles[STYLE_DEFAULT].back.allocated); + } + + if (vsDraw.selEOLFilled && eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (vsDraw.selAlpha == SC_ALPHA_NOALPHA)) { + surface->FillRectangle(rcSegment, SelectionBackground(vsDraw)); + } else { + if (overrideBackground) { + surface->FillRectangle(rcSegment, background); + } else if (vsDraw.styles[ll->styles[ll->numCharsInLine] & styleMask].eolFilled) { + surface->FillRectangle(rcSegment, vsDraw.styles[ll->styles[ll->numCharsInLine] & styleMask].back.allocated); + } else { + surface->FillRectangle(rcSegment, vsDraw.styles[STYLE_DEFAULT].back.allocated); + } + if (vsDraw.selEOLFilled && eolInSelection && vsDraw.selbackset && (line < pdoc->LinesTotal() - 1) && (vsDraw.selAlpha != SC_ALPHA_NOALPHA)) { + SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw), vsDraw.selAlpha); + } + } + + if (drawWrapMarkEnd) { + PRectangle rcPlace = rcSegment; + + if (wrapVisualFlagsLocation & SC_WRAPVISUALFLAGLOC_END_BY_TEXT) { + rcPlace.left = xEol + xStart; + 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; + rcPlace.left = rcPlace.right - vsDraw.aveCharWidth; + } + DrawWrapMarker(surface, rcPlace, true, wrapColour); + } +} + +void Editor::DrawIndicators(Surface *surface, ViewStyle &vsDraw, int line, int xStart, + PRectangle rcLine, LineLayout *ll, int subLine, int lineEnd, bool under) { + // Draw decorators + const int posLineStart = pdoc->LineStart(line); + const int lineStart = ll->LineStart(subLine); + const int subLineStart = ll->positions[lineStart]; + const int posLineEnd = posLineStart + lineEnd; + + if (!under) { + // Draw indicators + // foreach indicator... + for (int indicnum = 0, mask = 1 << pdoc->stylingBits; mask < 0x100; indicnum++) { + if (!(mask & ll->styleBitsSet)) { + mask <<= 1; + continue; + } + int startPos = -1; + // foreach style pos in line... + for (int indicPos = lineStart; indicPos <= lineEnd; indicPos++) { + // look for starts... + if (startPos < 0) { + // NOT in indicator run, looking for START + if (indicPos < lineEnd && (ll->indicators[indicPos] & mask)) + startPos = indicPos; + } + // ... or ends + if (startPos >= 0) { + // IN indicator run, looking for END + if (indicPos >= lineEnd || !(ll->indicators[indicPos] & mask)) { + // AT end of indicator run, DRAW it! + PRectangle rcIndic( + ll->positions[startPos] + xStart - subLineStart, + rcLine.top + vsDraw.maxAscent, + ll->positions[indicPos] + xStart - subLineStart, + rcLine.top + vsDraw.maxAscent + 3); + vsDraw.indicators[indicnum].Draw(surface, rcIndic, rcLine); + // RESET control var + startPos = -1; + } + } + } + mask <<= 1; + } + } + + for (Decoration *deco = pdoc->decorations.root; deco; deco = deco->next) { + if (under == vsDraw.indicators[deco->indicator].under) { + int startPos = posLineStart + lineStart; + if (!deco->rs.ValueAt(startPos)) { + startPos = deco->rs.EndRun(startPos); + } + while ((startPos < posLineEnd) && (deco->rs.ValueAt(startPos))) { + int endPos = deco->rs.EndRun(startPos); + if (endPos > posLineEnd) + endPos = posLineEnd; + PRectangle rcIndic( + ll->positions[startPos - posLineStart] + xStart - subLineStart, + rcLine.top + vsDraw.maxAscent, + ll->positions[endPos - posLineStart] + xStart - subLineStart, + rcLine.top + vsDraw.maxAscent + 3); + vsDraw.indicators[deco->indicator].Draw(surface, rcIndic, rcLine); + startPos = deco->rs.EndRun(endPos); + } + } + } +} + +void DrawTextBlob(Surface *surface, ViewStyle &vsDraw, PRectangle rcSegment, + const char *s, ColourAllocated textBack, ColourAllocated textFore, bool twoPhaseDraw) { + if (!twoPhaseDraw) { + surface->FillRectangle(rcSegment, textBack); + } + Font &ctrlCharsFont = vsDraw.styles[STYLE_CONTROLCHAR].font; + int normalCharHeight = surface->Ascent(ctrlCharsFont) - + surface->InternalLeading(ctrlCharsFont); + PRectangle rcCChar = rcSegment; + rcCChar.left = rcCChar.left + 1; + rcCChar.top = rcSegment.top + vsDraw.maxAscent - normalCharHeight; + rcCChar.bottom = rcSegment.top + vsDraw.maxAscent + 1; + PRectangle rcCentral = rcCChar; + rcCentral.top++; + rcCentral.bottom--; + surface->FillRectangle(rcCentral, textFore); + PRectangle rcChar = rcCChar; + rcChar.left++; + rcChar.right--; + surface->DrawTextClipped(rcChar, ctrlCharsFont, + rcSegment.top + vsDraw.maxAscent, s, istrlen(s), + textBack, textFore); +} + +void Editor::DrawLine(Surface *surface, ViewStyle &vsDraw, int line, int lineVisible, int xStart, + PRectangle rcLine, LineLayout *ll, int subLine) { + + PRectangle rcSegment = rcLine; + + // Using one font for all control characters so it can be controlled independently to ensure + // the box goes around the characters tightly. Seems to be no way to work out what height + // is taken by an individual character - internal leading gives varying results. + Font &ctrlCharsFont = vsDraw.styles[STYLE_CONTROLCHAR].font; + + // See if something overrides the line background color: Either if caret is on the line + // and background color is set for that, or if a marker is defined that forces its background + // color onto the line, or if a marker is defined but has no selection margin in which to + // display itself (as long as it's not an SC_MARK_EMPTY marker). These are checked in order + // with the earlier taking precedence. When multiple markers cause background override, + // the color for the highest numbered one is used. + bool overrideBackground = false; + ColourAllocated background; + if ((caret.active || vsDraw.showCaretLineBackgroundAlways) && vsDraw.showCaretLineBackground && (vsDraw.caretLineAlpha == SC_ALPHA_NOALPHA) && ll->containsCaret) { + overrideBackground = true; + background = vsDraw.caretLineBackground.allocated; + } + if (!overrideBackground) { + int marks = pdoc->GetMark(line); + for (int markBit = 0; (markBit < 32) && marks; markBit++) { + if ((marks & 1) && (vsDraw.markers[markBit].markType == SC_MARK_BACKGROUND) && + (vsDraw.markers[markBit].alpha == SC_ALPHA_NOALPHA)) { + background = vsDraw.markers[markBit].back.allocated; + overrideBackground = true; + } + marks >>= 1; + } + } + if (!overrideBackground) { + if (vsDraw.maskInLine) { + int marksMasked = pdoc->GetMark(line) & vsDraw.maskInLine; + if (marksMasked) { + for (int markBit = 0; (markBit < 32) && marksMasked; markBit++) { + if ((marksMasked & 1) && (vsDraw.markers[markBit].markType != SC_MARK_EMPTY) && + (vsDraw.markers[markBit].alpha == SC_ALPHA_NOALPHA)) { + overrideBackground = true; + background = vsDraw.markers[markBit].back.allocated; + } + marksMasked >>= 1; + } + } + } + } + + bool drawWhitespaceBackground = (vsDraw.viewWhitespace != wsInvisible) && + (!overrideBackground) && (vsDraw.whitespaceBackgroundSet); + + bool inIndentation = subLine == 0; // Do not handle indentation except on first subline. + int indentWidth = pdoc->IndentSize() * vsDraw.spaceWidth; + + int posLineStart = pdoc->LineStart(line); + + int startseg = ll->LineStart(subLine); + int subLineStart = ll->positions[startseg]; + int lineStart = 0; + int lineEnd = 0; + if (subLine < ll->lines) { + lineStart = ll->LineStart(subLine); + lineEnd = ll->LineStart(subLine + 1); + } + + ColourAllocated wrapColour = vsDraw.styles[STYLE_DEFAULT].fore.allocated; + if (vsDraw.whitespaceForegroundSet) + wrapColour = vsDraw.whitespaceForeground.allocated; + + bool drawWrapMarkEnd = false; + + if (wrapVisualFlags & SC_WRAPVISUALFLAG_END) { + if (subLine + 1 < ll->lines) { + drawWrapMarkEnd = ll->LineStart(subLine + 1) != 0; + } + } + + if (actualWrapVisualStartIndent != 0) { + + bool continuedWrapLine = false; + if (subLine < ll->lines) { + continuedWrapLine = ll->LineStart(subLine) != 0; + } + + if (continuedWrapLine) { + // draw continuation rect + PRectangle rcPlace = rcSegment; + + rcPlace.left = ll->positions[startseg] + xStart - subLineStart; + rcPlace.right = rcPlace.left + actualWrapVisualStartIndent * vsDraw.aveCharWidth; + + // default bgnd here.. + surface->FillRectangle(rcSegment, overrideBackground ? background : + vsDraw.styles[STYLE_DEFAULT].back.allocated); + + // main line style would be below but this would be inconsistent with end markers + // also would possibly not be the style at wrap point + //int styleMain = ll->styles[lineStart]; + //surface->FillRectangle(rcPlace, vsDraw.styles[styleMain].back.allocated); + + if (wrapVisualFlags & SC_WRAPVISUALFLAG_START) { + + if (wrapVisualFlagsLocation & SC_WRAPVISUALFLAGLOC_START_BY_TEXT) + rcPlace.left = rcPlace.right - vsDraw.aveCharWidth; + else + rcPlace.right = rcPlace.left + vsDraw.aveCharWidth; + + DrawWrapMarker(surface, rcPlace, false, wrapColour); + } + + xStart += actualWrapVisualStartIndent * vsDraw.aveCharWidth; + } + } + + // Does not take margin into account but not significant + int xStartVisible = subLineStart - xStart; + + BreakFinder bfBack(ll, lineStart, lineEnd, posLineStart, IsUnicodeMode(), xStartVisible); + int next = bfBack.First(); + + // Background drawing loop + while (twoPhaseDraw && (next < lineEnd)) { + + startseg = next; + next = bfBack.Next(); + int i = next - 1; + int iDoc = i + posLineStart; + + rcSegment.left = ll->positions[startseg] + xStart - subLineStart; + rcSegment.right = ll->positions[i + 1] + xStart - subLineStart; + // Only try to draw if really visible - enhances performance by not calling environment to + // draw strings that are completely past the right side of the window. + if ((rcSegment.left <= rcLine.right) && (rcSegment.right >= rcLine.left)) { + // Clip to line rectangle, since may have a huge position which will not work with some platforms + rcSegment.left = Platform::Maximum(rcSegment.left, rcLine.left); + rcSegment.right = Platform::Minimum(rcSegment.right, rcLine.right); + + int styleMain = ll->styles[i]; + bool inSelection = (iDoc >= ll->selStart) && (iDoc < ll->selEnd) && (ll->selStart != ll->selEnd); + bool inHotspot = (ll->hsStart != -1) && (iDoc >= ll->hsStart) && (iDoc < ll->hsEnd); + ColourAllocated textBack = TextBackground(vsDraw, overrideBackground, background, inSelection, inHotspot, styleMain, i, ll); + if (ll->chars[i] == '\t') { + // Tab display + if (drawWhitespaceBackground && + (!inIndentation || vsDraw.viewWhitespace == wsVisibleAlways)) + textBack = vsDraw.whitespaceBackground.allocated; + surface->FillRectangle(rcSegment, textBack); + } else if (IsControlCharacter(ll->chars[i])) { + // Control character display + inIndentation = false; + surface->FillRectangle(rcSegment, textBack); + } else { + // Normal text display + surface->FillRectangle(rcSegment, textBack); + if (vsDraw.viewWhitespace != wsInvisible || + (inIndentation && vsDraw.viewIndentationGuides == ivReal)) { + for (int cpos = 0; cpos <= i - startseg; cpos++) { + if (ll->chars[cpos + startseg] == ' ') { + if (drawWhitespaceBackground && + (!inIndentation || vsDraw.viewWhitespace == wsVisibleAlways)) { + PRectangle rcSpace(ll->positions[cpos + startseg] + xStart, rcSegment.top, + ll->positions[cpos + startseg + 1] + xStart, rcSegment.bottom); + surface->FillRectangle(rcSpace, vsDraw.whitespaceBackground.allocated); + } + } else { + inIndentation = false; + } + } + } + } + } else if (rcSegment.left > rcLine.right) { + break; + } + } + + if (twoPhaseDraw) { + DrawEOL(surface, vsDraw, rcLine, ll, line, lineEnd, + xStart, subLine, subLineStart, overrideBackground, background, + drawWrapMarkEnd, wrapColour); + } + + DrawIndicators(surface, vsDraw, line, xStart, rcLine, ll, subLine, lineEnd, true); + + if (vsDraw.edgeState == EDGE_LINE) { + int edgeX = theEdge * vsDraw.spaceWidth; + rcSegment.left = edgeX + xStart; + rcSegment.right = rcSegment.left + 1; + surface->FillRectangle(rcSegment, vsDraw.edgecolour.allocated); + } + + inIndentation = subLine == 0; // Do not handle indentation except on first subline. + // Foreground drawing loop + BreakFinder bfFore(ll, lineStart, lineEnd, posLineStart, IsUnicodeMode(), xStartVisible); + next = bfFore.First(); + + while (next < lineEnd) { + + startseg = next; + next = bfFore.Next(); + int i = next - 1; + + int iDoc = i + posLineStart; + + rcSegment.left = ll->positions[startseg] + xStart - subLineStart; + rcSegment.right = ll->positions[i + 1] + xStart - subLineStart; + // Only try to draw if really visible - enhances performance by not calling environment to + // draw strings that are completely past the right side of the window. + if ((rcSegment.left <= rcLine.right) && (rcSegment.right >= rcLine.left)) { + int styleMain = ll->styles[i]; + ColourAllocated textFore = vsDraw.styles[styleMain].fore.allocated; + Font &textFont = vsDraw.styles[styleMain].font; + //hotspot foreground + if (ll->hsStart != -1 && iDoc >= ll->hsStart && iDoc < hsEnd) { + if (vsDraw.hotspotForegroundSet) + textFore = vsDraw.hotspotForeground.allocated; + } + bool inSelection = (iDoc >= ll->selStart) && (iDoc < ll->selEnd) && (ll->selStart != ll->selEnd); + if (inSelection && (vsDraw.selforeset)) { + textFore = vsDraw.selforeground.allocated; + } + bool inHotspot = (ll->hsStart != -1) && (iDoc >= ll->hsStart) && (iDoc < ll->hsEnd); + ColourAllocated textBack = TextBackground(vsDraw, overrideBackground, background, inSelection, inHotspot, styleMain, i, ll); + if (ll->chars[i] == '\t') { + // Tab display + if (!twoPhaseDraw) { + if (drawWhitespaceBackground && + (!inIndentation || vsDraw.viewWhitespace == wsVisibleAlways)) + textBack = vsDraw.whitespaceBackground.allocated; + surface->FillRectangle(rcSegment, textBack); + } + if ((vsDraw.viewWhitespace != wsInvisible) || + (inIndentation && vsDraw.viewIndentationGuides != ivNone)) { + if (vsDraw.whitespaceForegroundSet) + textFore = vsDraw.whitespaceForeground.allocated; + 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)); + } + } + } + if (vsDraw.viewWhitespace != wsInvisible) { + if (!inIndentation || vsDraw.viewWhitespace == wsVisibleAlways) { + PRectangle rcTab(rcSegment.left + 1, rcSegment.top + 4, + rcSegment.right - 1, rcSegment.bottom - vsDraw.maxDescent); + DrawTabArrow(surface, rcTab, rcSegment.top + vsDraw.lineHeight / 2); + } + } + } else if (IsControlCharacter(ll->chars[i])) { + // Control character display + inIndentation = false; + if (controlCharSymbol < 32) { + // Draw the character + const char *ctrlChar = ControlCharacterString(ll->chars[i]); + DrawTextBlob(surface, vsDraw, rcSegment, ctrlChar, textBack, textFore, twoPhaseDraw); + } else { + char cc[2] = { static_cast(controlCharSymbol), '\0' }; + surface->DrawTextNoClip(rcSegment, ctrlCharsFont, + rcSegment.top + vsDraw.maxAscent, + cc, 1, textBack, textFore); + } + } else if ((i == startseg) && (static_cast(ll->chars[i]) >= 0x80) && IsUnicodeMode()) { + char hexits[3]; + sprintf(hexits, "%2X", ll->chars[i] & 0xff); + DrawTextBlob(surface, vsDraw, rcSegment, hexits, textBack, textFore, twoPhaseDraw); + } else { + // Normal text display + if (vsDraw.styles[styleMain].visible) { + if (twoPhaseDraw) { + surface->DrawTextTransparent(rcSegment, textFont, + rcSegment.top + vsDraw.maxAscent, ll->chars + startseg, + i - startseg + 1, textFore); + } else { + surface->DrawTextNoClip(rcSegment, textFont, + rcSegment.top + vsDraw.maxAscent, ll->chars + startseg, + i - startseg + 1, textFore, textBack); + } + } + if (vsDraw.viewWhitespace != wsInvisible || + (inIndentation && vsDraw.viewIndentationGuides != ivNone)) { + for (int cpos = 0; cpos <= i - startseg; cpos++) { + if (ll->chars[cpos + startseg] == ' ') { + if (vsDraw.viewWhitespace != wsInvisible) { + if (vsDraw.whitespaceForegroundSet) + textFore = vsDraw.whitespaceForeground.allocated; + if (!inIndentation || vsDraw.viewWhitespace == wsVisibleAlways) { + int xmid = (ll->positions[cpos + startseg] + ll->positions[cpos + startseg + 1]) / 2; + if (!twoPhaseDraw && drawWhitespaceBackground && + (!inIndentation || vsDraw.viewWhitespace == wsVisibleAlways)) { + textBack = vsDraw.whitespaceBackground.allocated; + PRectangle rcSpace(ll->positions[cpos + startseg] + xStart, rcSegment.top, ll->positions[cpos + startseg + 1] + xStart, rcSegment.bottom); + surface->FillRectangle(rcSpace, textBack); + } + PRectangle rcDot(xmid + xStart - subLineStart, rcSegment.top + vsDraw.lineHeight / 2, 0, 0); + rcDot.right = rcDot.left + 1; + rcDot.bottom = rcDot.top + 1; + surface->FillRectangle(rcDot, textFore); + } + } + 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])); + } + } + } else { + inIndentation = false; + } + } + } + } + if (ll->hsStart != -1 && vsDraw.hotspotUnderline && iDoc >= ll->hsStart && iDoc < ll->hsEnd ) { + PRectangle rcUL = rcSegment; + rcUL.top = rcUL.top + vsDraw.maxAscent + 1; + rcUL.bottom = rcUL.top + 1; + if (vsDraw.hotspotForegroundSet) + surface->FillRectangle(rcUL, vsDraw.hotspotForeground.allocated); + else + surface->FillRectangle(rcUL, textFore); + } else if (vsDraw.styles[styleMain].underline) { + PRectangle rcUL = rcSegment; + rcUL.top = rcUL.top + vsDraw.maxAscent + 1; + rcUL.bottom = rcUL.top + 1; + surface->FillRectangle(rcUL, textFore); + } + } else if (rcSegment.left > rcLine.right) { + break; + } + } + if ((vsDraw.viewIndentationGuides == ivLookForward || vsDraw.viewIndentationGuides == ivLookBoth) + && (subLine == 0)) { + int indentSpace = pdoc->GetLineIndentation(line); + // Find the most recent line with some text + + int lineLastWithText = line; + while (lineLastWithText > 0 && pdoc->IsWhiteLine(lineLastWithText)) { + lineLastWithText--; + } + if (lineLastWithText < line) { + // This line is empty, so use indentation of last line with text + int indentLastWithText = pdoc->GetLineIndentation(lineLastWithText); + int isFoldHeader = pdoc->GetLevel(lineLastWithText) & SC_FOLDLEVELHEADERFLAG; + if (isFoldHeader) { + // Level is one more level than parent + indentLastWithText += pdoc->IndentSize(); + } + if (vsDraw.viewIndentationGuides == ivLookForward) { + // In viLookForward mode, previous line only used if it is a fold header + if (isFoldHeader) { + indentSpace = Platform::Maximum(indentSpace, indentLastWithText); + } + } else { // viLookBoth + indentSpace = Platform::Maximum(indentSpace, indentLastWithText); + } + } + + int lineNextWithText = line; + while (lineNextWithText < pdoc->LinesTotal() && pdoc->IsWhiteLine(lineNextWithText)) { + lineNextWithText++; + } + if (lineNextWithText > line) { + // This line is empty, so use indentation of last line with text + indentSpace = Platform::Maximum(indentSpace, + pdoc->GetLineIndentation(lineNextWithText)); + } + + for (int indentPos = pdoc->IndentSize(); indentPos < indentSpace; indentPos += pdoc->IndentSize()) { + int xIndent = indentPos * vsDraw.spaceWidth; + DrawIndentGuide(surface, lineVisible, vsDraw.lineHeight, xIndent + xStart, rcSegment, + (ll->xHighlightGuide == xIndent)); + } + } + + DrawIndicators(surface, vsDraw, line, xStart, rcLine, ll, subLine, lineEnd, false); + + // End of the drawing of the current line + if (!twoPhaseDraw) { + DrawEOL(surface, vsDraw, rcLine, ll, line, lineEnd, + xStart, subLine, subLineStart, overrideBackground, background, + drawWrapMarkEnd, wrapColour); + } + if ((vsDraw.selAlpha != SC_ALPHA_NOALPHA) && (ll->selStart >= 0) && (ll->selEnd >= 0)) { + int startPosSel = (ll->selStart < posLineStart) ? posLineStart : ll->selStart; + int endPosSel = (ll->selEnd < (lineEnd + posLineStart)) ? ll->selEnd : (lineEnd + posLineStart); + if (startPosSel < endPosSel) { + rcSegment.left = xStart + ll->positions[startPosSel - posLineStart] - subLineStart; + rcSegment.right = xStart + ll->positions[endPosSel - posLineStart] - subLineStart; + rcSegment.left = Platform::Maximum(rcSegment.left, rcLine.left); + rcSegment.right = Platform::Minimum(rcSegment.right, rcLine.right); + SimpleAlphaRectangle(surface, rcSegment, SelectionBackground(vsDraw), vsDraw.selAlpha); + } + } + + // Draw any translucent whole line states + rcSegment.left = xStart; + rcSegment.right = rcLine.right - 1; + if ((caret.active || vsDraw.showCaretLineBackgroundAlways) && vsDraw.showCaretLineBackground && ll->containsCaret) { + SimpleAlphaRectangle(surface, rcSegment, vsDraw.caretLineBackground.allocated, vsDraw.caretLineAlpha); + } + int marks = pdoc->GetMark(line); + for (int markBit = 0; (markBit < 32) && marks; markBit++) { + if ((marks & 1) && (vsDraw.markers[markBit].markType == SC_MARK_BACKGROUND)) { + SimpleAlphaRectangle(surface, rcSegment, vsDraw.markers[markBit].back.allocated, vsDraw.markers[markBit].alpha); + } + marks >>= 1; + } + if (vsDraw.maskInLine) { + int marksMasked = pdoc->GetMark(line) & vsDraw.maskInLine; + if (marksMasked) { + for (int markBit = 0; (markBit < 32) && marksMasked; markBit++) { + if ((marksMasked & 1) && (vsDraw.markers[markBit].markType != SC_MARK_EMPTY)) { + SimpleAlphaRectangle(surface, rcSegment, vsDraw.markers[markBit].back.allocated, vsDraw.markers[markBit].alpha); + } + marksMasked >>= 1; + } + } + } +} + +void Editor::DrawBlockCaret(Surface *surface, ViewStyle &vsDraw, LineLayout *ll, int subLine, int xStart, int offset, int posCaret, PRectangle rcCaret) { + + int lineStart = ll->LineStart(subLine); + int posBefore = posCaret; + int posAfter = MovePositionOutsideChar(posCaret + 1, 1); + int numCharsToDraw = posAfter - posCaret; + + // Work out where the starting and ending offsets are. We need to + // see if the previous character shares horizontal space, such as a + // glyph / combining character. If so we'll need to draw that too. + int offsetFirstChar = offset; + int offsetLastChar = offset + (posAfter - posCaret); + while ((offsetLastChar - numCharsToDraw) >= lineStart) { + if ((ll->positions[offsetLastChar] - ll->positions[offsetLastChar - numCharsToDraw]) > 0) { + // The char does not share horizontal space + break; + } + // Char shares horizontal space, update the numChars to draw + // Update posBefore to point to the prev char + posBefore = MovePositionOutsideChar(posBefore - 1, -1); + numCharsToDraw = posAfter - posBefore; + offsetFirstChar = offset - (posCaret - posBefore); + } + + // See if the next character shares horizontal space, if so we'll + // need to draw that too. + numCharsToDraw = offsetLastChar - offsetFirstChar; + while ((offsetLastChar < ll->LineStart(subLine + 1)) && (offsetLastChar <= ll->numCharsInLine)) { + // Update posAfter to point to the 2nd next char, this is where + // the next character ends, and 2nd next begins. We'll need + // to compare these two + posBefore = posAfter; + posAfter = MovePositionOutsideChar(posAfter + 1, 1); + offsetLastChar = offset + (posAfter - posCaret); + if ((ll->positions[offsetLastChar] - ll->positions[offsetLastChar - (posAfter - posBefore)]) > 0) { + // The char does not share horizontal space + break; + } + // Char shares horizontal space, update the numChars to draw + numCharsToDraw = offsetLastChar - offsetFirstChar; + } + + // We now know what to draw, update the caret drawing rectangle + rcCaret.left = ll->positions[offsetFirstChar] - ll->positions[ll->LineStart(subLine)] + xStart; + rcCaret.right = ll->positions[offsetFirstChar+numCharsToDraw] - ll->positions[ll->LineStart(subLine)] + xStart; + + // This character is where the caret block is, we override the colours + // (inversed) for drawing the caret here. + int styleMain = ll->styles[offsetFirstChar]; + surface->DrawTextClipped(rcCaret, vsDraw.styles[styleMain].font, + rcCaret.top + vsDraw.maxAscent, ll->chars + offsetFirstChar, + numCharsToDraw, vsDraw.styles[styleMain].back.allocated, + vsDraw.caretcolour.allocated); +} + +void Editor::RefreshPixMaps(Surface *surfaceWindow) { + if (!pixmapSelPattern->Initialised()) { + const int patternSize = 8; + pixmapSelPattern->InitPixMap(patternSize, patternSize, surfaceWindow, wMain.GetID()); + // This complex procedure is to reproduce the checkerboard dithered pattern used by windows + // for scroll bars and Visual Studio for its selection margin. The colour of this pattern is half + // way between the chrome colour and the chrome highlight colour making a nice transition + // between the window chrome and the content area. And it works in low colour depths. + PRectangle rcPattern(0, 0, patternSize, patternSize); + + // Initialize default colours based on the chrome colour scheme. Typically the highlight is white. + ColourAllocated colourFMFill = vs.selbar.allocated; + ColourAllocated colourFMStripes = vs.selbarlight.allocated; + + if (!(vs.selbarlight.desired == ColourDesired(0xff, 0xff, 0xff))) { + // User has chosen an unusual chrome colour scheme so just use the highlight edge colour. + // (Typically, the highlight colour is white.) + colourFMFill = vs.selbarlight.allocated; + } + + if (vs.foldmarginColourSet) { + // override default fold margin colour + colourFMFill = vs.foldmarginColour.allocated; + } + if (vs.foldmarginHighlightColourSet) { + // override default fold margin highlight colour + colourFMStripes = vs.foldmarginHighlightColour.allocated; + } + + pixmapSelPattern->FillRectangle(rcPattern, colourFMFill); + pixmapSelPattern->PenColour(colourFMStripes); + for (int stripe = 0; stripe < patternSize; stripe++) { + // Alternating 1 pixel stripes is same as checkerboard. + pixmapSelPattern->MoveTo(0, stripe * 2); + pixmapSelPattern->LineTo(patternSize, stripe * 2 - patternSize); + } + } + + if (!pixmapIndentGuide->Initialised()) { + // 1 extra pixel in height so can handle odd/even positions and so produce a continuous line + pixmapIndentGuide->InitPixMap(1, vs.lineHeight + 1, surfaceWindow, wMain.GetID()); + pixmapIndentGuideHighlight->InitPixMap(1, vs.lineHeight + 1, surfaceWindow, wMain.GetID()); + PRectangle rcIG(0, 0, 1, vs.lineHeight); + pixmapIndentGuide->FillRectangle(rcIG, vs.styles[STYLE_INDENTGUIDE].back.allocated); + pixmapIndentGuide->PenColour(vs.styles[STYLE_INDENTGUIDE].fore.allocated); + pixmapIndentGuideHighlight->FillRectangle(rcIG, vs.styles[STYLE_BRACELIGHT].back.allocated); + pixmapIndentGuideHighlight->PenColour(vs.styles[STYLE_BRACELIGHT].fore.allocated); + for (int stripe = 1; stripe < vs.lineHeight + 1; stripe += 2) { + pixmapIndentGuide->MoveTo(0, stripe); + pixmapIndentGuide->LineTo(2, stripe); + pixmapIndentGuideHighlight->MoveTo(0, stripe); + pixmapIndentGuideHighlight->LineTo(2, stripe); + } + } + + if (bufferedDraw) { + if (!pixmapLine->Initialised()) { + PRectangle rcClient = GetClientRectangle(); + pixmapLine->InitPixMap(rcClient.Width(), vs.lineHeight, + surfaceWindow, wMain.GetID()); + pixmapSelMargin->InitPixMap(vs.fixedColumnWidth, + rcClient.Height(), surfaceWindow, wMain.GetID()); + } + } +} + +void Editor::Paint(Surface *surfaceWindow, PRectangle rcArea) { + //Platform::DebugPrintf("Paint:%1d (%3d,%3d) ... (%3d,%3d)\n", + // paintingAllText, rcArea.left, rcArea.top, rcArea.right, rcArea.bottom); + + pixmapLine->Release(); + RefreshStyleData(); + RefreshPixMaps(surfaceWindow); + + PRectangle rcClient = GetClientRectangle(); + //Platform::DebugPrintf("Client: (%3d,%3d) ... (%3d,%3d) %d\n", + // rcClient.left, rcClient.top, rcClient.right, rcClient.bottom); + + surfaceWindow->SetPalette(&palette, true); + pixmapLine->SetPalette(&palette, !hasFocus); + + int screenLinePaintFirst = rcArea.top / vs.lineHeight; + // The area to be painted plus one extra line is styled. + // The extra line is to determine when a style change, such as starting a comment flows on to other lines. + int lineStyleLast = topLine + (rcArea.bottom - 1) / vs.lineHeight + 1; + //Platform::DebugPrintf("Paint lines = %d .. %d\n", topLine + screenLinePaintFirst, lineStyleLast); + int endPosPaint = pdoc->Length(); + if (lineStyleLast < cs.LinesDisplayed()) + endPosPaint = pdoc->LineStart(cs.DocFromDisplay(lineStyleLast + 1)); + + int xStart = vs.fixedColumnWidth - xOffset; + int ypos = 0; + if (!bufferedDraw) + ypos += screenLinePaintFirst * vs.lineHeight; + int yposScreen = screenLinePaintFirst * vs.lineHeight; + + // Ensure we are styled as far as we are painting. + pdoc->EnsureStyledTo(endPosPaint); + bool paintAbandonedByStyling = paintState == paintAbandoned; + if (needUpdateUI) { + // Deselect palette by selecting a temporary palette + Palette palTemp; + surfaceWindow->SetPalette(&palTemp, true); + + NotifyUpdateUI(); + needUpdateUI = false; + + RefreshStyleData(); + RefreshPixMaps(surfaceWindow); + surfaceWindow->SetPalette(&palette, true); + pixmapLine->SetPalette(&palette, !hasFocus); + } + + // Call priority lines wrap on a window of lines which are likely + // to rendered with the following paint (that is wrap the visible + // lines first). + int startLineToWrap = cs.DocFromDisplay(topLine) - 5; + if (startLineToWrap < 0) + startLineToWrap = -1; + if (WrapLines(false, startLineToWrap)) { + // The wrapping process has changed the height of some lines so + // abandon this paint for a complete repaint. + if (AbandonPaint()) { + return; + } + RefreshPixMaps(surfaceWindow); // In case pixmaps invalidated by scrollbar change + } + PLATFORM_ASSERT(pixmapSelPattern->Initialised()); + + PaintSelMargin(surfaceWindow, rcArea); + + PRectangle rcRightMargin = rcClient; + rcRightMargin.left = rcRightMargin.right - vs.rightMarginWidth; + if (rcArea.Intersects(rcRightMargin)) { + surfaceWindow->FillRectangle(rcRightMargin, vs.styles[STYLE_DEFAULT].back.allocated); + } + + if (paintState == paintAbandoned) { + // Either styling or NotifyUpdateUI noticed that painting is needed + // outside the current painting rectangle + //Platform::DebugPrintf("Abandoning paint\n"); + if (wrapState != eWrapNone) { + if (paintAbandonedByStyling) { + // Styling has spilled over a line end, such as occurs by starting a multiline + // comment. The width of subsequent text may have changed, so rewrap. + NeedWrapping(cs.DocFromDisplay(topLine)); + } + } + return; + } + //Platform::DebugPrintf("start display %d, offset = %d\n", pdoc->Length(), xOffset); + + // Do the painting + if (rcArea.right > vs.fixedColumnWidth) { + + Surface *surface = surfaceWindow; + if (bufferedDraw) { + surface = pixmapLine; + PLATFORM_ASSERT(pixmapLine->Initialised()); + } + surface->SetUnicodeMode(IsUnicodeMode()); + surface->SetDBCSMode(CodePage()); + + int visibleLine = topLine + screenLinePaintFirst; + + int posCaret = currentPos; + if (posDrag >= 0) + posCaret = posDrag; + int lineCaret = pdoc->LineFromPosition(posCaret); + + // 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); + + // Loop on visible lines + //double durLayout = 0.0; + //double durPaint = 0.0; + //double durCopy = 0.0; + //ElapsedTime etWhole; + int lineDocPrevious = -1; // Used to avoid laying out one document line multiple times + AutoLineLayout ll(llc, 0); + SelectionLineIterator lineIterator(this); + while (visibleLine < cs.LinesDisplayed() && yposScreen < rcArea.bottom) { + + int lineDoc = cs.DocFromDisplay(visibleLine); + // Only visible lines should be handled by the code within the loop + PLATFORM_ASSERT(cs.GetVisible(lineDoc)); + int lineStartSet = cs.DisplayFromDoc(lineDoc); + int subLine = visibleLine - lineStartSet; + + // Copy this line and its styles from the document into local arrays + // and determine the x position at which each character starts. + //ElapsedTime et; + if (lineDoc != lineDocPrevious) { + ll.Set(0); + // For rectangular selection this accesses the layout cache so should be after layout returned. + lineIterator.SetAt(lineDoc); + ll.Set(RetrieveLineLayout(lineDoc)); + LayoutLine(lineDoc, surface, vs, ll, wrapWidth); + lineDocPrevious = lineDoc; + } + //durLayout += et.Duration(true); + + if (ll) { + if (selType == selStream) { + ll->selStart = SelectionStart(); + ll->selEnd = SelectionEnd(); + } else { + ll->selStart = lineIterator.startPos; + ll->selEnd = lineIterator.endPos; + } + ll->containsCaret = lineDoc == lineCaret; + if (hideSelection) { + ll->selStart = -1; + ll->selEnd = -1; + ll->containsCaret = false; + } + + GetHotSpotRange(ll->hsStart, ll->hsEnd); + + PRectangle rcLine = rcClient; + rcLine.top = ypos; + rcLine.bottom = ypos + vs.lineHeight; + + Range rangeLine(pdoc->LineStart(lineDoc), pdoc->LineStart(lineDoc + 1)); + // Highlight the current braces if any + ll->SetBracesHighlight(rangeLine, braces, static_cast(bracesMatchStyle), + highlightGuideColumn * vs.spaceWidth); + + // Draw the line + DrawLine(surface, vs, lineDoc, visibleLine, xStart, rcLine, ll, subLine); + //durPaint += et.Duration(true); + + // Restore the previous styles for the brace highlights in case layout is in cache. + ll->RestoreBracesHighlight(rangeLine, braces); + + bool expanded = cs.GetExpanded(lineDoc); + if ((foldFlags & SC_FOLDFLAG_BOX) == 0) { + // Paint the line above the fold + if ((expanded && (foldFlags & SC_FOLDFLAG_LINEBEFORE_EXPANDED)) + || + (!expanded && (foldFlags & SC_FOLDFLAG_LINEBEFORE_CONTRACTED))) { + if (pdoc->GetLevel(lineDoc) & SC_FOLDLEVELHEADERFLAG) { + PRectangle rcFoldLine = rcLine; + rcFoldLine.bottom = rcFoldLine.top + 1; + surface->FillRectangle(rcFoldLine, vs.styles[STYLE_DEFAULT].fore.allocated); + } + } + // Paint the line below the fold + if ((expanded && (foldFlags & SC_FOLDFLAG_LINEAFTER_EXPANDED)) + || + (!expanded && (foldFlags & SC_FOLDFLAG_LINEAFTER_CONTRACTED))) { + if (pdoc->GetLevel(lineDoc) & SC_FOLDLEVELHEADERFLAG) { + PRectangle rcFoldLine = rcLine; + rcFoldLine.top = rcFoldLine.bottom - 1; + surface->FillRectangle(rcFoldLine, vs.styles[STYLE_DEFAULT].fore.allocated); + } + } + } else { + int FoldLevelCurr = (pdoc->GetLevel(lineDoc) & SC_FOLDLEVELNUMBERMASK) - SC_FOLDLEVELBASE; + int FoldLevelPrev = (pdoc->GetLevel(lineDoc - 1) & SC_FOLDLEVELNUMBERMASK) - SC_FOLDLEVELBASE; + int FoldLevelFlags = (pdoc->GetLevel(lineDoc) & ~SC_FOLDLEVELNUMBERMASK) & ~(0xFFF0000); + int indentationStep = pdoc->IndentSize(); + // Draw line above fold + if ((FoldLevelPrev < FoldLevelCurr) + || + (FoldLevelFlags & SC_FOLDLEVELBOXHEADERFLAG + && + (pdoc->GetLevel(lineDoc - 1) & SC_FOLDLEVELBOXFOOTERFLAG) == 0)) { + PRectangle rcFoldLine = rcLine; + rcFoldLine.bottom = rcFoldLine.top + 1; + rcFoldLine.left += xStart + FoldLevelCurr * vs.spaceWidth * indentationStep - 1; + surface->FillRectangle(rcFoldLine, vs.styles[STYLE_DEFAULT].fore.allocated); + } + + // Line below the fold (or below a contracted fold) + if (FoldLevelFlags & SC_FOLDLEVELBOXFOOTERFLAG + || + (!expanded && (foldFlags & SC_FOLDFLAG_LINEAFTER_CONTRACTED))) { + PRectangle rcFoldLine = rcLine; + rcFoldLine.top = rcFoldLine.bottom - 1; + rcFoldLine.left += xStart + (FoldLevelCurr) * vs.spaceWidth * indentationStep - 1; + surface->FillRectangle(rcFoldLine, vs.styles[STYLE_DEFAULT].fore.allocated); + } + + PRectangle rcBoxLine = rcLine; + // Draw vertical line for every fold level + for (int i = 0; i <= FoldLevelCurr; i++) { + rcBoxLine.left = xStart + i * vs.spaceWidth * indentationStep - 1; + rcBoxLine.right = rcBoxLine.left + 1; + surface->FillRectangle(rcBoxLine, vs.styles[STYLE_DEFAULT].fore.allocated); + } + } + + // Draw the Caret + if (lineDoc == lineCaret) { + int offset = Platform::Minimum(posCaret - rangeLine.start, ll->maxLineLength); + if (ll->InLine(offset, subLine)) { + int xposCaret = ll->positions[offset] - ll->positions[ll->LineStart(subLine)] + xStart; + + if (actualWrapVisualStartIndent != 0) { + int lineStart = ll->LineStart(subLine); + if (lineStart != 0) // Wrapped + xposCaret += actualWrapVisualStartIndent * vs.aveCharWidth; + } + if ((xposCaret >= 0) && (vs.caretWidth > 0) && (vs.caretStyle != CARETSTYLE_INVISIBLE) && + ((posDrag >= 0) || (caret.active && caret.on))) { + bool caretAtEOF = false; + bool caretAtEOL = false; + bool drawBlockCaret = false; + int widthOverstrikeCaret; + int caretWidthOffset = 0; + PRectangle rcCaret = rcLine; + + if (posCaret == pdoc->Length()) { // At end of document + caretAtEOF = true; + widthOverstrikeCaret = vs.aveCharWidth; + } else if ((posCaret - rangeLine.start) >= ll->numCharsInLine) { // At end of line + caretAtEOL = true; + widthOverstrikeCaret = vs.aveCharWidth; + } else { + widthOverstrikeCaret = ll->positions[offset + 1] - ll->positions[offset]; + } + if (widthOverstrikeCaret < 3) // Make sure its visible + widthOverstrikeCaret = 3; + + if (offset > ll->LineStart(subLine)) + caretWidthOffset = 1; // Move back so overlaps both character cells. + if (posDrag >= 0) { + /* Dragging text, use a line caret */ + rcCaret.left = xposCaret - caretWidthOffset; + rcCaret.right = rcCaret.left + vs.caretWidth; + } else if (inOverstrike) { + /* Overstrike (insert mode), use a modified bar caret */ + rcCaret.top = rcCaret.bottom - 2; + rcCaret.left = xposCaret + 1; + rcCaret.right = rcCaret.left + widthOverstrikeCaret - 1; + } else if (vs.caretStyle == CARETSTYLE_BLOCK) { + /* Block caret */ + rcCaret.left = xposCaret; + if (!caretAtEOL && !caretAtEOF && (ll->chars[offset] != '\t') && !(IsControlCharacter(ll->chars[offset]))) { + drawBlockCaret = true; + rcCaret.right = xposCaret + widthOverstrikeCaret; + } else { + rcCaret.right = xposCaret + vs.aveCharWidth; + } + } else { + /* Line caret */ + rcCaret.left = xposCaret - caretWidthOffset; + rcCaret.right = rcCaret.left + vs.caretWidth; + } + if (drawBlockCaret) { + DrawBlockCaret(surface, vs, ll, subLine, xStart, offset, posCaret, rcCaret); + } else { + surface->FillRectangle(rcCaret, vs.caretcolour.allocated); + } + } + } + } + + if (bufferedDraw) { + Point from(vs.fixedColumnWidth, 0); + PRectangle rcCopyArea(vs.fixedColumnWidth, yposScreen, + rcClient.right, yposScreen + vs.lineHeight); + surfaceWindow->Copy(rcCopyArea, from, *pixmapLine); + } + //durCopy += et.Duration(true); + } + + if (!bufferedDraw) { + ypos += vs.lineHeight; + } + + yposScreen += vs.lineHeight; + visibleLine++; + + lineWidthMaxSeen = Platform::Maximum( + lineWidthMaxSeen, ll->positions[ll->numCharsInLine]); + //gdk_flush(); + } + ll.Set(0); + //if (durPaint < 0.00000001) + // durPaint = 0.00000001; + + // Right column limit indicator + PRectangle rcBeyondEOF = rcClient; + rcBeyondEOF.left = vs.fixedColumnWidth; + rcBeyondEOF.right = rcBeyondEOF.right; + rcBeyondEOF.top = (cs.LinesDisplayed() - topLine) * vs.lineHeight; + if (rcBeyondEOF.top < rcBeyondEOF.bottom) { + surfaceWindow->FillRectangle(rcBeyondEOF, vs.styles[STYLE_DEFAULT].back.allocated); + if (vs.edgeState == EDGE_LINE) { + int edgeX = theEdge * vs.spaceWidth; + rcBeyondEOF.left = edgeX + xStart; + rcBeyondEOF.right = rcBeyondEOF.left + 1; + surfaceWindow->FillRectangle(rcBeyondEOF, vs.edgecolour.allocated); + } + } + //Platform::DebugPrintf( + //"Layout:%9.6g Paint:%9.6g Ratio:%9.6g Copy:%9.6g Total:%9.6g\n", + //durLayout, durPaint, durLayout / durPaint, durCopy, etWhole.Duration()); + NotifyPainted(); + } +} + +// Space (3 space characters) between line numbers and text when printing. +#define lineNumberPrintSpace " " + +ColourDesired InvertedLight(ColourDesired orig) { + unsigned int r = orig.GetRed(); + unsigned int g = orig.GetGreen(); + unsigned int b = orig.GetBlue(); + unsigned int l = (r + g + b) / 3; // There is a better calculation for this that matches human eye + unsigned int il = 0xff - l; + if (l == 0) + return ColourDesired(0xff, 0xff, 0xff); + r = r * il / l; + g = g * il / l; + b = b * il / l; + return ColourDesired(Platform::Minimum(r, 0xff), Platform::Minimum(g, 0xff), Platform::Minimum(b, 0xff)); +} + +// This is mostly copied from the Paint method but with some things omitted +// such as the margin markers, line numbers, selection and caret +// Should be merged back into a combined Draw method. +long Editor::FormatRange(bool draw, RangeToFormat *pfr) { + if (!pfr) + return 0; + + AutoSurface surface(pfr->hdc, this); + if (!surface) + return 0; + AutoSurface surfaceMeasure(pfr->hdcTarget, this); + if (!surfaceMeasure) { + return 0; + } + + // Can't use measurements cached for screen + posCache.Clear(); + + ViewStyle vsPrint(vs); + + // Modify the view style for printing as do not normally want any of the transient features to be printed + // Printing supports only the line number margin. + int lineNumberIndex = -1; + for (int margin = 0; margin < ViewStyle::margins; margin++) { + if ((vsPrint.ms[margin].style == SC_MARGIN_NUMBER) && (vsPrint.ms[margin].width > 0)) { + lineNumberIndex = margin; + } else { + vsPrint.ms[margin].width = 0; + } + } + vsPrint.showMarkedLines = false; + vsPrint.fixedColumnWidth = 0; + vsPrint.zoomLevel = printMagnification; + vsPrint.viewIndentationGuides = ivNone; + // Don't show the selection when printing + vsPrint.selbackset = false; + vsPrint.selforeset = false; + vsPrint.selAlpha = SC_ALPHA_NOALPHA; + vsPrint.whitespaceBackgroundSet = false; + vsPrint.whitespaceForegroundSet = false; + vsPrint.showCaretLineBackground = false; + vsPrint.showCaretLineBackgroundAlways = false; + + // Set colours for printing according to users settings + for (size_t sty = 0;sty < vsPrint.stylesSize;sty++) { + if (printColourMode == SC_PRINT_INVERTLIGHT) { + vsPrint.styles[sty].fore.desired = InvertedLight(vsPrint.styles[sty].fore.desired); + vsPrint.styles[sty].back.desired = InvertedLight(vsPrint.styles[sty].back.desired); + } else if (printColourMode == SC_PRINT_BLACKONWHITE) { + vsPrint.styles[sty].fore.desired = ColourDesired(0, 0, 0); + vsPrint.styles[sty].back.desired = ColourDesired(0xff, 0xff, 0xff); + } else if (printColourMode == SC_PRINT_COLOURONWHITE) { + vsPrint.styles[sty].back.desired = ColourDesired(0xff, 0xff, 0xff); + } else if (printColourMode == SC_PRINT_COLOURONWHITEDEFAULTBG) { + if (sty <= STYLE_DEFAULT) { + vsPrint.styles[sty].back.desired = ColourDesired(0xff, 0xff, 0xff); + } + } + } + // White background for the line numbers + vsPrint.styles[STYLE_LINENUMBER].back.desired = ColourDesired(0xff, 0xff, 0xff); + + vsPrint.Refresh(*surfaceMeasure); + // Determining width must hapen after fonts have been realised in Refresh + int lineNumberWidth = 0; + if (lineNumberIndex >= 0) { + lineNumberWidth = surfaceMeasure->WidthText(vsPrint.styles[STYLE_LINENUMBER].font, + "99999" lineNumberPrintSpace, 5 + istrlen(lineNumberPrintSpace)); + vsPrint.ms[lineNumberIndex].width = lineNumberWidth; + vsPrint.Refresh(*surfaceMeasure); // Recalculate fixedColumnWidth + } + // Ensure colours are set up + vsPrint.RefreshColourPalette(palette, true); + vsPrint.RefreshColourPalette(palette, false); + + int linePrintStart = pdoc->LineFromPosition(pfr->chrg.cpMin); + int linePrintLast = linePrintStart + (pfr->rc.bottom - pfr->rc.top) / vsPrint.lineHeight - 1; + if (linePrintLast < linePrintStart) + linePrintLast = linePrintStart; + int linePrintMax = pdoc->LineFromPosition(pfr->chrg.cpMax); + if (linePrintLast > linePrintMax) + linePrintLast = linePrintMax; + //Platform::DebugPrintf("Formatting lines=[%0d,%0d,%0d] top=%0d bottom=%0d line=%0d %0d\n", + // linePrintStart, linePrintLast, linePrintMax, pfr->rc.top, pfr->rc.bottom, vsPrint.lineHeight, + // surfaceMeasure->Height(vsPrint.styles[STYLE_LINENUMBER].font)); + int endPosPrint = pdoc->Length(); + if (linePrintLast < pdoc->LinesTotal()) + endPosPrint = pdoc->LineStart(linePrintLast + 1); + + // Ensure we are styled to where we are formatting. + pdoc->EnsureStyledTo(endPosPrint); + + int xStart = vsPrint.fixedColumnWidth + pfr->rc.left; + int ypos = pfr->rc.top; + + int lineDoc = linePrintStart; + + int nPrintPos = pfr->chrg.cpMin; + int visibleLine = 0; + int widthPrint = pfr->rc.Width() - vsPrint.fixedColumnWidth; + if (printWrapState == eWrapNone) + widthPrint = LineLayout::wrapWidthInfinite; + + while (lineDoc <= linePrintLast && ypos < pfr->rc.bottom) { + + // When printing, the hdc and hdcTarget may be the same, so + // changing the state of surfaceMeasure may change the underlying + // state of surface. Therefore, any cached state is discarded before + // using each surface. + surfaceMeasure->FlushCachedState(); + + // Copy this line and its styles from the document into local arrays + // and determine the x position at which each character starts. + LineLayout ll(8000); + LayoutLine(lineDoc, surfaceMeasure, vsPrint, &ll, widthPrint); + + ll.selStart = -1; + ll.selEnd = -1; + ll.containsCaret = false; + + PRectangle rcLine; + rcLine.left = pfr->rc.left; + rcLine.top = ypos; + rcLine.right = pfr->rc.right - 1; + rcLine.bottom = ypos + vsPrint.lineHeight; + + // When document line is wrapped over multiple display lines, find where + // to start printing from to ensure a particular position is on the first + // line of the page. + if (visibleLine == 0) { + int startWithinLine = nPrintPos - pdoc->LineStart(lineDoc); + for (int iwl = 0; iwl < ll.lines - 1; iwl++) { + if (ll.LineStart(iwl) <= startWithinLine && ll.LineStart(iwl + 1) >= startWithinLine) { + visibleLine = -iwl; + } + } + + if (ll.lines > 1 && startWithinLine >= ll.LineStart(ll.lines - 1)) { + visibleLine = -(ll.lines - 1); + } + } + + if (draw && lineNumberWidth && + (ypos + vsPrint.lineHeight <= pfr->rc.bottom) && + (visibleLine >= 0)) { + char number[100]; + sprintf(number, "%d" lineNumberPrintSpace, lineDoc + 1); + PRectangle rcNumber = rcLine; + rcNumber.right = rcNumber.left + lineNumberWidth; + // Right justify + rcNumber.left = rcNumber.right - surfaceMeasure->WidthText( + vsPrint.styles[STYLE_LINENUMBER].font, number, istrlen(number)); + surface->FlushCachedState(); + surface->DrawTextNoClip(rcNumber, vsPrint.styles[STYLE_LINENUMBER].font, + ypos + vsPrint.maxAscent, number, istrlen(number), + vsPrint.styles[STYLE_LINENUMBER].fore.allocated, + vsPrint.styles[STYLE_LINENUMBER].back.allocated); + } + + // Draw the line + surface->FlushCachedState(); + + for (int iwl = 0; iwl < ll.lines; iwl++) { + if (ypos + vsPrint.lineHeight <= pfr->rc.bottom) { + if (visibleLine >= 0) { + if (draw) { + rcLine.top = ypos; + rcLine.bottom = ypos + vsPrint.lineHeight; + DrawLine(surface, vsPrint, lineDoc, visibleLine, xStart, rcLine, &ll, iwl); + } + ypos += vsPrint.lineHeight; + } + visibleLine++; + if (iwl == ll.lines - 1) + nPrintPos = pdoc->LineStart(lineDoc + 1); + else + nPrintPos += ll.LineStart(iwl + 1) - ll.LineStart(iwl); + } + } + + ++lineDoc; + } + + // Clear cache so measurements are not used for screen + posCache.Clear(); + + return nPrintPos; +} + +int Editor::TextWidth(int style, const char *text) { + RefreshStyleData(); + AutoSurface surface(this); + if (surface) { + return surface->WidthText(vs.styles[style].font, text, istrlen(text)); + } else { + return 1; + } +} + +// Empty method is overridden on GTK+ to show / hide scrollbars +void Editor::ReconfigureScrollBars() {} + +void Editor::SetScrollBars() { + RefreshStyleData(); + + int nMax = MaxScrollPos(); + int nPage = LinesOnScreen(); + bool modified = ModifyScrollBars(nMax + nPage - 1, nPage); + if (modified) { + DwellEnd(true); + } + + // TODO: ensure always showing as many lines as possible + // May not be, if, for example, window made larger + if (topLine > MaxScrollPos()) { + SetTopLine(Platform::Clamp(topLine, 0, MaxScrollPos())); + SetVerticalScrollPos(); + Redraw(); + } + if (modified) { + if (!AbandonPaint()) + Redraw(); + } + //Platform::DebugPrintf("end max = %d page = %d\n", nMax, nPage); +} + +void Editor::ChangeSize() { + DropGraphics(); + SetScrollBars(); + if (wrapState != eWrapNone) { + PRectangle rcTextArea = GetClientRectangle(); + rcTextArea.left = vs.fixedColumnWidth; + rcTextArea.right -= vs.rightMarginWidth; + if (wrapWidth != rcTextArea.Width()) { + NeedWrapping(); + Redraw(); + } + } +} + +void Editor::AddChar(char ch) { + char s[2]; + s[0] = ch; + s[1] = '\0'; + AddCharUTF(s, 1); +} + +// AddCharUTF inserts an array of bytes which may or may not be in UTF-8. +void Editor::AddCharUTF(char *s, unsigned int len, bool treatAsDBCS) { + bool wasSelection = currentPos != anchor; + ClearSelection(); + bool charReplaceAction = false; + if (inOverstrike && !wasSelection && !RangeContainsProtected(currentPos, currentPos + 1)) { + if (currentPos < (pdoc->Length())) { + if (!IsEOLChar(pdoc->CharAt(currentPos))) { + charReplaceAction = true; + pdoc->BeginUndoAction(); + pdoc->DelChar(currentPos); + } + } + } + if (pdoc->InsertString(currentPos, s, len)) { + SetEmptySelection(currentPos + len); + } + if (charReplaceAction) { + pdoc->EndUndoAction(); + } + // If in wrap mode rewrap current line so EnsureCaretVisible has accurate information + if (wrapState != eWrapNone) { + AutoSurface surface(this); + if (surface) { + WrapOneLine(surface, pdoc->LineFromPosition(currentPos)); + } + SetScrollBars(); + } + EnsureCaretVisible(); + // Avoid blinking during rapid typing: + ShowCaretAtCurrentPosition(); + if (!caretSticky) { + SetLastXChosen(); + } + + if (treatAsDBCS) { + NotifyChar((static_cast(s[0]) << 8) | + static_cast(s[1])); + } else { + int byte = static_cast(s[0]); + if ((byte < 0xC0) || (1 == len)) { + // Handles UTF-8 characters between 0x01 and 0x7F and single byte + // characters when not in UTF-8 mode. + // Also treats \0 and naked trail bytes 0x80 to 0xBF as valid + // characters representing themselves. + } else { + // Unroll 1 to 3 byte UTF-8 sequences. See reference data at: + // http://www.cl.cam.ac.uk/~mgk25/unicode.html + // http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt + if (byte < 0xE0) { + int byte2 = static_cast(s[1]); + if ((byte2 & 0xC0) == 0x80) { + // Two-byte-character lead-byte followed by a trail-byte. + byte = (((byte & 0x1F) << 6) | (byte2 & 0x3F)); + } + // A two-byte-character lead-byte not followed by trail-byte + // represents itself. + } else if (byte < 0xF0) { + int byte2 = static_cast(s[1]); + int byte3 = static_cast(s[2]); + if (((byte2 & 0xC0) == 0x80) && ((byte3 & 0xC0) == 0x80)) { + // Three-byte-character lead byte followed by two trail bytes. + byte = (((byte & 0x0F) << 12) | ((byte2 & 0x3F) << 6) | + (byte3 & 0x3F)); + } + // A three-byte-character lead-byte not followed by two trail-bytes + // represents itself. + } + } + NotifyChar(byte); + } +} + +void Editor::ClearSelection() { + if (!SelectionContainsProtected()) { + int startPos = SelectionStart(); + if (selType == selStream) { + unsigned int chars = SelectionEnd() - startPos; + if (0 != chars) { + pdoc->BeginUndoAction(); + pdoc->DeleteChars(startPos, chars); + pdoc->EndUndoAction(); + } + } else { + pdoc->BeginUndoAction(); + SelectionLineIterator lineIterator(this, false); + while (lineIterator.Iterate()) { + startPos = lineIterator.startPos; + unsigned int chars = lineIterator.endPos - startPos; + if (0 != chars) { + pdoc->DeleteChars(startPos, chars); + } + } + pdoc->EndUndoAction(); + selType = selStream; + } + SetEmptySelection(startPos); + } +} + +void Editor::ClearAll() { + pdoc->BeginUndoAction(); + if (0 != pdoc->Length()) { + pdoc->DeleteChars(0, pdoc->Length()); + } + if (!pdoc->IsReadOnly()) { + cs.Clear(); + } + pdoc->EndUndoAction(); + anchor = 0; + currentPos = 0; + SetTopLine(0); + SetVerticalScrollPos(); + InvalidateStyleRedraw(); +} + +void Editor::ClearDocumentStyle() { + Decoration *deco = pdoc->decorations.root; + while (deco) { + // Save next in case deco deleted + Decoration *decoNext = deco->next; + if (deco->indicator < INDIC_CONTAINER) { + pdoc->decorations.SetCurrentIndicator(deco->indicator); + pdoc->DecorationFillRange(0, 0, pdoc->Length()); + } + deco = decoNext; + } + pdoc->StartStyling(0, '\377'); + pdoc->SetStyleFor(pdoc->Length(), 0); + cs.ShowAll(); + pdoc->ClearLevels(); +} + +void Editor::CopyAllowLine() { + SelectionText selectedText; + CopySelectionRange(&selectedText, true); + CopyToClipboard(selectedText); +} + +void Editor::Cut() { + pdoc->CheckReadOnly(); + if (!pdoc->IsReadOnly() && !SelectionContainsProtected()) { + Copy(); + ClearSelection(); + } +} + +void Editor::PasteRectangular(int pos, const char *ptr, int len) { + if (pdoc->IsReadOnly() || SelectionContainsProtected()) { + return; + } + currentPos = pos; + int xInsert = XFromPosition(currentPos); + int line = pdoc->LineFromPosition(currentPos); + bool prevCr = false; + pdoc->BeginUndoAction(); + for (int i = 0; i < len; i++) { + if (IsEOLChar(ptr[i])) { + if ((ptr[i] == '\r') || (!prevCr)) + line++; + if (line >= pdoc->LinesTotal()) { + if (pdoc->eolMode != SC_EOL_LF) + pdoc->InsertChar(pdoc->Length(), '\r'); + if (pdoc->eolMode != SC_EOL_CR) + pdoc->InsertChar(pdoc->Length(), '\n'); + } + // Pad the end of lines with spaces if required + currentPos = PositionFromLineX(line, xInsert); + if ((XFromPosition(currentPos) < xInsert) && (i + 1 < len)) { + for (int i = 0; i < xInsert - XFromPosition(currentPos); i++) { + pdoc->InsertChar(currentPos, ' '); + currentPos++; + } + } + prevCr = ptr[i] == '\r'; + } else { + pdoc->InsertString(currentPos, ptr + i, 1); + currentPos++; + prevCr = false; + } + } + pdoc->EndUndoAction(); + SetEmptySelection(pos); +} + +bool Editor::CanPaste() { + return !pdoc->IsReadOnly() && !SelectionContainsProtected(); +} + +void Editor::Clear() { + if (currentPos == anchor) { + if (!RangeContainsProtected(currentPos, currentPos + 1)) { + DelChar(); + } + } else { + ClearSelection(); + } + SetEmptySelection(currentPos); +} + +void Editor::SelectAll() { + SetSelection(0, pdoc->Length()); + Redraw(); +} + +void Editor::Undo() { + if (pdoc->CanUndo()) { + InvalidateCaret(); + int newPos = pdoc->Undo(); + if (newPos >= 0) + SetEmptySelection(newPos); + EnsureCaretVisible(); + } +} + +void Editor::Redo() { + if (pdoc->CanRedo()) { + int newPos = pdoc->Redo(); + if (newPos >= 0) + SetEmptySelection(newPos); + EnsureCaretVisible(); + } +} + +void Editor::DelChar() { + if (!RangeContainsProtected(currentPos, currentPos + 1)) { + pdoc->DelChar(currentPos); + } + // Avoid blinking during rapid typing: + ShowCaretAtCurrentPosition(); +} + +void Editor::DelCharBack(bool allowLineStartDeletion) { + if (currentPos == anchor) { + if (!RangeContainsProtected(currentPos - 1, currentPos)) { + int lineCurrentPos = pdoc->LineFromPosition(currentPos); + if (allowLineStartDeletion || (pdoc->LineStart(lineCurrentPos) != currentPos)) { + if (pdoc->GetColumn(currentPos) <= pdoc->GetLineIndentation(lineCurrentPos) && + pdoc->GetColumn(currentPos) > 0 && pdoc->backspaceUnindents) { + pdoc->BeginUndoAction(); + int indentation = pdoc->GetLineIndentation(lineCurrentPos); + int indentationStep = pdoc->IndentSize(); + if (indentation % indentationStep == 0) { + pdoc->SetLineIndentation(lineCurrentPos, indentation - indentationStep); + } else { + pdoc->SetLineIndentation(lineCurrentPos, indentation - (indentation % indentationStep)); + } + SetEmptySelection(pdoc->GetLineIndentPosition(lineCurrentPos)); + pdoc->EndUndoAction(); + } else { + pdoc->DelCharBack(currentPos); + } + } + } + } else { + ClearSelection(); + SetEmptySelection(currentPos); + } + // Avoid blinking during rapid typing: + ShowCaretAtCurrentPosition(); +} + +void Editor::NotifyFocus(bool) {} + +void Editor::NotifyStyleToNeeded(int endStyleNeeded) { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_STYLENEEDED; + scn.position = endStyleNeeded; + NotifyParent(scn); +} + +void Editor::NotifyStyleNeeded(Document*, void *, int endStyleNeeded) { + NotifyStyleToNeeded(endStyleNeeded); +} + +void Editor::NotifyChar(int ch) { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_CHARADDED; + scn.ch = ch; + NotifyParent(scn); + if (recordingMacro) { + char txt[2]; + txt[0] = static_cast(ch); + txt[1] = '\0'; + NotifyMacroRecord(SCI_REPLACESEL, 0, reinterpret_cast(txt)); + } +} + +void Editor::NotifySavePoint(bool isSavePoint) { + SCNotification scn = {0}; + if (isSavePoint) { + scn.nmhdr.code = SCN_SAVEPOINTREACHED; + } else { + scn.nmhdr.code = SCN_SAVEPOINTLEFT; + } + NotifyParent(scn); +} + +void Editor::NotifyModifyAttempt() { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_MODIFYATTEMPTRO; + NotifyParent(scn); +} + +void Editor::NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt) { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_DOUBLECLICK; + scn.line = LineFromLocation(pt); + scn.position = PositionFromLocationClose(pt); + scn.modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) | + (alt ? SCI_ALT : 0); + NotifyParent(scn); +} + +void Editor::NotifyHotSpotDoubleClicked(int position, bool shift, bool ctrl, bool alt) { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_HOTSPOTDOUBLECLICK; + scn.position = position; + scn.modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) | + (alt ? SCI_ALT : 0); + NotifyParent(scn); +} + +void Editor::NotifyHotSpotClicked(int position, bool shift, bool ctrl, bool alt) { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_HOTSPOTCLICK; + scn.position = position; + scn.modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) | + (alt ? SCI_ALT : 0); + NotifyParent(scn); +} + +void Editor::NotifyUpdateUI() { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_UPDATEUI; + NotifyParent(scn); +} + +void Editor::NotifyPainted() { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_PAINTED; + NotifyParent(scn); +} + +void Editor::NotifyScrolled() { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_SCROLLED; + NotifyParent(scn); +} + +void Editor::NotifyIndicatorClick(bool click, int position, bool shift, bool ctrl, bool alt) { + int mask = pdoc->decorations.AllOnFor(position); + if ((click && mask) || pdoc->decorations.clickNotified) { + SCNotification scn = {0}; + pdoc->decorations.clickNotified = click; + scn.nmhdr.code = click ? SCN_INDICATORCLICK : SCN_INDICATORRELEASE; + scn.modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) | (alt ? SCI_ALT : 0); + scn.position = position; + NotifyParent(scn); + } +} + +bool Editor::NotifyMarginClick(Point pt, bool shift, bool ctrl, bool alt) { + int marginClicked = -1; + int x = 0; + for (int margin = 0; margin < ViewStyle::margins; margin++) { + if ((pt.x > x) && (pt.x < x + vs.ms[margin].width)) + marginClicked = margin; + x += vs.ms[margin].width; + } + if ((marginClicked >= 0) && vs.ms[marginClicked].sensitive) { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_MARGINCLICK; + scn.modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) | + (alt ? SCI_ALT : 0); + scn.position = pdoc->LineStart(LineFromLocation(pt)); + scn.margin = marginClicked; + NotifyParent(scn); + return true; + } else { + return false; + } +} + +void Editor::NotifyNeedShown(int pos, int len) { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_NEEDSHOWN; + scn.position = pos; + scn.length = len; + NotifyParent(scn); +} + +void Editor::NotifyDwelling(Point pt, bool state) { + SCNotification scn = {0}; + scn.nmhdr.code = state ? SCN_DWELLSTART : SCN_DWELLEND; + scn.position = PositionFromLocationClose(pt); + scn.x = pt.x; + scn.y = pt.y; + NotifyParent(scn); +} + +void Editor::NotifyZoom() { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_ZOOM; + NotifyParent(scn); +} + +// Notifications from document +void Editor::NotifyModifyAttempt(Document*, void *) { + //Platform::DebugPrintf("** Modify Attempt\n"); + NotifyModifyAttempt(); +} + +void Editor::NotifyMove(int position) { + SCNotification scn = {0}; + scn.nmhdr.code = SCN_POSCHANGED; + scn.position = position; + NotifyParent(scn); +} + +void Editor::NotifySavePoint(Document*, void *, bool atSavePoint) { + //Platform::DebugPrintf("** Save Point %s\n", atSavePoint ? "On" : "Off"); + NotifySavePoint(atSavePoint); +} + +void Editor::CheckModificationForWrap(DocModification mh) { + if (mh.modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) { + llc.Invalidate(LineLayout::llCheckTextAndStyle); + if (wrapState != eWrapNone) { + int lineDoc = pdoc->LineFromPosition(mh.position); + int lines = Platform::Maximum(0, mh.linesAdded); + NeedWrapping(lineDoc, lineDoc + lines + 1); + } + } +} + +// Move a position so it is still after the same character as before the insertion. +static inline int MovePositionForInsertion(int position, int startInsertion, int length) { + if (position > startInsertion) { + return position + length; + } + return position; +} + +// Move a position so it is still after the same character as before the deletion if that +// character is still present else after the previous surviving character. +static inline int MovePositionForDeletion(int position, int startDeletion, int length) { + if (position > startDeletion) { + int endDeletion = startDeletion + length; + if (position > endDeletion) { + return position - length; + } else { + return startDeletion; + } + } else { + return position; + } +} + +void Editor::NotifyModified(Document*, DocModification mh, void *) { + needUpdateUI = true; + if (paintState == painting) { + CheckForChangeOutsidePaint(Range(mh.position, mh.position + mh.length)); + } + if (mh.modificationType & SC_MOD_CHANGELINESTATE) { + if (paintState == painting) { + CheckForChangeOutsidePaint( + Range(pdoc->LineStart(mh.line), pdoc->LineStart(mh.line + 1))); + } else { + // Could check that change is before last visible line. + Redraw(); + } + } + if (mh.modificationType & (SC_MOD_CHANGESTYLE | SC_MOD_CHANGEINDICATOR)) { + if (mh.modificationType & SC_MOD_CHANGESTYLE) { + pdoc->IncrementStyleClock(); + } + if (paintState == notPainting) { + if (mh.position < pdoc->LineStart(topLine)) { + // Styling performed before this view + Redraw(); + } else { + InvalidateRange(mh.position, mh.position + mh.length); + } + } + if (mh.modificationType & SC_MOD_CHANGESTYLE) { + llc.Invalidate(LineLayout::llCheckTextAndStyle); + } + } else { + // Move selection and brace highlights + if (mh.modificationType & SC_MOD_INSERTTEXT) { + currentPos = MovePositionForInsertion(currentPos, mh.position, mh.length); + anchor = MovePositionForInsertion(anchor, mh.position, mh.length); + braces[0] = MovePositionForInsertion(braces[0], mh.position, mh.length); + braces[1] = MovePositionForInsertion(braces[1], mh.position, mh.length); + } else if (mh.modificationType & SC_MOD_DELETETEXT) { + currentPos = MovePositionForDeletion(currentPos, mh.position, mh.length); + anchor = MovePositionForDeletion(anchor, mh.position, mh.length); + braces[0] = MovePositionForDeletion(braces[0], mh.position, mh.length); + braces[1] = MovePositionForDeletion(braces[1], mh.position, mh.length); + } + if (cs.LinesDisplayed() < cs.LinesInDoc()) { + // Some lines are hidden so may need shown. + // TODO: check if the modified area is hidden. + if (mh.modificationType & SC_MOD_BEFOREINSERT) { + NotifyNeedShown(mh.position, 0); + } else if (mh.modificationType & SC_MOD_BEFOREDELETE) { + NotifyNeedShown(mh.position, mh.length); + } + } + if (mh.linesAdded != 0) { + // Update contraction state for inserted and removed lines + // lineOfPos should be calculated in context of state before modification, shouldn't it + int lineOfPos = pdoc->LineFromPosition(mh.position); + if (mh.linesAdded > 0) { + cs.InsertLines(lineOfPos, mh.linesAdded); + } else { + cs.DeleteLines(lineOfPos, -mh.linesAdded); + } + } + CheckModificationForWrap(mh); + if (mh.linesAdded != 0) { + // Avoid scrolling of display if change before current display + if (mh.position < posTopLine && !CanDeferToLastStep(mh)) { + int newTop = Platform::Clamp(topLine + mh.linesAdded, 0, MaxScrollPos()); + if (newTop != topLine) { + SetTopLine(newTop); + SetVerticalScrollPos(); + } + } + + //Platform::DebugPrintf("** %x Doc Changed\n", this); + // TODO: could invalidate from mh.startModification to end of screen + //InvalidateRange(mh.position, mh.position + mh.length); + if (paintState == notPainting && !CanDeferToLastStep(mh)) { + Redraw(); + } + } else { + //Platform::DebugPrintf("** %x Line Changed %d .. %d\n", this, + // mh.position, mh.position + mh.length); + if (paintState == notPainting && mh.length && !CanEliminate(mh)) { + InvalidateRange(mh.position, mh.position + mh.length); + } + } + } + + if (mh.linesAdded != 0 && !CanDeferToLastStep(mh)) { + SetScrollBars(); + } + + if (mh.modificationType & SC_MOD_CHANGEMARKER) { + if ((paintState == notPainting) || !PaintContainsMargin()) { + if (mh.modificationType & SC_MOD_CHANGEFOLD) { + // Fold changes can affect the drawing of following lines so redraw whole margin + RedrawSelMargin(); + } else { + RedrawSelMargin(mh.line); + } + } + } + + // NOW pay the piper WRT "deferred" visual updates + if (IsLastStep(mh)) { + SetScrollBars(); + Redraw(); + } + + // If client wants to see this modification + if (mh.modificationType & modEventMask) { + if ((mh.modificationType & (SC_MOD_CHANGESTYLE | SC_MOD_CHANGEINDICATOR)) == 0) { + // Real modification made to text of document. + NotifyChange(); // Send EN_CHANGE + } + + SCNotification scn = {0}; + scn.nmhdr.code = SCN_MODIFIED; + scn.position = mh.position; + scn.modificationType = mh.modificationType; + scn.text = mh.text; + scn.length = mh.length; + scn.linesAdded = mh.linesAdded; + scn.line = mh.line; + scn.foldLevelNow = mh.foldLevelNow; + scn.foldLevelPrev = mh.foldLevelPrev; + NotifyParent(scn); + } +} + +void Editor::NotifyDeleted(Document *, void *) { + /* Do nothing */ +} + +void Editor::NotifyMacroRecord(unsigned int iMessage, uptr_t wParam, sptr_t lParam) { + + // Enumerates all macroable messages + switch (iMessage) { + case SCI_CUT: + case SCI_COPY: + case SCI_PASTE: + case SCI_CLEAR: + case SCI_REPLACESEL: + case SCI_ADDTEXT: + case SCI_INSERTTEXT: + case SCI_APPENDTEXT: + case SCI_CLEARALL: + case SCI_SELECTALL: + case SCI_GOTOLINE: + case SCI_GOTOPOS: + case SCI_SEARCHANCHOR: + case SCI_SEARCHNEXT: + case SCI_SEARCHPREV: + case SCI_LINEDOWN: + case SCI_LINEDOWNEXTEND: + case SCI_PARADOWN: + case SCI_PARADOWNEXTEND: + case SCI_LINEUP: + case SCI_LINEUPEXTEND: + case SCI_PARAUP: + case SCI_PARAUPEXTEND: + case SCI_CHARLEFT: + case SCI_CHARLEFTEXTEND: + case SCI_CHARRIGHT: + case SCI_CHARRIGHTEXTEND: + case SCI_WORDLEFT: + case SCI_WORDLEFTEXTEND: + case SCI_WORDRIGHT: + case SCI_WORDRIGHTEXTEND: + case SCI_WORDPARTLEFT: + case SCI_WORDPARTLEFTEXTEND: + case SCI_WORDPARTRIGHT: + case SCI_WORDPARTRIGHTEXTEND: + case SCI_WORDLEFTEND: + case SCI_WORDLEFTENDEXTEND: + case SCI_WORDRIGHTEND: + case SCI_WORDRIGHTENDEXTEND: + case SCI_HOME: + case SCI_HOMEEXTEND: + case SCI_LINEEND: + case SCI_LINEENDEXTEND: + case SCI_HOMEWRAP: + case SCI_HOMEWRAPEXTEND: + case SCI_LINEENDWRAP: + case SCI_LINEENDWRAPEXTEND: + case SCI_DOCUMENTSTART: + case SCI_DOCUMENTSTARTEXTEND: + case SCI_DOCUMENTEND: + case SCI_DOCUMENTENDEXTEND: + case SCI_STUTTEREDPAGEUP: + case SCI_STUTTEREDPAGEUPEXTEND: + case SCI_STUTTEREDPAGEDOWN: + case SCI_STUTTEREDPAGEDOWNEXTEND: + case SCI_PAGEUP: + case SCI_PAGEUPEXTEND: + case SCI_PAGEDOWN: + case SCI_PAGEDOWNEXTEND: + case SCI_EDITTOGGLEOVERTYPE: + case SCI_CANCEL: + case SCI_DELETEBACK: + case SCI_TAB: + case SCI_BACKTAB: + case SCI_FORMFEED: + case SCI_VCHOME: + case SCI_VCHOMEEXTEND: + case SCI_VCHOMEWRAP: + case SCI_VCHOMEWRAPEXTEND: + case SCI_DELWORDLEFT: + case SCI_DELWORDRIGHT: + case SCI_DELWORDRIGHTEND: + case SCI_DELLINELEFT: + case SCI_DELLINERIGHT: + case SCI_LINECOPY: + case SCI_LINECUT: + case SCI_LINEDELETE: + case SCI_LINETRANSPOSE: + case SCI_LINEDUPLICATE: + case SCI_LOWERCASE: + case SCI_UPPERCASE: + case SCI_LINESCROLLDOWN: + case SCI_LINESCROLLUP: + case SCI_DELETEBACKNOTLINE: + case SCI_HOMEDISPLAY: + case SCI_HOMEDISPLAYEXTEND: + case SCI_LINEENDDISPLAY: + case SCI_LINEENDDISPLAYEXTEND: + case SCI_SETSELECTIONMODE: + case SCI_LINEDOWNRECTEXTEND: + case SCI_LINEUPRECTEXTEND: + case SCI_CHARLEFTRECTEXTEND: + case SCI_CHARRIGHTRECTEXTEND: + case SCI_HOMERECTEXTEND: + case SCI_VCHOMERECTEXTEND: + case SCI_LINEENDRECTEXTEND: + case SCI_PAGEUPRECTEXTEND: + case SCI_PAGEDOWNRECTEXTEND: + case SCI_SELECTIONDUPLICATE: + case SCI_COPYALLOWLINE: + break; + + // Filter out all others like display changes. Also, newlines are redundant + // with char insert messages. + case SCI_NEWLINE: + default: + // printf("Filtered out %ld of macro recording\n", iMessage); + return ; + } + + // Send notification + SCNotification scn = {0}; + scn.nmhdr.code = SCN_MACRORECORD; + scn.message = iMessage; + scn.wParam = wParam; + scn.lParam = lParam; + NotifyParent(scn); +} + +/** + * Force scroll and keep position relative to top of window. + * + * If stuttered = true and not already at first/last row, move to first/last row of window. + * If stuttered = true and already at first/last row, scroll as normal. + */ +void Editor::PageMove(int direction, selTypes sel, bool stuttered) { + int topLineNew, newPos; + + // I consider only the caretYSlop, and ignore the caretYPolicy-- is that a problem? + int currentLine = pdoc->LineFromPosition(currentPos); + int topStutterLine = topLine + caretYSlop; + int bottomStutterLine = + pdoc->LineFromPosition(PositionFromLocation( + Point(lastXChosen, direction * vs.lineHeight * LinesToScroll()))) + - caretYSlop - 1; + + if (stuttered && (direction < 0 && currentLine > topStutterLine)) { + topLineNew = topLine; + newPos = PositionFromLocation(Point(lastXChosen, vs.lineHeight * caretYSlop)); + + } else if (stuttered && (direction > 0 && currentLine < bottomStutterLine)) { + topLineNew = topLine; + newPos = PositionFromLocation(Point(lastXChosen, vs.lineHeight * (LinesToScroll() - caretYSlop))); + + } else { + Point pt = LocationFromPosition(currentPos); + + topLineNew = Platform::Clamp( + topLine + direction * LinesToScroll(), 0, MaxScrollPos()); + newPos = PositionFromLocation( + Point(lastXChosen, pt.y + direction * (vs.lineHeight * LinesToScroll()))); + } + + if (topLineNew != topLine) { + SetTopLine(topLineNew); + MovePositionTo(newPos, sel); + Redraw(); + SetVerticalScrollPos(); + } else { + MovePositionTo(newPos, sel); + } +} + +void Editor::ChangeCaseOfSelection(bool makeUpperCase) { + pdoc->BeginUndoAction(); + int startCurrent = currentPos; + int startAnchor = anchor; + if (selType == selStream) { + pdoc->ChangeCase(Range(SelectionStart(), SelectionEnd()), + makeUpperCase); + SetSelection(startCurrent, startAnchor); + } else { + SelectionLineIterator lineIterator(this, false); + while (lineIterator.Iterate()) { + pdoc->ChangeCase( + Range(lineIterator.startPos, lineIterator.endPos), + makeUpperCase); + } + // Would be nicer to keep the rectangular selection but this is complex + SetEmptySelection(startCurrent); + } + pdoc->EndUndoAction(); +} + +void Editor::LineTranspose() { + int line = pdoc->LineFromPosition(currentPos); + if (line > 0) { + pdoc->BeginUndoAction(); + int startPrev = pdoc->LineStart(line - 1); + int endPrev = pdoc->LineEnd(line - 1); + int start = pdoc->LineStart(line); + int end = pdoc->LineEnd(line); + char *line1 = CopyRange(startPrev, endPrev); + int len1 = endPrev - startPrev; + char *line2 = CopyRange(start, end); + int len2 = end - start; + pdoc->DeleteChars(start, len2); + pdoc->DeleteChars(startPrev, len1); + pdoc->InsertString(startPrev, line2, len2); + pdoc->InsertString(start - len1 + len2, line1, len1); + MovePositionTo(start - len1 + len2); + delete []line1; + delete []line2; + pdoc->EndUndoAction(); + } +} + +void Editor::Duplicate(bool forLine) { + int start = SelectionStart(); + int end = SelectionEnd(); + if (start == end) { + forLine = true; + } + if (forLine) { + int line = pdoc->LineFromPosition(currentPos); + start = pdoc->LineStart(line); + end = pdoc->LineEnd(line); + } + char *text = CopyRange(start, end); + if (forLine) { + const char *eol = StringFromEOLMode(pdoc->eolMode); + pdoc->InsertCString(end, eol); + pdoc->InsertString(end + istrlen(eol), text, end - start); + } else { + pdoc->InsertString(end, text, end - start); + } + delete []text; +} + +void Editor::CancelModes() { + moveExtendsSelection = false; +} + +void Editor::NewLine() { + 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(currentPos, eol)) { + SetEmptySelection(currentPos + istrlen(eol)); + while (*eol) { + NotifyChar(*eol); + eol++; + } + } + SetLastXChosen(); + SetScrollBars(); + EnsureCaretVisible(); + // Avoid blinking during rapid typing: + ShowCaretAtCurrentPosition(); +} + +void Editor::CursorUpOrDown(int direction, selTypes sel) { + Point pt = LocationFromPosition(currentPos); + int posNew = PositionFromLocation( + Point(lastXChosen, pt.y + direction * vs.lineHeight)); + 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); + while ((posNew > 0) && (pt.y == ptNew.y)) { + posNew--; + ptNew = LocationFromPosition(posNew); + } + } + MovePositionTo(posNew, sel); +} + +void Editor::ParaUpOrDown(int direction, selTypes sel) { + int lineDoc, savedPos = currentPos; + do { + MovePositionTo(direction > 0 ? pdoc->ParaDown(currentPos) : pdoc->ParaUp(currentPos), sel); + lineDoc = pdoc->LineFromPosition(currentPos); + if (direction > 0) { + if (currentPos >= pdoc->Length() && !cs.GetVisible(lineDoc)) { + if (sel == noSel) { + MovePositionTo(pdoc->LineEndPosition(savedPos)); + } + break; + } + } + } while (!cs.GetVisible(lineDoc)); +} + +int Editor::StartEndDisplayLine(int pos, bool start) { + RefreshStyleData(); + int line = pdoc->LineFromPosition(pos); + AutoSurface surface(this); + AutoLineLayout ll(llc, RetrieveLineLayout(line)); + int posRet = INVALID_POSITION; + if (surface && ll) { + unsigned int posLineStart = pdoc->LineStart(line); + LayoutLine(line, surface, vs, ll, wrapWidth); + int posInLine = pos - posLineStart; + if (posInLine <= ll->maxLineLength) { + for (int subLine = 0; subLine < ll->lines; subLine++) { + if ((posInLine >= ll->LineStart(subLine)) && (posInLine <= ll->LineStart(subLine + 1))) { + if (start) { + posRet = ll->LineStart(subLine) + posLineStart; + } else { + if (subLine == ll->lines - 1) + posRet = ll->LineStart(subLine + 1) + posLineStart; + else + posRet = ll->LineStart(subLine + 1) + posLineStart - 1; + } + } + } + } + } + if (posRet == INVALID_POSITION) { + return pos; + } else { + return posRet; + } +} + +int Editor::KeyCommand(unsigned int iMessage) { + switch (iMessage) { + case SCI_LINEDOWN: + CursorUpOrDown(1); + break; + case SCI_LINEDOWNEXTEND: + CursorUpOrDown(1, selStream); + break; + case SCI_LINEDOWNRECTEXTEND: + CursorUpOrDown(1, selRectangle); + break; + case SCI_PARADOWN: + ParaUpOrDown(1); + break; + case SCI_PARADOWNEXTEND: + ParaUpOrDown(1, selStream); + break; + case SCI_LINESCROLLDOWN: + ScrollTo(topLine + 1); + MoveCaretInsideView(false); + break; + case SCI_LINEUP: + CursorUpOrDown(-1); + break; + case SCI_LINEUPEXTEND: + CursorUpOrDown(-1, selStream); + break; + case SCI_LINEUPRECTEXTEND: + CursorUpOrDown(-1, selRectangle); + break; + case SCI_PARAUP: + ParaUpOrDown(-1); + break; + case SCI_PARAUPEXTEND: + ParaUpOrDown(-1, selStream); + break; + case SCI_LINESCROLLUP: + ScrollTo(topLine - 1); + MoveCaretInsideView(false); + break; + case SCI_CHARLEFT: + if (SelectionEmpty() || moveExtendsSelection) { + MovePositionTo(MovePositionSoVisible(currentPos - 1, -1)); + } else { + MovePositionTo(SelectionStart()); + } + SetLastXChosen(); + break; + case SCI_CHARLEFTEXTEND: + MovePositionTo(MovePositionSoVisible(currentPos - 1, -1), selStream); + SetLastXChosen(); + break; + case SCI_CHARLEFTRECTEXTEND: + MovePositionTo(MovePositionSoVisible(currentPos - 1, -1), selRectangle); + SetLastXChosen(); + break; + case SCI_CHARRIGHT: + if (SelectionEmpty() || moveExtendsSelection) { + MovePositionTo(MovePositionSoVisible(currentPos + 1, 1)); + } else { + MovePositionTo(SelectionEnd()); + } + SetLastXChosen(); + break; + case SCI_CHARRIGHTEXTEND: + MovePositionTo(MovePositionSoVisible(currentPos + 1, 1), selStream); + SetLastXChosen(); + break; + case SCI_CHARRIGHTRECTEXTEND: + MovePositionTo(MovePositionSoVisible(currentPos + 1, 1), selRectangle); + SetLastXChosen(); + break; + case SCI_WORDLEFT: + MovePositionTo(MovePositionSoVisible(pdoc->NextWordStart(currentPos, -1), -1)); + SetLastXChosen(); + break; + case SCI_WORDLEFTEXTEND: + MovePositionTo(MovePositionSoVisible(pdoc->NextWordStart(currentPos, -1), -1), selStream); + SetLastXChosen(); + break; + case SCI_WORDRIGHT: + MovePositionTo(MovePositionSoVisible(pdoc->NextWordStart(currentPos, 1), 1)); + SetLastXChosen(); + break; + case SCI_WORDRIGHTEXTEND: + MovePositionTo(MovePositionSoVisible(pdoc->NextWordStart(currentPos, 1), 1), selStream); + SetLastXChosen(); + break; + + case SCI_WORDLEFTEND: + MovePositionTo(MovePositionSoVisible(pdoc->NextWordEnd(currentPos, -1), -1)); + SetLastXChosen(); + break; + case SCI_WORDLEFTENDEXTEND: + MovePositionTo(MovePositionSoVisible(pdoc->NextWordEnd(currentPos, -1), -1), selStream); + SetLastXChosen(); + break; + case SCI_WORDRIGHTEND: + MovePositionTo(MovePositionSoVisible(pdoc->NextWordEnd(currentPos, 1), 1)); + SetLastXChosen(); + break; + case SCI_WORDRIGHTENDEXTEND: + MovePositionTo(MovePositionSoVisible(pdoc->NextWordEnd(currentPos, 1), 1), selStream); + SetLastXChosen(); + break; + + case SCI_HOME: + MovePositionTo(pdoc->LineStart(pdoc->LineFromPosition(currentPos))); + SetLastXChosen(); + break; + case SCI_HOMEEXTEND: + MovePositionTo(pdoc->LineStart(pdoc->LineFromPosition(currentPos)), selStream); + SetLastXChosen(); + break; + case SCI_HOMERECTEXTEND: + MovePositionTo(pdoc->LineStart(pdoc->LineFromPosition(currentPos)), selRectangle); + SetLastXChosen(); + break; + case SCI_LINEEND: + MovePositionTo(pdoc->LineEndPosition(currentPos)); + SetLastXChosen(); + break; + case SCI_LINEENDEXTEND: + MovePositionTo(pdoc->LineEndPosition(currentPos), selStream); + SetLastXChosen(); + break; + case SCI_LINEENDRECTEXTEND: + MovePositionTo(pdoc->LineEndPosition(currentPos), selRectangle); + SetLastXChosen(); + break; + case SCI_HOMEWRAP: { + int homePos = MovePositionSoVisible(StartEndDisplayLine(currentPos, true), -1); + if (currentPos <= homePos) + homePos = pdoc->LineStart(pdoc->LineFromPosition(currentPos)); + MovePositionTo(homePos); + SetLastXChosen(); + } + break; + case SCI_HOMEWRAPEXTEND: { + int homePos = MovePositionSoVisible(StartEndDisplayLine(currentPos, true), -1); + if (currentPos <= homePos) + homePos = pdoc->LineStart(pdoc->LineFromPosition(currentPos)); + MovePositionTo(homePos, selStream); + SetLastXChosen(); + } + break; + case SCI_LINEENDWRAP: { + int endPos = MovePositionSoVisible(StartEndDisplayLine(currentPos, false), 1); + int realEndPos = pdoc->LineEndPosition(currentPos); + if (endPos > realEndPos // if moved past visible EOLs + || currentPos >= endPos) // if at end of display line already + endPos = realEndPos; + MovePositionTo(endPos); + SetLastXChosen(); + } + break; + case SCI_LINEENDWRAPEXTEND: { + int endPos = MovePositionSoVisible(StartEndDisplayLine(currentPos, false), 1); + int realEndPos = pdoc->LineEndPosition(currentPos); + if (endPos > realEndPos // if moved past visible EOLs + || currentPos >= endPos) // if at end of display line already + endPos = realEndPos; + MovePositionTo(endPos, selStream); + SetLastXChosen(); + } + break; + case SCI_DOCUMENTSTART: + MovePositionTo(0); + SetLastXChosen(); + break; + case SCI_DOCUMENTSTARTEXTEND: + MovePositionTo(0, selStream); + SetLastXChosen(); + break; + case SCI_DOCUMENTEND: + MovePositionTo(pdoc->Length()); + SetLastXChosen(); + break; + case SCI_DOCUMENTENDEXTEND: + MovePositionTo(pdoc->Length(), selStream); + SetLastXChosen(); + break; + case SCI_STUTTEREDPAGEUP: + PageMove(-1, noSel, true); + break; + case SCI_STUTTEREDPAGEUPEXTEND: + PageMove(-1, selStream, true); + break; + case SCI_STUTTEREDPAGEDOWN: + PageMove(1, noSel, true); + break; + case SCI_STUTTEREDPAGEDOWNEXTEND: + PageMove(1, selStream, true); + break; + case SCI_PAGEUP: + PageMove(-1); + break; + case SCI_PAGEUPEXTEND: + PageMove(-1, selStream); + break; + case SCI_PAGEUPRECTEXTEND: + PageMove(-1, selRectangle); + break; + case SCI_PAGEDOWN: + PageMove(1); + break; + case SCI_PAGEDOWNEXTEND: + PageMove(1, selStream); + break; + case SCI_PAGEDOWNRECTEXTEND: + PageMove(1, selRectangle); + break; + case SCI_EDITTOGGLEOVERTYPE: + inOverstrike = !inOverstrike; + DropCaret(); + ShowCaretAtCurrentPosition(); + NotifyUpdateUI(); + break; + case SCI_CANCEL: // Cancel any modes - handled in subclass + // Also unselect text + CancelModes(); + break; + case SCI_DELETEBACK: + DelCharBack(true); + if (!caretSticky) { + SetLastXChosen(); + } + EnsureCaretVisible(); + break; + case SCI_DELETEBACKNOTLINE: + DelCharBack(false); + if (!caretSticky) { + SetLastXChosen(); + } + EnsureCaretVisible(); + break; + case SCI_TAB: + Indent(true); + if (!caretSticky) { + SetLastXChosen(); + } + EnsureCaretVisible(); + break; + case SCI_BACKTAB: + Indent(false); + if (!caretSticky) { + SetLastXChosen(); + } + EnsureCaretVisible(); + break; + case SCI_NEWLINE: + NewLine(); + break; + case SCI_FORMFEED: + AddChar('\f'); + break; + case SCI_VCHOME: + MovePositionTo(pdoc->VCHomePosition(currentPos)); + SetLastXChosen(); + break; + case SCI_VCHOMEEXTEND: + MovePositionTo(pdoc->VCHomePosition(currentPos), selStream); + SetLastXChosen(); + break; + case SCI_VCHOMERECTEXTEND: + MovePositionTo(pdoc->VCHomePosition(currentPos), selRectangle); + SetLastXChosen(); + break; + case SCI_VCHOMEWRAP: { + int homePos = pdoc->VCHomePosition(currentPos); + int viewLineStart = MovePositionSoVisible(StartEndDisplayLine(currentPos, true), -1); + if ((viewLineStart < currentPos) && (viewLineStart > homePos)) + homePos = viewLineStart; + + MovePositionTo(homePos); + SetLastXChosen(); + } + break; + case SCI_VCHOMEWRAPEXTEND: { + int homePos = pdoc->VCHomePosition(currentPos); + int viewLineStart = MovePositionSoVisible(StartEndDisplayLine(currentPos, true), -1); + if ((viewLineStart < currentPos) && (viewLineStart > homePos)) + homePos = viewLineStart; + + MovePositionTo(homePos, selStream); + SetLastXChosen(); + } + break; + case SCI_ZOOMIN: + if (vs.zoomLevel < 20) { + vs.zoomLevel++; + InvalidateStyleRedraw(); + NotifyZoom(); + } + break; + case SCI_ZOOMOUT: + if (vs.zoomLevel > -10) { + vs.zoomLevel--; + InvalidateStyleRedraw(); + NotifyZoom(); + } + break; + case SCI_DELWORDLEFT: { + int startWord = pdoc->NextWordStart(currentPos, -1); + pdoc->DeleteChars(startWord, currentPos - startWord); + SetLastXChosen(); + } + break; + case SCI_DELWORDRIGHT: { + int endWord = pdoc->NextWordStart(currentPos, 1); + pdoc->DeleteChars(currentPos, endWord - currentPos); + } + break; + case SCI_DELWORDRIGHTEND: { + int endWord = pdoc->NextWordEnd(currentPos, 1); + pdoc->DeleteChars(currentPos, endWord - currentPos); + } + break; + case SCI_DELLINELEFT: { + int line = pdoc->LineFromPosition(currentPos); + int start = pdoc->LineStart(line); + pdoc->DeleteChars(start, currentPos - start); + SetLastXChosen(); + } + break; + case SCI_DELLINERIGHT: { + int line = pdoc->LineFromPosition(currentPos); + int end = pdoc->LineEnd(line); + pdoc->DeleteChars(currentPos, end - currentPos); + } + break; + case SCI_LINECOPY: { + int lineStart = pdoc->LineFromPosition(SelectionStart()); + int lineEnd = pdoc->LineFromPosition(SelectionEnd()); + CopyRangeToClipboard(pdoc->LineStart(lineStart), + pdoc->LineStart(lineEnd + 1)); + } + break; + case SCI_LINECUT: { + int lineStart = pdoc->LineFromPosition(SelectionStart()); + int lineEnd = pdoc->LineFromPosition(SelectionEnd()); + int start = pdoc->LineStart(lineStart); + int end = pdoc->LineStart(lineEnd + 1); + SetSelection(start, end); + Cut(); + SetLastXChosen(); + } + break; + case SCI_LINEDELETE: { + int line = pdoc->LineFromPosition(currentPos); + int start = pdoc->LineStart(line); + int end = pdoc->LineStart(line + 1); + pdoc->DeleteChars(start, end - start); + } + break; + case SCI_LINETRANSPOSE: + LineTranspose(); + break; + case SCI_LINEDUPLICATE: + Duplicate(true); + break; + case SCI_SELECTIONDUPLICATE: + Duplicate(false); + break; + case SCI_LOWERCASE: + ChangeCaseOfSelection(false); + break; + case SCI_UPPERCASE: + ChangeCaseOfSelection(true); + break; + case SCI_WORDPARTLEFT: + MovePositionTo(MovePositionSoVisible(pdoc->WordPartLeft(currentPos), -1)); + SetLastXChosen(); + break; + case SCI_WORDPARTLEFTEXTEND: + MovePositionTo(MovePositionSoVisible(pdoc->WordPartLeft(currentPos), -1), selStream); + SetLastXChosen(); + break; + case SCI_WORDPARTRIGHT: + MovePositionTo(MovePositionSoVisible(pdoc->WordPartRight(currentPos), 1)); + SetLastXChosen(); + break; + case SCI_WORDPARTRIGHTEXTEND: + MovePositionTo(MovePositionSoVisible(pdoc->WordPartRight(currentPos), 1), selStream); + SetLastXChosen(); + break; + case SCI_HOMEDISPLAY: + MovePositionTo(MovePositionSoVisible( + StartEndDisplayLine(currentPos, true), -1)); + SetLastXChosen(); + break; + case SCI_HOMEDISPLAYEXTEND: + MovePositionTo(MovePositionSoVisible( + StartEndDisplayLine(currentPos, true), -1), selStream); + SetLastXChosen(); + break; + case SCI_LINEENDDISPLAY: + MovePositionTo(MovePositionSoVisible( + StartEndDisplayLine(currentPos, false), 1)); + SetLastXChosen(); + break; + case SCI_LINEENDDISPLAYEXTEND: + MovePositionTo(MovePositionSoVisible( + StartEndDisplayLine(currentPos, false), 1), selStream); + SetLastXChosen(); + break; + } + return 0; +} + +int Editor::KeyDefault(int, int) { + return 0; +} + +int Editor::KeyDown(int key, bool shift, bool ctrl, bool alt, bool *consumed) { + DwellEnd(false); + int modifiers = (shift ? SCI_SHIFT : 0) | (ctrl ? SCI_CTRL : 0) | + (alt ? SCI_ALT : 0); + int msg = kmap.Find(key, modifiers); + if (msg) { + if (consumed) + *consumed = true; + return WndProc(msg, 0, 0); + } else { + if (consumed) + *consumed = false; + return KeyDefault(key, modifiers); + } +} + +void Editor::SetWhitespaceVisible(int view) { + vs.viewWhitespace = static_cast(view); +} + +int Editor::GetWhitespaceVisible() { + return vs.viewWhitespace; +} + +void Editor::Indent(bool forwards) { + //Platform::DebugPrintf("INdent %d\n", forwards); + int lineOfAnchor = pdoc->LineFromPosition(anchor); + int lineCurrentPos = pdoc->LineFromPosition(currentPos); + if (lineOfAnchor == lineCurrentPos) { + if (forwards) { + pdoc->BeginUndoAction(); + ClearSelection(); + if (pdoc->GetColumn(currentPos) <= pdoc->GetColumn(pdoc->GetLineIndentPosition(lineCurrentPos)) && + pdoc->tabIndents) { + int indentation = pdoc->GetLineIndentation(lineCurrentPos); + int indentationStep = pdoc->IndentSize(); + pdoc->SetLineIndentation(lineCurrentPos, indentation + indentationStep - indentation % indentationStep); + SetEmptySelection(pdoc->GetLineIndentPosition(lineCurrentPos)); + } else { + if (pdoc->useTabs) { + pdoc->InsertChar(currentPos, '\t'); + SetEmptySelection(currentPos + 1); + } else { + int numSpaces = (pdoc->tabInChars) - + (pdoc->GetColumn(currentPos) % (pdoc->tabInChars)); + if (numSpaces < 1) + numSpaces = pdoc->tabInChars; + for (int i = 0; i < numSpaces; i++) { + pdoc->InsertChar(currentPos + i, ' '); + } + SetEmptySelection(currentPos + numSpaces); + } + } + pdoc->EndUndoAction(); + } else { + if (pdoc->GetColumn(currentPos) <= pdoc->GetLineIndentation(lineCurrentPos) && + pdoc->tabIndents) { + pdoc->BeginUndoAction(); + int indentation = pdoc->GetLineIndentation(lineCurrentPos); + int indentationStep = pdoc->IndentSize(); + pdoc->SetLineIndentation(lineCurrentPos, indentation - indentationStep); + SetEmptySelection(pdoc->GetLineIndentPosition(lineCurrentPos)); + pdoc->EndUndoAction(); + } else { + int newColumn = ((pdoc->GetColumn(currentPos) - 1) / pdoc->tabInChars) * + pdoc->tabInChars; + if (newColumn < 0) + newColumn = 0; + int newPos = currentPos; + while (pdoc->GetColumn(newPos) > newColumn) + newPos--; + SetEmptySelection(newPos); + } + } + } else { + int anchorPosOnLine = anchor - pdoc->LineStart(lineOfAnchor); + int currentPosPosOnLine = currentPos - pdoc->LineStart(lineCurrentPos); + // Multiple lines selected so indent / dedent + int lineTopSel = Platform::Minimum(lineOfAnchor, lineCurrentPos); + int lineBottomSel = Platform::Maximum(lineOfAnchor, lineCurrentPos); + if (pdoc->LineStart(lineBottomSel) == anchor || pdoc->LineStart(lineBottomSel) == currentPos) + lineBottomSel--; // If not selecting any characters on a line, do not indent + pdoc->BeginUndoAction(); + pdoc->Indent(forwards, lineBottomSel, lineTopSel); + pdoc->EndUndoAction(); + if (lineOfAnchor < lineCurrentPos) { + if (currentPosPosOnLine == 0) + SetSelection(pdoc->LineStart(lineCurrentPos), pdoc->LineStart(lineOfAnchor)); + else + SetSelection(pdoc->LineStart(lineCurrentPos + 1), pdoc->LineStart(lineOfAnchor)); + } else { + if (anchorPosOnLine == 0) + SetSelection(pdoc->LineStart(lineCurrentPos), pdoc->LineStart(lineOfAnchor)); + else + SetSelection(pdoc->LineStart(lineCurrentPos), pdoc->LineStart(lineOfAnchor + 1)); + } + } +} + +/** + * Search of a text in the document, in the given range. + * @return The position of the found text, -1 if not found. + */ +long Editor::FindText( + uptr_t wParam, ///< Search modes : @c SCFIND_MATCHCASE, @c SCFIND_WHOLEWORD, + ///< @c SCFIND_WORDSTART, @c SCFIND_REGEXP or @c SCFIND_POSIX. + sptr_t lParam) { ///< @c TextToFind structure: The text to search for in the given range. + + TextToFind *ft = reinterpret_cast(lParam); + int lengthFound = istrlen(ft->lpstrText); + int pos = pdoc->FindText(ft->chrg.cpMin, ft->chrg.cpMax, ft->lpstrText, + (wParam & SCFIND_MATCHCASE) != 0, + (wParam & SCFIND_WHOLEWORD) != 0, + (wParam & SCFIND_WORDSTART) != 0, + (wParam & SCFIND_REGEXP) != 0, + (wParam & SCFIND_POSIX) != 0, + &lengthFound); + if (pos != -1) { + ft->chrgText.cpMin = pos; + ft->chrgText.cpMax = pos + lengthFound; + } + return pos; +} + +/** + * Relocatable search support : Searches relative to current selection + * point and sets the selection to the found text range with + * each search. + */ +/** + * Anchor following searches at current selection start: This allows + * multiple incremental interactive searches to be macro recorded + * while still setting the selection to found text so the find/select + * operation is self-contained. + */ +void Editor::SearchAnchor() { + searchAnchor = SelectionStart(); +} + +/** + * Find text from current search anchor: Must call @c SearchAnchor first. + * Used for next text and previous text requests. + * @return The position of the found text, -1 if not found. + */ +long Editor::SearchText( + unsigned int iMessage, ///< Accepts both @c SCI_SEARCHNEXT and @c SCI_SEARCHPREV. + uptr_t wParam, ///< Search modes : @c SCFIND_MATCHCASE, @c SCFIND_WHOLEWORD, + ///< @c SCFIND_WORDSTART, @c SCFIND_REGEXP or @c SCFIND_POSIX. + sptr_t lParam) { ///< The text to search for. + + const char *txt = reinterpret_cast(lParam); + int pos; + int lengthFound = istrlen(txt); + if (iMessage == SCI_SEARCHNEXT) { + pos = pdoc->FindText(searchAnchor, pdoc->Length(), txt, + (wParam & SCFIND_MATCHCASE) != 0, + (wParam & SCFIND_WHOLEWORD) != 0, + (wParam & SCFIND_WORDSTART) != 0, + (wParam & SCFIND_REGEXP) != 0, + (wParam & SCFIND_POSIX) != 0, + &lengthFound); + } else { + pos = pdoc->FindText(searchAnchor, 0, txt, + (wParam & SCFIND_MATCHCASE) != 0, + (wParam & SCFIND_WHOLEWORD) != 0, + (wParam & SCFIND_WORDSTART) != 0, + (wParam & SCFIND_REGEXP) != 0, + (wParam & SCFIND_POSIX) != 0, + &lengthFound); + } + + if (pos != -1) { + SetSelection(pos, pos + lengthFound); + } + + return pos; +} + +/** + * Search for text in the target range of the document. + * @return The position of the found text, -1 if not found. + */ +long Editor::SearchInTarget(const char *text, int length) { + int lengthFound = length; + int pos = pdoc->FindText(targetStart, targetEnd, text, + (searchFlags & SCFIND_MATCHCASE) != 0, + (searchFlags & SCFIND_WHOLEWORD) != 0, + (searchFlags & SCFIND_WORDSTART) != 0, + (searchFlags & SCFIND_REGEXP) != 0, + (searchFlags & SCFIND_POSIX) != 0, + &lengthFound); + if (pos != -1) { + targetStart = pos; + targetEnd = pos + lengthFound; + } + return pos; +} + +void Editor::GoToLine(int lineNo) { + if (lineNo > pdoc->LinesTotal()) + lineNo = pdoc->LinesTotal(); + if (lineNo < 0) + lineNo = 0; + SetEmptySelection(pdoc->LineStart(lineNo)); + ShowCaretAtCurrentPosition(); + EnsureCaretVisible(); +} + +static bool Close(Point pt1, Point pt2) { + if (abs(pt1.x - pt2.x) > 3) + return false; + if (abs(pt1.y - pt2.y) > 3) + return false; + return true; +} + +char *Editor::CopyRange(int start, int end) { + char *text = 0; + if (start < end) { + int len = end - start; + text = new char[len + 1]; + if (text) { + for (int i = 0; i < len; i++) { + text[i] = pdoc->CharAt(start + i); + } + text[len] = '\0'; + } + } + return text; +} + +void Editor::CopySelectionFromRange(SelectionText *ss, bool allowLineCopy, int start, int end) { + bool isLine = allowLineCopy && (start == end); + if (isLine) { + int currentLine = pdoc->LineFromPosition(currentPos); + start = pdoc->LineStart(currentLine); + end = pdoc->LineEnd(currentLine); + + char *text = CopyRange(start, end); + int textLen = text ? strlen(text) : 0; + // include room for \r\n\0 + textLen += 3; + char *textWithEndl = new char[textLen]; + textWithEndl[0] = '\0'; + if (text) + strncat(textWithEndl, text, textLen); + if (pdoc->eolMode != SC_EOL_LF) + strncat(textWithEndl, "\r", textLen); + if (pdoc->eolMode != SC_EOL_CR) + strncat(textWithEndl, "\n", textLen); + ss->Set(textWithEndl, strlen(textWithEndl), + pdoc->dbcsCodePage, vs.styles[STYLE_DEFAULT].characterSet, false, true); + delete []text; + } else { + ss->Set(CopyRange(start, end), end - start + 1, + pdoc->dbcsCodePage, vs.styles[STYLE_DEFAULT].characterSet, false, false); + } +} + +void Editor::CopySelectionRange(SelectionText *ss, bool allowLineCopy) { + if (selType == selStream) { + CopySelectionFromRange(ss, allowLineCopy, SelectionStart(), SelectionEnd()); + } else { + char *text = 0; + int size = 0; + SelectionLineIterator lineIterator(this); + while (lineIterator.Iterate()) { + size += lineIterator.endPos - lineIterator.startPos; + if (selType != selLines) { + size++; + if (pdoc->eolMode == SC_EOL_CRLF) { + size++; + } + } + } + if (size > 0) { + text = new char[size + 1]; + if (text) { + int j = 0; + lineIterator.Reset(); + while (lineIterator.Iterate()) { + for (int i = lineIterator.startPos; + i < lineIterator.endPos; + i++) { + text[j++] = pdoc->CharAt(i); + } + if (selType != selLines) { + if (pdoc->eolMode != SC_EOL_LF) { + text[j++] = '\r'; + } + if (pdoc->eolMode != SC_EOL_CR) { + text[j++] = '\n'; + } + } + } + text[size] = '\0'; + } + } + ss->Set(text, size + 1, pdoc->dbcsCodePage, + vs.styles[STYLE_DEFAULT].characterSet, selType == selRectangle, selType == selLines); + } +} + +void Editor::CopyRangeToClipboard(int start, int end) { + start = pdoc->ClampPositionIntoDocument(start); + end = pdoc->ClampPositionIntoDocument(end); + SelectionText selectedText; + selectedText.Set(CopyRange(start, end), end - start + 1, + pdoc->dbcsCodePage, vs.styles[STYLE_DEFAULT].characterSet, false, false); + CopyToClipboard(selectedText); +} + +void Editor::CopyText(int length, const char *text) { + SelectionText selectedText; + selectedText.Copy(text, length + 1, + pdoc->dbcsCodePage, vs.styles[STYLE_DEFAULT].characterSet, false, false); + CopyToClipboard(selectedText); +} + +void Editor::SetDragPosition(int newPos) { + if (newPos >= 0) { + newPos = MovePositionOutsideChar(newPos, 1); + posDrop = newPos; + } + if (posDrag != newPos) { + caret.on = true; + SetTicking(true); + InvalidateCaret(); + posDrag = newPos; + InvalidateCaret(); + } +} + +void Editor::DisplayCursor(Window::Cursor c) { + if (cursorMode == SC_CURSORNORMAL) + wMain.SetCursor(c); + else + wMain.SetCursor(static_cast(cursorMode)); +} + +bool Editor::DragThreshold(Point ptStart, Point ptNow) { + int xMove = ptStart.x - ptNow.x; + int yMove = ptStart.y - ptNow.y; + int distanceSquared = xMove * xMove + yMove * yMove; + return distanceSquared > 16; +} + +void Editor::StartDrag() { + // Always handled by subclasses + //SetMouseCapture(true); + //DisplayCursor(Window::cursorArrow); +} + +void Editor::DropAt(int position, const char *value, bool moving, bool rectangular) { + //Platform::DebugPrintf("DropAt %d %d\n", inDragDrop, position); + if (inDragDrop == ddDragging) + dropWentOutside = false; + + int positionWasInSelection = PositionInSelection(position); + + bool positionOnEdgeOfSelection = + (position == SelectionStart()) || (position == SelectionEnd()); + + if ((inDragDrop != ddDragging) || !(0 == positionWasInSelection) || + (positionOnEdgeOfSelection && !moving)) { + + int selStart = SelectionStart(); + int selEnd = SelectionEnd(); + + pdoc->BeginUndoAction(); + + int positionAfterDeletion = position; + if ((inDragDrop == ddDragging) && moving) { + // Remove dragged out text + if (rectangular || selType == selLines) { + SelectionLineIterator lineIterator(this); + while (lineIterator.Iterate()) { + if (position >= lineIterator.startPos) { + if (position > lineIterator.endPos) { + positionAfterDeletion -= lineIterator.endPos - lineIterator.startPos; + } else { + positionAfterDeletion -= position - lineIterator.startPos; + } + } + } + } else { + if (position > selStart) { + positionAfterDeletion -= selEnd - selStart; + } + } + ClearSelection(); + } + position = positionAfterDeletion; + + if (rectangular) { + PasteRectangular(position, value, istrlen(value)); + pdoc->EndUndoAction(); + // Should try to select new rectangle but it may not be a rectangle now so just select the drop position + SetEmptySelection(position); + } else { + position = MovePositionOutsideChar(position, currentPos - position); + if (pdoc->InsertCString(position, value)) { + SetSelection(position + istrlen(value), position); + } + pdoc->EndUndoAction(); + } + } else if (inDragDrop == ddDragging) { + SetEmptySelection(position); + } +} + +/** + * @return -1 if given position is before the selection, + * 1 if position is after the selection, + * 0 if position is inside the selection, + */ +int Editor::PositionInSelection(int pos) { + pos = MovePositionOutsideChar(pos, currentPos - pos); + if (pos < SelectionStart()) { + return -1; + } + if (pos > SelectionEnd()) { + return 1; + } + if (selType == selStream) { + return 0; + } else { + SelectionLineIterator lineIterator(this); + lineIterator.SetAt(pdoc->LineFromPosition(pos)); + if (pos < lineIterator.startPos) { + return -1; + } else if (pos > lineIterator.endPos) { + return 1; + } else { + return 0; + } + } +} + +bool Editor::PointInSelection(Point pt) { + int pos = PositionFromLocation(pt); + if (0 == PositionInSelection(pos)) { + // Probably inside, but we must make a finer test + int selStart, selEnd; + if (selType == selStream) { + selStart = SelectionStart(); + selEnd = SelectionEnd(); + } else { + SelectionLineIterator lineIterator(this); + lineIterator.SetAt(pdoc->LineFromPosition(pos)); + selStart = lineIterator.startPos; + selEnd = lineIterator.endPos; + } + if (pos == selStart) { + // see if just before selection + Point locStart = LocationFromPosition(pos); + if (pt.x < locStart.x) { + return false; + } + } + if (pos == selEnd) { + // see if just after selection + Point locEnd = LocationFromPosition(pos); + if (pt.x > locEnd.x) { + return false; + } + } + return true; + } + return false; +} + +bool Editor::PointInSelMargin(Point pt) { + // Really means: "Point in a margin" + if (vs.fixedColumnWidth > 0) { // There is a margin + PRectangle rcSelMargin = GetClientRectangle(); + rcSelMargin.right = vs.fixedColumnWidth - vs.leftMarginWidth; + return rcSelMargin.Contains(pt); + } else { + return false; + } +} + +void Editor::LineSelection(int lineCurrent_, int lineAnchor_) { + if (lineAnchor_ < lineCurrent_) { + SetSelection(pdoc->LineStart(lineCurrent_ + 1), + pdoc->LineStart(lineAnchor_)); + } else if (lineAnchor_ > lineCurrent_) { + SetSelection(pdoc->LineStart(lineCurrent_), + pdoc->LineStart(lineAnchor_ + 1)); + } else { // Same line, select it + SetSelection(pdoc->LineStart(lineAnchor_ + 1), + pdoc->LineStart(lineAnchor_)); + } +} + +void Editor::DwellEnd(bool mouseMoved) { + if (mouseMoved) + ticksToDwell = dwellDelay; + else + ticksToDwell = SC_TIME_FOREVER; + if (dwelling && (dwellDelay < SC_TIME_FOREVER)) { + dwelling = false; + NotifyDwelling(ptMouseLast, dwelling); + } +} + +void Editor::ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt) { + //Platform::DebugPrintf("ButtonDown %d %d = %d alt=%d %d\n", curTime, lastClickTime, curTime - lastClickTime, alt, inDragDrop); + ptMouseLast = pt; + int newPos = PositionFromLocation(pt); + newPos = MovePositionOutsideChar(newPos, currentPos - newPos); + inDragDrop = ddNone; + moveExtendsSelection = false; + + bool processed = NotifyMarginClick(pt, shift, ctrl, alt); + if (processed) + return; + + NotifyIndicatorClick(true, newPos, shift, ctrl, alt); + + bool inSelMargin = PointInSelMargin(pt); + 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); + 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) { + selectionType = selLine; + } else { + selectionType = selChar; + originalAnchorPos = currentPos; + } + } + + if (selectionType == selWord) { + if (currentPos >= originalAnchorPos) { // Moved forward + SetSelection(pdoc->ExtendWordSelect(currentPos, 1), + pdoc->ExtendWordSelect(originalAnchorPos, -1)); + } else { // Moved backward + SetSelection(pdoc->ExtendWordSelect(currentPos, -1), + pdoc->ExtendWordSelect(originalAnchorPos, 1)); + } + } else if (selectionType == selLine) { + lineAnchor = LineFromLocation(pt); + SetSelection(pdoc->LineStart(lineAnchor + 1), pdoc->LineStart(lineAnchor)); + //Platform::DebugPrintf("Triple click: %d - %d\n", anchor, currentPos); + } else { + SetEmptySelection(currentPos); + } + //Platform::DebugPrintf("Double click: %d - %d\n", anchor, currentPos); + if (doubleClick) { + NotifyDoubleClick(pt, shift, ctrl, alt); + if (PositionIsHotspot(newPos)) + NotifyHotSpotDoubleClicked(newPos, shift, ctrl, alt); + } + } else { // Single click + if (inSelMargin) { + selType = selStream; + if (ctrl) { + SelectAll(); + lastClickTime = curTime; + return; + } + if (!shift) { + lineAnchor = LineFromLocation(pt); + // Single click in margin: select whole line + LineSelection(lineAnchor, lineAnchor); + SetSelection(pdoc->LineStart(lineAnchor + 1), + pdoc->LineStart(lineAnchor)); + } else { + // Single shift+click in margin: select from line anchor to clicked line + if (anchor > currentPos) + lineAnchor = pdoc->LineFromPosition(anchor - 1); + else + lineAnchor = pdoc->LineFromPosition(anchor); + int lineStart = LineFromLocation(pt); + LineSelection(lineStart, lineAnchor); + //lineAnchor = lineStart; // Keep the same anchor for ButtonMove + } + + SetDragPosition(invalidPosition); + SetMouseCapture(true); + selectionType = selLine; + } else { + if (PointIsHotspot(pt)) { + NotifyHotSpotClicked(newPos, shift, ctrl, alt); + } + if (!shift) { + if (PointInSelection(pt) && !SelectionEmpty()) + inDragDrop = ddInitial; + else + inDragDrop = ddNone; + } + SetMouseCapture(true); + if (inDragDrop != ddInitial) { + SetDragPosition(invalidPosition); + if (!shift) { + SetEmptySelection(newPos); + } + selType = alt ? selRectangle : selStream; + selectionType = selChar; + originalAnchorPos = currentPos; + SetRectangularRange(); + } + } + } + lastClickTime = curTime; + lastXChosen = pt.x; + ShowCaretAtCurrentPosition(); +} + +bool Editor::PositionIsHotspot(int position) { + return vs.styles[pdoc->StyleAt(position) & pdoc->stylingBitsMask].hotspot; +} + +bool Editor::PointIsHotspot(Point pt) { + int pos = PositionFromLocationClose(pt); + if (pos == INVALID_POSITION) + return false; + return PositionIsHotspot(pos); +} + +void Editor::SetHotSpotRange(Point *pt) { + if (pt) { + int pos = PositionFromLocation(*pt); + + // If we don't limit this to word characters then the + // range can encompass more than the run range and then + // the underline will not be drawn properly. + int hsStart_ = pdoc->ExtendStyleRange(pos, -1, vs.hotspotSingleLine); + int hsEnd_ = pdoc->ExtendStyleRange(pos, 1, vs.hotspotSingleLine); + + // Only invalidate the range if the hotspot range has changed... + if (hsStart_ != hsStart || hsEnd_ != hsEnd) { + if (hsStart != -1) { + InvalidateRange(hsStart, hsEnd); + } + hsStart = hsStart_; + hsEnd = hsEnd_; + InvalidateRange(hsStart, hsEnd); + } + } else { + if (hsStart != -1) { + int hsStart_ = hsStart; + int hsEnd_ = hsEnd; + hsStart = -1; + hsEnd = -1; + InvalidateRange(hsStart_, hsEnd_); + } else { + hsStart = -1; + hsEnd = -1; + } + } +} + +void Editor::GetHotSpotRange(int& hsStart_, int& hsEnd_) { + hsStart_ = hsStart; + hsEnd_ = hsEnd; +} + +void Editor::ButtonMove(Point pt) { + if ((ptMouseLast.x != pt.x) || (ptMouseLast.y != pt.y)) { + DwellEnd(true); + } + + int movePos = PositionFromLocation(pt); + movePos = MovePositionOutsideChar(movePos, currentPos - movePos); + + if (inDragDrop == ddInitial) { + if (DragThreshold(ptMouseLast, pt)) { + SetMouseCapture(false); + SetDragPosition(movePos); + CopySelectionRange(&drag); + StartDrag(); + } + return; + } + + ptMouseLast = pt; + //Platform::DebugPrintf("Move %d %d\n", pt.x, pt.y); + if (HaveMouseCapture()) { + + // Slow down autoscrolling/selection + autoScrollTimer.ticksToWait -= timer.tickSize; + if (autoScrollTimer.ticksToWait > 0) + return; + autoScrollTimer.ticksToWait = autoScrollDelay; + + // Adjust selection + if (posDrag >= 0) { + SetDragPosition(movePos); + } else { + if (selectionType == selChar) { + SetSelection(movePos); + } else if (selectionType == selWord) { + // Continue selecting by word + if (movePos == originalAnchorPos) { // Didn't move + // No need to do anything. Previously this case was lumped + // in with "Moved forward", but that can be harmful in this + // case: a handler for the NotifyDoubleClick re-adjusts + // the selection for a fancier definition of "word" (for + // example, in Perl it is useful to include the leading + // '$', '%' or '@' on variables for word selection). In this + // the ButtonMove() called via Tick() for auto-scrolling + // could result in the fancier word selection adjustment + // being unmade. + } else if (movePos > originalAnchorPos) { // Moved forward + SetSelection(pdoc->ExtendWordSelect(movePos, 1), + pdoc->ExtendWordSelect(originalAnchorPos, -1)); + } else { // Moved backward + SetSelection(pdoc->ExtendWordSelect(movePos, -1), + pdoc->ExtendWordSelect(originalAnchorPos, 1)); + } + } else { + // Continue selecting by line + int lineMove = LineFromLocation(pt); + LineSelection(lineMove, lineAnchor); + } + } + // While dragging to make rectangular selection, we don't want the current + // position to jump to the end of smaller or empty lines. + //xEndSelect = pt.x - vs.fixedColumnWidth + xOffset; + xEndSelect = XFromPosition(movePos); + + // Autoscroll + PRectangle rcClient = GetClientRectangle(); + if (pt.y > rcClient.bottom) { + int lineMove = cs.DisplayFromDoc(LineFromLocation(pt)); + if (lineMove < 0) { + lineMove = cs.DisplayFromDoc(pdoc->LinesTotal() - 1); + } + ScrollTo(lineMove - LinesOnScreen() + 1); + Redraw(); + } else if (pt.y < rcClient.top) { + int lineMove = cs.DisplayFromDoc(LineFromLocation(pt)); + ScrollTo(lineMove - 1); + Redraw(); + } + EnsureCaretVisible(false, false, true); + + if (hsStart != -1 && !PositionIsHotspot(movePos)) + SetHotSpotRange(NULL); + + } else { + if (vs.fixedColumnWidth > 0) { // There is a margin + if (PointInSelMargin(pt)) { + DisplayCursor(Window::cursorReverseArrow); + return; // No need to test for selection + } + } + // Display regular (drag) cursor over selection + if (PointInSelection(pt) && !SelectionEmpty()) { + DisplayCursor(Window::cursorArrow); + } else if (PointIsHotspot(pt)) { + DisplayCursor(Window::cursorHand); + SetHotSpotRange(&pt); + } else { + DisplayCursor(Window::cursorText); + SetHotSpotRange(NULL); + } + } +} + +void Editor::ButtonUp(Point pt, unsigned int curTime, bool ctrl) { + //Platform::DebugPrintf("ButtonUp %d %d\n", HaveMouseCapture(), inDragDrop); + int newPos = PositionFromLocation(pt); + newPos = MovePositionOutsideChar(newPos, currentPos - newPos); + if (inDragDrop == ddInitial) { + inDragDrop = ddNone; + SetEmptySelection(newPos); + } + if (HaveMouseCapture()) { + if (PointInSelMargin(pt)) { + DisplayCursor(Window::cursorReverseArrow); + } else { + DisplayCursor(Window::cursorText); + SetHotSpotRange(NULL); + } + ptMouseLast = pt; + SetMouseCapture(false); + int newPos = PositionFromLocation(pt); + newPos = MovePositionOutsideChar(newPos, currentPos - newPos); + NotifyIndicatorClick(false, newPos, false, false, false); + if (inDragDrop == ddDragging) { + int selStart = SelectionStart(); + int selEnd = SelectionEnd(); + if (selStart < selEnd) { + if (drag.len) { + if (ctrl) { + if (pdoc->InsertString(newPos, drag.s, drag.len)) { + SetSelection(newPos, newPos + drag.len); + } + } else if (newPos < selStart) { + pdoc->DeleteChars(selStart, drag.len); + if (pdoc->InsertString(newPos, drag.s, drag.len)) { + SetSelection(newPos, newPos + drag.len); + } + } else if (newPos > selEnd) { + pdoc->DeleteChars(selStart, drag.len); + newPos -= drag.len; + if (pdoc->InsertString(newPos, drag.s, drag.len)) { + SetSelection(newPos, newPos + drag.len); + } + } else { + SetEmptySelection(newPos); + } + drag.Free(); + } + selectionType = selChar; + } + } else { + if (selectionType == selChar) { + SetSelection(newPos); + } + } + SetRectangularRange(); + lastClickTime = curTime; + lastClick = pt; + lastXChosen = pt.x; + if (selType == selStream) { + SetLastXChosen(); + } + inDragDrop = ddNone; + EnsureCaretVisible(false); + } +} + +// Called frequently to perform background UI including +// caret blinking and automatic scrolling. +void Editor::Tick() { + if (HaveMouseCapture()) { + // Auto scroll + ButtonMove(ptMouseLast); + } + if (caret.period > 0) { + timer.ticksToWait -= timer.tickSize; + if (timer.ticksToWait <= 0) { + caret.on = !caret.on; + timer.ticksToWait = caret.period; + if (caret.active) { + InvalidateCaret(); + } + } + } + if (horizontalScrollBarVisible && trackLineWidth && (lineWidthMaxSeen > scrollWidth)) { + scrollWidth = lineWidthMaxSeen; + SetScrollBars(); + } + if ((dwellDelay < SC_TIME_FOREVER) && + (ticksToDwell > 0) && + (!HaveMouseCapture())) { + ticksToDwell -= timer.tickSize; + if (ticksToDwell <= 0) { + dwelling = true; + NotifyDwelling(ptMouseLast, dwelling); + } + } +} + +bool Editor::Idle() { + + bool idleDone; + + bool wrappingDone = wrapState == eWrapNone; + + if (!wrappingDone) { + // Wrap lines during idle. + WrapLines(false, -1); + // No more wrapping + if (wrapStart == wrapEnd) + wrappingDone = true; + } + + // Add more idle things to do here, but make sure idleDone is + // set correctly before the function returns. returning + // false will stop calling this idle funtion until SetIdle() is + // called again. + + idleDone = wrappingDone; // && thatDone && theOtherThingDone... + + return !idleDone; +} + +void Editor::SetFocusState(bool focusState) { + hasFocus = focusState; + NotifyFocus(hasFocus); + if (hasFocus) { + ShowCaretAtCurrentPosition(); + } else { + CancelModes(); + DropCaret(); + } +} + +bool Editor::PaintContains(PRectangle rc) { + if (rc.Empty()) { + return true; + } else { + return rcPaint.Contains(rc); + } +} + +bool Editor::PaintContainsMargin() { + PRectangle rcSelMargin = GetClientRectangle(); + rcSelMargin.right = vs.fixedColumnWidth; + return PaintContains(rcSelMargin); +} + +void Editor::CheckForChangeOutsidePaint(Range r) { + if (paintState == painting && !paintingAllText) { + //Platform::DebugPrintf("Checking range in paint %d-%d\n", r.start, r.end); + if (!r.Valid()) + return; + + PRectangle rcRange = RectangleFromRange(r.start, r.end); + PRectangle rcText = GetTextRectangle(); + if (rcRange.top < rcText.top) { + rcRange.top = rcText.top; + } + if (rcRange.bottom > rcText.bottom) { + rcRange.bottom = rcText.bottom; + } + + if (!PaintContains(rcRange)) { + AbandonPaint(); + } + } +} + +void Editor::SetBraceHighlight(Position pos0, Position pos1, int matchStyle) { + if ((pos0 != braces[0]) || (pos1 != braces[1]) || (matchStyle != bracesMatchStyle)) { + if ((braces[0] != pos0) || (matchStyle != bracesMatchStyle)) { + CheckForChangeOutsidePaint(Range(braces[0])); + CheckForChangeOutsidePaint(Range(pos0)); + braces[0] = pos0; + } + if ((braces[1] != pos1) || (matchStyle != bracesMatchStyle)) { + CheckForChangeOutsidePaint(Range(braces[1])); + CheckForChangeOutsidePaint(Range(pos1)); + braces[1] = pos1; + } + bracesMatchStyle = matchStyle; + if (paintState == notPainting) { + Redraw(); + } + } +} + +void Editor::SetDocPointer(Document *document) { + //Platform::DebugPrintf("** %x setdoc to %x\n", pdoc, document); + pdoc->RemoveWatcher(this, 0); + pdoc->Release(); + if (document == NULL) { + pdoc = new Document(); + } else { + pdoc = document; + } + pdoc->AddRef(); + + // Ensure all positions within document + selType = selStream; + currentPos = 0; + anchor = 0; + targetStart = 0; + targetEnd = 0; + + braces[0] = invalidPosition; + braces[1] = invalidPosition; + + // Reset the contraction state to fully shown. + cs.Clear(); + cs.InsertLines(0, pdoc->LinesTotal() - 1); + llc.Deallocate(); + NeedWrapping(); + + pdoc->AddWatcher(this, 0); + SetScrollBars(); + Redraw(); +} + +/** + * Recursively expand a fold, making lines visible except where they have an unexpanded parent. + */ +void Editor::Expand(int &line, bool doExpand) { + int lineMaxSubord = pdoc->GetLastChild(line); + line++; + while (line <= lineMaxSubord) { + if (doExpand) + cs.SetVisible(line, line, true); + int level = pdoc->GetLevel(line); + if (level & SC_FOLDLEVELHEADERFLAG) { + if (doExpand && cs.GetExpanded(line)) { + Expand(line, true); + } else { + Expand(line, false); + } + } else { + line++; + } + } +} + +void Editor::ToggleContraction(int line) { + if (line >= 0) { + if ((pdoc->GetLevel(line) & SC_FOLDLEVELHEADERFLAG) == 0) { + line = pdoc->GetFoldParent(line); + if (line < 0) + return; + } + + if (cs.GetExpanded(line)) { + int lineMaxSubord = pdoc->GetLastChild(line); + cs.SetExpanded(line, 0); + if (lineMaxSubord > line) { + cs.SetVisible(line + 1, lineMaxSubord, false); + + int lineCurrent = pdoc->LineFromPosition(currentPos); + if (lineCurrent > line && lineCurrent <= lineMaxSubord) { + // This does not re-expand the fold + EnsureCaretVisible(); + } + + SetScrollBars(); + Redraw(); + } + + } else { + if (!(cs.GetVisible(line))) { + EnsureLineVisible(line, false); + GoToLine(line); + } + cs.SetExpanded(line, 1); + Expand(line, true); + SetScrollBars(); + Redraw(); + } + } +} + +/** + * Recurse up from this line to find any folds that prevent this line from being visible + * and unfold them all. + */ +void Editor::EnsureLineVisible(int lineDoc, bool enforcePolicy) { + + // In case in need of wrapping to ensure DisplayFromDoc works. + WrapLines(true, -1); + + if (!cs.GetVisible(lineDoc)) { + int lineParent = pdoc->GetFoldParent(lineDoc); + if (lineParent >= 0) { + if (lineDoc != lineParent) + EnsureLineVisible(lineParent, enforcePolicy); + if (!cs.GetExpanded(lineParent)) { + cs.SetExpanded(lineParent, 1); + Expand(lineParent, true); + } + } + SetScrollBars(); + Redraw(); + } + if (enforcePolicy) { + int lineDisplay = cs.DisplayFromDoc(lineDoc); + if (visiblePolicy & VISIBLE_SLOP) { + if ((topLine > lineDisplay) || ((visiblePolicy & VISIBLE_STRICT) && (topLine + visibleSlop > lineDisplay))) { + SetTopLine(Platform::Clamp(lineDisplay - visibleSlop, 0, MaxScrollPos())); + SetVerticalScrollPos(); + Redraw(); + } else if ((lineDisplay > topLine + LinesOnScreen() - 1) || + ((visiblePolicy & VISIBLE_STRICT) && (lineDisplay > topLine + LinesOnScreen() - 1 - visibleSlop))) { + SetTopLine(Platform::Clamp(lineDisplay - LinesOnScreen() + 1 + visibleSlop, 0, MaxScrollPos())); + SetVerticalScrollPos(); + Redraw(); + } + } else { + if ((topLine > lineDisplay) || (lineDisplay > topLine + LinesOnScreen() - 1) || (visiblePolicy & VISIBLE_STRICT)) { + SetTopLine(Platform::Clamp(lineDisplay - LinesOnScreen() / 2 + 1, 0, MaxScrollPos())); + SetVerticalScrollPos(); + Redraw(); + } + } + } +} + +int Editor::ReplaceTarget(bool replacePatterns, const char *text, int length) { + pdoc->BeginUndoAction(); + if (length == -1) + length = istrlen(text); + if (replacePatterns) { + text = pdoc->SubstituteByPosition(text, &length); + if (!text) { + pdoc->EndUndoAction(); + return 0; + } + } + if (targetStart != targetEnd) + pdoc->DeleteChars(targetStart, targetEnd - targetStart); + targetEnd = targetStart; + pdoc->InsertString(targetStart, text, length); + targetEnd = targetStart + length; + pdoc->EndUndoAction(); + return length; +} + +bool Editor::IsUnicodeMode() const { + return pdoc && (SC_CP_UTF8 == pdoc->dbcsCodePage); +} + +int Editor::CodePage() const { + if (pdoc) + return pdoc->dbcsCodePage; + else + return 0; +} + +int Editor::WrapCount(int line) { + AutoSurface surface(this); + AutoLineLayout ll(llc, RetrieveLineLayout(line)); + + if (surface && ll) { + LayoutLine(line, surface, vs, ll, wrapWidth); + return ll->lines; + } else { + return 1; + } +} + +void Editor::AddStyledText(char *buffer, int appendLength) { + // The buffer consists of alternating character bytes and style bytes + size_t textLength = appendLength / 2; + char *text = new char[textLength]; + if (text) { + size_t i; + for (i = 0;i < textLength;i++) { + text[i] = buffer[i*2]; + } + pdoc->InsertString(CurrentPosition(), text, textLength); + for (i = 0;i < textLength;i++) { + text[i] = buffer[i*2+1]; + } + pdoc->StartStyling(CurrentPosition(), static_cast(0xff)); + pdoc->SetStyles(textLength, text); + delete []text; + } + SetEmptySelection(currentPos + textLength); +} + +static bool ValidMargin(unsigned long wParam) { + return wParam < ViewStyle::margins; +} + +static char *CharPtrFromSPtr(sptr_t lParam) { + return reinterpret_cast(lParam); +} + +void Editor::StyleSetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam) { + vs.EnsureStyle(wParam); + switch (iMessage) { + case SCI_STYLESETFORE: + vs.styles[wParam].fore.desired = ColourDesired(lParam); + break; + case SCI_STYLESETBACK: + vs.styles[wParam].back.desired = ColourDesired(lParam); + break; + case SCI_STYLESETBOLD: + vs.styles[wParam].bold = lParam != 0; + break; + case SCI_STYLESETITALIC: + vs.styles[wParam].italic = lParam != 0; + break; + case SCI_STYLESETEOLFILLED: + vs.styles[wParam].eolFilled = lParam != 0; + break; + case SCI_STYLESETSIZE: + vs.styles[wParam].size = lParam; + break; + case SCI_STYLESETFONT: + if (lParam != 0) { + vs.SetStyleFontName(wParam, CharPtrFromSPtr(lParam)); + } + break; + case SCI_STYLESETUNDERLINE: + vs.styles[wParam].underline = lParam != 0; + break; + case SCI_STYLESETCASE: + vs.styles[wParam].caseForce = static_cast(lParam); + break; + case SCI_STYLESETCHARACTERSET: + vs.styles[wParam].characterSet = lParam; + break; + case SCI_STYLESETVISIBLE: + vs.styles[wParam].visible = lParam != 0; + break; + case SCI_STYLESETCHANGEABLE: + vs.styles[wParam].changeable = lParam != 0; + break; + case SCI_STYLESETHOTSPOT: + vs.styles[wParam].hotspot = lParam != 0; + break; + } + InvalidateStyleRedraw(); +} + +sptr_t Editor::StyleGetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam) { + vs.EnsureStyle(wParam); + switch (iMessage) { + case SCI_STYLEGETFORE: + return vs.styles[wParam].fore.desired.AsLong(); + case SCI_STYLEGETBACK: + return vs.styles[wParam].back.desired.AsLong(); + case SCI_STYLEGETBOLD: + return vs.styles[wParam].bold ? 1 : 0; + case SCI_STYLEGETITALIC: + return vs.styles[wParam].italic ? 1 : 0; + case SCI_STYLEGETEOLFILLED: + return vs.styles[wParam].eolFilled ? 1 : 0; + case SCI_STYLEGETSIZE: + return vs.styles[wParam].size; + case SCI_STYLEGETFONT: + if (lParam != 0) + strcpy(CharPtrFromSPtr(lParam), vs.styles[wParam].fontName); + return strlen(vs.styles[wParam].fontName); + case SCI_STYLEGETUNDERLINE: + return vs.styles[wParam].underline ? 1 : 0; + case SCI_STYLEGETCASE: + return static_cast(vs.styles[wParam].caseForce); + case SCI_STYLEGETCHARACTERSET: + return vs.styles[wParam].characterSet; + case SCI_STYLEGETVISIBLE: + return vs.styles[wParam].visible ? 1 : 0; + case SCI_STYLEGETCHANGEABLE: + return vs.styles[wParam].changeable ? 1 : 0; + case SCI_STYLEGETHOTSPOT: + return vs.styles[wParam].hotspot ? 1 : 0; + } + return 0; +} + +sptr_t Editor::WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) { + //Platform::DebugPrintf("S start wnd proc %d %d %d\n",iMessage, wParam, lParam); + + // Optional macro recording hook + if (recordingMacro) + NotifyMacroRecord(iMessage, wParam, lParam); + + switch (iMessage) { + + case SCI_GETTEXT: { + if (lParam == 0) + return pdoc->Length() + 1; + if (wParam == 0) + return 0; + char *ptr = CharPtrFromSPtr(lParam); + unsigned int iChar = 0; + for (; iChar < wParam - 1; iChar++) + ptr[iChar] = pdoc->CharAt(iChar); + ptr[iChar] = '\0'; + return iChar; + } + + case SCI_SETTEXT: { + if (lParam == 0) + return 0; + pdoc->BeginUndoAction(); + pdoc->DeleteChars(0, pdoc->Length()); + SetEmptySelection(0); + pdoc->InsertCString(0, CharPtrFromSPtr(lParam)); + pdoc->EndUndoAction(); + return 1; + } + + case SCI_GETTEXTLENGTH: + return pdoc->Length(); + + case SCI_CUT: + Cut(); + SetLastXChosen(); + break; + + case SCI_COPY: + Copy(); + break; + + case SCI_COPYALLOWLINE: + CopyAllowLine(); + break; + + case SCI_COPYRANGE: + CopyRangeToClipboard(wParam, lParam); + break; + + case SCI_COPYTEXT: + CopyText(wParam, CharPtrFromSPtr(lParam)); + break; + + case SCI_PASTE: + Paste(); + if (!caretSticky) { + SetLastXChosen(); + } + EnsureCaretVisible(); + break; + + case SCI_CLEAR: + Clear(); + SetLastXChosen(); + EnsureCaretVisible(); + break; + + case SCI_UNDO: + Undo(); + SetLastXChosen(); + break; + + case SCI_CANUNDO: + return (pdoc->CanUndo() && !pdoc->IsReadOnly()) ? 1 : 0; + + case SCI_EMPTYUNDOBUFFER: + pdoc->DeleteUndoHistory(); + return 0; + + case SCI_GETFIRSTVISIBLELINE: + return topLine; + + case SCI_GETLINE: { // Risk of overwriting the end of the buffer + int lineStart = pdoc->LineStart(wParam); + int lineEnd = pdoc->LineStart(wParam + 1); + if (lParam == 0) { + return lineEnd - lineStart; + } + char *ptr = CharPtrFromSPtr(lParam); + int iPlace = 0; + for (int iChar = lineStart; iChar < lineEnd; iChar++) { + ptr[iPlace++] = pdoc->CharAt(iChar); + } + return iPlace; + } + + case SCI_GETLINECOUNT: + if (pdoc->LinesTotal() == 0) + return 1; + else + return pdoc->LinesTotal(); + + case SCI_GETMODIFY: + return !pdoc->IsSavePoint(); + + case SCI_SETSEL: { + int nStart = static_cast(wParam); + int nEnd = static_cast(lParam); + if (nEnd < 0) + nEnd = pdoc->Length(); + if (nStart < 0) + nStart = nEnd; // Remove selection + selType = selStream; + SetSelection(nEnd, nStart); + EnsureCaretVisible(); + } + break; + + case SCI_GETSELTEXT: { + if (lParam == 0) { + if (selType == selStream) { + return 1 + SelectionEnd() - SelectionStart(); + } else { + // TODO: why is selLines handled the slow way? + int size = 0; + int extraCharsPerLine = 0; + if (selType != selLines) + extraCharsPerLine = (pdoc->eolMode == SC_EOL_CRLF) ? 2 : 1; + SelectionLineIterator lineIterator(this); + while (lineIterator.Iterate()) { + size += lineIterator.endPos + extraCharsPerLine - lineIterator.startPos; + } + + return 1 + size; + } + } + SelectionText selectedText; + CopySelectionRange(&selectedText); + char *ptr = CharPtrFromSPtr(lParam); + int iChar = 0; + if (selectedText.len) { + for (; iChar < selectedText.len; iChar++) + ptr[iChar] = selectedText.s[iChar]; + } else { + ptr[0] = '\0'; + } + return iChar; + } + + case SCI_LINEFROMPOSITION: + if (static_cast(wParam) < 0) + return 0; + return pdoc->LineFromPosition(wParam); + + case SCI_POSITIONFROMLINE: + if (static_cast(wParam) < 0) + wParam = pdoc->LineFromPosition(SelectionStart()); + if (wParam == 0) + return 0; // Even if there is no text, there is a first line that starts at 0 + if (static_cast(wParam) > pdoc->LinesTotal()) + return -1; + //if (wParam > pdoc->LineFromPosition(pdoc->Length())) // Useful test, anyway... + // return -1; + return pdoc->LineStart(wParam); + + // Replacement of the old Scintilla interpretation of EM_LINELENGTH + case SCI_LINELENGTH: + if ((static_cast(wParam) < 0) || + (static_cast(wParam) > pdoc->LineFromPosition(pdoc->Length()))) + return 0; + return pdoc->LineStart(wParam + 1) - pdoc->LineStart(wParam); + + case SCI_REPLACESEL: { + if (lParam == 0) + return 0; + pdoc->BeginUndoAction(); + ClearSelection(); + char *replacement = CharPtrFromSPtr(lParam); + pdoc->InsertCString(currentPos, replacement); + pdoc->EndUndoAction(); + SetEmptySelection(currentPos + istrlen(replacement)); + EnsureCaretVisible(); + } + break; + + case SCI_SETTARGETSTART: + targetStart = wParam; + break; + + case SCI_GETTARGETSTART: + return targetStart; + + case SCI_SETTARGETEND: + targetEnd = wParam; + break; + + case SCI_GETTARGETEND: + return targetEnd; + + case SCI_TARGETFROMSELECTION: + if (currentPos < anchor) { + targetStart = currentPos; + targetEnd = anchor; + } else { + targetStart = anchor; + targetEnd = currentPos; + } + break; + + case SCI_REPLACETARGET: + PLATFORM_ASSERT(lParam); + return ReplaceTarget(false, CharPtrFromSPtr(lParam), wParam); + + case SCI_REPLACETARGETRE: + PLATFORM_ASSERT(lParam); + return ReplaceTarget(true, CharPtrFromSPtr(lParam), wParam); + + case SCI_SEARCHINTARGET: + PLATFORM_ASSERT(lParam); + return SearchInTarget(CharPtrFromSPtr(lParam), wParam); + + case SCI_SETSEARCHFLAGS: + searchFlags = wParam; + break; + + case SCI_GETSEARCHFLAGS: + return searchFlags; + + case SCI_POSITIONBEFORE: + return pdoc->MovePositionOutsideChar(wParam - 1, -1, true); + + case SCI_POSITIONAFTER: + return pdoc->MovePositionOutsideChar(wParam + 1, 1, true); + + case SCI_LINESCROLL: + ScrollTo(topLine + lParam); + HorizontalScrollTo(xOffset + wParam * vs.spaceWidth); + return 1; + + case SCI_SETXOFFSET: + xOffset = wParam; + SetHorizontalScrollPos(); + Redraw(); + break; + + case SCI_GETXOFFSET: + return xOffset; + + case SCI_CHOOSECARETX: + SetLastXChosen(); + break; + + case SCI_SCROLLCARET: + EnsureCaretVisible(); + break; + + case SCI_SETREADONLY: + pdoc->SetReadOnly(wParam != 0); + return 1; + + case SCI_GETREADONLY: + return pdoc->IsReadOnly(); + + case SCI_CANPASTE: + return CanPaste(); + + case SCI_POINTXFROMPOSITION: + if (lParam < 0) { + return 0; + } else { + Point pt = LocationFromPosition(lParam); + return pt.x; + } + + case SCI_POINTYFROMPOSITION: + if (lParam < 0) { + return 0; + } else { + Point pt = LocationFromPosition(lParam); + return pt.y; + } + + case SCI_FINDTEXT: + return FindText(wParam, lParam); + + case SCI_GETTEXTRANGE: { + if (lParam == 0) + return 0; + TextRange *tr = reinterpret_cast(lParam); + int cpMax = tr->chrg.cpMax; + if (cpMax == -1) + cpMax = pdoc->Length(); + PLATFORM_ASSERT(cpMax <= pdoc->Length()); + int len = cpMax - tr->chrg.cpMin; // No -1 as cpMin and cpMax are referring to inter character positions + pdoc->GetCharRange(tr->lpstrText, tr->chrg.cpMin, len); + // Spec says copied text is terminated with a NUL + tr->lpstrText[len] = '\0'; + return len; // Not including NUL + } + + case SCI_HIDESELECTION: + hideSelection = wParam != 0; + Redraw(); + break; + + case SCI_FORMATRANGE: + return FormatRange(wParam != 0, reinterpret_cast(lParam)); + + case SCI_GETMARGINLEFT: + return vs.leftMarginWidth; + + case SCI_GETMARGINRIGHT: + return vs.rightMarginWidth; + + case SCI_SETMARGINLEFT: + vs.leftMarginWidth = lParam; + InvalidateStyleRedraw(); + break; + + case SCI_SETMARGINRIGHT: + vs.rightMarginWidth = lParam; + InvalidateStyleRedraw(); + break; + + // Control specific mesages + + case SCI_ADDTEXT: { + if (lParam == 0) + return 0; + pdoc->InsertString(CurrentPosition(), CharPtrFromSPtr(lParam), wParam); + SetEmptySelection(currentPos + wParam); + return 0; + } + + case SCI_ADDSTYLEDTEXT: + if (lParam) + AddStyledText(CharPtrFromSPtr(lParam), wParam); + return 0; + + case SCI_INSERTTEXT: { + if (lParam == 0) + return 0; + int insertPos = wParam; + if (static_cast(wParam) == -1) + insertPos = CurrentPosition(); + int newCurrent = CurrentPosition(); + char *sz = CharPtrFromSPtr(lParam); + pdoc->InsertCString(insertPos, sz); + if (newCurrent > insertPos) + newCurrent += istrlen(sz); + SetEmptySelection(newCurrent); + return 0; + } + + case SCI_APPENDTEXT: + pdoc->InsertString(pdoc->Length(), CharPtrFromSPtr(lParam), wParam); + return 0; + + case SCI_CLEARALL: + ClearAll(); + return 0; + + case SCI_CLEARDOCUMENTSTYLE: + ClearDocumentStyle(); + return 0; + + case SCI_SETUNDOCOLLECTION: + pdoc->SetUndoCollection(wParam != 0); + return 0; + + case SCI_GETUNDOCOLLECTION: + return pdoc->IsCollectingUndo(); + + case SCI_BEGINUNDOACTION: + pdoc->BeginUndoAction(); + return 0; + + case SCI_ENDUNDOACTION: + pdoc->EndUndoAction(); + return 0; + + case SCI_GETCARETPERIOD: + return caret.period; + + case SCI_SETCARETPERIOD: + caret.period = wParam; + break; + + case SCI_SETWORDCHARS: { + pdoc->SetDefaultCharClasses(false); + if (lParam == 0) + return 0; + pdoc->SetCharClasses(reinterpret_cast(lParam), CharClassify::ccWord); + } + break; + + case SCI_SETWHITESPACECHARS: { + if (lParam == 0) + return 0; + pdoc->SetCharClasses(reinterpret_cast(lParam), CharClassify::ccSpace); + } + break; + + case SCI_SETCHARSDEFAULT: + pdoc->SetDefaultCharClasses(true); + break; + + case SCI_GETLENGTH: + return pdoc->Length(); + + case SCI_ALLOCATE: + pdoc->Allocate(wParam); + break; + + case SCI_GETCHARAT: + return pdoc->CharAt(wParam); + + case SCI_SETCURRENTPOS: + SetSelection(wParam, anchor); + break; + + case SCI_GETCURRENTPOS: + return currentPos; + + case SCI_SETANCHOR: + SetSelection(currentPos, wParam); + break; + + case SCI_GETANCHOR: + return anchor; + + case SCI_SETSELECTIONSTART: + SetSelection(Platform::Maximum(currentPos, wParam), wParam); + break; + + case SCI_GETSELECTIONSTART: + return Platform::Minimum(anchor, currentPos); + + case SCI_SETSELECTIONEND: + SetSelection(wParam, Platform::Minimum(anchor, wParam)); + break; + + case SCI_GETSELECTIONEND: + return Platform::Maximum(anchor, currentPos); + + case SCI_SETPRINTMAGNIFICATION: + printMagnification = wParam; + break; + + case SCI_GETPRINTMAGNIFICATION: + return printMagnification; + + case SCI_SETPRINTCOLOURMODE: + printColourMode = wParam; + break; + + case SCI_GETPRINTCOLOURMODE: + return printColourMode; + + case SCI_SETPRINTWRAPMODE: + printWrapState = (wParam == SC_WRAP_WORD) ? eWrapWord : eWrapNone; + break; + + case SCI_GETPRINTWRAPMODE: + return printWrapState; + + case SCI_GETSTYLEAT: + if (static_cast(wParam) >= pdoc->Length()) + return 0; + else + return pdoc->StyleAt(wParam); + + case SCI_REDO: + Redo(); + break; + + case SCI_SELECTALL: + SelectAll(); + break; + + case SCI_SETSAVEPOINT: + pdoc->SetSavePoint(); + break; + + case SCI_GETSTYLEDTEXT: { + if (lParam == 0) + return 0; + TextRange *tr = reinterpret_cast(lParam); + int iPlace = 0; + for (int iChar = tr->chrg.cpMin; iChar < tr->chrg.cpMax; iChar++) { + tr->lpstrText[iPlace++] = pdoc->CharAt(iChar); + tr->lpstrText[iPlace++] = pdoc->StyleAt(iChar); + } + tr->lpstrText[iPlace] = '\0'; + tr->lpstrText[iPlace + 1] = '\0'; + return iPlace; + } + + case SCI_CANREDO: + return (pdoc->CanRedo() && !pdoc->IsReadOnly()) ? 1 : 0; + + case SCI_MARKERLINEFROMHANDLE: + return pdoc->LineFromHandle(wParam); + + case SCI_MARKERDELETEHANDLE: + pdoc->DeleteMarkFromHandle(wParam); + break; + + case SCI_GETVIEWWS: + return vs.viewWhitespace; + + case SCI_SETVIEWWS: + vs.viewWhitespace = static_cast(wParam); + Redraw(); + break; + + case SCI_POSITIONFROMPOINT: + return PositionFromLocation(Point(wParam, lParam)); + + case SCI_POSITIONFROMPOINTCLOSE: + return PositionFromLocationClose(Point(wParam, lParam)); + + case SCI_GOTOLINE: + GoToLine(wParam); + break; + + case SCI_GOTOPOS: + SetEmptySelection(wParam); + EnsureCaretVisible(); + Redraw(); + break; + + case SCI_GETCURLINE: { + int lineCurrentPos = pdoc->LineFromPosition(currentPos); + int lineStart = pdoc->LineStart(lineCurrentPos); + unsigned int lineEnd = pdoc->LineStart(lineCurrentPos + 1); + if (lParam == 0) { + return 1 + lineEnd - lineStart; + } + PLATFORM_ASSERT(wParam > 0); + char *ptr = CharPtrFromSPtr(lParam); + unsigned int iPlace = 0; + for (unsigned int iChar = lineStart; iChar < lineEnd && iPlace < wParam - 1; iChar++) { + ptr[iPlace++] = pdoc->CharAt(iChar); + } + ptr[iPlace] = '\0'; + return currentPos - lineStart; + } + + case SCI_GETENDSTYLED: + return pdoc->GetEndStyled(); + + case SCI_GETEOLMODE: + return pdoc->eolMode; + + case SCI_SETEOLMODE: + pdoc->eolMode = wParam; + break; + + case SCI_STARTSTYLING: + pdoc->StartStyling(wParam, static_cast(lParam)); + break; + + case SCI_SETSTYLING: + pdoc->SetStyleFor(wParam, static_cast(lParam)); + break; + + case SCI_SETSTYLINGEX: // Specify a complete styling buffer + if (lParam == 0) + return 0; + pdoc->SetStyles(wParam, CharPtrFromSPtr(lParam)); + break; + + case SCI_SETBUFFEREDDRAW: + bufferedDraw = wParam != 0; + break; + + case SCI_GETBUFFEREDDRAW: + return bufferedDraw; + + case SCI_GETTWOPHASEDRAW: + return twoPhaseDraw; + + case SCI_SETTWOPHASEDRAW: + twoPhaseDraw = wParam != 0; + InvalidateStyleRedraw(); + break; + + case SCI_SETTABWIDTH: + if (wParam > 0) { + pdoc->tabInChars = wParam; + if (pdoc->indentInChars == 0) + pdoc->actualIndentInChars = pdoc->tabInChars; + } + InvalidateStyleRedraw(); + break; + + case SCI_GETTABWIDTH: + return pdoc->tabInChars; + + case SCI_SETINDENT: + pdoc->indentInChars = wParam; + if (pdoc->indentInChars != 0) + pdoc->actualIndentInChars = pdoc->indentInChars; + else + pdoc->actualIndentInChars = pdoc->tabInChars; + InvalidateStyleRedraw(); + break; + + case SCI_GETINDENT: + return pdoc->indentInChars; + + case SCI_SETUSETABS: + pdoc->useTabs = wParam != 0; + InvalidateStyleRedraw(); + break; + + case SCI_GETUSETABS: + return pdoc->useTabs; + + case SCI_SETLINEINDENTATION: + pdoc->SetLineIndentation(wParam, lParam); + break; + + case SCI_GETLINEINDENTATION: + return pdoc->GetLineIndentation(wParam); + + case SCI_GETLINEINDENTPOSITION: + return pdoc->GetLineIndentPosition(wParam); + + case SCI_SETTABINDENTS: + pdoc->tabIndents = wParam != 0; + break; + + case SCI_GETTABINDENTS: + return pdoc->tabIndents; + + case SCI_SETBACKSPACEUNINDENTS: + pdoc->backspaceUnindents = wParam != 0; + break; + + case SCI_GETBACKSPACEUNINDENTS: + return pdoc->backspaceUnindents; + + case SCI_SETMOUSEDWELLTIME: + dwellDelay = wParam; + ticksToDwell = dwellDelay; + break; + + case SCI_GETMOUSEDWELLTIME: + return dwellDelay; + + case SCI_WORDSTARTPOSITION: + return pdoc->ExtendWordSelect(wParam, -1, lParam != 0); + + case SCI_WORDENDPOSITION: + return pdoc->ExtendWordSelect(wParam, 1, lParam != 0); + + case SCI_SETWRAPMODE: + switch (wParam) { + case SC_WRAP_WORD: + wrapState = eWrapWord; + break; + case SC_WRAP_CHAR: + wrapState = eWrapChar; + break; + default: + wrapState = eWrapNone; + break; + } + xOffset = 0; + InvalidateStyleRedraw(); + ReconfigureScrollBars(); + break; + + case SCI_GETWRAPMODE: + return wrapState; + + case SCI_SETWRAPVISUALFLAGS: + wrapVisualFlags = wParam; + actualWrapVisualStartIndent = wrapVisualStartIndent; + if ((wrapVisualFlags & SC_WRAPVISUALFLAG_START) && (actualWrapVisualStartIndent == 0)) + actualWrapVisualStartIndent = 1; // must indent to show start visual + InvalidateStyleRedraw(); + ReconfigureScrollBars(); + break; + + case SCI_GETWRAPVISUALFLAGS: + return wrapVisualFlags; + + case SCI_SETWRAPVISUALFLAGSLOCATION: + wrapVisualFlagsLocation = wParam; + InvalidateStyleRedraw(); + break; + + case SCI_GETWRAPVISUALFLAGSLOCATION: + return wrapVisualFlagsLocation; + + case SCI_SETWRAPSTARTINDENT: + wrapVisualStartIndent = wParam; + actualWrapVisualStartIndent = wrapVisualStartIndent; + if ((wrapVisualFlags & SC_WRAPVISUALFLAG_START) && (actualWrapVisualStartIndent == 0)) + actualWrapVisualStartIndent = 1; // must indent to show start visual + InvalidateStyleRedraw(); + ReconfigureScrollBars(); + break; + + case SCI_GETWRAPSTARTINDENT: + return wrapVisualStartIndent; + + case SCI_SETLAYOUTCACHE: + llc.SetLevel(wParam); + break; + + case SCI_GETLAYOUTCACHE: + return llc.GetLevel(); + + case SCI_SETPOSITIONCACHE: + posCache.SetSize(wParam); + break; + + case SCI_GETPOSITIONCACHE: + return posCache.GetSize(); + + case SCI_SETSCROLLWIDTH: + PLATFORM_ASSERT(wParam > 0); + if ((wParam > 0) && (wParam != static_cast(scrollWidth))) { + lineWidthMaxSeen = 0; + scrollWidth = wParam; + SetScrollBars(); + } + break; + + case SCI_GETSCROLLWIDTH: + return scrollWidth; + + case SCI_SETSCROLLWIDTHTRACKING: + trackLineWidth = wParam != 0; + break; + + case SCI_GETSCROLLWIDTHTRACKING: + return trackLineWidth; + + case SCI_LINESJOIN: + LinesJoin(); + break; + + case SCI_LINESSPLIT: + LinesSplit(wParam); + break; + + case SCI_TEXTWIDTH: + PLATFORM_ASSERT(wParam < vs.stylesSize); + PLATFORM_ASSERT(lParam); + return TextWidth(wParam, CharPtrFromSPtr(lParam)); + + case SCI_TEXTHEIGHT: + return vs.lineHeight; + + case SCI_SETENDATLASTLINE: + PLATFORM_ASSERT((wParam == 0) || (wParam == 1)); + if (endAtLastLine != (wParam != 0)) { + endAtLastLine = wParam != 0; + SetScrollBars(); + } + break; + + case SCI_GETENDATLASTLINE: + return endAtLastLine; + + case SCI_SETCARETSTICKY: + PLATFORM_ASSERT((wParam == 0) || (wParam == 1)); + if (caretSticky != (wParam != 0)) { + caretSticky = wParam != 0; + } + break; + + case SCI_GETCARETSTICKY: + return caretSticky; + + case SCI_TOGGLECARETSTICKY: + caretSticky = !caretSticky; + break; + + case SCI_GETCOLUMN: + return pdoc->GetColumn(wParam); + + case SCI_FINDCOLUMN: + return pdoc->FindColumn(wParam, lParam); + + case SCI_SETHSCROLLBAR : + if (horizontalScrollBarVisible != (wParam != 0)) { + horizontalScrollBarVisible = wParam != 0; + SetScrollBars(); + ReconfigureScrollBars(); + } + break; + + case SCI_GETHSCROLLBAR: + return horizontalScrollBarVisible; + + case SCI_SETVSCROLLBAR: + if (verticalScrollBarVisible != (wParam != 0)) { + verticalScrollBarVisible = wParam != 0; + SetScrollBars(); + ReconfigureScrollBars(); + } + break; + + case SCI_GETVSCROLLBAR: + return verticalScrollBarVisible; + + case SCI_SETINDENTATIONGUIDES: + vs.viewIndentationGuides = IndentView(wParam); + Redraw(); + break; + + case SCI_GETINDENTATIONGUIDES: + return vs.viewIndentationGuides; + + case SCI_SETHIGHLIGHTGUIDE: + if ((highlightGuideColumn != static_cast(wParam)) || (wParam > 0)) { + highlightGuideColumn = wParam; + Redraw(); + } + break; + + case SCI_GETHIGHLIGHTGUIDE: + return highlightGuideColumn; + + case SCI_GETLINEENDPOSITION: + return pdoc->LineEnd(wParam); + + case SCI_SETCODEPAGE: + if (ValidCodePage(wParam)) { + pdoc->dbcsCodePage = wParam; + InvalidateStyleRedraw(); + } + break; + + case SCI_GETCODEPAGE: + return pdoc->dbcsCodePage; + + case SCI_SETUSEPALETTE: + palette.allowRealization = wParam != 0; + InvalidateStyleRedraw(); + break; + + case SCI_GETUSEPALETTE: + return palette.allowRealization; + + // Marker definition and setting + case SCI_MARKERDEFINE: + if (wParam <= MARKER_MAX) + vs.markers[wParam].markType = lParam; + InvalidateStyleData(); + RedrawSelMargin(); + break; + case SCI_MARKERSETFORE: + if (wParam <= MARKER_MAX) + vs.markers[wParam].fore.desired = ColourDesired(lParam); + InvalidateStyleData(); + RedrawSelMargin(); + break; + case SCI_MARKERSETBACK: + if (wParam <= MARKER_MAX) + vs.markers[wParam].back.desired = ColourDesired(lParam); + InvalidateStyleData(); + RedrawSelMargin(); + break; + case SCI_MARKERSETALPHA: + if (wParam <= MARKER_MAX) + vs.markers[wParam].alpha = lParam; + InvalidateStyleRedraw(); + break; + case SCI_MARKERADD: { + int markerID = pdoc->AddMark(wParam, lParam); + return markerID; + } + case SCI_MARKERADDSET: + if (lParam != 0) + pdoc->AddMarkSet(wParam, lParam); + break; + + case SCI_MARKERDELETE: + pdoc->DeleteMark(wParam, lParam); + break; + + case SCI_MARKERDELETEALL: + pdoc->DeleteAllMarks(static_cast(wParam)); + break; + + case SCI_MARKERGET: + return pdoc->GetMark(wParam); + + case SCI_MARKERNEXT: { + int lt = pdoc->LinesTotal(); + for (int iLine = wParam; iLine < lt; iLine++) { + if ((pdoc->GetMark(iLine) & lParam) != 0) + return iLine; + } + } + return -1; + + case SCI_MARKERPREVIOUS: { + for (int iLine = wParam; iLine >= 0; iLine--) { + if ((pdoc->GetMark(iLine) & lParam) != 0) + return iLine; + } + } + return -1; + + case SCI_MARKERDEFINEPIXMAP: + if (wParam <= MARKER_MAX) { + vs.markers[wParam].SetXPM(CharPtrFromSPtr(lParam)); + }; + InvalidateStyleData(); + RedrawSelMargin(); + break; + + case SCI_SETMARGINTYPEN: + if (ValidMargin(wParam)) { + vs.ms[wParam].style = lParam; + InvalidateStyleRedraw(); + } + break; + + case SCI_GETMARGINTYPEN: + if (ValidMargin(wParam)) + return vs.ms[wParam].style; + else + return 0; + + case SCI_SETMARGINWIDTHN: + if (ValidMargin(wParam)) { + // Short-circuit if the width is unchanged, to avoid unnecessary redraw. + if (vs.ms[wParam].width != lParam) { + vs.ms[wParam].width = lParam; + InvalidateStyleRedraw(); + } + } + break; + + case SCI_GETMARGINWIDTHN: + if (ValidMargin(wParam)) + return vs.ms[wParam].width; + else + return 0; + + case SCI_SETMARGINMASKN: + if (ValidMargin(wParam)) { + vs.ms[wParam].mask = lParam; + InvalidateStyleRedraw(); + } + break; + + case SCI_GETMARGINMASKN: + if (ValidMargin(wParam)) + return vs.ms[wParam].mask; + else + return 0; + + case SCI_SETMARGINSENSITIVEN: + if (ValidMargin(wParam)) { + vs.ms[wParam].sensitive = lParam != 0; + InvalidateStyleRedraw(); + } + break; + + case SCI_GETMARGINSENSITIVEN: + if (ValidMargin(wParam)) + return vs.ms[wParam].sensitive ? 1 : 0; + else + return 0; + + case SCI_STYLECLEARALL: + vs.ClearStyles(); + InvalidateStyleRedraw(); + break; + + case SCI_STYLESETFORE: + case SCI_STYLESETBACK: + case SCI_STYLESETBOLD: + case SCI_STYLESETITALIC: + case SCI_STYLESETEOLFILLED: + case SCI_STYLESETSIZE: + case SCI_STYLESETFONT: + case SCI_STYLESETUNDERLINE: + case SCI_STYLESETCASE: + case SCI_STYLESETCHARACTERSET: + case SCI_STYLESETVISIBLE: + case SCI_STYLESETCHANGEABLE: + case SCI_STYLESETHOTSPOT: + StyleSetMessage(iMessage, wParam, lParam); + break; + + case SCI_STYLEGETFORE: + case SCI_STYLEGETBACK: + case SCI_STYLEGETBOLD: + case SCI_STYLEGETITALIC: + case SCI_STYLEGETEOLFILLED: + case SCI_STYLEGETSIZE: + case SCI_STYLEGETFONT: + case SCI_STYLEGETUNDERLINE: + case SCI_STYLEGETCASE: + case SCI_STYLEGETCHARACTERSET: + case SCI_STYLEGETVISIBLE: + case SCI_STYLEGETCHANGEABLE: + case SCI_STYLEGETHOTSPOT: + return StyleGetMessage(iMessage, wParam, lParam); + + case SCI_STYLERESETDEFAULT: + vs.ResetDefaultStyle(); + InvalidateStyleRedraw(); + break; + case SCI_SETSTYLEBITS: + vs.EnsureStyle((1 << wParam) - 1); + pdoc->SetStylingBits(wParam); + break; + + case SCI_GETSTYLEBITS: + return pdoc->stylingBits; + + case SCI_SETLINESTATE: + return pdoc->SetLineState(wParam, lParam); + + case SCI_GETLINESTATE: + return pdoc->GetLineState(wParam); + + case SCI_GETMAXLINESTATE: + return pdoc->GetMaxLineState(); + + case SCI_GETCARETLINEVISIBLE: + return vs.showCaretLineBackground; + case SCI_SETCARETLINEVISIBLE: + vs.showCaretLineBackground = wParam != 0; + InvalidateStyleRedraw(); + break; + case SCI_GETCARETLINEVISIBLEALWAYS: + return vs.showCaretLineBackgroundAlways; + case SCI_SETCARETLINEVISIBLEALWAYS: + vs.showCaretLineBackgroundAlways = wParam != 0; + InvalidateStyleRedraw(); + break; + + case SCI_GETCARETLINEBACK: + return vs.caretLineBackground.desired.AsLong(); + case SCI_SETCARETLINEBACK: + vs.caretLineBackground.desired = wParam; + InvalidateStyleRedraw(); + break; + case SCI_GETCARETLINEBACKALPHA: + return vs.caretLineAlpha; + case SCI_SETCARETLINEBACKALPHA: + vs.caretLineAlpha = wParam; + InvalidateStyleRedraw(); + break; + + // Folding messages + + case SCI_VISIBLEFROMDOCLINE: + return cs.DisplayFromDoc(wParam); + + case SCI_DOCLINEFROMVISIBLE: + return cs.DocFromDisplay(wParam); + + case SCI_WRAPCOUNT: + return WrapCount(wParam); + + case SCI_SETFOLDLEVEL: { + int prev = pdoc->SetLevel(wParam, lParam); + if (prev != lParam) + RedrawSelMargin(); + return prev; + } + + case SCI_GETFOLDLEVEL: + return pdoc->GetLevel(wParam); + + case SCI_GETLASTCHILD: + return pdoc->GetLastChild(wParam, lParam); + + case SCI_GETFOLDPARENT: + return pdoc->GetFoldParent(wParam); + + case SCI_SHOWLINES: + cs.SetVisible(wParam, lParam, true); + SetScrollBars(); + Redraw(); + break; + + case SCI_HIDELINES: + cs.SetVisible(wParam, lParam, false); + SetScrollBars(); + Redraw(); + break; + + case SCI_GETLINEVISIBLE: + return cs.GetVisible(wParam); + + case SCI_SETFOLDEXPANDED: + if (cs.SetExpanded(wParam, lParam != 0)) { + RedrawSelMargin(); + } + break; + + case SCI_GETFOLDEXPANDED: + return cs.GetExpanded(wParam); + + case SCI_SETFOLDFLAGS: + foldFlags = wParam; + Redraw(); + break; + + case SCI_TOGGLEFOLD: + ToggleContraction(wParam); + break; + + case SCI_ENSUREVISIBLE: + EnsureLineVisible(wParam, false); + break; + + case SCI_ENSUREVISIBLEENFORCEPOLICY: + EnsureLineVisible(wParam, true); + break; + + case SCI_SEARCHANCHOR: + SearchAnchor(); + break; + + case SCI_SEARCHNEXT: + case SCI_SEARCHPREV: + return SearchText(iMessage, wParam, lParam); + +#ifdef INCLUDE_DEPRECATED_FEATURES + case SCI_SETCARETPOLICY: // Deprecated + caretXPolicy = caretYPolicy = wParam; + caretXSlop = caretYSlop = lParam; + break; +#endif + + case SCI_SETXCARETPOLICY: + caretXPolicy = wParam; + caretXSlop = lParam; + break; + + case SCI_SETYCARETPOLICY: + caretYPolicy = wParam; + caretYSlop = lParam; + break; + + case SCI_SETVISIBLEPOLICY: + visiblePolicy = wParam; + visibleSlop = lParam; + break; + + case SCI_LINESONSCREEN: + return LinesOnScreen(); + + case SCI_SETSELFORE: + vs.selforeset = wParam != 0; + vs.selforeground.desired = ColourDesired(lParam); + InvalidateStyleRedraw(); + break; + + case SCI_SETSELBACK: + vs.selbackset = wParam != 0; + vs.selbackground.desired = ColourDesired(lParam); + InvalidateStyleRedraw(); + break; + + case SCI_SETSELALPHA: + vs.selAlpha = wParam; + InvalidateStyleRedraw(); + break; + + case SCI_GETSELALPHA: + return vs.selAlpha; + + case SCI_GETSELEOLFILLED: + return vs.selEOLFilled; + + case SCI_SETSELEOLFILLED: + vs.selEOLFilled = wParam != 0; + InvalidateStyleRedraw(); + break; + + case SCI_SETWHITESPACEFORE: + vs.whitespaceForegroundSet = wParam != 0; + vs.whitespaceForeground.desired = ColourDesired(lParam); + InvalidateStyleRedraw(); + break; + + case SCI_SETWHITESPACEBACK: + vs.whitespaceBackgroundSet = wParam != 0; + vs.whitespaceBackground.desired = ColourDesired(lParam); + InvalidateStyleRedraw(); + break; + + case SCI_SETCARETFORE: + vs.caretcolour.desired = ColourDesired(wParam); + InvalidateStyleRedraw(); + break; + + case SCI_GETCARETFORE: + return vs.caretcolour.desired.AsLong(); + + case SCI_SETCARETSTYLE: + if (wParam >= CARETSTYLE_INVISIBLE && wParam <= CARETSTYLE_BLOCK) + vs.caretStyle = wParam; + else + /* Default to the line caret */ + vs.caretStyle = CARETSTYLE_LINE; + InvalidateStyleRedraw(); + break; + + case SCI_GETCARETSTYLE: + return vs.caretStyle; + + case SCI_SETCARETWIDTH: + if (wParam <= 0) + vs.caretWidth = 0; + else if (wParam >= 3) + vs.caretWidth = 3; + else + vs.caretWidth = wParam; + InvalidateStyleRedraw(); + break; + + case SCI_GETCARETWIDTH: + return vs.caretWidth; + + case SCI_ASSIGNCMDKEY: + kmap.AssignCmdKey(Platform::LowShortFromLong(wParam), + Platform::HighShortFromLong(wParam), lParam); + break; + + case SCI_CLEARCMDKEY: + kmap.AssignCmdKey(Platform::LowShortFromLong(wParam), + Platform::HighShortFromLong(wParam), SCI_NULL); + break; + + case SCI_CLEARALLCMDKEYS: + kmap.Clear(); + break; + + case SCI_INDICSETSTYLE: + if (wParam <= INDIC_MAX) { + vs.indicators[wParam].style = lParam; + InvalidateStyleRedraw(); + } + break; + + case SCI_INDICGETSTYLE: + return (wParam <= INDIC_MAX) ? vs.indicators[wParam].style : 0; + + case SCI_INDICSETFORE: + if (wParam <= INDIC_MAX) { + vs.indicators[wParam].fore.desired = ColourDesired(lParam); + InvalidateStyleRedraw(); + } + break; + + case SCI_INDICGETFORE: + return (wParam <= INDIC_MAX) ? vs.indicators[wParam].fore.desired.AsLong() : 0; + + case SCI_INDICSETUNDER: + if (wParam <= INDIC_MAX) { + vs.indicators[wParam].under = lParam != 0; + InvalidateStyleRedraw(); + } + break; + + case SCI_INDICGETUNDER: + return (wParam <= INDIC_MAX) ? vs.indicators[wParam].under : 0; + + case SCI_INDICSETALPHA: + if (wParam <= INDIC_MAX && lParam <= SC_ALPHA_OPAQUE && lParam > 0) { + vs.indicators[wParam].alpha = lParam; + InvalidateStyleRedraw(); + } + break; + + case SCI_INDICGETALPHA: + return (wParam <= INDIC_MAX) ? vs.indicators[wParam].alpha : 0; + + case SCI_SETINDICATORCURRENT: + pdoc->decorations.SetCurrentIndicator(wParam); + break; + case SCI_GETINDICATORCURRENT: + return pdoc->decorations.GetCurrentIndicator(); + case SCI_SETINDICATORVALUE: + pdoc->decorations.SetCurrentValue(wParam); + break; + case SCI_GETINDICATORVALUE: + return pdoc->decorations.GetCurrentValue(); + + case SCI_INDICATORFILLRANGE: + pdoc->DecorationFillRange(wParam, pdoc->decorations.GetCurrentValue(), lParam); + break; + + case SCI_INDICATORCLEARRANGE: + pdoc->DecorationFillRange(wParam, 0, lParam); + break; + + case SCI_INDICATORALLONFOR: + return pdoc->decorations.AllOnFor(wParam); + + case SCI_INDICATORVALUEAT: + return pdoc->decorations.ValueAt(wParam, lParam); + + case SCI_INDICATORSTART: + return pdoc->decorations.Start(wParam, lParam); + + case SCI_INDICATOREND: + return pdoc->decorations.End(wParam, lParam); + + case SCI_LINEDOWN: + case SCI_LINEDOWNEXTEND: + case SCI_PARADOWN: + case SCI_PARADOWNEXTEND: + case SCI_LINEUP: + case SCI_LINEUPEXTEND: + case SCI_PARAUP: + case SCI_PARAUPEXTEND: + case SCI_CHARLEFT: + case SCI_CHARLEFTEXTEND: + case SCI_CHARRIGHT: + case SCI_CHARRIGHTEXTEND: + case SCI_WORDLEFT: + case SCI_WORDLEFTEXTEND: + case SCI_WORDRIGHT: + case SCI_WORDRIGHTEXTEND: + case SCI_WORDLEFTEND: + case SCI_WORDLEFTENDEXTEND: + case SCI_WORDRIGHTEND: + case SCI_WORDRIGHTENDEXTEND: + case SCI_HOME: + case SCI_HOMEEXTEND: + case SCI_LINEEND: + case SCI_LINEENDEXTEND: + case SCI_HOMEWRAP: + case SCI_HOMEWRAPEXTEND: + case SCI_LINEENDWRAP: + case SCI_LINEENDWRAPEXTEND: + case SCI_DOCUMENTSTART: + case SCI_DOCUMENTSTARTEXTEND: + case SCI_DOCUMENTEND: + case SCI_DOCUMENTENDEXTEND: + + case SCI_STUTTEREDPAGEUP: + case SCI_STUTTEREDPAGEUPEXTEND: + case SCI_STUTTEREDPAGEDOWN: + case SCI_STUTTEREDPAGEDOWNEXTEND: + + case SCI_PAGEUP: + case SCI_PAGEUPEXTEND: + case SCI_PAGEDOWN: + case SCI_PAGEDOWNEXTEND: + case SCI_EDITTOGGLEOVERTYPE: + case SCI_CANCEL: + case SCI_DELETEBACK: + case SCI_TAB: + case SCI_BACKTAB: + case SCI_NEWLINE: + case SCI_FORMFEED: + case SCI_VCHOME: + case SCI_VCHOMEEXTEND: + case SCI_VCHOMEWRAP: + case SCI_VCHOMEWRAPEXTEND: + case SCI_ZOOMIN: + case SCI_ZOOMOUT: + case SCI_DELWORDLEFT: + case SCI_DELWORDRIGHT: + case SCI_DELWORDRIGHTEND: + case SCI_DELLINELEFT: + case SCI_DELLINERIGHT: + case SCI_LINECOPY: + case SCI_LINECUT: + case SCI_LINEDELETE: + case SCI_LINETRANSPOSE: + case SCI_LINEDUPLICATE: + case SCI_LOWERCASE: + case SCI_UPPERCASE: + case SCI_LINESCROLLDOWN: + case SCI_LINESCROLLUP: + case SCI_WORDPARTLEFT: + case SCI_WORDPARTLEFTEXTEND: + case SCI_WORDPARTRIGHT: + case SCI_WORDPARTRIGHTEXTEND: + case SCI_DELETEBACKNOTLINE: + case SCI_HOMEDISPLAY: + case SCI_HOMEDISPLAYEXTEND: + case SCI_LINEENDDISPLAY: + case SCI_LINEENDDISPLAYEXTEND: + case SCI_LINEDOWNRECTEXTEND: + case SCI_LINEUPRECTEXTEND: + case SCI_CHARLEFTRECTEXTEND: + case SCI_CHARRIGHTRECTEXTEND: + case SCI_HOMERECTEXTEND: + case SCI_VCHOMERECTEXTEND: + case SCI_LINEENDRECTEXTEND: + case SCI_PAGEUPRECTEXTEND: + case SCI_PAGEDOWNRECTEXTEND: + case SCI_SELECTIONDUPLICATE: + return KeyCommand(iMessage); + + case SCI_BRACEHIGHLIGHT: + SetBraceHighlight(static_cast(wParam), lParam, STYLE_BRACELIGHT); + break; + + case SCI_BRACEBADLIGHT: + SetBraceHighlight(static_cast(wParam), -1, STYLE_BRACEBAD); + break; + + case SCI_BRACEMATCH: + // wParam is position of char to find brace for, + // lParam is maximum amount of text to restyle to find it + return pdoc->BraceMatch(wParam, lParam); + + case SCI_GETVIEWEOL: + return vs.viewEOL; + + case SCI_SETVIEWEOL: + vs.viewEOL = wParam != 0; + InvalidateStyleRedraw(); + break; + + case SCI_SETZOOM: + vs.zoomLevel = wParam; + InvalidateStyleRedraw(); + NotifyZoom(); + break; + + case SCI_GETZOOM: + return vs.zoomLevel; + + case SCI_GETEDGECOLUMN: + return theEdge; + + case SCI_SETEDGECOLUMN: + theEdge = wParam; + InvalidateStyleRedraw(); + break; + + case SCI_GETEDGEMODE: + return vs.edgeState; + + case SCI_SETEDGEMODE: + vs.edgeState = wParam; + InvalidateStyleRedraw(); + break; + + case SCI_GETEDGECOLOUR: + return vs.edgecolour.desired.AsLong(); + + case SCI_SETEDGECOLOUR: + vs.edgecolour.desired = ColourDesired(wParam); + InvalidateStyleRedraw(); + break; + + case SCI_GETDOCPOINTER: + return reinterpret_cast(pdoc); + + case SCI_SETDOCPOINTER: + CancelModes(); + SetDocPointer(reinterpret_cast(lParam)); + return 0; + + case SCI_CREATEDOCUMENT: { + Document *doc = new Document(); + if (doc) { + doc->AddRef(); + } + return reinterpret_cast(doc); + } + + case SCI_ADDREFDOCUMENT: + (reinterpret_cast(lParam))->AddRef(); + break; + + case SCI_RELEASEDOCUMENT: + (reinterpret_cast(lParam))->Release(); + break; + + case SCI_SETMODEVENTMASK: + modEventMask = wParam; + return 0; + + case SCI_GETMODEVENTMASK: + return modEventMask; + + case SCI_CONVERTEOLS: + pdoc->ConvertLineEnds(wParam); + SetSelection(currentPos, anchor); // Ensure selection inside document + return 0; + + case SCI_SETLENGTHFORENCODE: + lengthForEncode = wParam; + return 0; + + case SCI_SELECTIONISRECTANGLE: + return selType == selRectangle ? 1 : 0; + + case SCI_SETSELECTIONMODE: { + switch (wParam) { + case SC_SEL_STREAM: + moveExtendsSelection = !moveExtendsSelection || (selType != selStream); + selType = selStream; + break; + case SC_SEL_RECTANGLE: + moveExtendsSelection = !moveExtendsSelection || (selType != selRectangle); + selType = selRectangle; + break; + case SC_SEL_LINES: + moveExtendsSelection = !moveExtendsSelection || (selType != selLines); + selType = selLines; + break; + default: + moveExtendsSelection = !moveExtendsSelection || (selType != selStream); + selType = selStream; + } + InvalidateSelection(currentPos, anchor, true); + } + case SCI_GETSELECTIONMODE: + switch (selType) { + case selStream: + return SC_SEL_STREAM; + case selRectangle: + return SC_SEL_RECTANGLE; + case selLines: + return SC_SEL_LINES; + default: // ?! + return SC_SEL_STREAM; + } + case SCI_GETLINESELSTARTPOSITION: { + SelectionLineIterator lineIterator(this); + lineIterator.SetAt(wParam); + return lineIterator.startPos; + } + case SCI_GETLINESELENDPOSITION: { + SelectionLineIterator lineIterator(this); + lineIterator.SetAt(wParam); + return lineIterator.endPos; + } + + case SCI_SETOVERTYPE: + inOverstrike = wParam != 0; + break; + + case SCI_GETOVERTYPE: + return inOverstrike ? 1 : 0; + + case SCI_SETFOCUS: + SetFocusState(wParam != 0); + break; + + case SCI_GETFOCUS: + return hasFocus; + + case SCI_SETSTATUS: + errorStatus = wParam; + break; + + case SCI_GETSTATUS: + return errorStatus; + + case SCI_SETMOUSEDOWNCAPTURES: + mouseDownCaptures = wParam != 0; + break; + + case SCI_GETMOUSEDOWNCAPTURES: + return mouseDownCaptures; + + case SCI_SETCURSOR: + cursorMode = wParam; + DisplayCursor(Window::cursorText); + break; + + case SCI_GETCURSOR: + return cursorMode; + + case SCI_SETCONTROLCHARSYMBOL: + controlCharSymbol = wParam; + break; + + case SCI_GETCONTROLCHARSYMBOL: + return controlCharSymbol; + + case SCI_STARTRECORD: + recordingMacro = true; + return 0; + + case SCI_STOPRECORD: + recordingMacro = false; + return 0; + + case SCI_MOVECARETINSIDEVIEW: + MoveCaretInsideView(); + break; + + case SCI_SETFOLDMARGINCOLOUR: + vs.foldmarginColourSet = wParam != 0; + vs.foldmarginColour.desired = ColourDesired(lParam); + InvalidateStyleRedraw(); + break; + + case SCI_SETFOLDMARGINHICOLOUR: + vs.foldmarginHighlightColourSet = wParam != 0; + vs.foldmarginHighlightColour.desired = ColourDesired(lParam); + InvalidateStyleRedraw(); + break; + + case SCI_SETHOTSPOTACTIVEFORE: + vs.hotspotForegroundSet = wParam != 0; + vs.hotspotForeground.desired = ColourDesired(lParam); + InvalidateStyleRedraw(); + break; + + case SCI_GETHOTSPOTACTIVEFORE: + return vs.hotspotForeground.desired.AsLong(); + + case SCI_SETHOTSPOTACTIVEBACK: + vs.hotspotBackgroundSet = wParam != 0; + vs.hotspotBackground.desired = ColourDesired(lParam); + InvalidateStyleRedraw(); + break; + + case SCI_GETHOTSPOTACTIVEBACK: + return vs.hotspotBackground.desired.AsLong(); + + case SCI_SETHOTSPOTACTIVEUNDERLINE: + vs.hotspotUnderline = wParam != 0; + InvalidateStyleRedraw(); + break; + + case SCI_GETHOTSPOTACTIVEUNDERLINE: + return vs.hotspotUnderline ? 1 : 0; + + case SCI_SETHOTSPOTSINGLELINE: + vs.hotspotSingleLine = wParam != 0; + InvalidateStyleRedraw(); + break; + + case SCI_GETHOTSPOTSINGLELINE: + return vs.hotspotSingleLine ? 1 : 0; + + case SCI_SETPASTECONVERTENDINGS: + convertPastes = wParam != 0; + break; + + case SCI_GETPASTECONVERTENDINGS: + return convertPastes ? 1 : 0; + + default: + return DefWndProc(iMessage, wParam, lParam); + } + //Platform::DebugPrintf("end wnd proc\n"); + return 0l; +} diff --git a/scintilla/src/Editor.h b/scintilla/src/Editor.h new file mode 100644 index 00000000..03ae1071 --- /dev/null +++ b/scintilla/src/Editor.h @@ -0,0 +1,523 @@ +// Scintilla source code edit control +/** @file Editor.h + ** Defines the main editor class. + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef EDITOR_H +#define EDITOR_H + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +/** + */ +class Caret { +public: + bool active; + bool on; + int period; + + Caret(); +}; + +/** + */ +class Timer { +public: + bool ticking; + int ticksToWait; + enum {tickSize = 100}; + TickerID tickerID; + + Timer(); +}; + +/** + */ +class Idler { +public: + bool state; + IdlerID idlerID; + + Idler(); +}; + +/** + * Hold a piece of text selected for copying or dragging. + * The text is expected to hold a terminating '\0' and this is counted in len. + */ +class SelectionText { +public: + char *s; + int len; + bool rectangular; + bool lineCopy; + int codePage; + int characterSet; + SelectionText() : s(0), len(0), rectangular(false), lineCopy(false), codePage(0), characterSet(0) {} + ~SelectionText() { + Free(); + } + void Free() { + Set(0, 0, 0, 0, false, false); + } + void Set(char *s_, int len_, int codePage_, int characterSet_, bool rectangular_, bool lineCopy_) { + delete []s; + s = s_; + if (s) + len = len_; + else + len = 0; + codePage = codePage_; + characterSet = characterSet_; + rectangular = rectangular_; + lineCopy = lineCopy_; + } + void Copy(const char *s_, int len_, int codePage_, int characterSet_, bool rectangular_, bool lineCopy_) { + delete []s; + s = new char[len_]; + if (s) { + len = len_; + for (int i = 0; i < len_; i++) { + s[i] = s_[i]; + } + } else { + len = 0; + } + codePage = codePage_; + characterSet = characterSet_; + rectangular = rectangular_; + lineCopy = lineCopy_; + } + void Copy(const SelectionText &other) { + Copy(other.s, other.len, other.codePage, other.characterSet, other.rectangular, other.lineCopy); + } +}; + +/** + */ +class Editor : public DocWatcher { + // Private so Editor objects can not be copied + Editor(const Editor &) : DocWatcher() {} + Editor &operator=(const Editor &) { return *this; } + +protected: // ScintillaBase subclass needs access to much of Editor + + /** On GTK+, Scintilla is a container widget holding two scroll bars + * whereas on Windows there is just one window with both scroll bars turned on. */ + Window wMain; ///< The Scintilla parent window + + /** Style resources may be expensive to allocate so are cached between uses. + * When a style attribute is changed, this cache is flushed. */ + bool stylesValid; + ViewStyle vs; + Palette palette; + + int printMagnification; + int printColourMode; + int printWrapState; + int cursorMode; + int controlCharSymbol; + + bool hasFocus; + bool hideSelection; + bool inOverstrike; + int errorStatus; + bool mouseDownCaptures; + + /** In bufferedDraw mode, graphics operations are drawn to a pixmap and then copied to + * the screen. This avoids flashing but is about 30% slower. */ + bool bufferedDraw; + /** In twoPhaseDraw mode, drawing is performed in two phases, first the background + * and then the foreground. This avoids chopping off characters that overlap the next run. */ + bool twoPhaseDraw; + + int xOffset; ///< Horizontal scrolled amount in pixels + int xCaretMargin; ///< Ensure this many pixels visible on both sides of caret + bool horizontalScrollBarVisible; + int scrollWidth; + bool trackLineWidth; + int lineWidthMaxSeen; + bool verticalScrollBarVisible; + bool endAtLastLine; + bool caretSticky; + + Surface *pixmapLine; + Surface *pixmapSelMargin; + Surface *pixmapSelPattern; + Surface *pixmapIndentGuide; + Surface *pixmapIndentGuideHighlight; + + LineLayoutCache llc; + PositionCache posCache; + + KeyMap kmap; + + Caret caret; + Timer timer; + Timer autoScrollTimer; + enum { autoScrollDelay = 200 }; + + Idler idler; + + Point lastClick; + unsigned int lastClickTime; + int dwellDelay; + int ticksToDwell; + bool dwelling; + enum { selChar, selWord, selLine } selectionType; + Point ptMouseLast; + enum { ddNone, ddInitial, ddDragging } inDragDrop; + bool dropWentOutside; + int posDrag; + int posDrop; + int lastXChosen; + int lineAnchor; + int originalAnchorPos; + int currentPos; + int anchor; + int targetStart; + int targetEnd; + int searchFlags; + int topLine; + int posTopLine; + int lengthForEncode; + + bool needUpdateUI; + Position braces[2]; + int bracesMatchStyle; + int highlightGuideColumn; + + int theEdge; + + enum { notPainting, painting, paintAbandoned } paintState; + PRectangle rcPaint; + bool paintingAllText; + + int modEventMask; + + SelectionText drag; + enum selTypes { noSel, selStream, selRectangle, selLines }; + selTypes selType; + bool moveExtendsSelection; + int xStartSelect; ///< x position of start of rectangular selection + int xEndSelect; ///< x position of end of rectangular selection + bool primarySelection; + + int caretXPolicy; + int caretXSlop; ///< Ensure this many pixels visible on both sides of caret + + int caretYPolicy; + int caretYSlop; ///< Ensure this many lines visible on both sides of caret + + int visiblePolicy; + int visibleSlop; + + int searchAnchor; + + bool recordingMacro; + + int foldFlags; + ContractionState cs; + + // Hotspot support + int hsStart; + int hsEnd; + + // Wrapping support + enum { eWrapNone, eWrapWord, eWrapChar } wrapState; + enum { wrapLineLarge = 0x7ffffff }; + int wrapWidth; + int wrapStart; + int wrapEnd; + int wrapVisualFlags; + int wrapVisualFlagsLocation; + int wrapVisualStartIndent; + int actualWrapVisualStartIndent; + + bool convertPastes; + + Document *pdoc; + + Editor(); + virtual ~Editor(); + virtual void Initialise() = 0; + virtual void Finalise(); + + void InvalidateStyleData(); + void InvalidateStyleRedraw(); + virtual void RefreshColourPalette(Palette &pal, bool want); + void RefreshStyleData(); + void DropGraphics(); + + virtual PRectangle GetClientRectangle(); + PRectangle GetTextRectangle(); + + int LinesOnScreen(); + int LinesToScroll(); + int MaxScrollPos(); + Point LocationFromPosition(int pos); + int XFromPosition(int pos); + int PositionFromLocation(Point pt); + int PositionFromLocationClose(Point pt); + int PositionFromLineX(int line, int x); + int LineFromLocation(Point pt); + void SetTopLine(int topLineNew); + + bool AbandonPaint(); + void RedrawRect(PRectangle rc); + void Redraw(); + void RedrawSelMargin(int line=-1); + PRectangle RectangleFromRange(int start, int end); + void InvalidateRange(int start, int end); + + int CurrentPosition(); + bool SelectionEmpty(); + int SelectionStart(); + int SelectionEnd(); + void SetRectangularRange(); + void InvalidateSelection(int currentPos_, int anchor_, bool invalidateWholeSelection); + void SetSelection(int currentPos_, int anchor_); + void SetSelection(int currentPos_); + void SetEmptySelection(int currentPos_); + bool RangeContainsProtected(int start, int end) const; + bool SelectionContainsProtected(); + int MovePositionOutsideChar(int pos, int moveDir, bool checkLineEnd=true); + int MovePositionTo(int newPos, selTypes sel=noSel, bool ensureVisible=true); + int MovePositionSoVisible(int pos, int moveDir); + void SetLastXChosen(); + + void ScrollTo(int line, bool moveThumb=true); + virtual void ScrollText(int linesToMove); + void HorizontalScrollTo(int xPos); + void MoveCaretInsideView(bool ensureVisible=true); + int DisplayFromPosition(int pos); + void EnsureCaretVisible(bool useMargin=true, bool vert=true, bool horiz=true); + void ShowCaretAtCurrentPosition(); + void DropCaret(); + void InvalidateCaret(); + virtual void UpdateSystemCaret(); + + void NeedWrapping(int docLineStart = 0, int docLineEnd = wrapLineLarge); + bool WrapOneLine(Surface *surface, int lineToWrap); + bool WrapLines(bool fullWrap, int priorityWrapLineStart); + void LinesJoin(); + void LinesSplit(int pixelWidth); + + int SubstituteMarkerIfEmpty(int markerCheck, int markerDefault); + void PaintSelMargin(Surface *surface, PRectangle &rc); + LineLayout *RetrieveLineLayout(int lineNumber); + void LayoutLine(int line, Surface *surface, ViewStyle &vstyle, LineLayout *ll, + int width=LineLayout::wrapWidthInfinite); + ColourAllocated SelectionBackground(ViewStyle &vsDraw); + ColourAllocated TextBackground(ViewStyle &vsDraw, bool overrideBackground, ColourAllocated background, bool inSelection, bool inHotspot, int styleMain, int i, LineLayout *ll); + void DrawIndentGuide(Surface *surface, int lineVisible, int lineHeight, int start, PRectangle rcSegment, bool highlight); + void DrawWrapMarker(Surface *surface, PRectangle rcPlace, bool isEndMarker, ColourAllocated wrapColour); + void DrawEOL(Surface *surface, ViewStyle &vsDraw, PRectangle rcLine, LineLayout *ll, + int line, int lineEnd, int xStart, int subLine, int subLineStart, + bool overrideBackground, ColourAllocated background, + bool drawWrapMark, ColourAllocated wrapColour); + void DrawIndicators(Surface *surface, ViewStyle &vsDraw, int line, int xStart, + PRectangle rcLine, LineLayout *ll, int subLine, int lineEnd, bool under); + void DrawLine(Surface *surface, ViewStyle &vsDraw, int line, int lineVisible, int xStart, + PRectangle rcLine, LineLayout *ll, int subLine=0); + void DrawBlockCaret(Surface *surface, ViewStyle &vsDraw, LineLayout *ll, int subLine, int xStart, int offset, int posCaret, PRectangle rcCaret); + void RefreshPixMaps(Surface *surfaceWindow); + void Paint(Surface *surfaceWindow, PRectangle rcArea); + long FormatRange(bool draw, RangeToFormat *pfr); + int TextWidth(int style, const char *text); + + virtual void SetVerticalScrollPos() = 0; + virtual void SetHorizontalScrollPos() = 0; + virtual bool ModifyScrollBars(int nMax, int nPage) = 0; + virtual void ReconfigureScrollBars(); + void SetScrollBars(); + void ChangeSize(); + + void AddChar(char ch); + virtual void AddCharUTF(char *s, unsigned int len, bool treatAsDBCS=false); + void ClearSelection(); + void ClearAll(); + void ClearDocumentStyle(); + void Cut(); + void PasteRectangular(int pos, const char *ptr, int len); + virtual void Copy() = 0; + virtual void CopyAllowLine(); + virtual bool CanPaste(); + virtual void Paste() = 0; + void Clear(); + void SelectAll(); + void Undo(); + void Redo(); + void DelChar(); + void DelCharBack(bool allowLineStartDeletion); + virtual void ClaimSelection() = 0; + + virtual void NotifyChange() = 0; + virtual void NotifyFocus(bool focus); + virtual int GetCtrlID() { return ctrlID; } + virtual void NotifyParent(SCNotification scn) = 0; + virtual void NotifyStyleToNeeded(int endStyleNeeded); + void NotifyChar(int ch); + void NotifyMove(int position); + void NotifySavePoint(bool isSavePoint); + void NotifyModifyAttempt(); + virtual void NotifyDoubleClick(Point pt, bool shift, bool ctrl, bool alt); + void NotifyHotSpotClicked(int position, bool shift, bool ctrl, bool alt); + void NotifyHotSpotDoubleClicked(int position, bool shift, bool ctrl, bool alt); + void NotifyUpdateUI(); + void NotifyPainted(); + void NotifyScrolled(); + void NotifyIndicatorClick(bool click, int position, bool shift, bool ctrl, bool alt); + bool NotifyMarginClick(Point pt, bool shift, bool ctrl, bool alt); + void NotifyNeedShown(int pos, int len); + void NotifyDwelling(Point pt, bool state); + void NotifyZoom(); + + void NotifyModifyAttempt(Document *document, void *userData); + void NotifySavePoint(Document *document, void *userData, bool atSavePoint); + void CheckModificationForWrap(DocModification mh); + void NotifyModified(Document *document, DocModification mh, void *userData); + void NotifyDeleted(Document *document, void *userData); + void NotifyStyleNeeded(Document *doc, void *userData, int endPos); + void NotifyMacroRecord(unsigned int iMessage, uptr_t wParam, sptr_t lParam); + + void PageMove(int direction, selTypes sel=noSel, bool stuttered = false); + void ChangeCaseOfSelection(bool makeUpperCase); + void LineTranspose(); + void Duplicate(bool forLine); + virtual void CancelModes(); + void NewLine(); + void CursorUpOrDown(int direction, selTypes sel=noSel); + void ParaUpOrDown(int direction, selTypes sel=noSel); + int StartEndDisplayLine(int pos, bool start); + virtual int KeyCommand(unsigned int iMessage); + virtual int KeyDefault(int /* key */, int /*modifiers*/); + int KeyDown(int key, bool shift, bool ctrl, bool alt, bool *consumed=0); + + int GetWhitespaceVisible(); + void SetWhitespaceVisible(int view); + + void Indent(bool forwards); + + long FindText(uptr_t wParam, sptr_t lParam); + void SearchAnchor(); + long SearchText(unsigned int iMessage, uptr_t wParam, sptr_t lParam); + long SearchInTarget(const char *text, int length); + void GoToLine(int lineNo); + + virtual void CopyToClipboard(const SelectionText &selectedText) = 0; + char *CopyRange(int start, int end); + void CopySelectionFromRange(SelectionText *ss, bool allowLineCopy, int start, int end); + void CopySelectionRange(SelectionText *ss, bool allowLineCopy=false); + void CopyRangeToClipboard(int start, int end); + void CopyText(int length, const char *text); + void SetDragPosition(int newPos); + virtual void DisplayCursor(Window::Cursor c); + virtual bool DragThreshold(Point ptStart, Point ptNow); + virtual void StartDrag(); + void DropAt(int position, const char *value, bool moving, bool rectangular); + /** PositionInSelection returns 0 if position in selection, -1 if position before selection, and 1 if after. + * Before means either before any line of selection or before selection on its line, with a similar meaning to after. */ + int PositionInSelection(int pos); + bool PointInSelection(Point pt); + bool PointInSelMargin(Point pt); + void LineSelection(int lineCurrent_, int lineAnchor_); + void DwellEnd(bool mouseMoved); + virtual void ButtonDown(Point pt, unsigned int curTime, bool shift, bool ctrl, bool alt); + void ButtonMove(Point pt); + void ButtonUp(Point pt, unsigned int curTime, bool ctrl); + + void Tick(); + bool Idle(); + virtual void SetTicking(bool on) = 0; + virtual bool SetIdle(bool) { return false; } + virtual void SetMouseCapture(bool on) = 0; + virtual bool HaveMouseCapture() = 0; + void SetFocusState(bool focusState); + + virtual bool PaintContains(PRectangle rc); + bool PaintContainsMargin(); + void CheckForChangeOutsidePaint(Range r); + void SetBraceHighlight(Position pos0, Position pos1, int matchStyle); + + void SetDocPointer(Document *document); + + void Expand(int &line, bool doExpand); + void ToggleContraction(int line); + void EnsureLineVisible(int lineDoc, bool enforcePolicy); + int ReplaceTarget(bool replacePatterns, const char *text, int length=-1); + + bool PositionIsHotspot(int position); + bool PointIsHotspot(Point pt); + void SetHotSpotRange(Point *pt); + void GetHotSpotRange(int& hsStart, int& hsEnd); + + int CodePage() const; + virtual bool ValidCodePage(int /* codePage */) const { return true; } + int WrapCount(int line); + void AddStyledText(char *buffer, int appendLength); + + virtual sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) = 0; + void StyleSetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam); + sptr_t StyleGetMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam); + + static const char *StringFromEOLMode(int eolMode); + +public: + // Public so the COM thunks can access it. + bool IsUnicodeMode() const; + // Public so scintilla_send_message can use it. + virtual sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam); + // Public so scintilla_set_id can use it. + int ctrlID; + friend class AutoSurface; + friend class SelectionLineIterator; +}; + +/** + * A smart pointer class to ensure Surfaces are set up and deleted correctly. + */ +class AutoSurface { +private: + Surface *surf; +public: + AutoSurface(Editor *ed) : surf(0) { + if (ed->wMain.GetID()) { + surf = Surface::Allocate(); + if (surf) { + surf->Init(ed->wMain.GetID()); + surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage()); + surf->SetDBCSMode(ed->CodePage()); + } + } + } + AutoSurface(SurfaceID sid, Editor *ed) : surf(0) { + if (ed->wMain.GetID()) { + surf = Surface::Allocate(); + if (surf) { + surf->Init(sid, ed->wMain.GetID()); + surf->SetUnicodeMode(SC_CP_UTF8 == ed->CodePage()); + surf->SetDBCSMode(ed->CodePage()); + } + } + } + ~AutoSurface() { + delete surf; + } + Surface *operator->() const { + return surf; + } + operator Surface *() const { + return surf; + } +}; + +#ifdef SCI_NAMESPACE +} +#endif + +#endif diff --git a/scintilla/src/ExternalLexer.cxx b/scintilla/src/ExternalLexer.cxx new file mode 100644 index 00000000..c0fad149 --- /dev/null +++ b/scintilla/src/ExternalLexer.cxx @@ -0,0 +1,263 @@ +// Scintilla source code edit control +/** @file ExternalLexer.cxx + ** Support external lexers in DLLs. + **/ +// Copyright 2001 Simon Steele , portions copyright Neil Hodgson. +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include + +#include "Platform.h" + +#include "Scintilla.h" + +#include "SciLexer.h" +#include "PropSet.h" +#include "Accessor.h" +#include "DocumentAccessor.h" +#include "KeyWords.h" +#include "ExternalLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +LexerManager *LexerManager::theInstance = NULL; + +//------------------------------------------ +// +// ExternalLexerModule +// +//------------------------------------------ + +char **WordListsToStrings(WordList *val[]) { + int dim = 0; + while (val[dim]) + dim++; + char **wls = new char * [dim + 1]; + for (int i = 0;i < dim;i++) { + SString words; + words = ""; + for (int n = 0; n < val[i]->len; n++) { + words += val[i]->words[n]; + if (n != val[i]->len - 1) + words += " "; + } + wls[i] = new char[words.length() + 1]; + strcpy(wls[i], words.c_str()); + } + wls[dim] = 0; + return wls; +} + +void DeleteWLStrings(char *strs[]) { + int dim = 0; + while (strs[dim]) { + delete strs[dim]; + dim++; + } + delete [] strs; +} + +void ExternalLexerModule::Lex(unsigned int startPos, int lengthDoc, int initStyle, + WordList *keywordlists[], Accessor &styler) const { + if (!fneLexer) + return ; + + char **kwds = WordListsToStrings(keywordlists); + char *ps = styler.GetProperties(); + + // The accessor passed in is always a DocumentAccessor so this cast and the subsequent + // access will work. Can not use the stricter dynamic_cast as that requires RTTI. + DocumentAccessor &da = static_cast(styler); + WindowID wID = da.GetWindow(); + + fneLexer(externalLanguage, startPos, lengthDoc, initStyle, kwds, wID, ps); + + delete ps; + DeleteWLStrings(kwds); +} + +void ExternalLexerModule::Fold(unsigned int startPos, int lengthDoc, int initStyle, + WordList *keywordlists[], Accessor &styler) const { + if (!fneFolder) + return ; + + char **kwds = WordListsToStrings(keywordlists); + char *ps = styler.GetProperties(); + + // The accessor passed in is always a DocumentAccessor so this cast and the subsequent + // access will work. Can not use the stricter dynamic_cast as that requires RTTI. + DocumentAccessor &da = static_cast(styler); + WindowID wID = da.GetWindow(); + + fneFolder(externalLanguage, startPos, lengthDoc, initStyle, kwds, wID, ps); + + delete ps; + DeleteWLStrings(kwds); +} + +void ExternalLexerModule::SetExternal(ExtLexerFunction fLexer, ExtFoldFunction fFolder, int index) { + fneLexer = fLexer; + fneFolder = fFolder; + externalLanguage = index; +} + +//------------------------------------------ +// +// LexerLibrary +// +//------------------------------------------ + +LexerLibrary::LexerLibrary(const char* ModuleName) { + // Initialise some members... + first = NULL; + last = NULL; + + // Load the DLL + lib = DynamicLibrary::Load(ModuleName); + if (lib->IsValid()) { + m_sModuleName = ModuleName; + //Cannot use reinterpret_cast because: ANSI C++ forbids casting between pointers to functions and objects + GetLexerCountFn GetLexerCount = (GetLexerCountFn)(sptr_t)lib->FindFunction("GetLexerCount"); + + if (GetLexerCount) { + ExternalLexerModule *lex; + LexerMinder *lm; + + // Find functions in the DLL + GetLexerNameFn GetLexerName = (GetLexerNameFn)(sptr_t)lib->FindFunction("GetLexerName"); + ExtLexerFunction Lexer = (ExtLexerFunction)(sptr_t)lib->FindFunction("Lex"); + ExtFoldFunction Folder = (ExtFoldFunction)(sptr_t)lib->FindFunction("Fold"); + + // Assign a buffer for the lexer name. + char lexname[100]; + strcpy(lexname, ""); + + int nl = GetLexerCount(); + + for (int i = 0; i < nl; i++) { + GetLexerName(i, lexname, 100); + lex = new ExternalLexerModule(SCLEX_AUTOMATIC, NULL, lexname, NULL); + + // Create a LexerMinder so we don't leak the ExternalLexerModule... + lm = new LexerMinder; + lm->self = lex; + lm->next = NULL; + if (first != NULL) { + last->next = lm; + last = lm; + } else { + first = lm; + last = lm; + } + + // The external lexer needs to know how to call into its DLL to + // do its lexing and folding, we tell it here. Folder may be null. + lex->SetExternal(Lexer, Folder, i); + } + } + } + next = NULL; +} + +LexerLibrary::~LexerLibrary() { + Release(); + delete lib; +} + +void LexerLibrary::Release() { + //TODO maintain a list of lexers created, and delete them! + LexerMinder *lm; + LexerMinder *next; + lm = first; + while (NULL != lm) { + next = lm->next; + delete lm->self; + delete lm; + lm = next; + } + + first = NULL; + last = NULL; +} + +//------------------------------------------ +// +// LexerManager +// +//------------------------------------------ + +/// Return the single LexerManager instance... +LexerManager *LexerManager::GetInstance() { + if(!theInstance) + theInstance = new LexerManager; + return theInstance; +} + +/// Delete any LexerManager instance... +void LexerManager::DeleteInstance() +{ + if(theInstance) { + delete theInstance; + theInstance = NULL; + } +} + +/// protected constructor - this is a singleton... +LexerManager::LexerManager() { + first = NULL; + last = NULL; +} + +LexerManager::~LexerManager() { + Clear(); +} + +void LexerManager::Load(const char* path) +{ + LoadLexerLibrary(path); +} + +void LexerManager::LoadLexerLibrary(const char* module) +{ + LexerLibrary *lib = new LexerLibrary(module); + if (NULL != first) { + last->next = lib; + last = lib; + } else { + first = lib; + last = lib; + } +} + +void LexerManager::Clear() +{ + if (NULL != first) { + LexerLibrary *cur = first; + LexerLibrary *next; + while (cur) { + next = cur->next; + delete cur; + cur = next; + } + first = NULL; + last = NULL; + } +} + +//------------------------------------------ +// +// LexerManager +// +//------------------------------------------ + +LMMinder::~LMMinder() +{ + LexerManager::DeleteInstance(); +} + +LMMinder minder; diff --git a/scintilla/src/ExternalLexer.h b/scintilla/src/ExternalLexer.h new file mode 100644 index 00000000..b72f7a20 --- /dev/null +++ b/scintilla/src/ExternalLexer.h @@ -0,0 +1,103 @@ +// Scintilla source code edit control +/** @file ExternalLexer.h + ** Support external lexers in DLLs. + **/ +// Copyright 2001 Simon Steele , portions copyright Neil Hodgson. +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef EXTERNALLEXER_H +#define EXTERNALLEXER_H + +#if PLAT_WIN +#define EXT_LEXER_DECL __stdcall +#else +#define EXT_LEXER_DECL +#endif + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +// External Lexer function definitions... +typedef void (EXT_LEXER_DECL *ExtLexerFunction)(unsigned int lexer, unsigned int startPos, int length, int initStyle, + char *words[], WindowID window, char *props); +typedef void (EXT_LEXER_DECL *ExtFoldFunction)(unsigned int lexer, unsigned int startPos, int length, int initStyle, + char *words[], WindowID window, char *props); +typedef void* (EXT_LEXER_DECL *GetLexerFunction)(unsigned int Index); +typedef int (EXT_LEXER_DECL *GetLexerCountFn)(); +typedef void (EXT_LEXER_DECL *GetLexerNameFn)(unsigned int Index, char *name, int buflength); + +//class DynamicLibrary; + +/// Sub-class of LexerModule to use an external lexer. +class ExternalLexerModule : protected LexerModule { +protected: + ExtLexerFunction fneLexer; + ExtFoldFunction fneFolder; + int externalLanguage; + char name[100]; +public: + ExternalLexerModule(int language_, LexerFunction fnLexer_, + const char *languageName_=0, LexerFunction fnFolder_=0) : LexerModule(language_, fnLexer_, 0, fnFolder_){ + strncpy(name, languageName_, sizeof(name)); + languageName = name; + }; + virtual void Lex(unsigned int startPos, int lengthDoc, int initStyle, + WordList *keywordlists[], Accessor &styler) const; + virtual void Fold(unsigned int startPos, int lengthDoc, int initStyle, + WordList *keywordlists[], Accessor &styler) const; + virtual void SetExternal(ExtLexerFunction fLexer, ExtFoldFunction fFolder, int index); +}; + +/// LexerMinder points to an ExternalLexerModule - so we don't leak them. +class LexerMinder { +public: + ExternalLexerModule *self; + LexerMinder *next; +}; + +/// LexerLibrary exists for every External Lexer DLL, contains LexerMinders. +class LexerLibrary { + DynamicLibrary *lib; + LexerMinder *first; + LexerMinder *last; + +public: + LexerLibrary(const char* ModuleName); + ~LexerLibrary(); + void Release(); + + LexerLibrary *next; + SString m_sModuleName; +}; + +/// LexerManager manages external lexers, contains LexerLibrarys. +class LexerManager { +public: + ~LexerManager(); + + static LexerManager *GetInstance(); + static void DeleteInstance(); + + void Load(const char* path); + void Clear(); + +private: + LexerManager(); + static LexerManager *theInstance; + + void LoadLexerLibrary(const char* module); + LexerLibrary *first; + LexerLibrary *last; +}; + +class LMMinder { +public: + ~LMMinder(); +}; + +#ifdef SCI_NAMESPACE +} +#endif + +#endif diff --git a/scintilla/src/Indicator.cxx b/scintilla/src/Indicator.cxx new file mode 100644 index 00000000..e059f150 --- /dev/null +++ b/scintilla/src/Indicator.cxx @@ -0,0 +1,82 @@ +// Scintilla source code edit control +/** @file Indicator.cxx + ** Defines the style of indicators which are text decorations such as underlining. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include "Platform.h" + +#include "Scintilla.h" +#include "Indicator.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +void Indicator::Draw(Surface *surface, const PRectangle &rc, const PRectangle &rcLine) { + surface->PenColour(fore.allocated); + int ymid = (rc.bottom + rc.top) / 2; + if (style == INDIC_SQUIGGLE) { + surface->MoveTo(rc.left, rc.top); + int x = rc.left + 2; + int y = 2; + while (x < rc.right) { + surface->LineTo(x, rc.top + y); + x += 2; + y = 2 - y; + } + surface->LineTo(rc.right, rc.top + y); // Finish the line + } else if (style == INDIC_TT) { + surface->MoveTo(rc.left, ymid); + int x = rc.left + 5; + while (x < rc.right) { + surface->LineTo(x, ymid); + surface->MoveTo(x-3, ymid); + surface->LineTo(x-3, ymid+2); + x++; + surface->MoveTo(x, ymid); + x += 5; + } + surface->LineTo(rc.right, ymid); // Finish the line + if (x - 3 <= rc.right) { + surface->MoveTo(x-3, ymid); + surface->LineTo(x-3, ymid+2); + } + } else if (style == INDIC_DIAGONAL) { + int x = rc.left; + while (x < rc.right) { + surface->MoveTo(x, rc.top+2); + int endX = x+3; + int endY = rc.top - 1; + if (endX > rc.right) { + endY += endX - rc.right; + endX = rc.right; + } + surface->LineTo(endX, endY); + x += 4; + } + } else if (style == INDIC_STRIKE) { + surface->MoveTo(rc.left, rc.top - 4); + surface->LineTo(rc.right, rc.top - 4); + } else if (style == INDIC_HIDDEN) { + // Draw nothing + } else if (style == INDIC_BOX) { + surface->MoveTo(rc.left, ymid+1); + surface->LineTo(rc.right, ymid+1); + surface->LineTo(rc.right, rcLine.top+1); + surface->LineTo(rc.left, rcLine.top+1); + surface->LineTo(rc.left, ymid+1); + } else if (style == INDIC_ROUNDBOX) { + PRectangle rcBox = rcLine; + rcBox.top = rcLine.top + 1; + rcBox.left = rc.left; + rcBox.right = rc.right; + surface->AlphaRectangle(rcBox, 1, fore.allocated, alpha, fore.allocated, ((alpha>SC_ALPHA_OPAQUE-20)?SC_ALPHA_OPAQUE:(alpha+20)), 0); + } else { // Either INDIC_PLAIN or unknown + surface->MoveTo(rc.left, ymid); + surface->LineTo(rc.right, ymid); + } +} + + diff --git a/scintilla/src/Indicator.h b/scintilla/src/Indicator.h new file mode 100644 index 00000000..765a416b --- /dev/null +++ b/scintilla/src/Indicator.h @@ -0,0 +1,32 @@ +// Scintilla source code edit control +/** @file Indicator.h + ** Defines the style of indicators which are text decorations such as underlining. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef INDICATOR_H +#define INDICATOR_H + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +/** + */ +class Indicator { +public: + int style; + int alpha; + bool under; + ColourPair fore; + Indicator() : style(INDIC_PLAIN), alpha(30), under(false), fore(ColourDesired(0,0,0)) { + } + void Draw(Surface *surface, const PRectangle &rc, const PRectangle &rcLine); +}; + +#ifdef SCI_NAMESPACE +} +#endif + +#endif diff --git a/scintilla/src/KeyMap.cxx b/scintilla/src/KeyMap.cxx new file mode 100644 index 00000000..38a4e240 --- /dev/null +++ b/scintilla/src/KeyMap.cxx @@ -0,0 +1,153 @@ +// Scintilla source code edit control +/** @file KeyMap.cxx + ** Defines a mapping between keystrokes and commands. + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include "Platform.h" + +#include "Scintilla.h" + +#include "KeyMap.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +KeyMap::KeyMap() : kmap(0), len(0), alloc(0) { + for (int i = 0; MapDefault[i].key; i++) { + AssignCmdKey(MapDefault[i].key, + MapDefault[i].modifiers, + MapDefault[i].msg); + } +} + +KeyMap::~KeyMap() { + Clear(); +} + +void KeyMap::Clear() { + delete []kmap; + kmap = 0; + len = 0; + alloc = 0; +} + +void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) { + if ((len+1) >= alloc) { + KeyToCommand *ktcNew = new KeyToCommand[alloc + 5]; + if (!ktcNew) + return; + for (int k = 0; k < len; k++) + ktcNew[k] = kmap[k]; + alloc += 5; + delete []kmap; + kmap = ktcNew; + } + for (int keyIndex = 0; keyIndex < len; keyIndex++) { + if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) { + kmap[keyIndex].msg = msg; + return; + } + } + kmap[len].key = key; + kmap[len].modifiers = modifiers; + kmap[len].msg = msg; + len++; +} + +unsigned int KeyMap::Find(int key, int modifiers) { + for (int i = 0; i < len; i++) { + if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) { + return kmap[i].msg; + } + } + return 0; +} + +const KeyToCommand KeyMap::MapDefault[] = { + {SCK_DOWN, SCI_NORM, SCI_LINEDOWN}, + {SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND}, + {SCK_DOWN, SCI_CTRL, SCI_LINESCROLLDOWN}, + {SCK_DOWN, SCI_ASHIFT, SCI_LINEDOWNRECTEXTEND}, + {SCK_UP, SCI_NORM, SCI_LINEUP}, + {SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND}, + {SCK_UP, SCI_CTRL, SCI_LINESCROLLUP}, + {SCK_UP, SCI_ASHIFT, SCI_LINEUPRECTEXTEND}, + {'[', SCI_CTRL, SCI_PARAUP}, + {'[', SCI_CSHIFT, SCI_PARAUPEXTEND}, + {']', SCI_CTRL, SCI_PARADOWN}, + {']', SCI_CSHIFT, SCI_PARADOWNEXTEND}, + {SCK_LEFT, SCI_NORM, SCI_CHARLEFT}, + {SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND}, + {SCK_LEFT, SCI_CTRL, SCI_WORDLEFT}, + {SCK_LEFT, SCI_CSHIFT, SCI_WORDLEFTEXTEND}, + {SCK_LEFT, SCI_ASHIFT, SCI_CHARLEFTRECTEXTEND}, + {SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT}, + {SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND}, + {SCK_RIGHT, SCI_CTRL, SCI_WORDRIGHT}, + {SCK_RIGHT, SCI_CSHIFT, SCI_WORDRIGHTEXTEND}, + {SCK_RIGHT, SCI_ASHIFT, SCI_CHARRIGHTRECTEXTEND}, + {'/', SCI_CTRL, SCI_WORDPARTLEFT}, + {'/', SCI_CSHIFT, SCI_WORDPARTLEFTEXTEND}, + {'\\', SCI_CTRL, SCI_WORDPARTRIGHT}, + {'\\', SCI_CSHIFT, SCI_WORDPARTRIGHTEXTEND}, + {SCK_HOME, SCI_NORM, SCI_VCHOME}, + {SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND}, + {SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART}, + {SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND}, + {SCK_HOME, SCI_ALT, SCI_HOMEDISPLAY}, +// {SCK_HOME, SCI_ASHIFT, SCI_HOMEDISPLAYEXTEND}, + {SCK_HOME, SCI_ASHIFT, SCI_VCHOMERECTEXTEND}, + {SCK_END, SCI_NORM, SCI_LINEEND}, + {SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND}, + {SCK_END, SCI_CTRL, SCI_DOCUMENTEND}, + {SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND}, + {SCK_END, SCI_ALT, SCI_LINEENDDISPLAY}, +// {SCK_END, SCI_ASHIFT, SCI_LINEENDDISPLAYEXTEND}, + {SCK_END, SCI_ASHIFT, SCI_LINEENDRECTEXTEND}, + {SCK_PRIOR, SCI_NORM, SCI_PAGEUP}, + {SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND}, + {SCK_PRIOR, SCI_ASHIFT, SCI_PAGEUPRECTEXTEND}, + {SCK_NEXT, SCI_NORM, SCI_PAGEDOWN}, + {SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND}, + {SCK_NEXT, SCI_ASHIFT, SCI_PAGEDOWNRECTEXTEND}, + {SCK_DELETE, SCI_NORM, SCI_CLEAR}, + {SCK_DELETE, SCI_SHIFT, SCI_CUT}, + {SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT}, + {SCK_DELETE, SCI_CSHIFT, SCI_DELLINERIGHT}, + {SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE}, + {SCK_INSERT, SCI_SHIFT, SCI_PASTE}, + {SCK_INSERT, SCI_CTRL, SCI_COPY}, + {SCK_ESCAPE, SCI_NORM, SCI_CANCEL}, + {SCK_BACK, SCI_NORM, SCI_DELETEBACK}, + {SCK_BACK, SCI_SHIFT, SCI_DELETEBACK}, + {SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT}, + {SCK_BACK, SCI_ALT, SCI_UNDO}, + {SCK_BACK, SCI_CSHIFT, SCI_DELLINELEFT}, + {'Z', SCI_CTRL, SCI_UNDO}, + {'Y', SCI_CTRL, SCI_REDO}, + {'X', SCI_CTRL, SCI_CUT}, + {'C', SCI_CTRL, SCI_COPY}, + {'V', SCI_CTRL, SCI_PASTE}, + {'A', SCI_CTRL, SCI_SELECTALL}, + {SCK_TAB, SCI_NORM, SCI_TAB}, + {SCK_TAB, SCI_SHIFT, SCI_BACKTAB}, + {SCK_RETURN, SCI_NORM, SCI_NEWLINE}, + {SCK_RETURN, SCI_SHIFT, SCI_NEWLINE}, + {SCK_ADD, SCI_CTRL, SCI_ZOOMIN}, + {SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT}, + {SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM}, + //'L', SCI_CTRL, SCI_FORMFEED, + {'L', SCI_CTRL, SCI_LINECUT}, + {'L', SCI_CSHIFT, SCI_LINEDELETE}, + {'T', SCI_CSHIFT, SCI_LINECOPY}, + {'T', SCI_CTRL, SCI_LINETRANSPOSE}, + {'D', SCI_CTRL, SCI_SELECTIONDUPLICATE}, + {'U', SCI_CTRL, SCI_LOWERCASE}, + {'U', SCI_CSHIFT, SCI_UPPERCASE}, + {0,0,0}, +}; + + diff --git a/scintilla/src/KeyMap.h b/scintilla/src/KeyMap.h new file mode 100644 index 00000000..c1b1a10e --- /dev/null +++ b/scintilla/src/KeyMap.h @@ -0,0 +1,51 @@ +// Scintilla source code edit control +/** @file KeyMap.h + ** Defines a mapping between keystrokes and commands. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#ifndef KEYTOCOMMAND_H +#define KEYTOCOMMAND_H + +#ifdef SCI_NAMESPACE +namespace Scintilla { +#endif + +#define SCI_NORM 0 +#define SCI_SHIFT SCMOD_SHIFT +#define SCI_CTRL SCMOD_CTRL +#define SCI_ALT SCMOD_ALT +#define SCI_CSHIFT (SCI_CTRL | SCI_SHIFT) +#define SCI_ASHIFT (SCI_ALT | SCI_SHIFT) + +/** + */ +class KeyToCommand { +public: + int key; + int modifiers; + unsigned int msg; +}; + +/** + */ +class KeyMap { + KeyToCommand *kmap; + int len; + int alloc; + static const KeyToCommand MapDefault[]; + +public: + KeyMap(); + ~KeyMap(); + void Clear(); + void AssignCmdKey(int key, int modifiers, unsigned int msg); + unsigned int Find(int key, int modifiers); // 0 returned on failure +}; + +#ifdef SCI_NAMESPACE +} +#endif + +#endif diff --git a/scintilla/src/KeyWords.cxx b/scintilla/src/KeyWords.cxx new file mode 100644 index 00000000..551c5b78 --- /dev/null +++ b/scintilla/src/KeyWords.cxx @@ -0,0 +1,238 @@ +// Scintilla source code edit control +/** @file KeyWords.cxx + ** Colourise for particular languages. + **/ +// Copyright 1998-2002 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +const LexerModule *LexerModule::base = 0; +int LexerModule::nextLanguage = SCLEX_AUTOMATIC+1; + +LexerModule::LexerModule(int language_, + LexerFunction fnLexer_, + const char *languageName_, + LexerFunction fnFolder_, + const char * const wordListDescriptions_[], + int styleBits_) : + language(language_), + fnLexer(fnLexer_), + fnFolder(fnFolder_), + wordListDescriptions(wordListDescriptions_), + styleBits(styleBits_), + languageName(languageName_) { + next = base; + base = this; + if (language == SCLEX_AUTOMATIC) { + language = nextLanguage; + nextLanguage++; + } +} + +int LexerModule::GetNumWordLists() const { + if (wordListDescriptions == NULL) { + return -1; + } else { + int numWordLists = 0; + + while (wordListDescriptions[numWordLists]) { + ++numWordLists; + } + + return numWordLists; + } +} + +const char *LexerModule::GetWordListDescription(int index) const { + static const char *emptyStr = ""; + + PLATFORM_ASSERT(index < GetNumWordLists()); + if (index >= GetNumWordLists()) { + return emptyStr; + } else { + return wordListDescriptions[index]; + } +} + +int LexerModule::GetStyleBitsNeeded() const { + return styleBits; +} + +const LexerModule *LexerModule::Find(int language) { + const LexerModule *lm = base; + while (lm) { + if (lm->language == language) { + return lm; + } + lm = lm->next; + } + return 0; +} + +const LexerModule *LexerModule::Find(const char *languageName) { + if (languageName) { + const LexerModule *lm = base; + while (lm) { + if (lm->languageName && 0 == strcmp(lm->languageName, languageName)) { + return lm; + } + lm = lm->next; + } + } + return 0; +} + +void LexerModule::Lex(unsigned int startPos, int lengthDoc, int initStyle, + WordList *keywordlists[], Accessor &styler) const { + if (fnLexer) + fnLexer(startPos, lengthDoc, initStyle, keywordlists, styler); +} + +void LexerModule::Fold(unsigned int startPos, int lengthDoc, int initStyle, + WordList *keywordlists[], Accessor &styler) const { + if (fnFolder) { + int lineCurrent = styler.GetLine(startPos); + // Move back one line in case deletion wrecked current line fold state + if (lineCurrent > 0) { + lineCurrent--; + int newStartPos = styler.LineStart(lineCurrent); + lengthDoc += startPos - newStartPos; + startPos = newStartPos; + initStyle = 0; + if (startPos > 0) { + initStyle = styler.StyleAt(startPos - 1); + } + } + fnFolder(startPos, lengthDoc, initStyle, keywordlists, styler); + } +} + +// Alternative historical name for Scintilla_LinkLexers +int wxForceScintillaLexers(void) { + return Scintilla_LinkLexers(); +} + +// To add or remove a lexer, add or remove its file and run LexGen.py. + +// Force a reference to all of the Scintilla lexers so that the linker will +// not remove the code of the lexers. +int Scintilla_LinkLexers() { + static int forcer = 0; + +// Shorten the code that declares a lexer and ensures it is linked in by calling a method. +#define LINK_LEXER(lexer) extern LexerModule lexer; forcer += lexer.GetLanguage(); + +//++Autogenerated -- run src/LexGen.py to regenerate +//**\(\tLINK_LEXER(\*);\n\) + LINK_LEXER(lmAbaqus); + LINK_LEXER(lmAda); + LINK_LEXER(lmAns1); + LINK_LEXER(lmAPDL); + LINK_LEXER(lmAsm); + LINK_LEXER(lmASP); + LINK_LEXER(lmASY); + LINK_LEXER(lmAU3); + LINK_LEXER(lmAVE); + LINK_LEXER(lmBaan); + LINK_LEXER(lmBash); + LINK_LEXER(lmBatch); + LINK_LEXER(lmBlitzBasic); + LINK_LEXER(lmBullant); + LINK_LEXER(lmCaml); + LINK_LEXER(lmClw); + LINK_LEXER(lmClwNoCase); + LINK_LEXER(lmCmake); + LINK_LEXER(lmConf); + LINK_LEXER(lmCPP); + LINK_LEXER(lmCPPNoCase); + LINK_LEXER(lmCsound); + LINK_LEXER(lmCss); + LINK_LEXER(lmD); + LINK_LEXER(lmDiff); + LINK_LEXER(lmEiffel); + LINK_LEXER(lmEiffelkw); + LINK_LEXER(lmErlang); + LINK_LEXER(lmErrorList); + LINK_LEXER(lmESCRIPT); + LINK_LEXER(lmF77); + LINK_LEXER(lmFlagShip); + LINK_LEXER(lmForth); + LINK_LEXER(lmFortran); + LINK_LEXER(lmFreeBasic); + LINK_LEXER(lmGAP); + LINK_LEXER(lmGui4Cli); + LINK_LEXER(lmHaskell); + LINK_LEXER(lmHTML); + LINK_LEXER(lmInno); + LINK_LEXER(lmKix); + LINK_LEXER(lmLatex); + LINK_LEXER(lmLISP); + LINK_LEXER(lmLot); + LINK_LEXER(lmLout); + LINK_LEXER(lmLua); + LINK_LEXER(lmMagikSF); + LINK_LEXER(lmMake); + LINK_LEXER(lmMatlab); + LINK_LEXER(lmMETAPOST); + LINK_LEXER(lmMMIXAL); + LINK_LEXER(lmMSSQL); + LINK_LEXER(lmNncrontab); + LINK_LEXER(lmNsis); + LINK_LEXER(lmNull); + LINK_LEXER(lmObjC); + LINK_LEXER(lmOctave); + LINK_LEXER(lmOpal); + LINK_LEXER(lmPascal); + LINK_LEXER(lmPB); + LINK_LEXER(lmPerl); + LINK_LEXER(lmPHP); + LINK_LEXER(lmPHPSCRIPT); + LINK_LEXER(lmPLM); + LINK_LEXER(lmPOV); + LINK_LEXER(lmPowerShell); + LINK_LEXER(lmProgress); + LINK_LEXER(lmProps); + LINK_LEXER(lmPS); + LINK_LEXER(lmPureBasic); + LINK_LEXER(lmPython); + LINK_LEXER(lmR); + LINK_LEXER(lmREBOL); + LINK_LEXER(lmRuby); + LINK_LEXER(lmScriptol); + LINK_LEXER(lmSearchResult); + LINK_LEXER(lmSmalltalk); + LINK_LEXER(lmSpecman); + LINK_LEXER(lmSpice); + LINK_LEXER(lmSQL); + LINK_LEXER(lmTADS3); + LINK_LEXER(lmTCL); + LINK_LEXER(lmTeX); + LINK_LEXER(lmUserDefine); + LINK_LEXER(lmVB); + LINK_LEXER(lmVBScript); + LINK_LEXER(lmVerilog); + LINK_LEXER(lmVHDL); + LINK_LEXER(lmXML); + LINK_LEXER(lmYAML); + +//--Autogenerated -- end of automatically generated section + + return 1; +} diff --git a/scintilla/src/LexAPDL.cxx b/scintilla/src/LexAPDL.cxx new file mode 100644 index 00000000..a9a6c540 --- /dev/null +++ b/scintilla/src/LexAPDL.cxx @@ -0,0 +1,256 @@ +// Scintilla source code edit control +/** @file LexAPDL.cxx + ** Lexer for APDL. Based on the lexer for Assembler by The Black Horus. + ** By Hadar Raz. + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static inline bool IsAWordChar(const int ch) { + return (ch < 0x80 && (isalnum(ch) || ch == '_')); +} + +static inline bool IsAnOperator(char ch) { + // '.' left out as it is used to make up numbers + if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || + ch == '(' || ch == ')' || ch == '=' || ch == '^' || + ch == '[' || ch == ']' || ch == '<' || ch == '&' || + ch == '>' || ch == ',' || ch == '|' || ch == '~' || + ch == '$' || ch == ':' || ch == '%') + return true; + return false; +} + +static void ColouriseAPDLDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler) { + + int stringStart = ' '; + + WordList &processors = *keywordlists[0]; + WordList &commands = *keywordlists[1]; + WordList &slashcommands = *keywordlists[2]; + WordList &starcommands = *keywordlists[3]; + WordList &arguments = *keywordlists[4]; + WordList &functions = *keywordlists[5]; + + // Do not leak onto next line + initStyle = SCE_APDL_DEFAULT; + StyleContext sc(startPos, length, initStyle, styler); + + for (; sc.More(); sc.Forward()) { + // Determine if the current state should terminate. + if (sc.state == SCE_APDL_NUMBER) { + if (!(IsADigit(sc.ch) || sc.ch == '.' || (sc.ch == 'e' || sc.ch == 'E') || + ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E')))) { + sc.SetState(SCE_APDL_DEFAULT); + } + } else if (sc.state == SCE_APDL_COMMENT) { + if (sc.atLineEnd) { + sc.SetState(SCE_APDL_DEFAULT); + } + } else if (sc.state == SCE_APDL_COMMENTBLOCK) { + if (sc.atLineEnd) { + if (sc.ch == '\r') { + sc.Forward(); + } + sc.ForwardSetState(SCE_APDL_DEFAULT); + } + } else if (sc.state == SCE_APDL_STRING) { + if (sc.atLineEnd) { + sc.SetState(SCE_APDL_DEFAULT); + } else if ((sc.ch == '\'' && stringStart == '\'') || (sc.ch == '\"' && stringStart == '\"')) { + sc.ForwardSetState(SCE_APDL_DEFAULT); + } + } else if (sc.state == SCE_APDL_WORD) { + if (!IsAWordChar(sc.ch)) { + char s[100]; + sc.GetCurrentLowered(s, sizeof(s)); + if (processors.InList(s)) { + sc.ChangeState(SCE_APDL_PROCESSOR); + } else if (slashcommands.InList(s)) { + sc.ChangeState(SCE_APDL_SLASHCOMMAND); + } else if (starcommands.InList(s)) { + sc.ChangeState(SCE_APDL_STARCOMMAND); + } else if (commands.InList(s)) { + sc.ChangeState(SCE_APDL_COMMAND); + } else if (arguments.InList(s)) { + sc.ChangeState(SCE_APDL_ARGUMENT); + } else if (functions.InList(s)) { + sc.ChangeState(SCE_APDL_FUNCTION); + } + sc.SetState(SCE_APDL_DEFAULT); + } + } else if (sc.state == SCE_APDL_OPERATOR) { + if (!IsAnOperator(static_cast(sc.ch))) { + sc.SetState(SCE_APDL_DEFAULT); + } + } + + // Determine if a new state should be entered. + if (sc.state == SCE_APDL_DEFAULT) { + if (sc.ch == '!' && sc.chNext == '!') { + sc.SetState(SCE_APDL_COMMENTBLOCK); + } else if (sc.ch == '!') { + sc.SetState(SCE_APDL_COMMENT); + } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { + sc.SetState(SCE_APDL_NUMBER); + } else if (sc.ch == '\'' || sc.ch == '\"') { + sc.SetState(SCE_APDL_STRING); + stringStart = sc.ch; + } else if (IsAWordChar(sc.ch) || ((sc.ch == '*' || sc.ch == '/') && !isgraph(sc.chPrev))) { + sc.SetState(SCE_APDL_WORD); + } else if (IsAnOperator(static_cast(sc.ch))) { + sc.SetState(SCE_APDL_OPERATOR); + } + } + } + sc.Complete(); +} + +//------------------------------------------------------------------------------ +// 06-27-07 Sergio Lucato +// - Included code folding for Ansys APDL lexer +// - Copyied from LexBasic.cxx and modified for APDL +//------------------------------------------------------------------------------ + +/* Bits: + * 1 - whitespace + * 2 - operator + * 4 - identifier + * 8 - decimal digit + * 16 - hex digit + * 32 - bin digit + */ +static int character_classification[128] = +{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 2, 0, 2, 2, 2, 2, 2, 2, 2, 6, 2, 2, 2, 10, 6, + 60, 60, 28, 28, 28, 28, 28, 28, 28, 28, 2, 2, 2, 2, 2, 2, + 2, 20, 20, 20, 20, 20, 20, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 4, + 2, 20, 20, 20, 20, 20, 20, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 0 +}; + +static bool IsSpace(int c) { + return c < 128 && (character_classification[c] & 1); +} + +static bool IsIdentifier(int c) { + return c < 128 && (character_classification[c] & 4); +} + +static int LowerCase(int c) +{ + if (c >= 'A' && c <= 'Z') + return 'a' + c - 'A'; + return c; +} + +static int CheckAPDLFoldPoint(char const *token, int &level) { + if (!strcmp(token, "*if") || + !strcmp(token, "*do") || + !strcmp(token, "*dowhile") ) { + level |= SC_FOLDLEVELHEADERFLAG; + return 1; + } + if (!strcmp(token, "*endif") || + !strcmp(token, "*enddo") ) { + return -1; + } + return 0; +} + +static void FoldAPDLDoc(unsigned int startPos, int length, int, + WordList *[], Accessor &styler) { + + int line = styler.GetLine(startPos); + int level = styler.LevelAt(line); + int go = 0, done = 0; + int endPos = startPos + length; + char word[256]; + int wordlen = 0; + int i; + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + // Scan for tokens at the start of the line (they may include + // whitespace, for tokens like "End Function" + for (i = startPos; i < endPos; i++) { + int c = styler.SafeGetCharAt(i); + if (!done && !go) { + if (wordlen) { // are we scanning a token already? + word[wordlen] = static_cast(LowerCase(c)); + if (!IsIdentifier(c)) { // done with token + word[wordlen] = '\0'; + go = CheckAPDLFoldPoint(word, level); + if (!go) { + // Treat any whitespace as single blank, for + // things like "End Function". + if (IsSpace(c) && IsIdentifier(word[wordlen - 1])) { + word[wordlen] = ' '; + if (wordlen < 255) + wordlen++; + } + else // done with this line + done = 1; + } + } else if (wordlen < 255) { + wordlen++; + } + } else { // start scanning at first non-whitespace character + if (!IsSpace(c)) { + if (IsIdentifier(c)) { + word[0] = static_cast(LowerCase(c)); + wordlen = 1; + } else // done with this line + done = 1; + } + } + } + if (c == '\n') { // line end + if (!done && wordlen == 0 && foldCompact) // line was only space + level |= SC_FOLDLEVELWHITEFLAG; + if (level != styler.LevelAt(line)) + styler.SetLevel(line, level); + level += go; + line++; + // reset state + wordlen = 0; + level &= ~SC_FOLDLEVELHEADERFLAG; + level &= ~SC_FOLDLEVELWHITEFLAG; + go = 0; + done = 0; + } + } +} + +static const char * const apdlWordListDesc[] = { + "processors", + "commands", + "slashommands", + "starcommands", + "arguments", + "functions", + 0 +}; + +LexerModule lmAPDL(SCLEX_APDL, ColouriseAPDLDoc, "apdl", FoldAPDLDoc, apdlWordListDesc); diff --git a/scintilla/src/LexASY.cxx b/scintilla/src/LexASY.cxx new file mode 100644 index 00000000..8a1785a5 --- /dev/null +++ b/scintilla/src/LexASY.cxx @@ -0,0 +1,270 @@ +// Scintilla source code edit control +//Author: instanton (email: soft_share126com) +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" +#include "CharacterSet.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static void ColouriseAsyDoc(unsigned int startPos, int length, int initStyle, + WordList *keywordlists[], Accessor &styler) { + + WordList &keywords = *keywordlists[0]; + WordList &keywords2 = *keywordlists[1]; + + CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true); + CharacterSet setWord(CharacterSet::setAlphaNum, "._", 0x80, true); + + int visibleChars = 0; + + StyleContext sc(startPos, length, initStyle, styler); + + for (; sc.More(); sc.Forward()) { + + if (sc.atLineStart) { + if (sc.state == SCE_ASY_STRING) { + sc.SetState(SCE_ASY_STRING); + } + visibleChars = 0; + } + + 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_ASY_OPERATOR: + sc.SetState(SCE_ASY_DEFAULT); + break; + case SCE_ASY_NUMBER: + if (!setWord.Contains(sc.ch)) { + sc.SetState(SCE_ASY_DEFAULT); + } + break; + case SCE_ASY_IDENTIFIER: + if (!setWord.Contains(sc.ch) || (sc.ch == '.')) { + char s[1000]; + sc.GetCurrentLowered(s, sizeof(s)); + if (keywords.InList(s)) { + sc.ChangeState(SCE_ASY_WORD); + } else if (keywords2.InList(s)) { + sc.ChangeState(SCE_ASY_WORD2); + } + sc.SetState(SCE_ASY_DEFAULT); + } + break; + case SCE_ASY_COMMENT: + if (sc.Match('*', '/')) { + sc.Forward(); + sc.ForwardSetState(SCE_ASY_DEFAULT); + } + break; + case SCE_ASY_COMMENTLINE: + if (sc.atLineStart) { + sc.SetState(SCE_ASY_DEFAULT); + } + break; + case SCE_ASY_STRING: + if (sc.atLineEnd) { + sc.ChangeState(SCE_ASY_STRINGEOL); + } else if (sc.ch == '\\') { + if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { + sc.Forward(); + } + } else if (sc.ch == '\"') { + sc.ForwardSetState(SCE_ASY_DEFAULT); + } + break; + case SCE_ASY_CHARACTER: + if (sc.atLineEnd) { + sc.ChangeState(SCE_ASY_STRINGEOL); + } else if (sc.ch == '\\') { + if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { + sc.Forward(); + } + } else if (sc.ch == '\'') { + sc.ForwardSetState(SCE_ASY_DEFAULT); + } + break; + } + + // Determine if a new state should be entered. + if (sc.state == SCE_ASY_DEFAULT) { + if (setWordStart.Contains(sc.ch) || (sc.ch == '@')) { + sc.SetState(SCE_ASY_IDENTIFIER); + } else if (sc.Match('/', '*')) { + sc.SetState(SCE_ASY_COMMENT); + sc.Forward(); // + } else if (sc.Match('/', '/')) { + sc.SetState(SCE_ASY_COMMENTLINE); + } else if (sc.ch == '\"') { + sc.SetState(SCE_ASY_STRING); + } else if (sc.ch == '\'') { + sc.SetState(SCE_ASY_CHARACTER); + } else if (sc.ch == '#' && visibleChars == 0) { + do { + sc.Forward(); + } while ((sc.ch == ' ' || sc.ch == '\t') && sc.More()); + if (sc.atLineEnd) { + sc.SetState(SCE_ASY_DEFAULT); + } + } else if (isoperator(static_cast(sc.ch))) { + sc.SetState(SCE_ASY_OPERATOR); + } + } + + } + sc.Complete(); +} + +static bool IsAsyCommentStyle(int style) { + return style == SCE_ASY_COMMENT; +} + + +static inline bool isASYidentifier(int ch) { + return + ((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z')) ; +} + +static int ParseASYWord(unsigned int pos, Accessor &styler, char *word) +{ + int length=0; + char ch=styler.SafeGetCharAt(pos); + *word=0; + + while(isASYidentifier(ch) && length<100){ + word[length]=ch; + length++; + ch=styler.SafeGetCharAt(pos+length); + } + word[length]=0; + return length; +} + +static bool IsASYDrawingLine(int line, Accessor &styler) { + int pos = styler.LineStart(line); + int eol_pos = styler.LineStart(line + 1) - 1; + + int startpos = pos; + char buffer[100]=""; + + while (startpos 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 && IsAsyCommentStyle(style)) { + if (!IsAsyCommentStyle(stylePrev) && (stylePrev != SCE_ASY_COMMENTLINEDOC)) { + levelNext++; + } else if (!IsAsyCommentStyle(styleNext) && (styleNext != SCE_ASY_COMMENTLINEDOC) && !atEOL) { + levelNext--; + } + } + if (style == SCE_ASY_OPERATOR) { + if (ch == '{') { + if (levelMinCurrent > levelNext) { + levelMinCurrent = levelNext; + } + levelNext++; + } else if (ch == '}') { + levelNext--; + } + } + + if (atEOL && IsASYDrawingLine(lineCurrent, styler)){ + if (lineCurrent==0 && IsASYDrawingLine(lineCurrent + 1, styler)) + levelNext++; + else if (lineCurrent!=0 && !IsASYDrawingLine(lineCurrent - 1, styler) + && IsASYDrawingLine(lineCurrent + 1, styler) + ) + levelNext++; + else if (lineCurrent!=0 && IsASYDrawingLine(lineCurrent - 1, styler) && + !IsASYDrawingLine(lineCurrent+1, styler)) + levelNext--; + } + + if (atEOL) { + int levelUse = levelCurrent; + if (foldAtElse) { + levelUse = levelMinCurrent; + } + int lev = levelUse | levelNext << 16; + if (visibleChars == 0 && foldCompact) + lev |= SC_FOLDLEVELWHITEFLAG; + if (levelUse < levelNext) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelCurrent = levelNext; + levelMinCurrent = levelCurrent; + visibleChars = 0; + } + if (!IsASpace(ch)) + visibleChars++; + } +} + +static const char * const asyWordLists[] = { + "Primary keywords and identifiers", + "Secondary keywords and identifiers", + 0, + }; + +LexerModule lmASY(SCLEX_ASYMPTOTE, ColouriseAsyDoc, "asy", FoldAsyDoc, asyWordLists); diff --git a/scintilla/src/LexAU3.cxx b/scintilla/src/LexAU3.cxx new file mode 100644 index 00000000..795d50b8 --- /dev/null +++ b/scintilla/src/LexAU3.cxx @@ -0,0 +1,906 @@ +// Scintilla source code edit control +// @file LexAU3.cxx +// Lexer for AutoIt3 http://www.hiddensoft.com/autoit3 +// by Jos van der Zande, jvdzande@yahoo.com +// +// Changes: +// March 28, 2004 - Added the standard Folding code +// April 21, 2004 - Added Preprosessor Table + Syntax Highlighting +// Fixed Number highlighting +// Changed default isoperator to IsAOperator to have a better match to AutoIt3 +// Fixed "#comments_start" -> "#comments-start" +// Fixed "#comments_end" -> "#comments-end" +// Fixed Sendkeys in Strings when not terminated with } +// Added support for Sendkey strings that have second parameter e.g. {UP 5} or {a down} +// April 26, 2004 - Fixed # pre-processor statement inside of comment block would invalidly change the color. +// Added logic for #include to treat the <> as string +// Added underscore to IsAOperator. +// May 17, 2004 - Changed the folding logic from indent to keyword folding. +// Added Folding logic for blocks of single-commentlines or commentblock. +// triggered by: fold.comment=1 +// Added Folding logic for preprocessor blocks triggered by fold.preprocessor=1 +// Added Special for #region - #endregion syntax highlight and folding. +// May 30, 2004 - Fixed issue with continuation lines on If statements. +// June 5, 2004 - Added comma to Operators for better readability. +// Added fold.compact support set with fold.compact=1 +// Changed folding inside of #cs-#ce. Default is no keyword folding inside comment blocks when fold.comment=1 +// it will now only happen when fold.comment=2. +// Sep 5, 2004 - Added logic to handle colourizing words on the last line. +// Typed Characters now show as "default" till they match any table. +// Oct 10, 2004 - Added logic to show Comments in "Special" directives. +// Nov 1, 2004 - Added better testing for Numbers supporting x and e notation. +// Nov 28, 2004 - Added logic to handle continuation lines for syntax highlighting. +// Jan 10, 2005 - Added Abbreviations Keyword used for expansion +// Mar 24, 2005 - Updated Abbreviations Keywords to fix when followed by Operator. +// Apr 18, 2005 - Updated #CE/#Comment-End logic to take a linecomment ";" into account +// - Added folding support for With...EndWith +// - Added support for a DOT in variable names +// - Fixed Underscore in CommentBlock +// May 23, 2005 - Fixed the SentKey lexing in case of a missing } +// Aug 11, 2005 - Fixed possible bug with s_save length > 100. +// Aug 23, 2005 - Added Switch/endswitch support to the folding logic. +// Sep 27, 2005 - Fixed the SentKey lexing logic in case of multiple sentkeys. +// Mar 12, 2006 - Fixed issue with <> coloring as String in stead of Operator in rare occasions. +// Apr 8, 2006 - Added support for AutoIt3 Standard UDF library (SCE_AU3_UDF) +// Mar 9, 2007 - Fixed bug with + following a String getting the wrong Color. +// Jun 20, 2007 - Fixed Commentblock issue when LF's are used as EOL. +// Jul 26, 2007 - Fixed #endregion undetected bug. +// +// Copyright for Scintilla: 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. +// Scintilla source code edit control + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static inline bool IsTypeCharacter(const int ch) +{ + return ch == '$'; +} +static inline bool IsAWordChar(const int ch) +{ + return (ch < 0x80) && (isalnum(ch) || ch == '_'); +} + +static inline bool IsAWordStart(const int ch) +{ + return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '@' || ch == '#' || ch == '$' || ch == '.'); +} + +static inline bool IsAOperator(char ch) { + if (isascii(ch) && isalnum(ch)) + return false; + if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || + ch == '&' || ch == '^' || ch == '=' || ch == '<' || ch == '>' || + ch == '(' || ch == ')' || ch == '[' || ch == ']' || ch == ',' ) + return true; + return false; +} + +/////////////////////////////////////////////////////////////////////////////// +// GetSendKey() filters the portion before and after a/multiple space(s) +// and return the first portion to be looked-up in the table +// also check if the second portion is valid... (up,down.on.off,toggle or a number) +/////////////////////////////////////////////////////////////////////////////// + +static int GetSendKey(const char *szLine, char *szKey) +{ + int nFlag = 0; + int nStartFound = 0; + int nKeyPos = 0; + int nSpecPos= 0; + int nSpecNum= 1; + int nPos = 0; + char cTemp; + char szSpecial[100]; + + // split the portion of the sendkey in the part before and after the spaces + while ( ( (cTemp = szLine[nPos]) != '\0')) + { + // skip leading Ctrl/Shift/Alt state + if (cTemp == '{') { + nStartFound = 1; + } + // + if (nStartFound == 1) { + if ((cTemp == ' ') && (nFlag == 0) ) // get the stuff till first space + { + nFlag = 1; + // Add } to the end of the first bit for table lookup later. + szKey[nKeyPos++] = '}'; + } + else if (cTemp == ' ') + { + // skip other spaces + } + else if (nFlag == 0) + { + // save first portion into var till space or } is hit + szKey[nKeyPos++] = cTemp; + } + else if ((nFlag == 1) && (cTemp != '}')) + { + // Save second portion into var... + szSpecial[nSpecPos++] = cTemp; + // check if Second portion is all numbers for repeat fuction + if (isdigit(cTemp) == false) {nSpecNum = 0;} + } + } + nPos++; // skip to next char + + } // End While + + + // Check if the second portion is either a number or one of these keywords + szKey[nKeyPos] = '\0'; + szSpecial[nSpecPos] = '\0'; + if (strcmp(szSpecial,"down")== 0 || strcmp(szSpecial,"up")== 0 || + strcmp(szSpecial,"on")== 0 || strcmp(szSpecial,"off")== 0 || + strcmp(szSpecial,"toggle")== 0 || nSpecNum == 1 ) + { + nFlag = 0; + } + else + { + nFlag = 1; + } + return nFlag; // 1 is bad, 0 is good + +} // GetSendKey() + +// +// Routine to check the last "none comment" character on a line to see if its a continuation +// +static bool IsContinuationLine(unsigned int szLine, Accessor &styler) +{ + int nsPos = styler.LineStart(szLine); + int nePos = styler.LineStart(szLine+1) - 2; + //int stylech = styler.StyleAt(nsPos); + while (nsPos < nePos) + { + //stylech = styler.StyleAt(nePos); + int stylech = styler.StyleAt(nsPos); + if (!(stylech == SCE_AU3_COMMENT)) { + char ch = styler.SafeGetCharAt(nePos); + if (!isspacechar(ch)) { + if (ch == '_') + return true; + else + return false; + } + } + nePos--; // skip to next char + } // End While + return false; +} // IsContinuationLine() + +// +// syntax highlighting logic +static void ColouriseAU3Doc(unsigned int startPos, + int length, int initStyle, + WordList *keywordlists[], + Accessor &styler) { + + WordList &keywords = *keywordlists[0]; + WordList &keywords2 = *keywordlists[1]; + WordList &keywords3 = *keywordlists[2]; + WordList &keywords4 = *keywordlists[3]; + WordList &keywords5 = *keywordlists[4]; + WordList &keywords6 = *keywordlists[5]; + WordList &keywords7 = *keywordlists[6]; + WordList &keywords8 = *keywordlists[7]; + // find the first previous line without continuation character at the end + int lineCurrent = styler.GetLine(startPos); + int s_startPos = startPos; + // When not inside a Block comment: find First line without _ + if (!(initStyle==SCE_AU3_COMMENTBLOCK)) { + while ((lineCurrent > 0 && IsContinuationLine(lineCurrent,styler)) || + (lineCurrent > 1 && IsContinuationLine(lineCurrent-1,styler))) { + lineCurrent--; + startPos = styler.LineStart(lineCurrent); // get start position + initStyle = 0; // reset the start style to 0 + } + } + // Set the new length to include it from the start and set the start position + length = length + s_startPos - startPos; // correct the total length to process + styler.StartAt(startPos); + + StyleContext sc(startPos, length, initStyle, styler); + char si; // string indicator "=1 '=2 + char ni; // Numeric indicator error=9 normal=0 normal+dec=1 hex=2 Enot=3 + char ci; // comment indicator 0=not linecomment(;) + char s_save[100]; + si=0; + ni=0; + ci=0; + //$$$ + for (; sc.More(); sc.Forward()) { + char s[100]; + sc.GetCurrentLowered(s, sizeof(s)); + // ********************************************** + // save the total current word for eof processing + if (IsAWordChar(sc.ch) || sc.ch == '}') + { + strcpy(s_save,s); + int tp = strlen(s_save); + if (tp < 99) { + s_save[tp] = static_cast(tolower(sc.ch)); + s_save[tp+1] = '\0'; + } + } + // ********************************************** + // + switch (sc.state) + { + case SCE_AU3_COMMENTBLOCK: + { + //Reset at line end + if (sc.atLineEnd) { + ci=0; + if ((strcmp(s, "#ce")== 0 || strcmp(s, "#comments-end")== 0)) + if (sc.atLineEnd) + sc.SetState(SCE_AU3_DEFAULT); + else + sc.SetState(SCE_AU3_COMMENTBLOCK); + break; + } + //skip rest of line when a ; is encountered + if (sc.chPrev == ';') { + ci=2; + sc.SetState(SCE_AU3_COMMENTBLOCK); + } + // skip rest of the line + if (ci==2) + break; + // check when first character is detected on the line + if (ci==0) { + if (IsAWordStart(static_cast(sc.ch)) || IsAOperator(static_cast(sc.ch))) { + ci=1; + sc.SetState(SCE_AU3_COMMENTBLOCK); + } + break; + } + if (!(IsAWordChar(sc.ch) || (sc.ch == '-' && strcmp(s, "#comments") == 0))) { + if ((strcmp(s, "#ce")== 0 || strcmp(s, "#comments-end")== 0)) + sc.SetState(SCE_AU3_COMMENT); // set to comment line for the rest of the line + else + ci=2; // line doesn't begin with #CE so skip the rest of the line + } + break; + } + case SCE_AU3_COMMENT: + { + if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);} + break; + } + case SCE_AU3_OPERATOR: + { + // check if its a COMobject + if (sc.chPrev == '.' && IsAWordChar(sc.ch)) { + sc.SetState(SCE_AU3_COMOBJ); + } + else { + sc.SetState(SCE_AU3_DEFAULT); + } + break; + } + case SCE_AU3_SPECIAL: + { + if (sc.ch == ';') {sc.SetState(SCE_AU3_COMMENT);} + if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);} + break; + } + case SCE_AU3_KEYWORD: + { + if (!(IsAWordChar(sc.ch) || (sc.ch == '-' && (strcmp(s, "#comments") == 0 || strcmp(s, "#include") == 0)))) + { + if (!IsTypeCharacter(sc.ch)) + { + if (strcmp(s, "#cs")== 0 || strcmp(s, "#comments-start")== 0 ) + { + sc.ChangeState(SCE_AU3_COMMENTBLOCK); + sc.SetState(SCE_AU3_COMMENTBLOCK); + break; + } + else if (keywords.InList(s)) { + sc.ChangeState(SCE_AU3_KEYWORD); + sc.SetState(SCE_AU3_DEFAULT); + } + else if (keywords2.InList(s)) { + sc.ChangeState(SCE_AU3_FUNCTION); + sc.SetState(SCE_AU3_DEFAULT); + } + else if (keywords3.InList(s)) { + sc.ChangeState(SCE_AU3_MACRO); + sc.SetState(SCE_AU3_DEFAULT); + } + else if (keywords5.InList(s)) { + sc.ChangeState(SCE_AU3_PREPROCESSOR); + sc.SetState(SCE_AU3_DEFAULT); + if (strcmp(s, "#include")== 0) + { + si = 3; // use to determine string start for #inlude <> + } + } + else if (keywords6.InList(s)) { + sc.ChangeState(SCE_AU3_SPECIAL); + sc.SetState(SCE_AU3_SPECIAL); + } + else if ((keywords7.InList(s)) && (!IsAOperator(static_cast(sc.ch)))) { + sc.ChangeState(SCE_AU3_EXPAND); + sc.SetState(SCE_AU3_DEFAULT); + } + else if (keywords8.InList(s)) { + sc.ChangeState(SCE_AU3_UDF); + sc.SetState(SCE_AU3_DEFAULT); + } + else if (strcmp(s, "_") == 0) { + sc.ChangeState(SCE_AU3_OPERATOR); + sc.SetState(SCE_AU3_DEFAULT); + } + else if (!IsAWordChar(sc.ch)) { + sc.ChangeState(SCE_AU3_DEFAULT); + sc.SetState(SCE_AU3_DEFAULT); + } + } + } + if (sc.atLineEnd) { + sc.SetState(SCE_AU3_DEFAULT);} + break; + } + case SCE_AU3_NUMBER: + { + // Numeric indicator error=9 normal=0 normal+dec=1 hex=2 E-not=3 + // + // test for Hex notation + if (strcmp(s, "0") == 0 && (sc.ch == 'x' || sc.ch == 'X') && ni == 0) + { + ni = 2; + break; + } + // test for E notation + if (IsADigit(sc.chPrev) && (sc.ch == 'e' || sc.ch == 'E') && ni <= 1) + { + ni = 3; + break; + } + // Allow Hex characters inside hex numeric strings + if ((ni == 2) && + (sc.ch == 'a' || sc.ch == 'b' || sc.ch == 'c' || sc.ch == 'd' || sc.ch == 'e' || sc.ch == 'f' || + sc.ch == 'A' || sc.ch == 'B' || sc.ch == 'C' || sc.ch == 'D' || sc.ch == 'E' || sc.ch == 'F' )) + { + break; + } + // test for 1 dec point only + if (sc.ch == '.') + { + if (ni==0) + { + ni=1; + } + else + { + ni=9; + } + break; + } + // end of numeric string ? + if (!(IsADigit(sc.ch))) + { + if (ni==9) + { + sc.ChangeState(SCE_AU3_DEFAULT); + } + sc.SetState(SCE_AU3_DEFAULT); + } + break; + } + case SCE_AU3_VARIABLE: + { + // Check if its a COMObject + if (sc.ch == '.' && !IsADigit(sc.chNext)) { + sc.SetState(SCE_AU3_OPERATOR); + } + else if (!IsAWordChar(sc.ch)) { + sc.SetState(SCE_AU3_DEFAULT); + } + break; + } + case SCE_AU3_COMOBJ: + { + if (!(IsAWordChar(sc.ch))) { + sc.SetState(SCE_AU3_DEFAULT); + } + break; + } + case SCE_AU3_STRING: + { + // check for " to end a double qouted string or + // check for ' to end a single qouted string + if ((si == 1 && sc.ch == '\"') || (si == 2 && sc.ch == '\'') || (si == 3 && sc.ch == '>')) + { + sc.ForwardSetState(SCE_AU3_DEFAULT); + si=0; + break; + } + if (sc.atLineEnd) + { + si=0; + // at line end and not found a continuation char then reset to default + int lineCurrent = styler.GetLine(sc.currentPos); + if (!IsContinuationLine(lineCurrent,styler)) + { + sc.SetState(SCE_AU3_DEFAULT); + break; + } + } + // find Sendkeys in a STRING + if (sc.ch == '{' || sc.ch == '+' || sc.ch == '!' || sc.ch == '^' || sc.ch == '#' ) { + sc.SetState(SCE_AU3_SENT);} + break; + } + + case SCE_AU3_SENT: + { + // Send key string ended + if (sc.chPrev == '}' && sc.ch != '}') + { + // set color to SENDKEY when valid sendkey .. else set back to regular string + char sk[100]; + // split {111 222} and return {111} and check if 222 is valid. + // if return code = 1 then invalid 222 so must be string + if (GetSendKey(s,sk)) + { + sc.ChangeState(SCE_AU3_STRING); + } + // if single char between {?} then its ok as sendkey for a single character + else if (strlen(sk) == 3) + { + sc.ChangeState(SCE_AU3_SENT); + } + // if sendkey {111} is in table then ok as sendkey + else if (keywords4.InList(sk)) + { + sc.ChangeState(SCE_AU3_SENT); + } + else + { + sc.ChangeState(SCE_AU3_STRING); + } + sc.SetState(SCE_AU3_STRING); + } + else + { + // check if the start is a valid SendKey start + int nPos = 0; + int nState = 1; + char cTemp; + while (!(nState == 2) && ((cTemp = s[nPos]) != '\0')) + { + if (cTemp == '{' && nState == 1) + { + nState = 2; + } + if (nState == 1 && !(cTemp == '+' || cTemp == '!' || cTemp == '^' || cTemp == '#' )) + { + nState = 0; + } + nPos++; + } + //Verify characters infront of { ... if not assume regular string + if (nState == 1 && (!(sc.ch == '{' || sc.ch == '+' || sc.ch == '!' || sc.ch == '^' || sc.ch == '#' ))) { + sc.ChangeState(SCE_AU3_STRING); + sc.SetState(SCE_AU3_STRING); + } + // If invalid character found then assume its a regular string + if (nState == 0) { + sc.ChangeState(SCE_AU3_STRING); + sc.SetState(SCE_AU3_STRING); + } + } + // check if next portion is again a sendkey + if (sc.atLineEnd) + { + sc.ChangeState(SCE_AU3_STRING); + sc.SetState(SCE_AU3_DEFAULT); + si = 0; // reset string indicator + } + //* check in next characters following a sentkey are again a sent key + // Need this test incase of 2 sentkeys like {F1}{ENTER} but not detect {{} + if (sc.state == SCE_AU3_STRING && (sc.ch == '{' || sc.ch == '+' || sc.ch == '!' || sc.ch == '^' || sc.ch == '#' )) { + sc.SetState(SCE_AU3_SENT);} + // check to see if the string ended... + // Sendkey string isn't complete but the string ended.... + if ((si == 1 && sc.ch == '\"') || (si == 2 && sc.ch == '\'')) + { + sc.ChangeState(SCE_AU3_STRING); + sc.ForwardSetState(SCE_AU3_DEFAULT); + } + break; + } + } //switch (sc.state) + + // Determine if a new state should be entered: + + if (sc.state == SCE_AU3_DEFAULT) + { + if (sc.ch == ';') {sc.SetState(SCE_AU3_COMMENT);} + else if (sc.ch == '#') {sc.SetState(SCE_AU3_KEYWORD);} + else if (sc.ch == '$') {sc.SetState(SCE_AU3_VARIABLE);} + else if (sc.ch == '.' && !IsADigit(sc.chNext)) {sc.SetState(SCE_AU3_OPERATOR);} + else if (sc.ch == '@') {sc.SetState(SCE_AU3_KEYWORD);} + //else if (sc.ch == '_') {sc.SetState(SCE_AU3_KEYWORD);} + else if (sc.ch == '<' && si==3) {sc.SetState(SCE_AU3_STRING);} // string after #include + else if (sc.ch == '\"') { + sc.SetState(SCE_AU3_STRING); + si = 1; } + else if (sc.ch == '\'') { + sc.SetState(SCE_AU3_STRING); + si = 2; } + else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) + { + sc.SetState(SCE_AU3_NUMBER); + ni = 0; + } + else if (IsAWordStart(sc.ch)) {sc.SetState(SCE_AU3_KEYWORD);} + else if (IsAOperator(static_cast(sc.ch))) {sc.SetState(SCE_AU3_OPERATOR);} + else if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);} + } + } //for (; sc.More(); sc.Forward()) + + //************************************* + // Colourize the last word correctly + //************************************* + if (sc.state == SCE_AU3_KEYWORD) + { + if (strcmp(s_save, "#cs")== 0 || strcmp(s_save, "#comments-start")== 0 ) + { + sc.ChangeState(SCE_AU3_COMMENTBLOCK); + sc.SetState(SCE_AU3_COMMENTBLOCK); + } + else if (keywords.InList(s_save)) { + sc.ChangeState(SCE_AU3_KEYWORD); + sc.SetState(SCE_AU3_KEYWORD); + } + else if (keywords2.InList(s_save)) { + sc.ChangeState(SCE_AU3_FUNCTION); + sc.SetState(SCE_AU3_FUNCTION); + } + else if (keywords3.InList(s_save)) { + sc.ChangeState(SCE_AU3_MACRO); + sc.SetState(SCE_AU3_MACRO); + } + else if (keywords5.InList(s_save)) { + sc.ChangeState(SCE_AU3_PREPROCESSOR); + sc.SetState(SCE_AU3_PREPROCESSOR); + } + else if (keywords6.InList(s_save)) { + sc.ChangeState(SCE_AU3_SPECIAL); + sc.SetState(SCE_AU3_SPECIAL); + } + else if (keywords7.InList(s_save) && sc.atLineEnd) { + sc.ChangeState(SCE_AU3_EXPAND); + sc.SetState(SCE_AU3_EXPAND); + } + else if (keywords8.InList(s_save)) { + sc.ChangeState(SCE_AU3_UDF); + sc.SetState(SCE_AU3_UDF); + } + else { + sc.ChangeState(SCE_AU3_DEFAULT); + sc.SetState(SCE_AU3_DEFAULT); + } + } + if (sc.state == SCE_AU3_SENT) + { + // Send key string ended + if (sc.chPrev == '}' && sc.ch != '}') + { + // set color to SENDKEY when valid sendkey .. else set back to regular string + char sk[100]; + // split {111 222} and return {111} and check if 222 is valid. + // if return code = 1 then invalid 222 so must be string + if (GetSendKey(s_save,sk)) + { + sc.ChangeState(SCE_AU3_STRING); + } + // if single char between {?} then its ok as sendkey for a single character + else if (strlen(sk) == 3) + { + sc.ChangeState(SCE_AU3_SENT); + } + // if sendkey {111} is in table then ok as sendkey + else if (keywords4.InList(sk)) + { + sc.ChangeState(SCE_AU3_SENT); + } + else + { + sc.ChangeState(SCE_AU3_STRING); + } + sc.SetState(SCE_AU3_STRING); + } + // check if next portion is again a sendkey + if (sc.atLineEnd) + { + sc.ChangeState(SCE_AU3_STRING); + sc.SetState(SCE_AU3_DEFAULT); + } + } + //************************************* + sc.Complete(); +} + +// +static bool IsStreamCommentStyle(int style) { + return style == SCE_AU3_COMMENT || style == SCE_AU3_COMMENTBLOCK; +} + +// +// Routine to find first none space on the current line and return its Style +// needed for comment lines not starting on pos 1 +static int GetStyleFirstWord(unsigned int szLine, Accessor &styler) +{ + int nsPos = styler.LineStart(szLine); + int nePos = styler.LineStart(szLine+1) - 1; + while (isspacechar(styler.SafeGetCharAt(nsPos)) && nsPos < nePos) + { + nsPos++; // skip to next char + + } // End While + return styler.StyleAt(nsPos); + +} // GetStyleFirstWord() + + +// +static void FoldAU3Doc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) +{ + int endPos = startPos + length; + // get settings from the config files for folding comments and preprocessor lines + bool foldComment = styler.GetPropertyInt("fold.comment") != 0; + bool foldInComment = styler.GetPropertyInt("fold.comment") == 2; + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + bool foldpreprocessor = styler.GetPropertyInt("fold.preprocessor") != 0; + // Backtrack to previous line in case need to fix its fold status + int lineCurrent = styler.GetLine(startPos); + if (startPos > 0) { + if (lineCurrent > 0) { + lineCurrent--; + startPos = styler.LineStart(lineCurrent); + } + } + // vars for style of previous/current/next lines + int style = GetStyleFirstWord(lineCurrent,styler); + int stylePrev = 0; + // find the first previous line without continuation character at the end + while ((lineCurrent > 0 && IsContinuationLine(lineCurrent,styler)) || + (lineCurrent > 1 && IsContinuationLine(lineCurrent-1,styler))) { + lineCurrent--; + startPos = styler.LineStart(lineCurrent); + } + if (lineCurrent > 0) { + stylePrev = GetStyleFirstWord(lineCurrent-1,styler); + } + // vars for getting first word to check for keywords + bool FirstWordStart = false; + bool FirstWordEnd = false; + char szKeyword[11]=""; + int szKeywordlen = 0; + char szThen[5]=""; + int szThenlen = 0; + bool ThenFoundLast = false; + // var for indentlevel + int levelCurrent = SC_FOLDLEVELBASE; + if (lineCurrent > 0) + levelCurrent = styler.LevelAt(lineCurrent-1) >> 16; + int levelNext = levelCurrent; + // + int visibleChars = 0; + char chNext = styler.SafeGetCharAt(startPos); + char chPrev = ' '; + // + for (int i = startPos; i < endPos; i++) { + char ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + if (IsAWordChar(ch)) { + visibleChars++; + } + // get the syle for the current character neede to check in comment + int stylech = styler.StyleAt(i); + // get first word for the line for indent check max 9 characters + if (FirstWordStart && (!(FirstWordEnd))) { + if (!IsAWordChar(ch)) { + FirstWordEnd = true; + szKeyword[szKeywordlen] = '\0'; + } + else { + if (szKeywordlen < 10) { + szKeyword[szKeywordlen++] = static_cast(tolower(ch)); + } + } + } + // start the capture of the first word + if (!(FirstWordStart)) { + if (IsAWordChar(ch) || IsAWordStart(ch) || ch == ';') { + FirstWordStart = true; + szKeyword[szKeywordlen++] = static_cast(tolower(ch)); + } + } + // only process this logic when not in comment section + if (!(stylech == SCE_AU3_COMMENT)) { + if (ThenFoundLast) { + if (IsAWordChar(ch)) { + ThenFoundLast = false; + } + } + // find out if the word "then" is the last on a "if" line + if (FirstWordEnd && strcmp(szKeyword,"if") == 0) { + if (szThenlen == 4) { + szThen[0] = szThen[1]; + szThen[1] = szThen[2]; + szThen[2] = szThen[3]; + szThen[3] = static_cast(tolower(ch)); + if (strcmp(szThen,"then") == 0 ) { + ThenFoundLast = true; + } + } + else { + szThen[szThenlen++] = static_cast(tolower(ch)); + if (szThenlen == 5) { + szThen[4] = '\0'; + } + } + } + } + // End of Line found so process the information + if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) { + // ************************** + // Folding logic for Keywords + // ************************** + // if a keyword is found on the current line and the line doesn't end with _ (continuation) + // and we are not inside a commentblock. + if (szKeywordlen > 0 && (!(chPrev == '_')) && + ((!(IsStreamCommentStyle(style)) || foldInComment)) ) { + szKeyword[szKeywordlen] = '\0'; + // only fold "if" last keyword is "then" (else its a one line if) + if (strcmp(szKeyword,"if") == 0 && ThenFoundLast) { + levelNext++; + } + // create new fold for these words + if (strcmp(szKeyword,"do") == 0 || strcmp(szKeyword,"for") == 0 || + strcmp(szKeyword,"func") == 0 || strcmp(szKeyword,"while") == 0|| + strcmp(szKeyword,"with") == 0 || strcmp(szKeyword,"#region") == 0 ) { + levelNext++; + } + // create double Fold for select&switch because Case will subtract one of the current level + if (strcmp(szKeyword,"select") == 0 || strcmp(szKeyword,"switch") == 0) { + levelNext++; + levelNext++; + } + // end the fold for these words before the current line + if (strcmp(szKeyword,"endfunc") == 0 || strcmp(szKeyword,"endif") == 0 || + strcmp(szKeyword,"next") == 0 || strcmp(szKeyword,"until") == 0 || + strcmp(szKeyword,"endwith") == 0 ||strcmp(szKeyword,"wend") == 0){ + levelNext--; + levelCurrent--; + } + // end the fold for these words before the current line and Start new fold + if (strcmp(szKeyword,"case") == 0 || strcmp(szKeyword,"else") == 0 || + strcmp(szKeyword,"elseif") == 0 ) { + levelCurrent--; + } + // end the double fold for this word before the current line + if (strcmp(szKeyword,"endselect") == 0 || strcmp(szKeyword,"endswitch") == 0 ) { + levelNext--; + levelNext--; + levelCurrent--; + levelCurrent--; + } + // end the fold for these words on the current line + if (strcmp(szKeyword,"#endregion") == 0 ) { + levelNext--; + } + } + // Preprocessor and Comment folding + int styleNext = GetStyleFirstWord(lineCurrent + 1,styler); + // ************************************* + // Folding logic for preprocessor blocks + // ************************************* + // process preprosessor line + if (foldpreprocessor && style == SCE_AU3_PREPROCESSOR) { + if (!(stylePrev == SCE_AU3_PREPROCESSOR) && (styleNext == SCE_AU3_PREPROCESSOR)) { + levelNext++; + } + // fold till the last line for normal comment lines + else if (stylePrev == SCE_AU3_PREPROCESSOR && !(styleNext == SCE_AU3_PREPROCESSOR)) { + levelNext--; + } + } + // ********************************* + // Folding logic for Comment blocks + // ********************************* + if (foldComment && IsStreamCommentStyle(style)) { + // Start of a comment block + if (!(stylePrev==style) && IsStreamCommentStyle(styleNext) && styleNext==style) { + levelNext++; + } + // fold till the last line for normal comment lines + else if (IsStreamCommentStyle(stylePrev) + && !(styleNext == SCE_AU3_COMMENT) + && stylePrev == SCE_AU3_COMMENT + && style == SCE_AU3_COMMENT) { + levelNext--; + } + // fold till the one but last line for Blockcomment lines + else if (IsStreamCommentStyle(stylePrev) + && !(styleNext == SCE_AU3_COMMENTBLOCK) + && style == SCE_AU3_COMMENTBLOCK) { + levelNext--; + levelCurrent--; + } + } + int levelUse = levelCurrent; + 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); + } + // reset values for the next line + lineCurrent++; + stylePrev = style; + style = styleNext; + levelCurrent = levelNext; + visibleChars = 0; + // if the last character is an Underscore then don't reset since the line continues on the next line. + if (!(chPrev == '_')) { + szKeywordlen = 0; + szThenlen = 0; + FirstWordStart = false; + FirstWordEnd = false; + ThenFoundLast = false; + } + } + // save the last processed character + if (!isspacechar(ch)) { + chPrev = ch; + visibleChars++; + } + } +} + + +// + +static const char * const AU3WordLists[] = { + "#autoit keywords", + "#autoit functions", + "#autoit macros", + "#autoit Sent keys", + "#autoit Pre-processors", + "#autoit Special", + "#autoit Expand", + "#autoit UDF", + 0 +}; +LexerModule lmAU3(SCLEX_AU3, ColouriseAU3Doc, "au3", FoldAU3Doc , AU3WordLists); diff --git a/scintilla/src/LexAVE.cxx b/scintilla/src/LexAVE.cxx new file mode 100644 index 00000000..8b2a1dc5 --- /dev/null +++ b/scintilla/src/LexAVE.cxx @@ -0,0 +1,229 @@ +// SciTE - Scintilla based Text Editor +/** @file LexAVE.cxx + ** Lexer for Avenue. + ** + ** Written by Alexey Yutkin . + **/ +// Copyright 1998-2002 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + + +static inline bool IsAWordChar(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); +} +static inline bool IsEnumChar(const int ch) { + return (ch < 0x80) && (isalnum(ch)|| ch == '_'); +} +static inline bool IsANumberChar(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '.' ); +} + +inline bool IsAWordStart(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '_'); +} + +inline bool isAveOperator(char ch) { + if (isalnum(ch)) + return false; + // '.' left out as it is used to make up numbers + if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || + ch == '(' || ch == ')' || ch == '=' || + ch == '{' || ch == '}' || + ch == '[' || ch == ']' || ch == ';' || + ch == '<' || ch == '>' || ch == ',' || + ch == '.' ) + return true; + return false; +} + +static void ColouriseAveDoc( + unsigned int startPos, + int length, + int initStyle, + WordList *keywordlists[], + Accessor &styler) { + + WordList &keywords = *keywordlists[0]; + WordList &keywords2 = *keywordlists[1]; + WordList &keywords3 = *keywordlists[2]; + WordList &keywords4 = *keywordlists[3]; + WordList &keywords5 = *keywordlists[4]; + WordList &keywords6 = *keywordlists[5]; + + // Do not leak onto next line + if (initStyle == SCE_AVE_STRINGEOL) { + initStyle = SCE_AVE_DEFAULT; + } + + StyleContext sc(startPos, length, initStyle, styler); + + for (; sc.More(); sc.Forward()) { + if (sc.atLineEnd) { + // Update the line state, so it can be seen by next line + int currentLine = styler.GetLine(sc.currentPos); + styler.SetLineState(currentLine, 0); + } + if (sc.atLineStart && (sc.state == SCE_AVE_STRING)) { + // Prevent SCE_AVE_STRINGEOL from leaking back to previous line + sc.SetState(SCE_AVE_STRING); + } + + + // Determine if the current state should terminate. + if (sc.state == SCE_AVE_OPERATOR) { + sc.SetState(SCE_AVE_DEFAULT); + } else if (sc.state == SCE_AVE_NUMBER) { + if (!IsANumberChar(sc.ch)) { + sc.SetState(SCE_AVE_DEFAULT); + } + } else if (sc.state == SCE_AVE_ENUM) { + if (!IsEnumChar(sc.ch)) { + sc.SetState(SCE_AVE_DEFAULT); + } + } else if (sc.state == SCE_AVE_IDENTIFIER) { + if (!IsAWordChar(sc.ch) || (sc.ch == '.')) { + char s[100]; + //sc.GetCurrent(s, sizeof(s)); + sc.GetCurrentLowered(s, sizeof(s)); + if (keywords.InList(s)) { + sc.ChangeState(SCE_AVE_WORD); + } else if (keywords2.InList(s)) { + sc.ChangeState(SCE_AVE_WORD2); + } else if (keywords3.InList(s)) { + sc.ChangeState(SCE_AVE_WORD3); + } else if (keywords4.InList(s)) { + sc.ChangeState(SCE_AVE_WORD4); + } else if (keywords5.InList(s)) { + sc.ChangeState(SCE_AVE_WORD5); + } else if (keywords6.InList(s)) { + sc.ChangeState(SCE_AVE_WORD6); + } + sc.SetState(SCE_AVE_DEFAULT); + } + } else if (sc.state == SCE_AVE_COMMENT) { + if (sc.atLineEnd) { + sc.SetState(SCE_AVE_DEFAULT); + } + } else if (sc.state == SCE_AVE_STRING) { + if (sc.ch == '\"') { + sc.ForwardSetState(SCE_AVE_DEFAULT); + } else if (sc.atLineEnd) { + sc.ChangeState(SCE_AVE_STRINGEOL); + sc.ForwardSetState(SCE_AVE_DEFAULT); + } + } + + // Determine if a new state should be entered. + if (sc.state == SCE_AVE_DEFAULT) { + if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { + sc.SetState(SCE_AVE_NUMBER); + } else if (IsAWordStart(sc.ch)) { + sc.SetState(SCE_AVE_IDENTIFIER); + } else if (sc.Match('\"')) { + sc.SetState(SCE_AVE_STRING); + } else if (sc.Match('\'')) { + sc.SetState(SCE_AVE_COMMENT); + sc.Forward(); + } else if (isAveOperator(static_cast(sc.ch))) { + sc.SetState(SCE_AVE_OPERATOR); + } else if (sc.Match('#')) { + sc.SetState(SCE_AVE_ENUM); + sc.Forward(); + } + } + } + sc.Complete(); +} + +static void FoldAveDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[], + Accessor &styler) { + unsigned int lengthDoc = startPos + length; + int visibleChars = 0; + int lineCurrent = styler.GetLine(startPos); + int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; + int levelCurrent = levelPrev; + char chNext = static_cast(tolower(styler[startPos])); + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + int styleNext = styler.StyleAt(startPos); + char s[10]; + + for (unsigned int i = startPos; i < lengthDoc; i++) { + char ch = static_cast(tolower(chNext)); + chNext = static_cast(tolower(styler.SafeGetCharAt(i + 1))); + int style = styleNext; + styleNext = styler.StyleAt(i + 1); + bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); + if (style == SCE_AVE_WORD) { + if (ch == 't' || ch == 'f' || ch == 'w' || ch == 'e') { + for (unsigned int j = 0; j < 6; j++) { + if (!iswordchar(styler[i + j])) { + break; + } + s[j] = static_cast(tolower(styler[i + j])); + s[j + 1] = '\0'; + } + + if ((strcmp(s, "then") == 0) || (strcmp(s, "for") == 0) || (strcmp(s, "while") == 0)) { + levelCurrent++; + } + if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0)) { + // Normally "elseif" and "then" will be on the same line and will cancel + // each other out. // As implemented, this does not support fold.at.else. + levelCurrent--; + } + } + } else if (style == SCE_AVE_OPERATOR) { + if (ch == '{' || ch == '(') { + levelCurrent++; + } else if (ch == '}' || ch == ')') { + levelCurrent--; + } + } + + if (atEOL) { + int lev = levelPrev; + if (visibleChars == 0 && foldCompact) { + lev |= SC_FOLDLEVELWHITEFLAG; + } + if ((levelCurrent > levelPrev) && (visibleChars > 0)) { + lev |= SC_FOLDLEVELHEADERFLAG; + } + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelPrev = levelCurrent; + visibleChars = 0; + } + if (!isspacechar(ch)) { + visibleChars++; + } + } + // Fill in the real level of the next line, keeping the current flags as they will be filled in later + + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, levelPrev | flagsNext); +} + +LexerModule lmAVE(SCLEX_AVE, ColouriseAveDoc, "ave", FoldAveDoc); + + diff --git a/scintilla/src/LexAbaqus.cxx b/scintilla/src/LexAbaqus.cxx new file mode 100644 index 00000000..f0c37808 --- /dev/null +++ b/scintilla/src/LexAbaqus.cxx @@ -0,0 +1,260 @@ +// Scintilla source code edit control +/** @file LexABAQUS.cxx + ** Lexer for ABAQUS. Based on the lexer for APDL by Hadar Raz. + ** By Sergio Lucato. + **/ +// The License.txt file describes the conditions under which this software may be distributed. + +// Code folding copyied and modified from LexBasic.cxx + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static inline bool IsAWordChar(const int ch) { + return (ch < 0x80 && (isalnum(ch) || ch == '_')); +} + +static inline bool IsAnOperator(char ch) { + // '.' left out as it is used to make up numbers + if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || + ch == '(' || ch == ')' || ch == '=' || ch == '^' || + ch == '[' || ch == ']' || ch == '<' || ch == '&' || + ch == '>' || ch == ',' || ch == '|' || ch == '~' || + ch == '$' || ch == ':' || ch == '%') + return true; + return false; +} + +static void ColouriseABAQUSDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler) { + + int stringStart = ' '; + + WordList &processors = *keywordlists[0]; + WordList &commands = *keywordlists[1]; + WordList &slashcommands = *keywordlists[2]; + WordList &starcommands = *keywordlists[3]; + WordList &arguments = *keywordlists[4]; + WordList &functions = *keywordlists[5]; + + // Do not leak onto next line + initStyle = SCE_ABAQUS_DEFAULT; + StyleContext sc(startPos, length, initStyle, styler); + + for (; sc.More(); sc.Forward()) { + // Determine if the current state should terminate. + if (sc.state == SCE_ABAQUS_NUMBER) { + if (!(IsADigit(sc.ch) || sc.ch == '.' || (sc.ch == 'e' || sc.ch == 'E') || + ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E')))) { + sc.SetState(SCE_ABAQUS_DEFAULT); + } + } else if (sc.state == SCE_ABAQUS_COMMENT) { + if (sc.atLineEnd) { + sc.SetState(SCE_ABAQUS_DEFAULT); + } + } else if (sc.state == SCE_ABAQUS_COMMENTBLOCK) { + if (sc.atLineEnd) { + if (sc.ch == '\r') { + sc.Forward(); + } + sc.ForwardSetState(SCE_ABAQUS_DEFAULT); + } + } else if (sc.state == SCE_ABAQUS_STRING) { + if (sc.atLineEnd) { + sc.SetState(SCE_ABAQUS_DEFAULT); + } else if ((sc.ch == '\'' && stringStart == '\'') || (sc.ch == '\"' && stringStart == '\"')) { + sc.ForwardSetState(SCE_ABAQUS_DEFAULT); + } + } else if (sc.state == SCE_ABAQUS_WORD) { + if (!IsAWordChar(sc.ch)) { + char s[100]; + sc.GetCurrentLowered(s, sizeof(s)); + if (processors.InList(s)) { + sc.ChangeState(SCE_ABAQUS_PROCESSOR); + } else if (slashcommands.InList(s)) { + sc.ChangeState(SCE_ABAQUS_SLASHCOMMAND); + } else if (starcommands.InList(s)) { + sc.ChangeState(SCE_ABAQUS_STARCOMMAND); + } else if (commands.InList(s)) { + sc.ChangeState(SCE_ABAQUS_COMMAND); + } else if (arguments.InList(s)) { + sc.ChangeState(SCE_ABAQUS_ARGUMENT); + } else if (functions.InList(s)) { + sc.ChangeState(SCE_ABAQUS_FUNCTION); + } + sc.SetState(SCE_ABAQUS_DEFAULT); + } + } else if (sc.state == SCE_ABAQUS_OPERATOR) { + if (!IsAnOperator(static_cast(sc.ch))) { + sc.SetState(SCE_ABAQUS_DEFAULT); + } + } + + // Determine if a new state should be entered. + if (sc.state == SCE_ABAQUS_DEFAULT) { + if (sc.ch == '*' && sc.chNext == '*') { + sc.SetState(SCE_ABAQUS_COMMENTBLOCK); + } else if (sc.ch == '!') { + sc.SetState(SCE_ABAQUS_COMMENT); + } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { + sc.SetState(SCE_ABAQUS_NUMBER); + } else if (sc.ch == '\'' || sc.ch == '\"') { + sc.SetState(SCE_ABAQUS_STRING); + stringStart = sc.ch; + } else if (IsAWordChar(sc.ch) || ((sc.ch == '*' || sc.ch == '/') && !isgraph(sc.chPrev))) { + sc.SetState(SCE_ABAQUS_WORD); + } else if (IsAnOperator(static_cast(sc.ch))) { + sc.SetState(SCE_ABAQUS_OPERATOR); + } + } + } + sc.Complete(); +} + +//------------------------------------------------------------------------------ +// This copyied and modified from LexBasic.cxx +//------------------------------------------------------------------------------ + +/* Bits: + * 1 - whitespace + * 2 - operator + * 4 - identifier + * 8 - decimal digit + * 16 - hex digit + * 32 - bin digit + */ +static int character_classification[128] = +{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 2, 0, 2, 2, 2, 2, 2, 2, 2, 6, 2, 2, 2, 10, 6, + 60, 60, 28, 28, 28, 28, 28, 28, 28, 28, 2, 2, 2, 2, 2, 2, + 2, 20, 20, 20, 20, 20, 20, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 4, + 2, 20, 20, 20, 20, 20, 20, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 0 +}; + +static bool IsSpace(int c) { + return c < 128 && (character_classification[c] & 1); +} + +static bool IsIdentifier(int c) { + return c < 128 && (character_classification[c] & 4); +} + +static int LowerCase(int c) +{ + if (c >= 'A' && c <= 'Z') + return 'a' + c - 'A'; + return c; +} + +static int CheckABAQUSFoldPoint(char const *token, int &level) { + if (!strcmp(token, "*step") || + !strcmp(token, "*part") || + !strcmp(token, "*instance") || + !strcmp(token, "*assembly") || + !strcmp(token, "***region") ) { + level |= SC_FOLDLEVELHEADERFLAG; + return 1; + } + if (!strcmp(token, "*end step") || + !strcmp(token, "*end part") || + !strcmp(token, "*end instance") || + !strcmp(token, "*end assembly") || + !strcmp(token, "***end region") ) { + return -1; + } + return 0; +} + +static void FoldABAQUSDoc(unsigned int startPos, int length, int, + WordList *[], Accessor &styler) { + + int line = styler.GetLine(startPos); + int level = styler.LevelAt(line); + int go = 0, done = 0; + int endPos = startPos + length; + char word[256]; + int wordlen = 0; + int i; + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + // Scan for tokens at the start of the line (they may include + // whitespace, for tokens like "End Function" + for (i = startPos; i < endPos; i++) { + int c = styler.SafeGetCharAt(i); + if (!done && !go) { + if (wordlen) { // are we scanning a token already? + word[wordlen] = static_cast(LowerCase(c)); + if (!IsIdentifier(c)) { // done with token + word[wordlen] = '\0'; + go = CheckABAQUSFoldPoint(word, level); + if (!go) { + // Treat any whitespace as single blank, for + // things like "End Function". + if (IsSpace(c) && IsIdentifier(word[wordlen - 1])) { + word[wordlen] = ' '; + if (wordlen < 255) + wordlen++; + } + else // done with this line + done = 1; + } + } else if (wordlen < 255) { + wordlen++; + } + } else { // start scanning at first non-whitespace character + if (!IsSpace(c)) { + if (IsIdentifier(c)) { + word[0] = static_cast(LowerCase(c)); + wordlen = 1; + } else // done with this line + done = 1; + } + } + } + if (c == '\n') { // line end + if (!done && wordlen == 0 && foldCompact) // line was only space + level |= SC_FOLDLEVELWHITEFLAG; + if (level != styler.LevelAt(line)) + styler.SetLevel(line, level); + level += go; + line++; + // reset state + wordlen = 0; + level &= ~SC_FOLDLEVELHEADERFLAG; + level &= ~SC_FOLDLEVELWHITEFLAG; + go = 0; + done = 0; + } + } +} + +static const char * const abaqusWordListDesc[] = { + "processors", + "commands", + "slashommands", + "starcommands", + "arguments", + "functions", + 0 +}; + +LexerModule lmAbaqus(SCLEX_ABAQUS, ColouriseABAQUSDoc, "abaqus", FoldABAQUSDoc, abaqusWordListDesc); diff --git a/scintilla/src/LexAda.cxx b/scintilla/src/LexAda.cxx new file mode 100644 index 00000000..9d1b4570 --- /dev/null +++ b/scintilla/src/LexAda.cxx @@ -0,0 +1,524 @@ +// Scintilla source code edit control +/** @file LexAda.cxx + ** Lexer for Ada 95 + **/ +// Copyright 2002 by Sergey Koshcheyev +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include + +#include "Platform.h" + +#include "Accessor.h" +#include "StyleContext.h" +#include "PropSet.h" +#include "KeyWords.h" +#include "SciLexer.h" +#include "SString.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +/* + * Interface + */ + +static void ColouriseDocument( + unsigned int startPos, + int length, + int initStyle, + WordList *keywordlists[], + Accessor &styler); + +static const char * const adaWordListDesc[] = { + "Keywords", + 0 +}; + +LexerModule lmAda(SCLEX_ADA, ColouriseDocument, "ada", NULL, adaWordListDesc); + +/* + * Implementation + */ + +// Functions that have apostropheStartsAttribute as a parameter set it according to whether +// an apostrophe encountered after processing the current token will start an attribute or +// a character literal. +static void ColouriseCharacter(StyleContext& sc, bool& apostropheStartsAttribute); +static void ColouriseComment(StyleContext& sc, bool& apostropheStartsAttribute); +static void ColouriseContext(StyleContext& sc, char chEnd, int stateEOL); +static void ColouriseDelimiter(StyleContext& sc, bool& apostropheStartsAttribute); +static void ColouriseLabel(StyleContext& sc, WordList& keywords, bool& apostropheStartsAttribute); +static void ColouriseNumber(StyleContext& sc, bool& apostropheStartsAttribute); +static void ColouriseString(StyleContext& sc, bool& apostropheStartsAttribute); +static void ColouriseWhiteSpace(StyleContext& sc, bool& apostropheStartsAttribute); +static void ColouriseWord(StyleContext& sc, WordList& keywords, bool& apostropheStartsAttribute); + +static inline bool IsDelimiterCharacter(int ch); +static inline bool IsNumberStartCharacter(int ch); +static inline bool IsNumberCharacter(int ch); +static inline bool IsSeparatorOrDelimiterCharacter(int ch); +static bool IsValidIdentifier(const SString& identifier); +static bool IsValidNumber(const SString& number); +static inline bool IsWordStartCharacter(int ch); +static inline bool IsWordCharacter(int ch); + +static void ColouriseCharacter(StyleContext& sc, bool& apostropheStartsAttribute) { + apostropheStartsAttribute = true; + + sc.SetState(SCE_ADA_CHARACTER); + + // Skip the apostrophe and one more character (so that '' is shown as non-terminated and ''' + // is handled correctly) + sc.Forward(); + sc.Forward(); + + ColouriseContext(sc, '\'', SCE_ADA_CHARACTEREOL); +} + +static void ColouriseContext(StyleContext& sc, char chEnd, int stateEOL) { + while (!sc.atLineEnd && !sc.Match(chEnd)) { + sc.Forward(); + } + + if (!sc.atLineEnd) { + sc.ForwardSetState(SCE_ADA_DEFAULT); + } else { + sc.ChangeState(stateEOL); + } +} + +static void ColouriseComment(StyleContext& sc, bool& /*apostropheStartsAttribute*/) { + // Apostrophe meaning is not changed, but the parameter is present for uniformity + + sc.SetState(SCE_ADA_COMMENTLINE); + + while (!sc.atLineEnd) { + sc.Forward(); + } +} + +static void ColouriseDelimiter(StyleContext& sc, bool& apostropheStartsAttribute) { + apostropheStartsAttribute = sc.Match (')'); + sc.SetState(SCE_ADA_DELIMITER); + sc.ForwardSetState(SCE_ADA_DEFAULT); +} + +static void ColouriseLabel(StyleContext& sc, WordList& keywords, bool& apostropheStartsAttribute) { + apostropheStartsAttribute = false; + + sc.SetState(SCE_ADA_LABEL); + + // Skip "<<" + sc.Forward(); + sc.Forward(); + + SString identifier; + + while (!sc.atLineEnd && !IsSeparatorOrDelimiterCharacter(sc.ch)) { + identifier += static_cast(tolower(sc.ch)); + sc.Forward(); + } + + // Skip ">>" + if (sc.Match('>', '>')) { + sc.Forward(); + sc.Forward(); + } else { + sc.ChangeState(SCE_ADA_ILLEGAL); + } + + // If the name is an invalid identifier or a keyword, then make it invalid label + if (!IsValidIdentifier(identifier) || keywords.InList(identifier.c_str())) { + sc.ChangeState(SCE_ADA_ILLEGAL); + } + + sc.SetState(SCE_ADA_DEFAULT); + +} + +static void ColouriseNumber(StyleContext& sc, bool& apostropheStartsAttribute) { + apostropheStartsAttribute = true; + + SString number; + sc.SetState(SCE_ADA_NUMBER); + + // Get all characters up to a delimiter or a separator, including points, but excluding + // double points (ranges). + while (!IsSeparatorOrDelimiterCharacter(sc.ch) || (sc.ch == '.' && sc.chNext != '.')) { + number += static_cast(sc.ch); + sc.Forward(); + } + + // Special case: exponent with sign + if ((sc.chPrev == 'e' || sc.chPrev == 'E') && + (sc.ch == '+' || sc.ch == '-')) { + number += static_cast(sc.ch); + sc.Forward (); + + while (!IsSeparatorOrDelimiterCharacter(sc.ch)) { + number += static_cast(sc.ch); + sc.Forward(); + } + } + + if (!IsValidNumber(number)) { + sc.ChangeState(SCE_ADA_ILLEGAL); + } + + sc.SetState(SCE_ADA_DEFAULT); +} + +static void ColouriseString(StyleContext& sc, bool& apostropheStartsAttribute) { + apostropheStartsAttribute = true; + + sc.SetState(SCE_ADA_STRING); + sc.Forward(); + + ColouriseContext(sc, '"', SCE_ADA_STRINGEOL); +} + +static void ColouriseWhiteSpace(StyleContext& sc, bool& /*apostropheStartsAttribute*/) { + // Apostrophe meaning is not changed, but the parameter is present for uniformity + sc.SetState(SCE_ADA_DEFAULT); + sc.ForwardSetState(SCE_ADA_DEFAULT); +} + +static void ColouriseWord(StyleContext& sc, WordList& keywords, bool& apostropheStartsAttribute) { + apostropheStartsAttribute = true; + sc.SetState(SCE_ADA_IDENTIFIER); + + SString word; + + while (!sc.atLineEnd && !IsSeparatorOrDelimiterCharacter(sc.ch)) { + word += static_cast(tolower(sc.ch)); + sc.Forward(); + } + + if (!IsValidIdentifier(word)) { + sc.ChangeState(SCE_ADA_ILLEGAL); + + } else if (keywords.InList(word.c_str())) { + sc.ChangeState(SCE_ADA_WORD); + + if (word != "all") { + apostropheStartsAttribute = false; + } + } + + sc.SetState(SCE_ADA_DEFAULT); +} + +// +// ColouriseDocument +// + +static void ColouriseDocument( + unsigned int startPos, + int length, + int initStyle, + WordList *keywordlists[], + Accessor &styler) { + WordList &keywords = *keywordlists[0]; + + StyleContext sc(startPos, length, initStyle, styler); + + int lineCurrent = styler.GetLine(startPos); + bool apostropheStartsAttribute = (styler.GetLineState(lineCurrent) & 1) != 0; + + while (sc.More()) { + if (sc.atLineEnd) { + // Go to the next line + sc.Forward(); + lineCurrent++; + + // Remember the line state for future incremental lexing + styler.SetLineState(lineCurrent, apostropheStartsAttribute); + + // Don't continue any styles on the next line + sc.SetState(SCE_ADA_DEFAULT); + } + + // Comments + if (sc.Match('-', '-')) { + ColouriseComment(sc, apostropheStartsAttribute); + + // Strings + } else if (sc.Match('"')) { + ColouriseString(sc, apostropheStartsAttribute); + + // Characters + } else if (sc.Match('\'') && !apostropheStartsAttribute) { + ColouriseCharacter(sc, apostropheStartsAttribute); + + // Labels + } else if (sc.Match('<', '<')) { + ColouriseLabel(sc, keywords, apostropheStartsAttribute); + + // Whitespace + } else if (IsASpace(sc.ch)) { + ColouriseWhiteSpace(sc, apostropheStartsAttribute); + + // Delimiters + } else if (IsDelimiterCharacter(sc.ch)) { + ColouriseDelimiter(sc, apostropheStartsAttribute); + + // Numbers + } else if (IsADigit(sc.ch) || sc.ch == '#') { + ColouriseNumber(sc, apostropheStartsAttribute); + + // Keywords or identifiers + } else { + ColouriseWord(sc, keywords, apostropheStartsAttribute); + } + } + + sc.Complete(); +} + +static inline bool IsDelimiterCharacter(int ch) { + switch (ch) { + case '&': + case '\'': + case '(': + case ')': + case '*': + case '+': + case ',': + case '-': + case '.': + case '/': + case ':': + case ';': + case '<': + case '=': + case '>': + case '|': + return true; + default: + return false; + } +} + +static inline bool IsNumberCharacter(int ch) { + return IsNumberStartCharacter(ch) || + ch == '_' || + ch == '.' || + ch == '#' || + (ch >= 'a' && ch <= 'f') || + (ch >= 'A' && ch <= 'F'); +} + +static inline bool IsNumberStartCharacter(int ch) { + return IsADigit(ch); +} + +static inline bool IsSeparatorOrDelimiterCharacter(int ch) { + return IsASpace(ch) || IsDelimiterCharacter(ch); +} + +static bool IsValidIdentifier(const SString& identifier) { + // First character can't be '_', so initialize the flag to true + bool lastWasUnderscore = true; + + size_t length = identifier.length(); + + // Zero-length identifiers are not valid (these can occur inside labels) + if (length == 0) { + return false; + } + + // Check for valid character at the start + if (!IsWordStartCharacter(identifier[0])) { + return false; + } + + // Check for only valid characters and no double underscores + for (size_t i = 0; i < length; i++) { + if (!IsWordCharacter(identifier[i]) || + (identifier[i] == '_' && lastWasUnderscore)) { + return false; + } + lastWasUnderscore = identifier[i] == '_'; + } + + // Check for underscore at the end + if (lastWasUnderscore == true) { + return false; + } + + // All checks passed + return true; +} + +static bool IsValidNumber(const SString& number) { + int hashPos = number.search("#"); + bool seenDot = false; + + size_t i = 0; + size_t length = number.length(); + + if (length == 0) + return false; // Just in case + + // Decimal number + if (hashPos == -1) { + bool canBeSpecial = false; + + for (; i < length; i++) { + if (number[i] == '_') { + if (!canBeSpecial) { + return false; + } + canBeSpecial = false; + } else if (number[i] == '.') { + if (!canBeSpecial || seenDot) { + return false; + } + canBeSpecial = false; + seenDot = true; + } else if (IsADigit(number[i])) { + canBeSpecial = true; + } else { + break; + } + } + + if (!canBeSpecial) + return false; + } else { + // Based number + bool canBeSpecial = false; + int base = 0; + + // Parse base + for (; i < length; i++) { + int ch = number[i]; + if (ch == '_') { + if (!canBeSpecial) + return false; + canBeSpecial = false; + } else if (IsADigit(ch)) { + base = base * 10 + (ch - '0'); + if (base > 16) + return false; + canBeSpecial = true; + } else if (ch == '#' && canBeSpecial) { + break; + } else { + return false; + } + } + + if (base < 2) + return false; + if (i == length) + return false; + + i++; // Skip over '#' + + // Parse number + canBeSpecial = false; + + for (; i < length; i++) { + int ch = tolower(number[i]); + + if (ch == '_') { + if (!canBeSpecial) { + return false; + } + canBeSpecial = false; + + } else if (ch == '.') { + if (!canBeSpecial || seenDot) { + return false; + } + canBeSpecial = false; + seenDot = true; + + } else if (IsADigit(ch)) { + if (ch - '0' >= base) { + return false; + } + canBeSpecial = true; + + } else if (ch >= 'a' && ch <= 'f') { + if (ch - 'a' + 10 >= base) { + return false; + } + canBeSpecial = true; + + } else if (ch == '#' && canBeSpecial) { + break; + + } else { + return false; + } + } + + if (i == length) { + return false; + } + + i++; + } + + // Exponent (optional) + if (i < length) { + if (number[i] != 'e' && number[i] != 'E') + return false; + + i++; // Move past 'E' + + if (i == length) { + return false; + } + + if (number[i] == '+') + i++; + else if (number[i] == '-') { + if (seenDot) { + i++; + } else { + return false; // Integer literals should not have negative exponents + } + } + + if (i == length) { + return false; + } + + bool canBeSpecial = false; + + for (; i < length; i++) { + if (number[i] == '_') { + if (!canBeSpecial) { + return false; + } + canBeSpecial = false; + } else if (IsADigit(number[i])) { + canBeSpecial = true; + } else { + return false; + } + } + + if (!canBeSpecial) + return false; + } + + // if i == length, number was parsed successfully. + return i == length; +} + +static inline bool IsWordCharacter(int ch) { + return IsWordStartCharacter(ch) || IsADigit(ch); +} + +static inline bool IsWordStartCharacter(int ch) { + return (isascii(ch) && isalpha(ch)) || ch == '_'; +} diff --git a/scintilla/src/LexAsm.cxx b/scintilla/src/LexAsm.cxx new file mode 100644 index 00000000..d80546fb --- /dev/null +++ b/scintilla/src/LexAsm.cxx @@ -0,0 +1,181 @@ +// Scintilla source code edit control +/** @file LexAsm.cxx + ** Lexer for Assembler, just for the MASM syntax + ** Written by The Black Horus + ** Enhancements and NASM stuff by Kein-Hong Man, 2003-10 + ** SCE_ASM_COMMENTBLOCK and SCE_ASM_CHARACTER are for future GNU as colouring + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static inline bool IsAWordChar(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '.' || + ch == '_' || ch == '?'); +} + +static inline bool IsAWordStart(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.' || + ch == '%' || ch == '@' || ch == '$' || ch == '?'); +} + +static inline bool IsAsmOperator(char ch) { + if (isalnum(ch)) + return false; + // '.' left out as it is used to make up numbers + if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || + ch == '(' || ch == ')' || ch == '=' || ch == '^' || + ch == '[' || ch == ']' || ch == '<' || ch == '&' || + ch == '>' || ch == ',' || ch == '|' || ch == '~' || + ch == '%' || ch == ':') + return true; + return false; +} + +static void ColouriseAsmDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler) { + + WordList &cpuInstruction = *keywordlists[0]; + WordList &mathInstruction = *keywordlists[1]; + WordList ®isters = *keywordlists[2]; + WordList &directive = *keywordlists[3]; + WordList &directiveOperand = *keywordlists[4]; + WordList &extInstruction = *keywordlists[5]; + + // Do not leak onto next line + if (initStyle == SCE_ASM_STRINGEOL) + initStyle = SCE_ASM_DEFAULT; + + StyleContext sc(startPos, length, initStyle, styler); + + for (; sc.More(); sc.Forward()) + { + + // Prevent SCE_ASM_STRINGEOL from leaking back to previous line + if (sc.atLineStart && (sc.state == SCE_ASM_STRING)) { + sc.SetState(SCE_ASM_STRING); + } else if (sc.atLineStart && (sc.state == SCE_ASM_CHARACTER)) { + sc.SetState(SCE_ASM_CHARACTER); + } + + // 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(); + } + continue; + } + } + + // Determine if the current state should terminate. + if (sc.state == SCE_ASM_OPERATOR) { + if (!IsAsmOperator(static_cast(sc.ch))) { + sc.SetState(SCE_ASM_DEFAULT); + } + }else if (sc.state == SCE_ASM_NUMBER) { + if (!IsAWordChar(sc.ch)) { + sc.SetState(SCE_ASM_DEFAULT); + } + } else if (sc.state == SCE_ASM_IDENTIFIER) { + if (!IsAWordChar(sc.ch) ) { + char s[100]; + sc.GetCurrentLowered(s, sizeof(s)); + + if (cpuInstruction.InList(s)) { + sc.ChangeState(SCE_ASM_CPUINSTRUCTION); + } else if (mathInstruction.InList(s)) { + sc.ChangeState(SCE_ASM_MATHINSTRUCTION); + } else if (registers.InList(s)) { + sc.ChangeState(SCE_ASM_REGISTER); + } else if (directive.InList(s)) { + sc.ChangeState(SCE_ASM_DIRECTIVE); + } else if (directiveOperand.InList(s)) { + sc.ChangeState(SCE_ASM_DIRECTIVEOPERAND); + } else if (extInstruction.InList(s)) { + sc.ChangeState(SCE_ASM_EXTINSTRUCTION); + } + sc.SetState(SCE_ASM_DEFAULT); + } + } + else if (sc.state == SCE_ASM_COMMENT ) { + if (sc.atLineEnd) { + sc.SetState(SCE_ASM_DEFAULT); + } + } else if (sc.state == SCE_ASM_STRING) { + if (sc.ch == '\\') { + if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { + sc.Forward(); + } + } else if (sc.ch == '\"') { + sc.ForwardSetState(SCE_ASM_DEFAULT); + } else if (sc.atLineEnd) { + sc.ChangeState(SCE_ASM_STRINGEOL); + sc.ForwardSetState(SCE_ASM_DEFAULT); + } + } else if (sc.state == SCE_ASM_CHARACTER) { + if (sc.ch == '\\') { + if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { + sc.Forward(); + } + } else if (sc.ch == '\'') { + sc.ForwardSetState(SCE_ASM_DEFAULT); + } else if (sc.atLineEnd) { + sc.ChangeState(SCE_ASM_STRINGEOL); + sc.ForwardSetState(SCE_ASM_DEFAULT); + } + } + + // Determine if a new state should be entered. + if (sc.state == SCE_ASM_DEFAULT) { + if (sc.ch == ';'){ + sc.SetState(SCE_ASM_COMMENT); + } else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) { + sc.SetState(SCE_ASM_NUMBER); + } else if (IsAWordStart(sc.ch)) { + sc.SetState(SCE_ASM_IDENTIFIER); + } else if (sc.ch == '\"') { + sc.SetState(SCE_ASM_STRING); + } else if (sc.ch == '\'') { + sc.SetState(SCE_ASM_CHARACTER); + } else if (IsAsmOperator(static_cast(sc.ch))) { + sc.SetState(SCE_ASM_OPERATOR); + } + } + + } + sc.Complete(); +} + +static const char * const asmWordListDesc[] = { + "CPU instructions", + "FPU instructions", + "Registers", + "Directives", + "Directive operands", + "Extended instructions", + 0 +}; + +LexerModule lmAsm(SCLEX_ASM, ColouriseAsmDoc, "asm", 0, asmWordListDesc); + + diff --git a/scintilla/src/LexAsn1.cxx b/scintilla/src/LexAsn1.cxx new file mode 100644 index 00000000..28bf6d91 --- /dev/null +++ b/scintilla/src/LexAsn1.cxx @@ -0,0 +1,185 @@ +// Scintilla source code edit control +/** @file LexAsn1.cxx + ** Lexer for ASN.1 + **/ +// Copyright 2004 by Herr Pfarrer rpfarrer yahoo de +// Last Updated: 20/07/2004 +// The License.txt file describes the conditions under which this software may be distributed. +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +// Some char test functions +static bool isAsn1Number(int ch) +{ + return (ch >= '0' && ch <= '9'); +} + +static bool isAsn1Letter(int ch) +{ + return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); +} + +static bool isAsn1Char(int ch) +{ + return (ch == '-' ) || isAsn1Number(ch) || isAsn1Letter (ch); +} + +// +// Function determining the color of a given code portion +// Based on a "state" +// +static void ColouriseAsn1Doc(unsigned int startPos, int length, int initStyle, WordList *keywordLists[], Accessor &styler) +{ + // The keywords + WordList &Keywords = *keywordLists[0]; + WordList &Attributes = *keywordLists[1]; + WordList &Descriptors = *keywordLists[2]; + WordList &Types = *keywordLists[3]; + + // Parse the whole buffer character by character using StyleContext + StyleContext sc(startPos, length, initStyle, styler); + for (; sc.More(); sc.Forward()) + { + // The state engine + switch (sc.state) + { + case SCE_ASN1_DEFAULT: // Plain characters +asn1_default: + if (sc.ch == '-' && sc.chNext == '-') + // A comment begins here + sc.SetState(SCE_ASN1_COMMENT); + else if (sc.ch == '"') + // A string begins here + sc.SetState(SCE_ASN1_STRING); + else if (isAsn1Number (sc.ch)) + // A number starts here (identifier should start with a letter in ASN.1) + sc.SetState(SCE_ASN1_SCALAR); + else if (isAsn1Char (sc.ch)) + // An identifier starts here (identifier always start with a letter) + sc.SetState(SCE_ASN1_IDENTIFIER); + else if (sc.ch == ':') + // A ::= operator starts here + sc.SetState(SCE_ASN1_OPERATOR); + break; + case SCE_ASN1_COMMENT: // A comment + if (sc.ch == '\r' || sc.ch == '\n') + // A comment ends here + sc.SetState(SCE_ASN1_DEFAULT); + break; + case SCE_ASN1_IDENTIFIER: // An identifier (keyword, attribute, descriptor or type) + if (!isAsn1Char (sc.ch)) + { + // The end of identifier is here: we can look for it in lists by now and change its state + char s[100]; + sc.GetCurrent(s, sizeof(s)); + if (Keywords.InList(s)) + // It's a keyword, change its state + sc.ChangeState(SCE_ASN1_KEYWORD); + else if (Attributes.InList(s)) + // It's an attribute, change its state + sc.ChangeState(SCE_ASN1_ATTRIBUTE); + else if (Descriptors.InList(s)) + // It's a descriptor, change its state + sc.ChangeState(SCE_ASN1_DESCRIPTOR); + else if (Types.InList(s)) + // It's a type, change its state + sc.ChangeState(SCE_ASN1_TYPE); + + // Set to default now + sc.SetState(SCE_ASN1_DEFAULT); + } + break; + case SCE_ASN1_STRING: // A string delimited by "" + if (sc.ch == '"') + { + // A string ends here + sc.ForwardSetState(SCE_ASN1_DEFAULT); + + // To correctly manage a char sticking to the string quote + goto asn1_default; + } + break; + case SCE_ASN1_SCALAR: // A plain number + if (!isAsn1Number (sc.ch)) + // A number ends here + sc.SetState(SCE_ASN1_DEFAULT); + break; + case SCE_ASN1_OPERATOR: // The affectation operator ::= and wath follows (eg: ::= { org 6 } OID or ::= 12 trap) + if (sc.ch == '{') + { + // An OID definition starts here: enter the sub loop + for (; sc.More(); sc.Forward()) + { + if (isAsn1Number (sc.ch) && (!isAsn1Char (sc.chPrev) || isAsn1Number (sc.chPrev))) + // The OID number is highlighted + sc.SetState(SCE_ASN1_OID); + else if (isAsn1Char (sc.ch)) + // The OID parent identifier is plain + sc.SetState(SCE_ASN1_IDENTIFIER); + else + sc.SetState(SCE_ASN1_DEFAULT); + + if (sc.ch == '}') + // Here ends the OID and the operator sub loop: go back to main loop + break; + } + } + else if (isAsn1Number (sc.ch)) + { + // A trap number definition starts here: enter the sub loop + for (; sc.More(); sc.Forward()) + { + if (isAsn1Number (sc.ch)) + // The trap number is highlighted + sc.SetState(SCE_ASN1_OID); + else + { + // The number ends here: go back to main loop + sc.SetState(SCE_ASN1_DEFAULT); + break; + } + } + } + else if (sc.ch != ':' && sc.ch != '=' && sc.ch != ' ') + // The operator doesn't imply an OID definition nor a trap, back to main loop + goto asn1_default; // To be sure to handle actually the state change + break; + } + } + sc.Complete(); +} + +static void FoldAsn1Doc(unsigned int, int, int, WordList *[], Accessor &styler) +{ + // No folding enabled, no reason to continue... + if( styler.GetPropertyInt("fold") == 0 ) + return; + + // No folding implemented: doesn't make sense for ASN.1 +} + +static const char * const asn1WordLists[] = { + "Keywords", + "Attributes", + "Descriptors", + "Types", + 0, }; + + +LexerModule lmAns1(SCLEX_ASN1, ColouriseAsn1Doc, "asn1", FoldAsn1Doc, asn1WordLists); diff --git a/scintilla/src/LexBaan.cxx b/scintilla/src/LexBaan.cxx new file mode 100644 index 00000000..97dd1f4b --- /dev/null +++ b/scintilla/src/LexBaan.cxx @@ -0,0 +1,193 @@ +// Scintilla source code edit control +/** @file LexBaan.cxx + ** Lexer for Baan. + ** Based heavily on LexCPP.cxx + **/ +// Copyright 2001- by Vamsi Potluru & Praveen Ambekar +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static inline bool IsAWordChar(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '$' || ch == ':'); +} + +static inline bool IsAWordStart(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '_'); +} + +static void ColouriseBaanDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler) { + + WordList &keywords = *keywordlists[0]; + WordList &keywords2 = *keywordlists[1]; + bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0; + + if (initStyle == SCE_BAAN_STRINGEOL) // Does not leak onto next line + initStyle = SCE_BAAN_DEFAULT; + + int visibleChars = 0; + + StyleContext sc(startPos, length, initStyle, styler); + + for (; sc.More(); sc.Forward()) { + + if (sc.state == SCE_BAAN_OPERATOR) { + sc.SetState(SCE_BAAN_DEFAULT); + } else if (sc.state == SCE_BAAN_NUMBER) { + if (!IsAWordChar(sc.ch)) { + sc.SetState(SCE_BAAN_DEFAULT); + } + } else if (sc.state == SCE_BAAN_IDENTIFIER) { + if (!IsAWordChar(sc.ch)) { + char s[100]; + sc.GetCurrentLowered(s, sizeof(s)); + if (keywords.InList(s)) { + sc.ChangeState(SCE_BAAN_WORD); + } else if (keywords2.InList(s)) { + sc.ChangeState(SCE_BAAN_WORD2); + } + sc.SetState(SCE_BAAN_DEFAULT); + } + } else if (sc.state == SCE_BAAN_PREPROCESSOR) { + if (stylingWithinPreprocessor) { + if (IsASpace(sc.ch)) { + sc.SetState(SCE_BAAN_DEFAULT); + } + } else { + if (sc.atLineEnd && (sc.chNext != '^')) { + sc.SetState(SCE_BAAN_DEFAULT); + } + } + } else if (sc.state == SCE_BAAN_COMMENT) { + if (sc.atLineEnd) { + sc.SetState(SCE_BAAN_DEFAULT); + } + } else if (sc.state == SCE_BAAN_COMMENTDOC) { + if (sc.MatchIgnoreCase("enddllusage")) { + for (unsigned int i = 0; i < 10; i++){ + sc.Forward(); + } + sc.ForwardSetState(SCE_BAAN_DEFAULT); + } + } else if (sc.state == SCE_BAAN_STRING) { + if (sc.ch == '\"') { + sc.ForwardSetState(SCE_BAAN_DEFAULT); + } else if ((sc.atLineEnd) && (sc.chNext != '^')) { + sc.ChangeState(SCE_BAAN_STRINGEOL); + sc.ForwardSetState(SCE_C_DEFAULT); + visibleChars = 0; + } + } + + if (sc.state == SCE_BAAN_DEFAULT) { + if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { + sc.SetState(SCE_BAAN_NUMBER); + } else if (sc.MatchIgnoreCase("dllusage")){ + sc.SetState(SCE_BAAN_COMMENTDOC); + do { + sc.Forward(); + } while ((!sc.atLineEnd) && sc.More()); + } else if (IsAWordStart(sc.ch)) { + sc.SetState(SCE_BAAN_IDENTIFIER); + } else if (sc.Match('|')){ + sc.SetState(SCE_BAAN_COMMENT); + } else if (sc.ch == '\"') { + sc.SetState(SCE_BAAN_STRING); + } else if (sc.ch == '#' && visibleChars == 0) { + // Preprocessor commands are alone on their line + sc.SetState(SCE_BAAN_PREPROCESSOR); + // Skip whitespace between # and preprocessor word + do { + sc.Forward(); + } while (IsASpace(sc.ch) && sc.More()); + } else if (isoperator(static_cast(sc.ch))) { + sc.SetState(SCE_BAAN_OPERATOR); + } + } + if (sc.atLineEnd) { + // Reset states to begining of colourise so no surprises + // if different sets of lines lexed. + visibleChars = 0; + } + if (!IsASpace(sc.ch)) { + visibleChars++; + } + } + sc.Complete(); +} + +static void FoldBaanDoc(unsigned int startPos, int length, int initStyle, WordList *[], + Accessor &styler) { + bool foldComment = styler.GetPropertyInt("fold.comment") != 0; + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + unsigned int endPos = startPos + length; + 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; + 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 && + (style == SCE_BAAN_COMMENT || style == SCE_BAAN_COMMENTDOC)) { + if (style != stylePrev) { + levelCurrent++; + } else if ((style != styleNext) && !atEOL) { + // Comments don't end at end of line and the next character may be unstyled. + levelCurrent--; + } + } + if (style == SCE_BAAN_OPERATOR) { + if (ch == '{') { + levelCurrent++; + } else if (ch == '}') { + levelCurrent--; + } + } + if (atEOL) { + int lev = levelPrev; + if (visibleChars == 0 && foldCompact) + lev |= SC_FOLDLEVELWHITEFLAG; + if ((levelCurrent > levelPrev) && (visibleChars > 0)) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelPrev = levelCurrent; + visibleChars = 0; + } + if (!isspacechar(ch)) + visibleChars++; + } + // Fill in the real level of the next line, keeping the current flags as they will be filled in later + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, levelPrev | flagsNext); +} + +LexerModule lmBaan(SCLEX_BAAN, ColouriseBaanDoc, "baan", FoldBaanDoc); diff --git a/scintilla/src/LexBash.cxx b/scintilla/src/LexBash.cxx new file mode 100644 index 00000000..d5ecfd92 --- /dev/null +++ b/scintilla/src/LexBash.cxx @@ -0,0 +1,683 @@ +// Scintilla source code edit control +/** @file LexBash.cxx + ** Lexer for Bash. + **/ +// Copyright 2004-2007 by Neil Hodgson +// Adapted from LexPerl by Kein-Hong Man 2004 +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +// define this if you want 'invalid octals' to be marked as errors +// usually, this is not a good idea, permissive lexing is better +#undef PEDANTIC_OCTAL + +#define BASH_BASE_ERROR 65 +#define BASH_BASE_DECIMAL 66 +#define BASH_BASE_HEX 67 +#ifdef PEDANTIC_OCTAL +#define BASH_BASE_OCTAL 68 +#define BASH_BASE_OCTAL_ERROR 69 +#endif + +#define HERE_DELIM_MAX 256 + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static inline int translateBashDigit(char ch) { + if (ch >= '0' && ch <= '9') { + return ch - '0'; + } else if (ch >= 'a' && ch <= 'z') { + return ch - 'a' + 10; + } else if (ch >= 'A' && ch <= 'Z') { + return ch - 'A' + 36; + } else if (ch == '@') { + return 62; + } else if (ch == '_') { + return 63; + } + return BASH_BASE_ERROR; +} + +static inline bool isEOLChar(char ch) { + return (ch == '\r') || (ch == '\n'); +} + +static bool isSingleCharOp(char ch) { + char strCharSet[2]; + strCharSet[0] = ch; + strCharSet[1] = '\0'; + return (NULL != strstr("rwxoRWXOezsfdlpSbctugkTBMACahGLNn", strCharSet)); +} + +static inline bool isBashOperator(char ch) { + if (ch == '^' || ch == '&' || ch == '\\' || ch == '%' || + ch == '(' || ch == ')' || ch == '-' || ch == '+' || + ch == '=' || ch == '|' || ch == '{' || ch == '}' || + ch == '[' || ch == ']' || ch == ':' || ch == ';' || + ch == '>' || ch == ',' || ch == '/' || ch == '<' || + ch == '?' || ch == '!' || ch == '.' || ch == '~' || + ch == '@') + return true; + return false; +} + +static int classifyWordBash(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { + char s[100]; + for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) { + s[i] = styler[start + i]; + s[i + 1] = '\0'; + } + char chAttr = SCE_SH_IDENTIFIER; + if (keywords.InList(s)) + chAttr = SCE_SH_WORD; + styler.ColourTo(end, chAttr); + return chAttr; +} + +static inline int getBashNumberBase(unsigned int start, unsigned int end, Accessor &styler) { + int base = 0; + for (unsigned int i = 0; i < end - start + 1 && i < 10; i++) { + base = base * 10 + (styler[start + i] - '0'); + } + if (base > 64 || (end - start) > 1) { + return BASH_BASE_ERROR; + } + return base; +} + +static inline bool isEndVar(char ch) { + return !isalnum(ch) && ch != '$' && ch != '_'; +} + +static inline bool isNonQuote(char ch) { + return isalnum(ch) || ch == '_'; +} + +static bool isMatch(Accessor &styler, int lengthDoc, int pos, const char *val) { + if ((pos + static_cast(strlen(val))) >= lengthDoc) { + return false; + } + while (*val) { + if (*val != styler[pos++]) { + return false; + } + val++; + } + return true; +} + +static char opposite(char ch) { + if (ch == '(') + return ')'; + if (ch == '[') + return ']'; + if (ch == '{') + return '}'; + if (ch == '<') + return '>'; + return ch; +} + +static void ColouriseBashDoc(unsigned int startPos, int length, int initStyle, + WordList *keywordlists[], Accessor &styler) { + + // Lexer for bash often has to backtrack to start of current style to determine + // which characters are being used as quotes, how deeply nested is the + // start position and what the termination string is for here documents + + WordList &keywords = *keywordlists[0]; + + class HereDocCls { + public: + int State; // 0: '<<' encountered + // 1: collect the delimiter + // 2: here doc text (lines after the delimiter) + char Quote; // the char after '<<' + bool Quoted; // true if Quote in ('\'','"','`') + bool Indent; // indented delimiter (for <<-) + int DelimiterLength; // strlen(Delimiter) + char *Delimiter; // the Delimiter, 256: sizeof PL_tokenbuf + HereDocCls() { + State = 0; + Quote = 0; + Quoted = false; + Indent = 0; + DelimiterLength = 0; + Delimiter = new char[HERE_DELIM_MAX]; + Delimiter[0] = '\0'; + } + ~HereDocCls() { + delete []Delimiter; + } + }; + HereDocCls HereDoc; + + class QuoteCls { + public: + int Rep; + int Count; + char Up; + char Down; + QuoteCls() { + this->New(1); + } + void New(int r) { + Rep = r; + Count = 0; + Up = '\0'; + Down = '\0'; + } + void Open(char u) { + Count++; + Up = u; + Down = opposite(Up); + } + }; + QuoteCls Quote; + + int state = initStyle; + int numBase = 0; + unsigned int lengthDoc = startPos + length; + + // If in a long distance lexical state, seek to the beginning to find quote characters + // Bash strings can be multi-line with embedded newlines, so backtrack. + // Bash numbers have additional state during lexing, so backtrack too. + if (state == SCE_SH_HERE_Q) { + while ((startPos > 1) && (styler.StyleAt(startPos) != SCE_SH_HERE_DELIM)) { + startPos--; + } + startPos = styler.LineStart(styler.GetLine(startPos)); + state = styler.StyleAt(startPos - 1); + } + if (state == SCE_SH_STRING + || state == SCE_SH_BACKTICKS + || state == SCE_SH_CHARACTER + || state == SCE_SH_NUMBER + || state == SCE_SH_IDENTIFIER + || state == SCE_SH_COMMENTLINE + ) { + while ((startPos > 1) && (styler.StyleAt(startPos - 1) == state)) { + startPos--; + } + state = SCE_SH_DEFAULT; + } + + styler.StartAt(startPos); + char chPrev = styler.SafeGetCharAt(startPos - 1); + if (startPos == 0) + chPrev = '\n'; + char chNext = styler[startPos]; + styler.StartSegment(startPos); + + for (unsigned int i = startPos; i < lengthDoc; i++) { + char ch = chNext; + // if the current character is not consumed due to the completion of an + // earlier style, lexing can be restarted via a simple goto + restartLexer: + chNext = styler.SafeGetCharAt(i + 1); + char chNext2 = styler.SafeGetCharAt(i + 2); + + if (styler.IsLeadByte(ch)) { + chNext = styler.SafeGetCharAt(i + 2); + chPrev = ' '; + i += 1; + continue; + } + + if ((chPrev == '\r' && ch == '\n')) { // skip on DOS/Windows + styler.ColourTo(i, state); + chPrev = ch; + continue; + } + + if (HereDoc.State == 1 && isEOLChar(ch)) { + // Begin of here-doc (the line after the here-doc delimiter): + // Lexically, the here-doc starts from the next line after the >>, but the + // first line of here-doc seem to follow the style of the last EOL sequence + HereDoc.State = 2; + if (HereDoc.Quoted) { + if (state == SCE_SH_HERE_DELIM) { + // Missing quote at end of string! We are stricter than bash. + // Colour here-doc anyway while marking this bit as an error. + state = SCE_SH_ERROR; + } + styler.ColourTo(i - 1, state); + // HereDoc.Quote always == '\'' + state = SCE_SH_HERE_Q; + } else { + styler.ColourTo(i - 1, state); + // always switch + state = SCE_SH_HERE_Q; + } + } + + if (state == SCE_SH_DEFAULT) { + if (ch == '\\') { // escaped character + if (i < lengthDoc - 1) + i++; + ch = chNext; + chNext = chNext2; + styler.ColourTo(i, SCE_SH_IDENTIFIER); + } else if (isdigit(ch)) { + state = SCE_SH_NUMBER; + numBase = BASH_BASE_DECIMAL; + if (ch == '0') { // hex,octal + if (chNext == 'x' || chNext == 'X') { + numBase = BASH_BASE_HEX; + i++; + ch = chNext; + chNext = chNext2; + } else if (isdigit(chNext)) { +#ifdef PEDANTIC_OCTAL + numBase = BASH_BASE_OCTAL; +#else + numBase = BASH_BASE_HEX; +#endif + } + } + } else if (iswordstart(ch)) { + state = SCE_SH_WORD; + if (!iswordchar(chNext) && chNext != '+' && chNext != '-') { + // We need that if length of word == 1! + // This test is copied from the SCE_SH_WORD handler. + classifyWordBash(styler.GetStartSegment(), i, keywords, styler); + state = SCE_SH_DEFAULT; + } + } else if (ch == '#') { + state = SCE_SH_COMMENTLINE; + } else if (ch == '\"') { + state = SCE_SH_STRING; + Quote.New(1); + Quote.Open(ch); + } else if (ch == '\'') { + state = SCE_SH_CHARACTER; + Quote.New(1); + Quote.Open(ch); + } else if (ch == '`') { + state = SCE_SH_BACKTICKS; + Quote.New(1); + Quote.Open(ch); + } else if (ch == '$') { + if (chNext == '{') { + state = SCE_SH_PARAM; + goto startQuote; + } else if (chNext == '\'') { + state = SCE_SH_CHARACTER; + goto startQuote; + } else if (chNext == '"') { + state = SCE_SH_STRING; + goto startQuote; + } else if (chNext == '(' && chNext2 == '(') { + styler.ColourTo(i, SCE_SH_OPERATOR); + state = SCE_SH_DEFAULT; + goto skipChar; + } else if (chNext == '(' || chNext == '`') { + state = SCE_SH_BACKTICKS; + startQuote: + Quote.New(1); + Quote.Open(chNext); + goto skipChar; + } else { + state = SCE_SH_SCALAR; + skipChar: + i++; + ch = chNext; + chNext = chNext2; + } + } else if (ch == '*') { + if (chNext == '*') { // exponentiation + i++; + ch = chNext; + chNext = chNext2; + } + styler.ColourTo(i, SCE_SH_OPERATOR); + } else if (ch == '<' && chNext == '<') { + state = SCE_SH_HERE_DELIM; + HereDoc.State = 0; + HereDoc.Indent = false; + } else if (ch == '-' // file test operators + && isSingleCharOp(chNext) + && !isalnum((chNext2 = styler.SafeGetCharAt(i+2))) + && isspace(chPrev)) { + styler.ColourTo(i + 1, SCE_SH_WORD); + state = SCE_SH_DEFAULT; + i++; + ch = chNext; + chNext = chNext2; + } else if (isBashOperator(ch)) { + styler.ColourTo(i, SCE_SH_OPERATOR); + } else { + // keep colouring defaults to make restart easier + styler.ColourTo(i, SCE_SH_DEFAULT); + } + } else if (state == SCE_SH_NUMBER) { + int digit = translateBashDigit(ch); + if (numBase == BASH_BASE_DECIMAL) { + if (ch == '#') { + numBase = getBashNumberBase(styler.GetStartSegment(), i - 1, styler); + if (numBase == BASH_BASE_ERROR) // take the rest as comment + goto numAtEnd; + } else if (!isdigit(ch)) + goto numAtEnd; + } else if (numBase == BASH_BASE_HEX) { + if ((digit < 16) || (digit >= 36 && digit <= 41)) { + // hex digit 0-9a-fA-F + } else + goto numAtEnd; +#ifdef PEDANTIC_OCTAL + } else if (numBase == BASH_BASE_OCTAL || + numBase == BASH_BASE_OCTAL_ERROR) { + if (digit > 7) { + if (digit <= 9) { + numBase = BASH_BASE_OCTAL_ERROR; + } else + goto numAtEnd; + } +#endif + } else if (numBase == BASH_BASE_ERROR) { + if (digit > 9) + goto numAtEnd; + } else { // DD#DDDD number style handling + if (digit != BASH_BASE_ERROR) { + if (numBase <= 36) { + // case-insensitive if base<=36 + if (digit >= 36) digit -= 26; + } + if (digit >= numBase) { + if (digit <= 9) { + numBase = BASH_BASE_ERROR; + } else + goto numAtEnd; + } + } else { + numAtEnd: + if (numBase == BASH_BASE_ERROR +#ifdef PEDANTIC_OCTAL + || numBase == BASH_BASE_OCTAL_ERROR +#endif + ) + state = SCE_SH_ERROR; + styler.ColourTo(i - 1, state); + state = SCE_SH_DEFAULT; + goto restartLexer; + } + } + } else if (state == SCE_SH_WORD) { + if (!iswordchar(chNext) && chNext != '+' && chNext != '-') { + // "." never used in Bash variable names + // but used in file names + classifyWordBash(styler.GetStartSegment(), i, keywords, styler); + state = SCE_SH_DEFAULT; + ch = ' '; + } + } else if (state == SCE_SH_IDENTIFIER) { + if (!iswordchar(chNext) && chNext != '+' && chNext != '-') { + styler.ColourTo(i, SCE_SH_IDENTIFIER); + state = SCE_SH_DEFAULT; + ch = ' '; + } + } else { + if (state == SCE_SH_COMMENTLINE) { + if (ch == '\\' && isEOLChar(chNext)) { + // comment continuation + if (chNext == '\r' && chNext2 == '\n') { + i += 2; + ch = styler.SafeGetCharAt(i); + chNext = styler.SafeGetCharAt(i + 1); + } else { + i++; + ch = chNext; + chNext = chNext2; + } + } else if (isEOLChar(ch)) { + styler.ColourTo(i - 1, state); + state = SCE_SH_DEFAULT; + goto restartLexer; + } else if (isEOLChar(chNext)) { + styler.ColourTo(i, state); + state = SCE_SH_DEFAULT; + } + } else if (state == SCE_SH_HERE_DELIM) { + // + // From Bash info: + // --------------- + // Specifier format is: <<[-]WORD + // Optional '-' is for removal of leading tabs from here-doc. + // Whitespace acceptable after <<[-] operator + // + if (HereDoc.State == 0) { // '<<' encountered + HereDoc.State = 1; + HereDoc.Quote = chNext; + HereDoc.Quoted = false; + HereDoc.DelimiterLength = 0; + HereDoc.Delimiter[HereDoc.DelimiterLength] = '\0'; + if (chNext == '\'' || chNext == '\"') { // a quoted here-doc delimiter (' or ") + i++; + ch = chNext; + chNext = chNext2; + HereDoc.Quoted = true; + } else if (!HereDoc.Indent && chNext == '-') { // <<- indent case + HereDoc.Indent = true; + HereDoc.State = 0; + } else if (isalpha(chNext) || chNext == '_' || chNext == '\\' + || chNext == '-' || chNext == '+' || chNext == '!') { + // an unquoted here-doc delimiter, no special handling + // TODO check what exactly bash considers part of the delim + } else if (chNext == '<') { // HERE string <<< + i++; + ch = chNext; + chNext = chNext2; + styler.ColourTo(i, SCE_SH_HERE_DELIM); + state = SCE_SH_DEFAULT; + HereDoc.State = 0; + } else if (isspacechar(chNext)) { + // eat whitespace + HereDoc.State = 0; + } else if (isdigit(chNext) || chNext == '=' || chNext == '$') { + // left shift << or <<= operator cases + styler.ColourTo(i, SCE_SH_OPERATOR); + state = SCE_SH_DEFAULT; + HereDoc.State = 0; + } else { + // symbols terminates; deprecated zero-length delimiter + } + } else if (HereDoc.State == 1) { // collect the delimiter + if (HereDoc.Quoted) { // a quoted here-doc delimiter + if (ch == HereDoc.Quote) { // closing quote => end of delimiter + styler.ColourTo(i, state); + state = SCE_SH_DEFAULT; + } else { + if (ch == '\\' && chNext == HereDoc.Quote) { // escaped quote + i++; + ch = chNext; + chNext = chNext2; + } + HereDoc.Delimiter[HereDoc.DelimiterLength++] = ch; + HereDoc.Delimiter[HereDoc.DelimiterLength] = '\0'; + } + } else { // an unquoted here-doc delimiter + if (isalnum(ch) || ch == '_' || ch == '-' || ch == '+' || ch == '!') { + HereDoc.Delimiter[HereDoc.DelimiterLength++] = ch; + HereDoc.Delimiter[HereDoc.DelimiterLength] = '\0'; + } else if (ch == '\\') { + // skip escape prefix + } else { + styler.ColourTo(i - 1, state); + state = SCE_SH_DEFAULT; + goto restartLexer; + } + } + if (HereDoc.DelimiterLength >= HERE_DELIM_MAX - 1) { + styler.ColourTo(i - 1, state); + state = SCE_SH_ERROR; + goto restartLexer; + } + } + } else if (HereDoc.State == 2) { + // state == SCE_SH_HERE_Q + if (isMatch(styler, lengthDoc, i, HereDoc.Delimiter)) { + if (!HereDoc.Indent && isEOLChar(chPrev)) { + endHereDoc: + // standard HERE delimiter + i += HereDoc.DelimiterLength; + chPrev = styler.SafeGetCharAt(i - 1); + ch = styler.SafeGetCharAt(i); + if (isEOLChar(ch)) { + styler.ColourTo(i - 1, state); + state = SCE_SH_DEFAULT; + HereDoc.State = 0; + goto restartLexer; + } + chNext = styler.SafeGetCharAt(i + 1); + } else if (HereDoc.Indent) { + // indented HERE delimiter + unsigned int bk = (i > 0)? i - 1: 0; + while (i > 0) { + ch = styler.SafeGetCharAt(bk--); + if (isEOLChar(ch)) { + goto endHereDoc; + } else if (!isspacechar(ch)) { + break; // got leading non-whitespace + } + } + } + } + } else if (state == SCE_SH_SCALAR) { // variable names + if (isEndVar(ch)) { + if ((state == SCE_SH_SCALAR) + && i == (styler.GetStartSegment() + 1)) { + // Special variable: $(, $_ etc. + styler.ColourTo(i, state); + state = SCE_SH_DEFAULT; + } else { + styler.ColourTo(i - 1, state); + state = SCE_SH_DEFAULT; + goto restartLexer; + } + } + } else if (state == SCE_SH_STRING + || state == SCE_SH_CHARACTER + || state == SCE_SH_BACKTICKS + || state == SCE_SH_PARAM + ) { + if (!Quote.Down && !isspacechar(ch)) { + Quote.Open(ch); + } else if (ch == '\\' && Quote.Up != '\\') { + i++; + ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + } else if (ch == Quote.Down) { + Quote.Count--; + if (Quote.Count == 0) { + Quote.Rep--; + if (Quote.Rep <= 0) { + styler.ColourTo(i, state); + state = SCE_SH_DEFAULT; + ch = ' '; + } + if (Quote.Up == Quote.Down) { + Quote.Count++; + } + } + } else if (ch == Quote.Up) { + Quote.Count++; + } + } + } + if (state == SCE_SH_ERROR) { + break; + } + chPrev = ch; + } + styler.ColourTo(lengthDoc - 1, state); +} + +static bool IsCommentLine(int line, Accessor &styler) { + int pos = styler.LineStart(line); + int eol_pos = styler.LineStart(line + 1) - 1; + for (int i = pos; i < eol_pos; i++) { + char ch = styler[i]; + if (ch == '#') + return true; + else if (ch != ' ' && ch != '\t') + return false; + } + return false; +} + +static void FoldBashDoc(unsigned int startPos, int length, int, WordList *[], + Accessor &styler) { + bool foldComment = styler.GetPropertyInt("fold.comment") != 0; + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + unsigned int endPos = startPos + length; + 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); + for (unsigned int i = startPos; i < endPos; i++) { + char ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + int style = styleNext; + styleNext = styler.StyleAt(i + 1); + bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); + // Comment folding + if (foldComment && atEOL && IsCommentLine(lineCurrent, styler)) + { + if (!IsCommentLine(lineCurrent - 1, styler) + && IsCommentLine(lineCurrent + 1, styler)) + levelCurrent++; + else if (IsCommentLine(lineCurrent - 1, styler) + && !IsCommentLine(lineCurrent+1, styler)) + levelCurrent--; + } + if (style == SCE_SH_OPERATOR) { + if (ch == '{') { + levelCurrent++; + } else if (ch == '}') { + levelCurrent--; + } + } + if (atEOL) { + int lev = levelPrev; + if (visibleChars == 0 && foldCompact) + lev |= SC_FOLDLEVELWHITEFLAG; + if ((levelCurrent > levelPrev) && (visibleChars > 0)) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelPrev = levelCurrent; + visibleChars = 0; + } + if (!isspacechar(ch)) + visibleChars++; + } + // Fill in the real level of the next line, keeping the current flags as they will be filled in later + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, levelPrev | flagsNext); +} + +static const char * const bashWordListDesc[] = { + "Keywords", + 0 +}; + +LexerModule lmBash(SCLEX_BASH, ColouriseBashDoc, "bash", FoldBashDoc, bashWordListDesc); diff --git a/scintilla/src/LexBasic.cxx b/scintilla/src/LexBasic.cxx new file mode 100644 index 00000000..5aa23b5a --- /dev/null +++ b/scintilla/src/LexBasic.cxx @@ -0,0 +1,374 @@ +// Scintilla source code edit control +/** @file LexBasic.cxx + ** Lexer for BlitzBasic and PureBasic. + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +// This tries to be a unified Lexer/Folder for all the BlitzBasic/BlitzMax/PurBasic basics +// and derivatives. Once they diverge enough, might want to split it into multiple +// lexers for more code clearity. +// +// Mail me (elias users sf net) for any bugs. + +// Folding only works for simple things like functions or types. + +// You may want to have a look at my ctags lexer as well, if you additionally to coloring +// and folding need to extract things like label tags in your editor. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +/* Bits: + * 1 - whitespace + * 2 - operator + * 4 - identifier + * 8 - decimal digit + * 16 - hex digit + * 32 - bin digit + */ +static int character_classification[128] = +{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 10, 2, + 60, 60, 28, 28, 28, 28, 28, 28, 28, 28, 2, 2, 2, 2, 2, 2, + 2, 20, 20, 20, 20, 20, 20, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 4, + 2, 20, 20, 20, 20, 20, 20, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2, 0 +}; + +static bool IsSpace(int c) { + return c < 128 && (character_classification[c] & 1); +} + +static bool IsOperator(int c) { + return c < 128 && (character_classification[c] & 2); +} + +static bool IsIdentifier(int c) { + return c < 128 && (character_classification[c] & 4); +} + +static bool IsDigit(int c) { + return c < 128 && (character_classification[c] & 8); +} + +static bool IsHexDigit(int c) { + return c < 128 && (character_classification[c] & 16); +} + +static bool IsBinDigit(int c) { + return c < 128 && (character_classification[c] & 32); +} + +static int LowerCase(int c) +{ + if (c >= 'A' && c <= 'Z') + return 'a' + c - 'A'; + return c; +} + +static void ColouriseBasicDoc(unsigned int startPos, int length, int initStyle, + WordList *keywordlists[], Accessor &styler, char comment_char) { + bool wasfirst = true, isfirst = true; // true if first token in a line + styler.StartAt(startPos); + + StyleContext sc(startPos, length, initStyle, styler); + + // Can't use sc.More() here else we miss the last character + for (; ; sc.Forward()) { + if (sc.state == SCE_B_IDENTIFIER) { + if (!IsIdentifier(sc.ch)) { + // Labels + if (wasfirst && sc.Match(':')) { + sc.ChangeState(SCE_B_LABEL); + sc.ForwardSetState(SCE_B_DEFAULT); + } else { + char s[100]; + int kstates[4] = { + SCE_B_KEYWORD, + SCE_B_KEYWORD2, + SCE_B_KEYWORD3, + SCE_B_KEYWORD4, + }; + sc.GetCurrentLowered(s, sizeof(s)); + for (int i = 0; i < 4; i++) { + if (keywordlists[i]->InList(s)) { + sc.ChangeState(kstates[i]); + } + } + // Types, must set them as operator else they will be + // matched as number/constant + if (sc.Match('.') || sc.Match('$') || sc.Match('%') || + sc.Match('#')) { + sc.SetState(SCE_B_OPERATOR); + } else { + sc.SetState(SCE_B_DEFAULT); + } + } + } + } else if (sc.state == SCE_B_OPERATOR) { + if (!IsOperator(sc.ch) || sc.Match('#')) + sc.SetState(SCE_B_DEFAULT); + } else if (sc.state == SCE_B_LABEL) { + if (!IsIdentifier(sc.ch)) + sc.SetState(SCE_B_DEFAULT); + } else if (sc.state == SCE_B_CONSTANT) { + if (!IsIdentifier(sc.ch)) + sc.SetState(SCE_B_DEFAULT); + } else if (sc.state == SCE_B_NUMBER) { + if (!IsDigit(sc.ch)) + sc.SetState(SCE_B_DEFAULT); + } else if (sc.state == SCE_B_HEXNUMBER) { + if (!IsHexDigit(sc.ch)) + sc.SetState(SCE_B_DEFAULT); + } else if (sc.state == SCE_B_BINNUMBER) { + if (!IsBinDigit(sc.ch)) + sc.SetState(SCE_B_DEFAULT); + } else if (sc.state == SCE_B_STRING) { + if (sc.ch == '"') { + sc.ForwardSetState(SCE_B_DEFAULT); + } + if (sc.atLineEnd) { + sc.ChangeState(SCE_B_ERROR); + sc.SetState(SCE_B_DEFAULT); + } + } else if (sc.state == SCE_B_COMMENT || sc.state == SCE_B_PREPROCESSOR) { + if (sc.atLineEnd) { + sc.SetState(SCE_B_DEFAULT); + } + } + + if (sc.atLineStart) + isfirst = true; + + if (sc.state == SCE_B_DEFAULT || sc.state == SCE_B_ERROR) { + if (isfirst && sc.Match('.')) { + sc.SetState(SCE_B_LABEL); + } else if (isfirst && sc.Match('#')) { + wasfirst = isfirst; + sc.SetState(SCE_B_IDENTIFIER); + } else if (sc.Match(comment_char)) { + // Hack to make deprecated QBASIC '$Include show + // up in freebasic with SCE_B_PREPROCESSOR. + if (comment_char == '\'' && sc.Match(comment_char, '$')) + sc.SetState(SCE_B_PREPROCESSOR); + else + sc.SetState(SCE_B_COMMENT); + } else if (sc.Match('"')) { + sc.SetState(SCE_B_STRING); + } else if (IsDigit(sc.ch)) { + sc.SetState(SCE_B_NUMBER); + } else if (sc.Match('$')) { + sc.SetState(SCE_B_HEXNUMBER); + } else if (sc.Match('%')) { + sc.SetState(SCE_B_BINNUMBER); + } else if (sc.Match('#')) { + sc.SetState(SCE_B_CONSTANT); + } else if (IsOperator(sc.ch)) { + sc.SetState(SCE_B_OPERATOR); + } else if (IsIdentifier(sc.ch)) { + wasfirst = isfirst; + sc.SetState(SCE_B_IDENTIFIER); + } else if (!IsSpace(sc.ch)) { + sc.SetState(SCE_B_ERROR); + } + } + + if (!IsSpace(sc.ch)) + isfirst = false; + + if (!sc.More()) + break; + } + sc.Complete(); +} + +static int CheckBlitzFoldPoint(char const *token, int &level) { + if (!strcmp(token, "function") || + !strcmp(token, "type")) { + level |= SC_FOLDLEVELHEADERFLAG; + return 1; + } + if (!strcmp(token, "end function") || + !strcmp(token, "end type")) { + return -1; + } + return 0; +} + +static int CheckPureFoldPoint(char const *token, int &level) { + if (!strcmp(token, "procedure") || + !strcmp(token, "enumeration") || + !strcmp(token, "interface") || + !strcmp(token, "structure")) { + level |= SC_FOLDLEVELHEADERFLAG; + return 1; + } + if (!strcmp(token, "endprocedure") || + !strcmp(token, "endenumeration") || + !strcmp(token, "endinterface") || + !strcmp(token, "endstructure")) { + return -1; + } + return 0; +} + +static int CheckFreeFoldPoint(char const *token, int &level) { + if (!strcmp(token, "function") || + !strcmp(token, "sub") || + !strcmp(token, "type")) { + level |= SC_FOLDLEVELHEADERFLAG; + return 1; + } + if (!strcmp(token, "end function") || + !strcmp(token, "end sub") || + !strcmp(token, "end type")) { + return -1; + } + return 0; +} + +static void FoldBasicDoc(unsigned int startPos, int length, + Accessor &styler, int (*CheckFoldPoint)(char const *, int &)) { + int line = styler.GetLine(startPos); + int level = styler.LevelAt(line); + int go = 0, done = 0; + int endPos = startPos + length; + char word[256]; + int wordlen = 0; + int i; + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + // Scan for tokens at the start of the line (they may include + // whitespace, for tokens like "End Function" + for (i = startPos; i < endPos; i++) { + int c = styler.SafeGetCharAt(i); + if (!done && !go) { + if (wordlen) { // are we scanning a token already? + word[wordlen] = static_cast(LowerCase(c)); + if (!IsIdentifier(c)) { // done with token + word[wordlen] = '\0'; + go = CheckFoldPoint(word, level); + if (!go) { + // Treat any whitespace as single blank, for + // things like "End Function". + if (IsSpace(c) && IsIdentifier(word[wordlen - 1])) { + word[wordlen] = ' '; + if (wordlen < 255) + wordlen++; + } + else // done with this line + done = 1; + } + } else if (wordlen < 255) { + wordlen++; + } + } else { // start scanning at first non-whitespace character + if (!IsSpace(c)) { + if (IsIdentifier(c)) { + word[0] = static_cast(LowerCase(c)); + wordlen = 1; + } else // done with this line + done = 1; + } + } + } + if (c == '\n') { // line end + if (!done && wordlen == 0 && foldCompact) // line was only space + level |= SC_FOLDLEVELWHITEFLAG; + if (level != styler.LevelAt(line)) + styler.SetLevel(line, level); + level += go; + line++; + // reset state + wordlen = 0; + level &= ~SC_FOLDLEVELHEADERFLAG; + level &= ~SC_FOLDLEVELWHITEFLAG; + go = 0; + done = 0; + } + } +} + +static void ColouriseBlitzBasicDoc(unsigned int startPos, int length, int initStyle, + WordList *keywordlists[], Accessor &styler) { + ColouriseBasicDoc(startPos, length, initStyle, keywordlists, styler, ';'); +} + +static void ColourisePureBasicDoc(unsigned int startPos, int length, int initStyle, + WordList *keywordlists[], Accessor &styler) { + ColouriseBasicDoc(startPos, length, initStyle, keywordlists, styler, ';'); +} + +static void ColouriseFreeBasicDoc(unsigned int startPos, int length, int initStyle, + WordList *keywordlists[], Accessor &styler) { + ColouriseBasicDoc(startPos, length, initStyle, keywordlists, styler, '\''); +} + +static void FoldBlitzBasicDoc(unsigned int startPos, int length, int, + WordList *[], Accessor &styler) { + FoldBasicDoc(startPos, length, styler, CheckBlitzFoldPoint); +} + +static void FoldPureBasicDoc(unsigned int startPos, int length, int, + WordList *[], Accessor &styler) { + FoldBasicDoc(startPos, length, styler, CheckPureFoldPoint); +} + +static void FoldFreeBasicDoc(unsigned int startPos, int length, int, + WordList *[], Accessor &styler) { + FoldBasicDoc(startPos, length, styler, CheckFreeFoldPoint); +} + +static const char * const blitzbasicWordListDesc[] = { + "BlitzBasic Keywords", + "user1", + "user2", + "user3", + 0 +}; + +static const char * const purebasicWordListDesc[] = { + "PureBasic Keywords", + "PureBasic PreProcessor Keywords", + "user defined 1", + "user defined 2", + 0 +}; + +static const char * const freebasicWordListDesc[] = { + "FreeBasic Keywords", + "FreeBasic PreProcessor Keywords", + "user defined 1", + "user defined 2", + 0 +}; + +LexerModule lmBlitzBasic(SCLEX_BLITZBASIC, ColouriseBlitzBasicDoc, "blitzbasic", + FoldBlitzBasicDoc, blitzbasicWordListDesc); + +LexerModule lmPureBasic(SCLEX_PUREBASIC, ColourisePureBasicDoc, "purebasic", + FoldPureBasicDoc, purebasicWordListDesc); + +LexerModule lmFreeBasic(SCLEX_FREEBASIC, ColouriseFreeBasicDoc, "freebasic", + FoldFreeBasicDoc, freebasicWordListDesc); + + diff --git a/scintilla/src/LexBullant.cxx b/scintilla/src/LexBullant.cxx new file mode 100644 index 00000000..b476ee5b --- /dev/null +++ b/scintilla/src/LexBullant.cxx @@ -0,0 +1,228 @@ +// SciTE - Scintilla based Text Editor +// LexBullant.cxx - lexer for Bullant + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static int classifyWordBullant(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { + char s[100]; + for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) { + s[i] = static_cast(tolower(styler[start + i])); + s[i + 1] = '\0'; + } + int lev= 0; + char chAttr = SCE_C_IDENTIFIER; + if (isdigit(s[0]) || (s[0] == '.')){ + chAttr = SCE_C_NUMBER; + } + else { + if (keywords.InList(s)) { + chAttr = SCE_C_WORD; + if (strcmp(s, "end") == 0) + lev = -1; + else if (strcmp(s, "method") == 0 || + strcmp(s, "case") == 0 || + strcmp(s, "class") == 0 || + strcmp(s, "debug") == 0 || + strcmp(s, "test") == 0 || + strcmp(s, "if") == 0 || + strcmp(s, "lock") == 0 || + strcmp(s, "transaction") == 0 || + strcmp(s, "trap") == 0 || + strcmp(s, "until") == 0 || + strcmp(s, "while") == 0) + lev = 1; + } + } + styler.ColourTo(end, chAttr); + return lev; +} + +static void ColouriseBullantDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler) { + WordList &keywords = *keywordlists[0]; + + styler.StartAt(startPos); + + bool fold = styler.GetPropertyInt("fold") != 0; + int lineCurrent = styler.GetLine(startPos); + int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; + int levelCurrent = levelPrev; + + int state = initStyle; + if (state == SCE_C_STRINGEOL) // Does not leak onto next line + state = SCE_C_DEFAULT; + char chPrev = ' '; + char chNext = styler[startPos]; + unsigned int lengthDoc = startPos + length; + int visibleChars = 0; + styler.StartSegment(startPos); + int endFoundThisLine = 0; + for (unsigned int i = startPos; i < lengthDoc; i++) { + char ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + + if ((ch == '\r' && chNext != '\n') || (ch == '\n')) { + // Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix) + // Avoid triggering two times on Dos/Win + // End of line + endFoundThisLine = 0; + if (state == SCE_C_STRINGEOL) { + styler.ColourTo(i, state); + state = SCE_C_DEFAULT; + } + if (fold) { + int lev = levelPrev; + if (visibleChars == 0) + lev |= SC_FOLDLEVELWHITEFLAG; + if ((levelCurrent > levelPrev) && (visibleChars > 0)) + lev |= SC_FOLDLEVELHEADERFLAG; + styler.SetLevel(lineCurrent, lev); + lineCurrent++; + levelPrev = levelCurrent; + } + visibleChars = 0; + +/* int indentBlock = GetLineIndentation(lineCurrent); + if (blockChange==1){ + lineCurrent++; + int pos=SetLineIndentation(lineCurrent, indentBlock + indentSize); + } else if (blockChange==-1) { + indentBlock -= indentSize; + if (indentBlock < 0) + indentBlock = 0; + SetLineIndentation(lineCurrent, indentBlock); + lineCurrent++; + } + blockChange=0; +*/ } + if (!isspace(ch)) + visibleChars++; + + if (styler.IsLeadByte(ch)) { + chNext = styler.SafeGetCharAt(i + 2); + chPrev = ' '; + i += 1; + continue; + } + + if (state == SCE_C_DEFAULT) { + if (iswordstart(ch)) { + styler.ColourTo(i-1, state); + state = SCE_C_IDENTIFIER; + } else if (ch == '@' && chNext == 'o') { + if ((styler.SafeGetCharAt(i+2) =='f') && (styler.SafeGetCharAt(i+3) == 'f')) { + styler.ColourTo(i-1, state); + state = SCE_C_COMMENT; + } + } else if (ch == '#') { + styler.ColourTo(i-1, state); + state = SCE_C_COMMENTLINE; + } else if (ch == '\"') { + styler.ColourTo(i-1, state); + state = SCE_C_STRING; + } else if (ch == '\'') { + styler.ColourTo(i-1, state); + state = SCE_C_CHARACTER; + } else if (isoperator(ch)) { + styler.ColourTo(i-1, state); + styler.ColourTo(i, SCE_C_OPERATOR); + } + } else if (state == SCE_C_IDENTIFIER) { + if (!iswordchar(ch)) { + int levelChange = classifyWordBullant(styler.GetStartSegment(), i - 1, keywords, styler); + state = SCE_C_DEFAULT; + chNext = styler.SafeGetCharAt(i + 1); + if (ch == '#') { + state = SCE_C_COMMENTLINE; + } else if (ch == '\"') { + state = SCE_C_STRING; + } else if (ch == '\'') { + state = SCE_C_CHARACTER; + } else if (isoperator(ch)) { + styler.ColourTo(i, SCE_C_OPERATOR); + } + if (endFoundThisLine == 0) + levelCurrent+=levelChange; + if (levelChange == -1) + endFoundThisLine=1; + } + } else if (state == SCE_C_COMMENT) { + if (ch == '@' && chNext == 'o') { + if (styler.SafeGetCharAt(i+2) == 'n') { + styler.ColourTo(i+2, state); + state = SCE_C_DEFAULT; + i+=2; + } + } + } else if (state == SCE_C_COMMENTLINE) { + if (ch == '\r' || ch == '\n') { + endFoundThisLine = 0; + styler.ColourTo(i-1, state); + state = SCE_C_DEFAULT; + } + } else if (state == SCE_C_STRING) { + if (ch == '\\') { + if (chNext == '\"' || chNext == '\'' || chNext == '\\') { + i++; + ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + } + } else if (ch == '\"') { + styler.ColourTo(i, state); + state = SCE_C_DEFAULT; + } else if (chNext == '\r' || chNext == '\n') { + endFoundThisLine = 0; + styler.ColourTo(i-1, SCE_C_STRINGEOL); + state = SCE_C_STRINGEOL; + } + } else if (state == SCE_C_CHARACTER) { + if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { + endFoundThisLine = 0; + styler.ColourTo(i-1, SCE_C_STRINGEOL); + state = SCE_C_STRINGEOL; + } else if (ch == '\\') { + if (chNext == '\"' || chNext == '\'' || chNext == '\\') { + i++; + ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + } + } else if (ch == '\'') { + styler.ColourTo(i, state); + state = SCE_C_DEFAULT; + } + } + chPrev = ch; + } + styler.ColourTo(lengthDoc - 1, state); + + // Fill in the real level of the next line, keeping the current flags as they will be filled in later + if (fold) { + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + //styler.SetLevel(lineCurrent, levelCurrent | flagsNext); + styler.SetLevel(lineCurrent, levelPrev | flagsNext); + + } +} + +static const char * const bullantWordListDesc[] = { + "Keywords", + 0 +}; + +LexerModule lmBullant(SCLEX_BULLANT, ColouriseBullantDoc, "bullant", 0, bullantWordListDesc); diff --git a/scintilla/src/LexCLW.cxx b/scintilla/src/LexCLW.cxx new file mode 100644 index 00000000..3416bf20 --- /dev/null +++ b/scintilla/src/LexCLW.cxx @@ -0,0 +1,679 @@ +// Scintilla source code edit control +/** @file LexClw.cxx + ** Lexer for Clarion. + ** 2004/12/17 Updated Lexer + **/ +// Copyright 2003-2004 by Ron Schofield +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +// Is an end of line character +inline bool IsEOL(const int ch) { + + return(ch == '\n'); +} + +// Convert character to uppercase +static char CharacterUpper(char chChar) { + + if (chChar < 'a' || chChar > 'z') { + return(chChar); + } + else { + return(static_cast(chChar - 'a' + 'A')); + } +} + +// Convert string to uppercase +static void StringUpper(char *szString) { + + while (*szString) { + *szString = CharacterUpper(*szString); + szString++; + } +} + +// Is a label start character +inline bool IsALabelStart(const int iChar) { + + return(isalpha(iChar) || iChar == '_'); +} + +// Is a label character +inline bool IsALabelCharacter(const int iChar) { + + return(isalnum(iChar) || iChar == '_' || iChar == ':'); +} + +// Is the character is a ! and the the next character is not a ! +inline bool IsACommentStart(const int iChar) { + + return(iChar == '!'); +} + +// Is the character a Clarion hex character (ABCDEF) +inline bool IsAHexCharacter(const int iChar, bool bCaseSensitive) { + + // Case insensitive. + if (!bCaseSensitive) { + if (strchr("ABCDEFabcdef", iChar) != NULL) { + return(true); + } + } + // Case sensitive + else { + if (strchr("ABCDEF", iChar) != NULL) { + return(true); + } + } + return(false); +} + +// Is the character a Clarion base character (B=Binary, O=Octal, H=Hex) +inline bool IsANumericBaseCharacter(const int iChar, bool bCaseSensitive) { + + // Case insensitive. + if (!bCaseSensitive) { + // If character is a numeric base character + if (strchr("BOHboh", iChar) != NULL) { + return(true); + } + } + // Case sensitive + else { + // If character is a numeric base character + if (strchr("BOH", iChar) != NULL) { + return(true); + } + } + return(false); +} + +// Set the correct numeric constant state +inline bool SetNumericConstantState(StyleContext &scDoc) { + + int iPoints = 0; // Point counter + char cNumericString[512]; // Numeric string buffer + + // Buffer the current numberic string + scDoc.GetCurrent(cNumericString, sizeof(cNumericString)); + // Loop through the string until end of string (NULL termination) + for (int iIndex = 0; cNumericString[iIndex] != '\0'; iIndex++) { + // Depending on the character + switch (cNumericString[iIndex]) { + // Is a . (point) + case '.' : + // Increment point counter + iPoints++; + break; + default : + break; + } + } + // If points found (can be more than one for improper formatted number + if (iPoints > 0) { + return(true); + } + // Else no points found + else { + return(false); + } +} + +// Get the next word in uppercase from the current position (keyword lookahead) +inline bool GetNextWordUpper(Accessor &styler, unsigned int uiStartPos, int iLength, char *cWord) { + + unsigned int iIndex = 0; // Buffer Index + + // Loop through the remaining string from the current position + for (int iOffset = uiStartPos; iOffset < iLength; iOffset++) { + // Get the character from the buffer using the offset + char cCharacter = styler[iOffset]; + if (IsEOL(cCharacter)) { + break; + } + // If the character is alphabet character + if (isalpha(cCharacter)) { + // Add UPPERCASE character to the word buffer + cWord[iIndex++] = CharacterUpper(cCharacter); + } + } + // Add null termination + cWord[iIndex] = '\0'; + // If no word was found + if (iIndex == 0) { + // Return failure + return(false); + } + // Else word was found + else { + // Return success + return(true); + } +} + +// Clarion Language Colouring Procedure +static void ColouriseClarionDoc(unsigned int uiStartPos, int iLength, int iInitStyle, WordList *wlKeywords[], Accessor &accStyler, bool bCaseSensitive) { + + int iParenthesesLevel = 0; // Parenthese Level + int iColumn1Label = false; // Label starts in Column 1 + + WordList &wlClarionKeywords = *wlKeywords[0]; // Clarion Keywords + WordList &wlCompilerDirectives = *wlKeywords[1]; // Compiler Directives + WordList &wlRuntimeExpressions = *wlKeywords[2]; // Runtime Expressions + WordList &wlBuiltInProcsFuncs = *wlKeywords[3]; // Builtin Procedures and Functions + WordList &wlStructsDataTypes = *wlKeywords[4]; // Structures and Data Types + WordList &wlAttributes = *wlKeywords[5]; // Procedure Attributes + WordList &wlStandardEquates = *wlKeywords[6]; // Standard Equates + WordList &wlLabelReservedWords = *wlKeywords[7]; // Clarion Reserved Keywords (Labels) + WordList &wlProcLabelReservedWords = *wlKeywords[8]; // Clarion Reserved Keywords (Procedure Labels) + + const char wlProcReservedKeywordList[] = + "PROCEDURE FUNCTION"; + WordList wlProcReservedKeywords; + wlProcReservedKeywords.Set(wlProcReservedKeywordList); + + const char wlCompilerKeywordList[] = + "COMPILE OMIT"; + WordList wlCompilerKeywords; + wlCompilerKeywords.Set(wlCompilerKeywordList); + + const char wlLegacyStatementsList[] = + "BOF EOF FUNCTION POINTER SHARE"; + WordList wlLegacyStatements; + wlLegacyStatements.Set(wlLegacyStatementsList); + + StyleContext scDoc(uiStartPos, iLength, iInitStyle, accStyler); + + // lex source code + for (; scDoc.More(); scDoc.Forward()) + { + // + // Determine if the current state should terminate. + // + + // Label State Handling + if (scDoc.state == SCE_CLW_LABEL) { + // If the character is not a valid label + if (!IsALabelCharacter(scDoc.ch)) { + // If the character is a . (dot syntax) + if (scDoc.ch == '.') { + // Turn off column 1 label flag as label now cannot be reserved work + iColumn1Label = false; + // Uncolour the . (dot) to default state, move forward one character, + // and change back to the label state. + scDoc.SetState(SCE_CLW_DEFAULT); + scDoc.Forward(); + scDoc.SetState(SCE_CLW_LABEL); + } + // Else check label + else { + char cLabel[512]; // Label buffer + // Buffer the current label string + scDoc.GetCurrent(cLabel,sizeof(cLabel)); + // If case insensitive, convert string to UPPERCASE to match passed keywords. + if (!bCaseSensitive) { + StringUpper(cLabel); + } + // Else if UPPERCASE label string is in the Clarion compiler keyword list + if (wlCompilerKeywords.InList(cLabel) && iColumn1Label){ + // change the label to error state + scDoc.ChangeState(SCE_CLW_COMPILER_DIRECTIVE); + } + // Else if UPPERCASE label string is in the Clarion reserved keyword list + else if (wlLabelReservedWords.InList(cLabel) && iColumn1Label){ + // change the label to error state + scDoc.ChangeState(SCE_CLW_ERROR); + } + // Else if UPPERCASE label string is + else if (wlProcLabelReservedWords.InList(cLabel) && iColumn1Label) { + char cWord[512]; // Word buffer + // Get the next word from the current position + if (GetNextWordUpper(accStyler,scDoc.currentPos,uiStartPos+iLength,cWord)) { + // If the next word is a procedure reserved word + if (wlProcReservedKeywords.InList(cWord)) { + // Change the label to error state + scDoc.ChangeState(SCE_CLW_ERROR); + } + } + } + // Else if label string is in the compiler directive keyword list + else if (wlCompilerDirectives.InList(cLabel)) { + // change the state to compiler directive state + scDoc.ChangeState(SCE_CLW_COMPILER_DIRECTIVE); + } + // Terminate the label state and set to default state + scDoc.SetState(SCE_CLW_DEFAULT); + } + } + } + // Keyword State Handling + else if (scDoc.state == SCE_CLW_KEYWORD) { + // If character is : (colon) + if (scDoc.ch == ':') { + char cEquate[512]; // Equate buffer + // Move forward to include : (colon) in buffer + scDoc.Forward(); + // Buffer the equate string + scDoc.GetCurrent(cEquate,sizeof(cEquate)); + // If case insensitive, convert string to UPPERCASE to match passed keywords. + if (!bCaseSensitive) { + StringUpper(cEquate); + } + // If statement string is in the equate list + if (wlStandardEquates.InList(cEquate)) { + // Change to equate state + scDoc.ChangeState(SCE_CLW_STANDARD_EQUATE); + } + } + // If the character is not a valid label character + else if (!IsALabelCharacter(scDoc.ch)) { + char cStatement[512]; // Statement buffer + // Buffer the statement string + scDoc.GetCurrent(cStatement,sizeof(cStatement)); + // If case insensitive, convert string to UPPERCASE to match passed keywords. + if (!bCaseSensitive) { + StringUpper(cStatement); + } + // If statement string is in the Clarion keyword list + if (wlClarionKeywords.InList(cStatement)) { + // Change the statement string to the Clarion keyword state + scDoc.ChangeState(SCE_CLW_KEYWORD); + } + // Else if statement string is in the compiler directive keyword list + else if (wlCompilerDirectives.InList(cStatement)) { + // Change the statement string to the compiler directive state + scDoc.ChangeState(SCE_CLW_COMPILER_DIRECTIVE); + } + // Else if statement string is in the runtime expressions keyword list + else if (wlRuntimeExpressions.InList(cStatement)) { + // Change the statement string to the runtime expressions state + scDoc.ChangeState(SCE_CLW_RUNTIME_EXPRESSIONS); + } + // Else if statement string is in the builtin procedures and functions keyword list + else if (wlBuiltInProcsFuncs.InList(cStatement)) { + // Change the statement string to the builtin procedures and functions state + scDoc.ChangeState(SCE_CLW_BUILTIN_PROCEDURES_FUNCTION); + } + // Else if statement string is in the tructures and data types keyword list + else if (wlStructsDataTypes.InList(cStatement)) { + // Change the statement string to the structures and data types state + scDoc.ChangeState(SCE_CLW_STRUCTURE_DATA_TYPE); + } + // Else if statement string is in the procedure attribute keyword list + else if (wlAttributes.InList(cStatement)) { + // Change the statement string to the procedure attribute state + scDoc.ChangeState(SCE_CLW_ATTRIBUTE); + } + // Else if statement string is in the standard equate keyword list + else if (wlStandardEquates.InList(cStatement)) { + // Change the statement string to the standard equate state + scDoc.ChangeState(SCE_CLW_STANDARD_EQUATE); + } + // Else if statement string is in the deprecated or legacy keyword list + else if (wlLegacyStatements.InList(cStatement)) { + // Change the statement string to the standard equate state + scDoc.ChangeState(SCE_CLW_DEPRECATED); + } + // Else the statement string doesn't match any work list + else { + // Change the statement string to the default state + scDoc.ChangeState(SCE_CLW_DEFAULT); + } + // Terminate the keyword state and set to default state + scDoc.SetState(SCE_CLW_DEFAULT); + } + } + // String State Handling + else if (scDoc.state == SCE_CLW_STRING) { + // If the character is an ' (single quote) + if (scDoc.ch == '\'') { + // Set the state to default and move forward colouring + // the ' (single quote) as default state + // terminating the string state + scDoc.SetState(SCE_CLW_DEFAULT); + scDoc.Forward(); + } + // If the next character is an ' (single quote) + if (scDoc.chNext == '\'') { + // Move forward one character and set to default state + // colouring the next ' (single quote) as default state + // terminating the string state + scDoc.ForwardSetState(SCE_CLW_DEFAULT); + scDoc.Forward(); + } + } + // Picture String State Handling + else if (scDoc.state == SCE_CLW_PICTURE_STRING) { + // If the character is an ( (open parenthese) + if (scDoc.ch == '(') { + // Increment the parenthese level + iParenthesesLevel++; + } + // Else if the character is a ) (close parenthese) + else if (scDoc.ch == ')') { + // If the parenthese level is set to zero + // parentheses matched + if (!iParenthesesLevel) { + scDoc.SetState(SCE_CLW_DEFAULT); + } + // Else parenthese level is greater than zero + // still looking for matching parentheses + else { + // Decrement the parenthese level + iParenthesesLevel--; + } + } + } + // Standard Equate State Handling + else if (scDoc.state == SCE_CLW_STANDARD_EQUATE) { + if (!isalnum(scDoc.ch)) { + scDoc.SetState(SCE_CLW_DEFAULT); + } + } + // Integer Constant State Handling + else if (scDoc.state == SCE_CLW_INTEGER_CONSTANT) { + // If the character is not a digit (0-9) + // or character is not a hexidecimal character (A-F) + // or character is not a . (point) + // or character is not a numberic base character (B,O,H) + if (!(isdigit(scDoc.ch) + || IsAHexCharacter(scDoc.ch, bCaseSensitive) + || scDoc.ch == '.' + || IsANumericBaseCharacter(scDoc.ch, bCaseSensitive))) { + // If the number was a real + if (SetNumericConstantState(scDoc)) { + // Colour the matched string to the real constant state + scDoc.ChangeState(SCE_CLW_REAL_CONSTANT); + } + // Else the number was an integer + else { + // Colour the matched string to an integer constant state + scDoc.ChangeState(SCE_CLW_INTEGER_CONSTANT); + } + // Terminate the integer constant state and set to default state + scDoc.SetState(SCE_CLW_DEFAULT); + } + } + + // + // Determine if a new state should be entered. + // + + // Beginning of Line Handling + if (scDoc.atLineStart) { + // Reset the column 1 label flag + iColumn1Label = false; + // If column 1 character is a label start character + if (IsALabelStart(scDoc.ch)) { + // Label character is found in column 1 + // so set column 1 label flag and clear last column 1 label + iColumn1Label = true; + // Set the state to label + scDoc.SetState(SCE_CLW_LABEL); + } + // else if character is a space or tab + else if (IsASpace(scDoc.ch)){ + // Set to default state + scDoc.SetState(SCE_CLW_DEFAULT); + } + // else if comment start (!) or is an * (asterisk) + else if (IsACommentStart(scDoc.ch) || scDoc.ch == '*' ) { + // then set the state to comment. + scDoc.SetState(SCE_CLW_COMMENT); + } + // else the character is a ? (question mark) + else if (scDoc.ch == '?') { + // Change to the compiler directive state, move forward, + // colouring the ? (question mark), change back to default state. + scDoc.ChangeState(SCE_CLW_COMPILER_DIRECTIVE); + scDoc.Forward(); + scDoc.SetState(SCE_CLW_DEFAULT); + } + // else an invalid character in column 1 + else { + // Set to error state + scDoc.SetState(SCE_CLW_ERROR); + } + } + // End of Line Handling + else if (scDoc.atLineEnd) { + // Reset to the default state at the end of each line. + scDoc.SetState(SCE_CLW_DEFAULT); + } + // Default Handling + else { + // If in default state + if (scDoc.state == SCE_CLW_DEFAULT) { + // If is a letter could be a possible statement + if (isalpha(scDoc.ch)) { + // Set the state to Clarion Keyword and verify later + scDoc.SetState(SCE_CLW_KEYWORD); + } + // else is a number + else if (isdigit(scDoc.ch)) { + // Set the state to Integer Constant and verify later + scDoc.SetState(SCE_CLW_INTEGER_CONSTANT); + } + // else if the start of a comment or a | (line continuation) + else if (IsACommentStart(scDoc.ch) || scDoc.ch == '|') { + // then set the state to comment. + scDoc.SetState(SCE_CLW_COMMENT); + } + // else if the character is a ' (single quote) + else if (scDoc.ch == '\'') { + // If the character is also a ' (single quote) + // Embedded Apostrophe + if (scDoc.chNext == '\'') { + // Move forward colouring it as default state + scDoc.ForwardSetState(SCE_CLW_DEFAULT); + } + else { + // move to the next character and then set the state to comment. + scDoc.ForwardSetState(SCE_CLW_STRING); + } + } + // else the character is an @ (ampersand) + else if (scDoc.ch == '@') { + // Case insensitive. + if (!bCaseSensitive) { + // If character is a valid picture token character + if (strchr("DEKNPSTdeknpst", scDoc.chNext) != NULL) { + // Set to the picture string state + scDoc.SetState(SCE_CLW_PICTURE_STRING); + } + } + // Case sensitive + else { + // If character is a valid picture token character + if (strchr("DEKNPST", scDoc.chNext) != NULL) { + // Set the picture string state + scDoc.SetState(SCE_CLW_PICTURE_STRING); + } + } + } + } + } + } + // lexing complete + scDoc.Complete(); +} + +// Clarion Language Case Sensitive Colouring Procedure +static void ColouriseClarionDocSensitive(unsigned int uiStartPos, int iLength, int iInitStyle, WordList *wlKeywords[], Accessor &accStyler) { + + ColouriseClarionDoc(uiStartPos, iLength, iInitStyle, wlKeywords, accStyler, true); +} + +// Clarion Language Case Insensitive Colouring Procedure +static void ColouriseClarionDocInsensitive(unsigned int uiStartPos, int iLength, int iInitStyle, WordList *wlKeywords[], Accessor &accStyler) { + + ColouriseClarionDoc(uiStartPos, iLength, iInitStyle, wlKeywords, accStyler, false); +} + +// Fill Buffer + +static void FillBuffer(unsigned int uiStart, unsigned int uiEnd, Accessor &accStyler, char *szBuffer, unsigned int uiLength) { + + unsigned int uiPos = 0; + + while ((uiPos < uiEnd - uiStart + 1) && (uiPos < uiLength-1)) { + szBuffer[uiPos] = static_cast(toupper(accStyler[uiStart + uiPos])); + uiPos++; + } + szBuffer[uiPos] = '\0'; +} + +// Classify Clarion Fold Point + +static int ClassifyClarionFoldPoint(int iLevel, const char* szString) { + + if (!(isdigit(szString[0]) || (szString[0] == '.'))) { + if (strcmp(szString, "PROCEDURE") == 0) { + // iLevel = SC_FOLDLEVELBASE + 1; + } + else if (strcmp(szString, "MAP") == 0 || + strcmp(szString,"ACCEPT") == 0 || + strcmp(szString,"BEGIN") == 0 || + strcmp(szString,"CASE") == 0 || + strcmp(szString,"EXECUTE") == 0 || + strcmp(szString,"IF") == 0 || + strcmp(szString,"ITEMIZE") == 0 || + strcmp(szString,"INTERFACE") == 0 || + strcmp(szString,"JOIN") == 0 || + strcmp(szString,"LOOP") == 0 || + strcmp(szString,"MODULE") == 0 || + strcmp(szString,"RECORD") == 0) { + iLevel++; + } + else if (strcmp(szString, "APPLICATION") == 0 || + strcmp(szString, "CLASS") == 0 || + strcmp(szString, "DETAIL") == 0 || + strcmp(szString, "FILE") == 0 || + strcmp(szString, "FOOTER") == 0 || + strcmp(szString, "FORM") == 0 || + strcmp(szString, "GROUP") == 0 || + strcmp(szString, "HEADER") == 0 || + strcmp(szString, "INTERFACE") == 0 || + strcmp(szString, "MENU") == 0 || + strcmp(szString, "MENUBAR") == 0 || + strcmp(szString, "OLE") == 0 || + strcmp(szString, "OPTION") == 0 || + strcmp(szString, "QUEUE") == 0 || + strcmp(szString, "REPORT") == 0 || + strcmp(szString, "SHEET") == 0 || + strcmp(szString, "TAB") == 0 || + strcmp(szString, "TOOLBAR") == 0 || + strcmp(szString, "VIEW") == 0 || + strcmp(szString, "WINDOW") == 0) { + iLevel++; + } + else if (strcmp(szString, "END") == 0 || + strcmp(szString, "UNTIL") == 0 || + strcmp(szString, "WHILE") == 0) { + iLevel--; + } + } + return(iLevel); +} + +// Clarion Language Folding Procedure +static void FoldClarionDoc(unsigned int uiStartPos, int iLength, int iInitStyle, WordList *[], Accessor &accStyler) { + + unsigned int uiEndPos = uiStartPos + iLength; + int iLineCurrent = accStyler.GetLine(uiStartPos); + int iLevelPrev = accStyler.LevelAt(iLineCurrent) & SC_FOLDLEVELNUMBERMASK; + int iLevelCurrent = iLevelPrev; + char chNext = accStyler[uiStartPos]; + int iStyle = iInitStyle; + int iStyleNext = accStyler.StyleAt(uiStartPos); + int iVisibleChars = 0; + int iLastStart = 0; + + for (unsigned int uiPos = uiStartPos; uiPos < uiEndPos; uiPos++) { + + char chChar = chNext; + chNext = accStyler.SafeGetCharAt(uiPos + 1); + int iStylePrev = iStyle; + iStyle = iStyleNext; + iStyleNext = accStyler.StyleAt(uiPos + 1); + bool bEOL = (chChar == '\r' && chNext != '\n') || (chChar == '\n'); + + if (iStylePrev == SCE_CLW_DEFAULT) { + if (iStyle == SCE_CLW_KEYWORD || iStyle == SCE_CLW_STRUCTURE_DATA_TYPE) { + // Store last word start point. + iLastStart = uiPos; + } + } + + if (iStylePrev == SCE_CLW_KEYWORD || iStylePrev == SCE_CLW_STRUCTURE_DATA_TYPE) { + if(iswordchar(chChar) && !iswordchar(chNext)) { + char chBuffer[100]; + FillBuffer(iLastStart, uiPos, accStyler, chBuffer, sizeof(chBuffer)); + iLevelCurrent = ClassifyClarionFoldPoint(iLevelCurrent,chBuffer); + // if ((iLevelCurrent == SC_FOLDLEVELBASE + 1) && iLineCurrent > 1) { + // accStyler.SetLevel(iLineCurrent-1,SC_FOLDLEVELBASE); + // iLevelPrev = SC_FOLDLEVELBASE; + // } + } + } + + if (bEOL) { + int iLevel = iLevelPrev; + if ((iLevelCurrent > iLevelPrev) && (iVisibleChars > 0)) + iLevel |= SC_FOLDLEVELHEADERFLAG; + if (iLevel != accStyler.LevelAt(iLineCurrent)) { + accStyler.SetLevel(iLineCurrent,iLevel); + } + iLineCurrent++; + iLevelPrev = iLevelCurrent; + iVisibleChars = 0; + } + + if (!isspacechar(chChar)) + iVisibleChars++; + } + + // Fill in the real level of the next line, keeping the current flags + // as they will be filled in later. + int iFlagsNext = accStyler.LevelAt(iLineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + accStyler.SetLevel(iLineCurrent, iLevelPrev | iFlagsNext); +} + +// Word List Descriptions +static const char * const rgWordListDescriptions[] = { + "Clarion Keywords", + "Compiler Directives", + "Built-in Procedures and Functions", + "Runtime Expressions", + "Structure and Data Types", + "Attributes", + "Standard Equates", + "Reserved Words (Labels)", + "Reserved Words (Procedure Labels)", + 0, +}; + +// Case Sensitive Clarion Language Lexer +LexerModule lmClw(SCLEX_CLW, ColouriseClarionDocSensitive, "clarion", FoldClarionDoc, rgWordListDescriptions); + +// Case Insensitive Clarion Language Lexer +LexerModule lmClwNoCase(SCLEX_CLWNOCASE, ColouriseClarionDocInsensitive, "clarionnocase", FoldClarionDoc, rgWordListDescriptions); diff --git a/scintilla/src/LexCPP.cxx b/scintilla/src/LexCPP.cxx new file mode 100644 index 00000000..21c36ff3 --- /dev/null +++ b/scintilla/src/LexCPP.cxx @@ -0,0 +1,474 @@ +// Scintilla source code edit control +/** @file LexCPP.cxx + ** Lexer for C++, C, Java, and JavaScript. + **/ +// Copyright 1998-2005 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" +#include "CharacterSet.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static bool IsSpaceEquiv(int state) { + return (state <= SCE_C_COMMENTDOC) || + // including SCE_C_DEFAULT, SCE_C_COMMENT, SCE_C_COMMENTLINE + (state == SCE_C_COMMENTLINEDOC) || (state == SCE_C_COMMENTDOCKEYWORD) || + (state == SCE_C_COMMENTDOCKEYWORDERROR); +} + +// Preconditions: sc.currentPos points to a character after '+' or '-'. +// The test for pos reaching 0 should be redundant, +// and is in only for safety measures. +// Limitation: this code will give the incorrect answer for code like +// a = b+++/ptn/... +// Putting a space between the '++' post-inc operator and the '+' binary op +// fixes this, and is highly recommended for readability anyway. +static bool FollowsPostfixOperator(StyleContext &sc, Accessor &styler) { + int pos = (int) sc.currentPos; + while (--pos > 0) { + char ch = styler[pos]; + if (ch == '+' || ch == '-') { + return styler[pos - 1] == ch; + } + } + return false; +} + +static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler, bool caseSensitive) { + + WordList &keywords = *keywordlists[0]; + WordList &keywords2 = *keywordlists[1]; + WordList &keywords3 = *keywordlists[2]; + WordList &keywords4 = *keywordlists[3]; + + bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0; + + CharacterSet setOKBeforeRE(CharacterSet::setNone, "([{=,:;!%^&*|?~+-"); + CharacterSet setCouldBePostOp(CharacterSet::setNone, "+-"); + + CharacterSet setDoxygen(CharacterSet::setLower, "$@\\&<>#{}[]"); + + CharacterSet setWordStart(CharacterSet::setAlpha, "_", 0x80, true); + CharacterSet setWord(CharacterSet::setAlphaNum, "._", 0x80, true); + if (styler.GetPropertyInt("lexer.cpp.allow.dollars", 1) != 0) { + setWordStart.Add('$'); + setWord.Add('$'); + } + + int chPrevNonWhite = ' '; + int visibleChars = 0; + bool lastWordWasUUID = false; + int styleBeforeDCKeyword = SCE_C_DEFAULT; + bool continuationLine = false; + + if (initStyle == SCE_C_PREPROCESSOR) { + // Set continuationLine if last character of previous line is '\' + int lineCurrent = styler.GetLine(startPos); + if (lineCurrent > 0) { + int chBack = styler.SafeGetCharAt(startPos-1, 0); + int chBack2 = styler.SafeGetCharAt(startPos-2, 0); + int lineEndChar = '!'; + if (chBack2 == '\r' && chBack == '\n') { + lineEndChar = styler.SafeGetCharAt(startPos-3, 0); + } else if (chBack == '\n' || chBack == '\r') { + lineEndChar = chBack2; + } + continuationLine = lineEndChar == '\\'; + } + } + + // 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_C_OPERATOR) { + chPrevNonWhite = styler.SafeGetCharAt(back); + } + } + + StyleContext sc(startPos, length, initStyle, styler); + + for (; sc.More(); sc.Forward()) { + + if (sc.atLineStart) { + if (sc.state == SCE_C_STRING) { + // Prevent SCE_C_STRINGEOL from leaking back to previous line which + // ends with a line continuation by locking in the state upto this position. + sc.SetState(SCE_C_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_C_OPERATOR: + sc.SetState(SCE_C_DEFAULT); + break; + case SCE_C_NUMBER: + // We accept almost anything because of hex. and number suffixes + if (!setWord.Contains(sc.ch)) { + sc.SetState(SCE_C_DEFAULT); + } + break; + case SCE_C_IDENTIFIER: + if (!setWord.Contains(sc.ch) || (sc.ch == '.')) { + char s[1000]; + if (caseSensitive) { + sc.GetCurrent(s, sizeof(s)); + } else { + sc.GetCurrentLowered(s, sizeof(s)); + } + if (keywords.InList(s)) { + lastWordWasUUID = strcmp(s, "uuid") == 0; + sc.ChangeState(SCE_C_WORD); + } else if (keywords2.InList(s)) { + sc.ChangeState(SCE_C_WORD2); + } else if (keywords4.InList(s)) { + sc.ChangeState(SCE_C_GLOBALCLASS); + } + sc.SetState(SCE_C_DEFAULT); + } + break; + case SCE_C_PREPROCESSOR: + if (sc.atLineStart && !continuationLine) { + sc.SetState(SCE_C_DEFAULT); + } else if (stylingWithinPreprocessor) { + if (IsASpace(sc.ch)) { + sc.SetState(SCE_C_DEFAULT); + } + } else { + if (sc.Match('/', '*') || sc.Match('/', '/')) { + sc.SetState(SCE_C_DEFAULT); + } + } + break; + case SCE_C_COMMENT: + if (sc.Match('*', '/')) { + sc.Forward(); + sc.ForwardSetState(SCE_C_DEFAULT); + } + break; + case SCE_C_COMMENTDOC: + if (sc.Match('*', '/')) { + sc.Forward(); + sc.ForwardSetState(SCE_C_DEFAULT); + } else if (sc.ch == '@' || sc.ch == '\\') { // JavaDoc and Doxygen support + // Verify that we have the conditions to mark a comment-doc-keyword + if ((IsASpace(sc.chPrev) || sc.chPrev == '*') && (!IsASpace(sc.chNext))) { + styleBeforeDCKeyword = SCE_C_COMMENTDOC; + sc.SetState(SCE_C_COMMENTDOCKEYWORD); + } + } + break; + case SCE_C_COMMENTLINE: + if (sc.atLineStart) { + sc.SetState(SCE_C_DEFAULT); + } + break; + case SCE_C_COMMENTLINEDOC: + if (sc.atLineStart) { + sc.SetState(SCE_C_DEFAULT); + } else if (sc.ch == '@' || sc.ch == '\\') { // JavaDoc and Doxygen support + // Verify that we have the conditions to mark a comment-doc-keyword + if ((IsASpace(sc.chPrev) || sc.chPrev == '/' || sc.chPrev == '!') && (!IsASpace(sc.chNext))) { + styleBeforeDCKeyword = SCE_C_COMMENTLINEDOC; + sc.SetState(SCE_C_COMMENTDOCKEYWORD); + } + } + break; + case SCE_C_COMMENTDOCKEYWORD: + if ((styleBeforeDCKeyword == SCE_C_COMMENTDOC) && sc.Match('*', '/')) { + sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR); + sc.Forward(); + sc.ForwardSetState(SCE_C_DEFAULT); + } else if (!setDoxygen.Contains(sc.ch)) { + char s[100]; + if (caseSensitive) { + sc.GetCurrent(s, sizeof(s)); + } else { + sc.GetCurrentLowered(s, sizeof(s)); + } + if (!IsASpace(sc.ch) || !keywords3.InList(s + 1)) { + sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR); + } + sc.SetState(styleBeforeDCKeyword); + } + break; + case SCE_C_STRING: + if (sc.atLineEnd) { + sc.ChangeState(SCE_C_STRINGEOL); + } else if (sc.ch == '\\') { + if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { + sc.Forward(); + } + } else if (sc.ch == '\"') { + sc.ForwardSetState(SCE_C_DEFAULT); + } + break; + case SCE_C_CHARACTER: + if (sc.atLineEnd) { + sc.ChangeState(SCE_C_STRINGEOL); + } else if (sc.ch == '\\') { + if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { + sc.Forward(); + } + } else if (sc.ch == '\'') { + sc.ForwardSetState(SCE_C_DEFAULT); + } + break; + case SCE_C_REGEX: + if (sc.atLineStart) { + sc.SetState(SCE_C_DEFAULT); + } else if (sc.ch == '/') { + sc.Forward(); + while ((sc.ch < 0x80) && islower(sc.ch)) + sc.Forward(); // gobble regex flags + sc.SetState(SCE_C_DEFAULT); + } else if (sc.ch == '\\') { + // Gobble up the quoted character + if (sc.chNext == '\\' || sc.chNext == '/') { + sc.Forward(); + } + } + break; + case SCE_C_STRINGEOL: + if (sc.atLineStart) { + sc.SetState(SCE_C_DEFAULT); + } + break; + case SCE_C_VERBATIM: + if (sc.ch == '\"') { + if (sc.chNext == '\"') { + sc.Forward(); + } else { + sc.ForwardSetState(SCE_C_DEFAULT); + } + } + break; + case SCE_C_UUID: + if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') { + sc.SetState(SCE_C_DEFAULT); + } + } + + // Determine if a new state should be entered. + if (sc.state == SCE_C_DEFAULT) { + if (sc.Match('@', '\"')) { + sc.SetState(SCE_C_VERBATIM); + sc.Forward(); + } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { + if (lastWordWasUUID) { + sc.SetState(SCE_C_UUID); + lastWordWasUUID = false; + } else { + sc.SetState(SCE_C_NUMBER); + } + } else if (setWordStart.Contains(sc.ch) || (sc.ch == '@')) { + if (lastWordWasUUID) { + sc.SetState(SCE_C_UUID); + lastWordWasUUID = false; + } else { + sc.SetState(SCE_C_IDENTIFIER); + } + } else if (sc.Match('/', '*')) { + if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style + sc.SetState(SCE_C_COMMENTDOC); + } else { + sc.SetState(SCE_C_COMMENT); + } + sc.Forward(); // Eat the * so it isn't used for the end of the comment + } else if (sc.Match('/', '/')) { + if ((sc.Match("///") && !sc.Match("////")) || sc.Match("//!")) + // Support of Qt/Doxygen doc. style + sc.SetState(SCE_C_COMMENTLINEDOC); + else + sc.SetState(SCE_C_COMMENTLINE); + } else if (sc.ch == '/' && setOKBeforeRE.Contains(chPrevNonWhite) && + (!setCouldBePostOp.Contains(chPrevNonWhite) || !FollowsPostfixOperator(sc, styler))) { + sc.SetState(SCE_C_REGEX); // JavaScript's RegEx + } else if (sc.ch == '\"') { + sc.SetState(SCE_C_STRING); + } else if (sc.ch == '\'') { + sc.SetState(SCE_C_CHARACTER); + } else if (sc.ch == '#' && visibleChars == 0) { + // Preprocessor commands are alone on their line + sc.SetState(SCE_C_PREPROCESSOR); + // Skip whitespace between # and preprocessor word + do { + sc.Forward(); + } while ((sc.ch == ' ' || sc.ch == '\t') && sc.More()); + if (sc.atLineEnd) { + sc.SetState(SCE_C_DEFAULT); + } + } else if (isoperator(static_cast(sc.ch))) { + sc.SetState(SCE_C_OPERATOR); + } + } + + if (!IsASpace(sc.ch) && !IsSpaceEquiv(sc.state)) { + chPrevNonWhite = sc.ch; + visibleChars++; + } + continuationLine = false; + } + sc.Complete(); +} + +static bool IsStreamCommentStyle(int style) { + return style == SCE_C_COMMENT || + style == SCE_C_COMMENTDOC || + style == SCE_C_COMMENTDOCKEYWORD || + style == SCE_C_COMMENTDOCKEYWORDERROR; +} + +// 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 FoldCppDoc(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; + bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0; + unsigned int endPos = startPos + length; + int visibleChars = 0; + int lineCurrent = styler.GetLine(startPos); + int levelCurrent = SC_FOLDLEVELBASE; + if (lineCurrent > 0) + levelCurrent = styler.LevelAt(lineCurrent-1) >> 16; + int levelMinCurrent = levelCurrent; + int levelNext = levelCurrent; + char chNext = 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_C_COMMENTLINEDOC)) { + levelNext++; + } else if (!IsStreamCommentStyle(styleNext) && (styleNext != SCE_C_COMMENTLINEDOC) && !atEOL) { + // Comments don't end at end of line and the next character may be unstyled. + levelNext--; + } + } + if (foldComment && (style == SCE_C_COMMENTLINE)) { + if ((ch == '/') && (chNext == '/')) { + char chNext2 = styler.SafeGetCharAt(i + 2); + if (chNext2 == '{') { + levelNext++; + } else if (chNext2 == '}') { + levelNext--; + } + } + } + if (foldPreprocessor && (style == SCE_C_PREPROCESSOR)) { + if (ch == '#') { + unsigned int j = i + 1; + while ((j < endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) { + j++; + } + if (styler.Match(j, "region") || styler.Match(j, "if")) { + levelNext++; + } else if (styler.Match(j, "end")) { + levelNext--; + } + } + } + if (style == SCE_C_OPERATOR) { + if (ch == '{') { + // Measure the minimum before a '{' to allow + // folding on "} else {" + if (levelMinCurrent > levelNext) { + levelMinCurrent = levelNext; + } + levelNext++; + } else if (ch == '}') { + levelNext--; + } + } + if (!IsASpace(ch)) + visibleChars++; + if (atEOL || (i == endPos-1)) { + int levelUse = levelCurrent; + if (foldAtElse) { + levelUse = levelMinCurrent; + } + int lev = levelUse | levelNext << 16; + if (visibleChars == 0 && foldCompact) + lev |= SC_FOLDLEVELWHITEFLAG; + if (levelUse < levelNext) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelCurrent = levelNext; + levelMinCurrent = levelCurrent; + visibleChars = 0; + } + } + char lastChar = styler.SafeGetCharAt(endPos-1); + if ((unsigned)styler.Length() == endPos && (lastChar == '\n' || lastChar == '\r')) { + styler.SetLevel(lineCurrent, levelCurrent); + } +} + +static const char * const cppWordLists[] = { + "Primary keywords and identifiers", + "Secondary keywords and identifiers", + "Documentation comment keywords", + "Unused", + "Global classes and typedefs", + 0, + }; + +static void ColouriseCppDocSensitive(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler) { + ColouriseCppDoc(startPos, length, initStyle, keywordlists, styler, true); +} + +static void ColouriseCppDocInsensitive(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler) { + ColouriseCppDoc(startPos, length, initStyle, keywordlists, styler, false); +} + +LexerModule lmCPP(SCLEX_CPP, ColouriseCppDocSensitive, "cpp", FoldCppDoc, cppWordLists); +LexerModule lmCPPNoCase(SCLEX_CPPNOCASE, ColouriseCppDocInsensitive, "cppnocase", FoldCppDoc, cppWordLists); diff --git a/scintilla/src/LexCSS.cxx b/scintilla/src/LexCSS.cxx new file mode 100644 index 00000000..9be4aeee --- /dev/null +++ b/scintilla/src/LexCSS.cxx @@ -0,0 +1,302 @@ +// Scintilla source code edit control +/** @file LexCSS.cxx +** Lexer for Cascading Style Sheets +** Written by Jakub Vr?na +** Improved by Philippe Lhoste (CSS2) +**/ +// Copyright 1998-2002 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + + +static inline bool IsAWordChar(const unsigned int ch) { + return (isalnum(ch) || ch == '-' || ch == '_' || ch >= 161); // _ is not in fact correct CSS word-character +} + +inline bool IsCssOperator(const int ch) { + if (!((ch < 0x80) && isalnum(ch)) && + (ch == '{' || ch == '}' || ch == ':' || ch == ',' || ch == ';' || + ch == '.' || ch == '#' || ch == '!' || ch == '@' || + /* CSS2 */ + ch == '*' || ch == '>' || ch == '+' || ch == '=' || ch == '~' || ch == '|' || + ch == '[' || ch == ']' || ch == '(' || ch == ')')) { + return true; + } + return false; +} + +static void ColouriseCssDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { + WordList &keywords = *keywordlists[0]; + WordList &pseudoClasses = *keywordlists[1]; + WordList &keywords2 = *keywordlists[2]; + + StyleContext sc(startPos, length, initStyle, styler); + + int lastState = -1; // before operator + int lastStateC = -1; // before comment + int op = ' '; // last operator + + for (; sc.More(); sc.Forward()) { + if (sc.state == SCE_CSS_COMMENT && sc.Match('*', '/')) { + if (lastStateC == -1) { + // backtrack to get last state: + // comments are like whitespace, so we must return to the previous state + unsigned int i = startPos; + for (; i > 0; i--) { + if ((lastStateC = styler.StyleAt(i-1)) != SCE_CSS_COMMENT) { + if (lastStateC == SCE_CSS_OPERATOR) { + op = styler.SafeGetCharAt(i-1); + while (--i) { + lastState = styler.StyleAt(i-1); + if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT) + break; + } + if (i == 0) + lastState = SCE_CSS_DEFAULT; + } + break; + } + } + if (i == 0) + lastStateC = SCE_CSS_DEFAULT; + } + sc.Forward(); + sc.ForwardSetState(lastStateC); + } + + if (sc.state == SCE_CSS_COMMENT) + continue; + + if (sc.state == SCE_CSS_DOUBLESTRING || sc.state == SCE_CSS_SINGLESTRING) { + if (sc.ch != (sc.state == SCE_CSS_DOUBLESTRING ? '\"' : '\'')) + continue; + unsigned int i = sc.currentPos; + while (i && styler[i-1] == '\\') + i--; + if ((sc.currentPos - i) % 2 == 1) + continue; + sc.ForwardSetState(SCE_CSS_VALUE); + } + + if (sc.state == SCE_CSS_OPERATOR) { + if (op == ' ') { + unsigned int i = startPos; + op = styler.SafeGetCharAt(i-1); + while (--i) { + lastState = styler.StyleAt(i-1); + if (lastState != SCE_CSS_OPERATOR && lastState != SCE_CSS_COMMENT) + break; + } + } + switch (op) { + case '@': + if (lastState == SCE_CSS_DEFAULT) + sc.SetState(SCE_CSS_DIRECTIVE); + break; + case '*': + if (lastState == SCE_CSS_DEFAULT) + sc.SetState(SCE_CSS_TAG); + break; + case '>': + case '+': + if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_PSEUDOCLASS || lastState == SCE_CSS_CLASS + || lastState == SCE_CSS_ID || lastState == SCE_CSS_UNKNOWN_PSEUDOCLASS) + sc.SetState(SCE_CSS_DEFAULT); + break; + case '[': + if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_PSEUDOCLASS || lastState == SCE_CSS_DEFAULT || + lastState == SCE_CSS_CLASS || lastState == SCE_CSS_ID || lastState == SCE_CSS_UNKNOWN_PSEUDOCLASS) + sc.SetState(SCE_CSS_ATTRIBUTE); + break; + case ']': + if (lastState == SCE_CSS_ATTRIBUTE) + sc.SetState(SCE_CSS_TAG); + break; + case '{': + if (lastState == SCE_CSS_DIRECTIVE) + sc.SetState(SCE_CSS_DEFAULT); + else if (lastState == SCE_CSS_TAG) + sc.SetState(SCE_CSS_IDENTIFIER); + break; + case '}': + if (lastState == SCE_CSS_DEFAULT || lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT || + lastState == SCE_CSS_IDENTIFIER || lastState == SCE_CSS_IDENTIFIER2) + sc.SetState(SCE_CSS_DEFAULT); + break; + case ':': + if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_PSEUDOCLASS || lastState == SCE_CSS_DEFAULT || + lastState == SCE_CSS_CLASS || lastState == SCE_CSS_ID || lastState == SCE_CSS_UNKNOWN_PSEUDOCLASS) + sc.SetState(SCE_CSS_PSEUDOCLASS); + else if (lastState == SCE_CSS_IDENTIFIER || lastState == SCE_CSS_IDENTIFIER2 || lastState == SCE_CSS_UNKNOWN_IDENTIFIER) + sc.SetState(SCE_CSS_VALUE); + break; + case '.': + if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_PSEUDOCLASS || lastState == SCE_CSS_DEFAULT || + lastState == SCE_CSS_CLASS || lastState == SCE_CSS_ID || lastState == SCE_CSS_UNKNOWN_PSEUDOCLASS) + sc.SetState(SCE_CSS_CLASS); + break; + case '#': + if (lastState == SCE_CSS_TAG || lastState == SCE_CSS_PSEUDOCLASS || lastState == SCE_CSS_DEFAULT || + lastState == SCE_CSS_CLASS || lastState == SCE_CSS_ID || lastState == SCE_CSS_UNKNOWN_PSEUDOCLASS) + sc.SetState(SCE_CSS_ID); + break; + case ',': + if (lastState == SCE_CSS_TAG) + sc.SetState(SCE_CSS_DEFAULT); + break; + case ';': + if (lastState == SCE_CSS_DIRECTIVE) + sc.SetState(SCE_CSS_DEFAULT); + else if (lastState == SCE_CSS_VALUE || lastState == SCE_CSS_IMPORTANT) + sc.SetState(SCE_CSS_IDENTIFIER); + break; + case '!': + if (lastState == SCE_CSS_VALUE) + sc.SetState(SCE_CSS_IMPORTANT); + break; + } + } + + if (IsAWordChar(sc.ch)) { + if (sc.state == SCE_CSS_DEFAULT) + sc.SetState(SCE_CSS_TAG); + continue; + } + + if (IsAWordChar(sc.chPrev) && ( + sc.state == SCE_CSS_IDENTIFIER || sc.state == SCE_CSS_IDENTIFIER2 + || sc.state == SCE_CSS_UNKNOWN_IDENTIFIER + || sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS + || sc.state == SCE_CSS_IMPORTANT + )) { + char s[100]; + sc.GetCurrentLowered(s, sizeof(s)); + char *s2 = s; + while (*s2 && !IsAWordChar(*s2)) + s2++; + switch (sc.state) { + case SCE_CSS_IDENTIFIER: + case SCE_CSS_IDENTIFIER2: + case SCE_CSS_UNKNOWN_IDENTIFIER: + if (keywords.InList(s2)) + sc.ChangeState(SCE_CSS_IDENTIFIER); + else if (keywords2.InList(s2)) + sc.ChangeState(SCE_CSS_IDENTIFIER2); + else + sc.ChangeState(SCE_CSS_UNKNOWN_IDENTIFIER); + break; + case SCE_CSS_PSEUDOCLASS: + if (!pseudoClasses.InList(s2)) + sc.ChangeState(SCE_CSS_UNKNOWN_PSEUDOCLASS); + break; + case SCE_CSS_UNKNOWN_PSEUDOCLASS: + if (pseudoClasses.InList(s2)) + sc.ChangeState(SCE_CSS_PSEUDOCLASS); + break; + case SCE_CSS_IMPORTANT: + if (strcmp(s2, "important") != 0) + sc.ChangeState(SCE_CSS_VALUE); + break; + } + } + + if (sc.ch != '.' && sc.ch != ':' && sc.ch != '#' && (sc.state == SCE_CSS_CLASS || sc.state == SCE_CSS_PSEUDOCLASS || sc.state == SCE_CSS_UNKNOWN_PSEUDOCLASS || sc.state == SCE_CSS_ID)) + sc.SetState(SCE_CSS_TAG); + + if (sc.Match('/', '*')) { + lastStateC = sc.state; + sc.SetState(SCE_CSS_COMMENT); + sc.Forward(); + } else if (sc.state == SCE_CSS_VALUE && (sc.ch == '\"' || sc.ch == '\'')) { + sc.SetState((sc.ch == '\"' ? SCE_CSS_DOUBLESTRING : SCE_CSS_SINGLESTRING)); + } else if (IsCssOperator(sc.ch) + && (sc.state != SCE_CSS_ATTRIBUTE || sc.ch == ']') + && (sc.state != SCE_CSS_VALUE || sc.ch == ';' || sc.ch == '}' || sc.ch == '!') + && (sc.state != SCE_CSS_DIRECTIVE || sc.ch == ';' || sc.ch == '{') + ) { + if (sc.state != SCE_CSS_OPERATOR) + lastState = sc.state; + sc.SetState(SCE_CSS_OPERATOR); + op = sc.ch; + } + } + + sc.Complete(); +} + +static void FoldCSSDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { + bool foldComment = styler.GetPropertyInt("fold.comment") != 0; + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + unsigned int endPos = startPos + length; + int visibleChars = 0; + int lineCurrent = styler.GetLine(startPos); + int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; + int levelCurrent = levelPrev; + char chNext = styler[startPos]; + bool inComment = (styler.StyleAt(startPos-1) == SCE_CSS_COMMENT); + for (unsigned int i = startPos; i < endPos; i++) { + char ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + int style = styler.StyleAt(i); + bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); + if (foldComment) { + if (!inComment && (style == SCE_CSS_COMMENT)) + levelCurrent++; + else if (inComment && (style != SCE_CSS_COMMENT)) + levelCurrent--; + inComment = (style == SCE_CSS_COMMENT); + } + if (style == SCE_CSS_OPERATOR) { + if (ch == '{') { + levelCurrent++; + } else if (ch == '}') { + levelCurrent--; + } + } + if (atEOL) { + int lev = levelPrev; + if (visibleChars == 0 && foldCompact) + lev |= SC_FOLDLEVELWHITEFLAG; + if ((levelCurrent > levelPrev) && (visibleChars > 0)) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelPrev = levelCurrent; + visibleChars = 0; + } + if (!isspacechar(ch)) + visibleChars++; + } + // Fill in the real level of the next line, keeping the current flags as they will be filled in later + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, levelPrev | flagsNext); +} + +static const char * const cssWordListDesc[] = { + "CSS1 Keywords", + "Pseudo classes", + "CSS2 Keywords", + 0 +}; + +LexerModule lmCss(SCLEX_CSS, ColouriseCssDoc, "css", FoldCSSDoc, cssWordListDesc); diff --git a/scintilla/src/LexCaml.cxx b/scintilla/src/LexCaml.cxx new file mode 100644 index 00000000..845ac657 --- /dev/null +++ b/scintilla/src/LexCaml.cxx @@ -0,0 +1,403 @@ +// Scintilla source code edit control +/** @file LexCaml.cxx + ** Lexer for Objective Caml. + **/ +// Copyright 2005 by Robert Roessler +// The License.txt file describes the conditions under which this software may be distributed. +/* Release History + 20050204 Initial release. + 20050205 Quick compiler standards/"cleanliness" adjustment. + 20050206 Added cast for IsLeadByte(). + 20050209 Changes to "external" build support. + 20050306 Fix for 1st-char-in-doc "corner" case. + 20050502 Fix for [harmless] one-past-the-end coloring. + 20050515 Refined numeric token recognition logic. + 20051125 Added 2nd "optional" keywords class. + 20051129 Support "magic" (read-only) comments for RCaml. + 20051204 Swtich to using StyleContext infrastructure. +*/ + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +// Since the Microsoft __iscsym[f] funcs are not ANSI... +inline int iscaml(int c) {return isalnum(c) || c == '_';} +inline int iscamlf(int c) {return isalpha(c) || c == '_';} +inline int iscamld(int c) {return isdigit(c) || c == '_';} + +static const int baseT[24] = { + 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* A - L */ + 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0,16 /* M - X */ +}; + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +#ifdef BUILD_AS_EXTERNAL_LEXER +/* + (actually seems to work!) +*/ +#include "WindowAccessor.h" +#include "ExternalLexer.h" + +#if PLAT_WIN +#include +#endif + +static void ColouriseCamlDoc( + unsigned int startPos, int length, + int initStyle, + WordList *keywordlists[], + Accessor &styler); + +static void FoldCamlDoc( + unsigned int startPos, int length, + int initStyle, + WordList *keywordlists[], + Accessor &styler); + +static void InternalLexOrFold(int lexOrFold, unsigned int startPos, int length, + int initStyle, char *words[], WindowID window, char *props); + +static const char* LexerName = "caml"; + +#ifdef TRACE +void Platform::DebugPrintf(const char *format, ...) { + char buffer[2000]; + va_list pArguments; + va_start(pArguments, format); + vsprintf(buffer,format,pArguments); + va_end(pArguments); + Platform::DebugDisplay(buffer); +} +#else +void Platform::DebugPrintf(const char *, ...) { +} +#endif + +bool Platform::IsDBCSLeadByte(int codePage, char ch) { + return ::IsDBCSLeadByteEx(codePage, ch) != 0; +} + +long Platform::SendScintilla(WindowID w, unsigned int msg, unsigned long wParam, long lParam) { + return ::SendMessage(reinterpret_cast(w), msg, wParam, lParam); +} + +long Platform::SendScintillaPointer(WindowID w, unsigned int msg, unsigned long wParam, void *lParam) { + return ::SendMessage(reinterpret_cast(w), msg, wParam, + reinterpret_cast(lParam)); +} + +void EXT_LEXER_DECL Fold(unsigned int lexer, unsigned int startPos, int length, + int initStyle, char *words[], WindowID window, char *props) +{ + // below useless evaluation(s) to supress "not used" warnings + lexer; + // build expected data structures and do the Fold + InternalLexOrFold(1, startPos, length, initStyle, words, window, props); + +} + +int EXT_LEXER_DECL GetLexerCount() +{ + return 1; // just us [Objective] Caml lexers here! +} + +void EXT_LEXER_DECL GetLexerName(unsigned int Index, char *name, int buflength) +{ + // below useless evaluation(s) to supress "not used" warnings + Index; + // return as much of our lexer name as will fit (what's up with Index?) + if (buflength > 0) { + buflength--; + int n = strlen(LexerName); + if (n > buflength) + n = buflength; + memcpy(name, LexerName, n), name[n] = '\0'; + } +} + +void EXT_LEXER_DECL Lex(unsigned int lexer, unsigned int startPos, int length, + int initStyle, char *words[], WindowID window, char *props) +{ + // below useless evaluation(s) to supress "not used" warnings + lexer; + // build expected data structures and do the Lex + InternalLexOrFold(0, startPos, length, initStyle, words, window, props); +} + +static void InternalLexOrFold(int foldOrLex, unsigned int startPos, int length, + int initStyle, char *words[], WindowID window, char *props) +{ + // create and initialize a WindowAccessor (including contained PropSet) + PropSet ps; + ps.SetMultiple(props); + WindowAccessor wa(window, ps); + // create and initialize WordList(s) + int nWL = 0; + for (; words[nWL]; nWL++) ; // count # of WordList PTRs needed + WordList** wl = new WordList* [nWL + 1];// alloc WordList PTRs + int i = 0; + for (; i < nWL; i++) { + wl[i] = new WordList(); // (works or THROWS bad_alloc EXCEPTION) + wl[i]->Set(words[i]); + } + wl[i] = 0; + // call our "internal" folder/lexer (... then do Flush!) + if (foldOrLex) + FoldCamlDoc(startPos, length, initStyle, wl, wa); + else + ColouriseCamlDoc(startPos, length, initStyle, wl, wa); + wa.Flush(); + // clean up before leaving + for (i = nWL - 1; i >= 0; i--) + delete wl[i]; + delete [] wl; +} + +static +#endif /* BUILD_AS_EXTERNAL_LEXER */ + +void ColouriseCamlDoc( + unsigned int startPos, int length, + int initStyle, + WordList *keywordlists[], + Accessor &styler) +{ + // initialize styler + StyleContext sc(startPos, length, initStyle, styler); + // set up [initial] state info (terminating states that shouldn't "bleed") + int nesting = 0; + if (sc.state < SCE_CAML_STRING) + sc.state = SCE_CAML_DEFAULT; + if (sc.state >= SCE_CAML_COMMENT) + nesting = (sc.state & 0x0f) - SCE_CAML_COMMENT; + + int chBase = 0, chToken = 0, chLit = 0; + WordList& keywords = *keywordlists[0]; + WordList& keywords2 = *keywordlists[1]; + WordList& keywords3 = *keywordlists[2]; + const int useMagic = styler.GetPropertyInt("lexer.caml.magic", 0); + + // foreach char in range... + while (sc.More()) { + // set up [per-char] state info + int state2 = -1; // (ASSUME no state change) + int chColor = sc.currentPos - 1;// (ASSUME standard coloring range) + bool advance = true; // (ASSUME scanner "eats" 1 char) + + // step state machine + switch (sc.state & 0x0f) { + case SCE_CAML_DEFAULT: + chToken = sc.currentPos; // save [possible] token start (JIC) + // it's wide open; what do we have? + if (iscamlf(sc.ch)) + state2 = SCE_CAML_IDENTIFIER; + else if (sc.Match('`') && iscamlf(sc.chNext)) + state2 = SCE_CAML_TAGNAME; + else if (sc.Match('#') && isdigit(sc.chNext)) + state2 = SCE_CAML_LINENUM; + else if (isdigit(sc.ch)) { + state2 = SCE_CAML_NUMBER, chBase = 10; + if (sc.Match('0') && strchr("bBoOxX", sc.chNext)) + chBase = baseT[tolower(sc.chNext) - 'a'], sc.Forward(); + } else if (sc.Match('\'')) /* (char literal?) */ + state2 = SCE_CAML_CHAR, chLit = 0; + else if (sc.Match('\"')) + state2 = SCE_CAML_STRING; + else if (sc.Match('(', '*')) + state2 = SCE_CAML_COMMENT, + sc.ch = ' ', // (make SURE "(*)" isn't seen as a closed comment) + sc.Forward(); + else if (strchr("!?~" /* Caml "prefix-symbol" */ + "=<>@^|&+-*/$%" /* Caml "infix-symbol" */ + "()[]{};,:.#", sc.ch)) /* Caml "bracket" or ;,:.# */ + state2 = SCE_CAML_OPERATOR; + break; + + case SCE_CAML_IDENTIFIER: + // [try to] interpret as [additional] identifier char + if (!(iscaml(sc.ch) || sc.Match('\''))) { + const int n = sc.currentPos - chToken; + if (n < 24) { + // length is believable as keyword, [re-]construct token + char t[24]; + for (int i = -n; i < 0; i++) + t[n + i] = static_cast(sc.GetRelative(i)); + t[n] = '\0'; + // special-case "_" token as KEYWORD + if ((n == 1 && sc.chPrev == '_') || keywords.InList(t)) + sc.ChangeState(SCE_CAML_KEYWORD); + else if (keywords2.InList(t)) + sc.ChangeState(SCE_CAML_KEYWORD2); + else if (keywords3.InList(t)) + sc.ChangeState(SCE_CAML_KEYWORD3); + } + state2 = SCE_CAML_DEFAULT, advance = false; + } + break; + + case SCE_CAML_TAGNAME: + // [try to] interpret as [additional] tagname char + if (!(iscaml(sc.ch) || sc.Match('\''))) + state2 = SCE_CAML_DEFAULT, advance = false; + break; + + /*case SCE_CAML_KEYWORD: + case SCE_CAML_KEYWORD2: + case SCE_CAML_KEYWORD3: + // [try to] interpret as [additional] keyword char + if (!iscaml(ch)) + state2 = SCE_CAML_DEFAULT, advance = false; + break;*/ + + case SCE_CAML_LINENUM: + // [try to] interpret as [additional] linenum directive char + if (!isdigit(sc.ch)) + state2 = SCE_CAML_DEFAULT, advance = false; + break; + + case SCE_CAML_OPERATOR: { + // [try to] interpret as [additional] operator char + const char* o = 0; + if (iscaml(sc.ch) || isspace(sc.ch) /* ident or whitespace */ + || (o = strchr(")]};,\'\"`#", sc.ch),o)/* "termination" chars */ + || !strchr("!$%&*+-./:<=>?@^|~", sc.ch)/* "operator" chars */) { + // check for INCLUSIVE termination + if (o && strchr(")]};,", sc.ch)) { + if ((sc.Match(')') && sc.chPrev == '(') + || (sc.Match(']') && sc.chPrev == '[')) + // special-case "()" and "[]" tokens as KEYWORDS + sc.ChangeState(SCE_CAML_KEYWORD); + chColor++; + } else + advance = false; + state2 = SCE_CAML_DEFAULT; + } + break; + } + + case SCE_CAML_NUMBER: + // [try to] interpret as [additional] numeric literal char + // N.B. - improperly accepts "extra" digits in base 2 or 8 literals + if (iscamld(sc.ch) || IsADigit(sc.ch, chBase)) + break; + // how about an integer suffix? + if ((sc.Match('l') || sc.Match('L') || sc.Match('n')) + && (iscamld(sc.chPrev) || IsADigit(sc.chPrev, chBase))) + break; + // or a floating-point literal? + if (chBase == 10) { + // with a decimal point? + if (sc.Match('.') && iscamld(sc.chPrev)) + break; + // with an exponent? (I) + if ((sc.Match('e') || sc.Match('E')) + && (iscamld(sc.chPrev) || sc.chPrev == '.')) + break; + // with an exponent? (II) + if ((sc.Match('+') || sc.Match('-')) + && (sc.chPrev == 'e' || sc.chPrev == 'E')) + break; + } + // it looks like we have run out of number + state2 = SCE_CAML_DEFAULT, advance = false; + break; + + case SCE_CAML_CHAR: + // [try to] interpret as [additional] char literal char + if (sc.Match('\\')) { + chLit = 1; // (definitely IS a char literal) + if (sc.chPrev == '\\') + sc.ch = ' '; // (so termination test isn't fooled) + // should we be terminating - one way or another? + } else if ((sc.Match('\'') && sc.chPrev != '\\') || sc.atLineEnd) { + state2 = SCE_CAML_DEFAULT; + if (sc.Match('\'')) + chColor++; + else + sc.ChangeState(SCE_CAML_IDENTIFIER); + // ... maybe a char literal, maybe not + } else if (chLit < 1 && sc.currentPos - chToken >= 2) + sc.ChangeState(SCE_CAML_IDENTIFIER), advance = false; + break; + + case SCE_CAML_STRING: + // [try to] interpret as [additional] string literal char + if (sc.Match('\\') && sc.chPrev == '\\') + sc.ch = ' '; // (so '\\' doesn't cause us trouble) + else if (sc.Match('\"') && sc.chPrev != '\\') + state2 = SCE_CAML_DEFAULT, chColor++; + break; + + case SCE_CAML_COMMENT: + case SCE_CAML_COMMENT1: + case SCE_CAML_COMMENT2: + case SCE_CAML_COMMENT3: + // we're IN a comment - does this start a NESTED comment? + if (sc.Match('(', '*')) + state2 = sc.state + 1, chToken = sc.currentPos, + sc.ch = ' ', // (make SURE "(*)" isn't seen as a closed comment) + sc.Forward(), nesting++; + // [try to] interpret as [additional] comment char + else if (sc.Match(')') && sc.chPrev == '*') { + if (nesting) + state2 = (sc.state & 0x0f) - 1, chToken = 0, nesting--; + else + state2 = SCE_CAML_DEFAULT; + chColor++; + // enable "magic" (read-only) comment AS REQUIRED + } else if (useMagic && sc.currentPos - chToken == 4 + && sc.Match('c') && sc.chPrev == 'r' && sc.GetRelative(-2) == '@') + sc.state |= 0x10; // (switch to read-only comment style) + break; + } + + // handle state change and char coloring as required + if (state2 >= 0) + styler.ColourTo(chColor, sc.state), sc.ChangeState(state2); + // move to next char UNLESS re-scanning current char + if (advance) + sc.Forward(); + } + + // do any required terminal char coloring (JIC) + sc.Complete(); +} + +#ifdef BUILD_AS_EXTERNAL_LEXER +static +#endif /* BUILD_AS_EXTERNAL_LEXER */ +void FoldCamlDoc( + unsigned int startPos, int length, + int initStyle, + WordList *keywordlists[], + Accessor &styler) +{ + // below useless evaluation(s) to supress "not used" warnings + startPos || length || initStyle || keywordlists[0] || styler.Length(); +} + +static const char * const camlWordListDesc[] = { + "Keywords", // primary Objective Caml keywords + "Keywords2", // "optional" keywords (typically from Pervasives) + "Keywords3", // "optional" keywords (typically typenames) + 0 +}; + +#ifndef BUILD_AS_EXTERNAL_LEXER +LexerModule lmCaml(SCLEX_CAML, ColouriseCamlDoc, "caml", FoldCamlDoc, camlWordListDesc); +#endif /* BUILD_AS_EXTERNAL_LEXER */ diff --git a/scintilla/src/LexCmake.cxx b/scintilla/src/LexCmake.cxx new file mode 100644 index 00000000..c29d7390 --- /dev/null +++ b/scintilla/src/LexCmake.cxx @@ -0,0 +1,456 @@ +// Scintilla source code edit control +/** @file LexCmake.cxx + ** Lexer for Cmake + **/ +// Copyright 2007 by Cristian Adam +// based on the NSIS lexer +// The License.txt file describes the conditions under which this software may be distributed. +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static bool isCmakeNumber(char ch) +{ + return(ch >= '0' && ch <= '9'); +} + +static bool isCmakeChar(char ch) +{ + return(ch == '.' ) || (ch == '_' ) || isCmakeNumber(ch) || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); +} + +static bool isCmakeLetter(char ch) +{ + return(ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'); +} + +static bool CmakeNextLineHasElse(unsigned int start, unsigned int end, Accessor &styler) +{ + int nNextLine = -1; + for ( unsigned int i = start; i < end; i++ ) { + char cNext = styler.SafeGetCharAt( i ); + if ( cNext == '\n' ) { + nNextLine = i+1; + break; + } + } + + if ( nNextLine == -1 ) // We never foudn the next line... + return false; + + for ( unsigned int firstChar = nNextLine; firstChar < end; firstChar++ ) { + char cNext = styler.SafeGetCharAt( firstChar ); + if ( cNext == ' ' ) + continue; + if ( cNext == '\t' ) + continue; + if ( styler.Match(firstChar, "ELSE") || styler.Match(firstChar, "else")) + return true; + break; + } + + return false; +} + +static int calculateFoldCmake(unsigned int start, unsigned int end, int foldlevel, Accessor &styler, bool bElse) +{ + // If the word is too long, it is not what we are looking for + if ( end - start > 20 ) + return foldlevel; + + int newFoldlevel = foldlevel; + + char s[20]; // The key word we are looking for has atmost 13 characters + for (unsigned int i = 0; i < end - start + 1 && i < 19; i++) { + s[i] = static_cast( styler[ start + i ] ); + s[i + 1] = '\0'; + } + + if ( CompareCaseInsensitive(s, "IF") == 0 || CompareCaseInsensitive(s, "WHILE") == 0 + || CompareCaseInsensitive(s, "MACRO") == 0 || CompareCaseInsensitive(s, "FOREACH") == 0 + || CompareCaseInsensitive(s, "ELSEIF") == 0 ) + newFoldlevel++; + else if ( CompareCaseInsensitive(s, "ENDIF") == 0 || CompareCaseInsensitive(s, "ENDWHILE") == 0 + || CompareCaseInsensitive(s, "ENDMACRO") == 0 || CompareCaseInsensitive(s, "ENDFOREACH") == 0) + newFoldlevel--; + else if ( bElse && CompareCaseInsensitive(s, "ELSEIF") == 0 ) + newFoldlevel++; + else if ( bElse && CompareCaseInsensitive(s, "ELSE") == 0 ) + newFoldlevel++; + + return newFoldlevel; +} + +static int classifyWordCmake(unsigned int start, unsigned int end, WordList *keywordLists[], Accessor &styler ) +{ + char word[100] = {0}; + char lowercaseWord[100] = {0}; + + WordList &Commands = *keywordLists[0]; + WordList &Parameters = *keywordLists[1]; + WordList &UserDefined = *keywordLists[2]; + + for (unsigned int i = 0; i < end - start + 1 && i < 99; i++) { + word[i] = static_cast( styler[ start + i ] ); + lowercaseWord[i] = static_cast(tolower(word[i])); + } + + // Check for special words... + if ( CompareCaseInsensitive(word, "MACRO") == 0 || CompareCaseInsensitive(word, "ENDMACRO") == 0 ) + return SCE_CMAKE_MACRODEF; + + if ( CompareCaseInsensitive(word, "IF") == 0 || CompareCaseInsensitive(word, "ENDIF") == 0 ) + return SCE_CMAKE_IFDEFINEDEF; + + if ( CompareCaseInsensitive(word, "ELSEIF") == 0 || CompareCaseInsensitive(word, "ELSE") == 0 ) + return SCE_CMAKE_IFDEFINEDEF; + + if ( CompareCaseInsensitive(word, "WHILE") == 0 || CompareCaseInsensitive(word, "ENDWHILE") == 0) + return SCE_CMAKE_WHILEDEF; + + if ( CompareCaseInsensitive(word, "FOREACH") == 0 || CompareCaseInsensitive(word, "ENDFOREACH") == 0) + return SCE_CMAKE_FOREACHDEF; + + if ( Commands.InList(lowercaseWord) ) + return SCE_CMAKE_COMMANDS; + + if ( Parameters.InList(word) ) + return SCE_CMAKE_PARAMETERS; + + + if ( UserDefined.InList(word) ) + return SCE_CMAKE_USERDEFINED; + + if ( strlen(word) > 3 ) { + if ( word[1] == '{' && word[strlen(word)-1] == '}' ) + return SCE_CMAKE_VARIABLE; + } + + // To check for numbers + if ( isCmakeNumber( word[0] ) ) { + bool bHasSimpleCmakeNumber = true; + for (unsigned int j = 1; j < end - start + 1 && j < 99; j++) { + if ( !isCmakeNumber( word[j] ) ) { + bHasSimpleCmakeNumber = false; + break; + } + } + + if ( bHasSimpleCmakeNumber ) + return SCE_CMAKE_NUMBER; + } + + return SCE_CMAKE_DEFAULT; +} + +static void ColouriseCmakeDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) +{ + int state = SCE_CMAKE_DEFAULT; + if ( startPos > 0 ) + state = styler.StyleAt(startPos-1); // Use the style from the previous line, usually default, but could be commentbox + + styler.StartAt( startPos ); + styler.GetLine( startPos ); + + unsigned int nLengthDoc = startPos + length; + styler.StartSegment( startPos ); + + char cCurrChar; + bool bVarInString = false; + bool bClassicVarInString = false; + + unsigned int i; + for ( i = startPos; i < nLengthDoc; i++ ) { + cCurrChar = styler.SafeGetCharAt( i ); + char cNextChar = styler.SafeGetCharAt(i+1); + + switch (state) { + case SCE_CMAKE_DEFAULT: + if ( cCurrChar == '#' ) { // we have a comment line + styler.ColourTo(i-1, state ); + state = SCE_CMAKE_COMMENT; + break; + } + if ( cCurrChar == '"' ) { + styler.ColourTo(i-1, state ); + state = SCE_CMAKE_STRINGDQ; + bVarInString = false; + bClassicVarInString = false; + break; + } + if ( cCurrChar == '\'' ) { + styler.ColourTo(i-1, state ); + state = SCE_CMAKE_STRINGRQ; + bVarInString = false; + bClassicVarInString = false; + break; + } + if ( cCurrChar == '`' ) { + styler.ColourTo(i-1, state ); + state = SCE_CMAKE_STRINGLQ; + bVarInString = false; + bClassicVarInString = false; + break; + } + + // CMake Variable + if ( cCurrChar == '$' || isCmakeChar(cCurrChar)) { + styler.ColourTo(i-1,state); + state = SCE_CMAKE_VARIABLE; + + // If it is a number, we must check and set style here first... + if ( isCmakeNumber(cCurrChar) && (cNextChar == '\t' || cNextChar == ' ' || cNextChar == '\r' || cNextChar == '\n' ) ) + styler.ColourTo( i, SCE_CMAKE_NUMBER); + + break; + } + + break; + case SCE_CMAKE_COMMENT: + if ( cNextChar == '\n' || cNextChar == '\r' ) { + // Special case: + if ( cCurrChar == '\\' ) { + styler.ColourTo(i-2,state); + styler.ColourTo(i,SCE_CMAKE_DEFAULT); + } + else { + styler.ColourTo(i,state); + state = SCE_CMAKE_DEFAULT; + } + } + break; + case SCE_CMAKE_STRINGDQ: + case SCE_CMAKE_STRINGLQ: + case SCE_CMAKE_STRINGRQ: + + if ( styler.SafeGetCharAt(i-1) == '\\' && styler.SafeGetCharAt(i-2) == '$' ) + break; // Ignore the next character, even if it is a quote of some sort + + if ( cCurrChar == '"' && state == SCE_CMAKE_STRINGDQ ) { + styler.ColourTo(i,state); + state = SCE_CMAKE_DEFAULT; + break; + } + + if ( cCurrChar == '`' && state == SCE_CMAKE_STRINGLQ ) { + styler.ColourTo(i,state); + state = SCE_CMAKE_DEFAULT; + break; + } + + if ( cCurrChar == '\'' && state == SCE_CMAKE_STRINGRQ ) { + styler.ColourTo(i,state); + state = SCE_CMAKE_DEFAULT; + break; + } + + if ( cNextChar == '\r' || cNextChar == '\n' ) { + int nCurLine = styler.GetLine(i+1); + int nBack = i; + // We need to check if the previous line has a \ in it... + bool bNextLine = false; + + while ( nBack > 0 ) { + if ( styler.GetLine(nBack) != nCurLine ) + break; + + char cTemp = styler.SafeGetCharAt(nBack, 'a'); // Letter 'a' is safe here + + if ( cTemp == '\\' ) { + bNextLine = true; + break; + } + if ( cTemp != '\r' && cTemp != '\n' && cTemp != '\t' && cTemp != ' ' ) + break; + + nBack--; + } + + if ( bNextLine ) { + styler.ColourTo(i+1,state); + } + if ( bNextLine == false ) { + styler.ColourTo(i,state); + state = SCE_CMAKE_DEFAULT; + } + } + break; + + case SCE_CMAKE_VARIABLE: + + // CMake Variable: + if ( cCurrChar == '$' ) + state = SCE_CMAKE_DEFAULT; + else if ( cCurrChar == '\\' && (cNextChar == 'n' || cNextChar == 'r' || cNextChar == 't' ) ) + state = SCE_CMAKE_DEFAULT; + else if ( (isCmakeChar(cCurrChar) && !isCmakeChar( cNextChar) && cNextChar != '}') || cCurrChar == '}' ) { + state = classifyWordCmake( styler.GetStartSegment(), i, keywordLists, styler ); + styler.ColourTo( i, state); + state = SCE_CMAKE_DEFAULT; + } + else if ( !isCmakeChar( cCurrChar ) && cCurrChar != '{' && cCurrChar != '}' ) { + if ( classifyWordCmake( styler.GetStartSegment(), i-1, keywordLists, styler) == SCE_CMAKE_NUMBER ) + styler.ColourTo( i-1, SCE_CMAKE_NUMBER ); + + state = SCE_CMAKE_DEFAULT; + + if ( cCurrChar == '"' ) { + state = SCE_CMAKE_STRINGDQ; + bVarInString = false; + bClassicVarInString = false; + } + else if ( cCurrChar == '`' ) { + state = SCE_CMAKE_STRINGLQ; + bVarInString = false; + bClassicVarInString = false; + } + else if ( cCurrChar == '\'' ) { + state = SCE_CMAKE_STRINGRQ; + bVarInString = false; + bClassicVarInString = false; + } + else if ( cCurrChar == '#' ) { + state = SCE_CMAKE_COMMENT; + } + } + break; + } + + if ( state == SCE_CMAKE_COMMENT) { + styler.ColourTo(i,state); + } + else if ( state == SCE_CMAKE_STRINGDQ || state == SCE_CMAKE_STRINGLQ || state == SCE_CMAKE_STRINGRQ ) { + bool bIngoreNextDollarSign = false; + + if ( bVarInString && cCurrChar == '$' ) { + bVarInString = false; + bIngoreNextDollarSign = true; + } + else if ( bVarInString && cCurrChar == '\\' && (cNextChar == 'n' || cNextChar == 'r' || cNextChar == 't' || cNextChar == '"' || cNextChar == '`' || cNextChar == '\'' ) ) { + styler.ColourTo( i+1, SCE_CMAKE_STRINGVAR); + bVarInString = false; + bIngoreNextDollarSign = false; + } + + else if ( bVarInString && !isCmakeChar(cNextChar) ) { + int nWordState = classifyWordCmake( styler.GetStartSegment(), i, keywordLists, styler); + if ( nWordState == SCE_CMAKE_VARIABLE ) + styler.ColourTo( i, SCE_CMAKE_STRINGVAR); + bVarInString = false; + } + // Covers "${TEST}..." + else if ( bClassicVarInString && cNextChar == '}' ) { + styler.ColourTo( i+1, SCE_CMAKE_STRINGVAR); + bClassicVarInString = false; + } + + // Start of var in string + if ( !bIngoreNextDollarSign && cCurrChar == '$' && cNextChar == '{' ) { + styler.ColourTo( i-1, state); + bClassicVarInString = true; + bVarInString = false; + } + else if ( !bIngoreNextDollarSign && cCurrChar == '$' ) { + styler.ColourTo( i-1, state); + bVarInString = true; + bClassicVarInString = false; + } + } + } + + // Colourise remaining document + styler.ColourTo(nLengthDoc-1,state); +} + +static void FoldCmakeDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) +{ + // No folding enabled, no reason to continue... + if ( styler.GetPropertyInt("fold") == 0 ) + return; + + bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) == 1; + + int lineCurrent = styler.GetLine(startPos); + unsigned int safeStartPos = styler.LineStart( lineCurrent ); + + bool bArg1 = true; + int nWordStart = -1; + + int levelCurrent = SC_FOLDLEVELBASE; + if (lineCurrent > 0) + levelCurrent = styler.LevelAt(lineCurrent-1) >> 16; + int levelNext = levelCurrent; + + for (unsigned int i = safeStartPos; i < startPos + length; i++) { + char chCurr = styler.SafeGetCharAt(i); + + if ( bArg1 ) { + if ( nWordStart == -1 && (isCmakeLetter(chCurr)) ) { + nWordStart = i; + } + else if ( isCmakeLetter(chCurr) == false && nWordStart > -1 ) { + int newLevel = calculateFoldCmake( nWordStart, i-1, levelNext, styler, foldAtElse); + + if ( newLevel == levelNext ) { + if ( foldAtElse ) { + if ( CmakeNextLineHasElse(i, startPos + length, styler) ) + levelNext--; + } + } + else + levelNext = newLevel; + bArg1 = false; + } + } + + if ( chCurr == '\n' ) { + if ( bArg1 && foldAtElse) { + if ( CmakeNextLineHasElse(i, startPos + length, styler) ) + levelNext--; + } + + // If we are on a new line... + int levelUse = levelCurrent; + int lev = levelUse | levelNext << 16; + if (levelUse < levelNext ) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) + styler.SetLevel(lineCurrent, lev); + + lineCurrent++; + levelCurrent = levelNext; + bArg1 = true; // New line, lets look at first argument again + nWordStart = -1; + } + } + + int levelUse = levelCurrent; + int lev = levelUse | levelNext << 16; + if (levelUse < levelNext) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) + styler.SetLevel(lineCurrent, lev); +} + +static const char * const cmakeWordLists[] = { + "Commands", + "Parameters", + "UserDefined", + 0, + 0,}; + +LexerModule lmCmake(SCLEX_CMAKE, ColouriseCmakeDoc, "cmake", FoldCmakeDoc, cmakeWordLists); diff --git a/scintilla/src/LexConf.cxx b/scintilla/src/LexConf.cxx new file mode 100644 index 00000000..d3931740 --- /dev/null +++ b/scintilla/src/LexConf.cxx @@ -0,0 +1,188 @@ +// Scintilla source code edit control +/** @file LexConf.cxx + ** Lexer for Apache Configuration Files. + ** + ** First working version contributed by Ahmad Zawawi on October 28, 2000. + ** i created this lexer because i needed something pretty when dealing + ** when Apache Configuration files... + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static void ColouriseConfDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) +{ + int state = SCE_CONF_DEFAULT; + char chNext = styler[startPos]; + int lengthDoc = startPos + length; + // create a buffer large enough to take the largest chunk... + char *buffer = new char[length]; + int bufferCount = 0; + + // this assumes that we have 2 keyword list in conf.properties + WordList &directives = *keywordLists[0]; + WordList ¶ms = *keywordLists[1]; + + // go through all provided text segment + // using the hand-written state machine shown below + styler.StartAt(startPos); + styler.StartSegment(startPos); + for (int i = startPos; i < lengthDoc; i++) { + char ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + + if (styler.IsLeadByte(ch)) { + chNext = styler.SafeGetCharAt(i + 2); + i++; + continue; + } + switch(state) { + case SCE_CONF_DEFAULT: + if( ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ') { + // whitespace is simply ignored here... + styler.ColourTo(i,SCE_CONF_DEFAULT); + break; + } else if( ch == '#' ) { + // signals the start of a comment... + state = SCE_CONF_COMMENT; + styler.ColourTo(i,SCE_CONF_COMMENT); + } else if( ch == '.' /*|| ch == '/'*/) { + // signals the start of a file... + state = SCE_CONF_EXTENSION; + styler.ColourTo(i,SCE_CONF_EXTENSION); + } else if( ch == '"') { + state = SCE_CONF_STRING; + styler.ColourTo(i,SCE_CONF_STRING); + } else if( ispunct(ch) ) { + // signals an operator... + // no state jump necessary for this + // simple case... + styler.ColourTo(i,SCE_CONF_OPERATOR); + } else if( isalpha(ch) ) { + // signals the start of an identifier + bufferCount = 0; + buffer[bufferCount++] = static_cast(tolower(ch)); + state = SCE_CONF_IDENTIFIER; + } else if( isdigit(ch) ) { + // signals the start of a number + bufferCount = 0; + buffer[bufferCount++] = ch; + //styler.ColourTo(i,SCE_CONF_NUMBER); + state = SCE_CONF_NUMBER; + } else { + // style it the default style.. + styler.ColourTo(i,SCE_CONF_DEFAULT); + } + break; + + case SCE_CONF_COMMENT: + // if we find a newline here, + // we simply go to default state + // else continue to work on it... + if( ch == '\n' || ch == '\r' ) { + state = SCE_CONF_DEFAULT; + } else { + styler.ColourTo(i,SCE_CONF_COMMENT); + } + break; + + case SCE_CONF_EXTENSION: + // if we find a non-alphanumeric char, + // we simply go to default state + // else we're still dealing with an extension... + if( isalnum(ch) || (ch == '_') || + (ch == '-') || (ch == '$') || + (ch == '/') || (ch == '.') || (ch == '*') ) + { + styler.ColourTo(i,SCE_CONF_EXTENSION); + } else { + state = SCE_CONF_DEFAULT; + chNext = styler[i--]; + } + break; + + case SCE_CONF_STRING: + // if we find the end of a string char, we simply go to default state + // else we're still dealing with an string... + if( (ch == '"' && styler.SafeGetCharAt(i-1)!='\\') || (ch == '\n') || (ch == '\r') ) { + state = SCE_CONF_DEFAULT; + } + styler.ColourTo(i,SCE_CONF_STRING); + break; + + case SCE_CONF_IDENTIFIER: + // stay in CONF_IDENTIFIER state until we find a non-alphanumeric + if( isalnum(ch) || (ch == '_') || (ch == '-') || (ch == '/') || (ch == '$') || (ch == '.') || (ch == '*')) { + buffer[bufferCount++] = static_cast(tolower(ch)); + } else { + state = SCE_CONF_DEFAULT; + buffer[bufferCount] = '\0'; + + // check if the buffer contains a keyword, and highlight it if it is a keyword... + if(directives.InList(buffer)) { + styler.ColourTo(i-1,SCE_CONF_DIRECTIVE ); + } else if(params.InList(buffer)) { + styler.ColourTo(i-1,SCE_CONF_PARAMETER ); + } else if(strchr(buffer,'/') || strchr(buffer,'.')) { + styler.ColourTo(i-1,SCE_CONF_EXTENSION); + } else { + styler.ColourTo(i-1,SCE_CONF_DEFAULT); + } + + // push back the faulty character + chNext = styler[i--]; + + } + break; + + case SCE_CONF_NUMBER: + // stay in CONF_NUMBER state until we find a non-numeric + if( isdigit(ch) || ch == '.') { + buffer[bufferCount++] = ch; + } else { + state = SCE_CONF_DEFAULT; + buffer[bufferCount] = '\0'; + + // Colourize here... + if( strchr(buffer,'.') ) { + // it is an IP address... + styler.ColourTo(i-1,SCE_CONF_IP); + } else { + // normal number + styler.ColourTo(i-1,SCE_CONF_NUMBER); + } + + // push back a character + chNext = styler[i--]; + } + break; + + } + } + delete []buffer; +} + +static const char * const confWordListDesc[] = { + "Directives", + "Parameters", + 0 +}; + +LexerModule lmConf(SCLEX_CONF, ColouriseConfDoc, "conf", 0, confWordListDesc); diff --git a/scintilla/src/LexCrontab.cxx b/scintilla/src/LexCrontab.cxx new file mode 100644 index 00000000..6f9ba149 --- /dev/null +++ b/scintilla/src/LexCrontab.cxx @@ -0,0 +1,222 @@ +// Scintilla source code edit control +/** @file LexCrontab.cxx + ** Lexer to use with extended crontab files used by a powerful + ** Windows scheduler/event monitor/automation manager nnCron. + ** (http://nemtsev.eserv.ru/) + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static void ColouriseNncrontabDoc(unsigned int startPos, int length, int, WordList +*keywordLists[], Accessor &styler) +{ + int state = SCE_NNCRONTAB_DEFAULT; + char chNext = styler[startPos]; + int lengthDoc = startPos + length; + // create a buffer large enough to take the largest chunk... + char *buffer = new char[length]; + int bufferCount = 0; + // used when highliting environment variables inside quoted string: + bool insideString = false; + + // this assumes that we have 3 keyword list in conf.properties + WordList §ion = *keywordLists[0]; + WordList &keyword = *keywordLists[1]; + WordList &modifier = *keywordLists[2]; + + // go through all provided text segment + // using the hand-written state machine shown below + styler.StartAt(startPos); + styler.StartSegment(startPos); + for (int i = startPos; i < lengthDoc; i++) { + char ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + + if (styler.IsLeadByte(ch)) { + chNext = styler.SafeGetCharAt(i + 2); + i++; + continue; + } + switch(state) { + case SCE_NNCRONTAB_DEFAULT: + if( ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ') { + // whitespace is simply ignored here... + styler.ColourTo(i,SCE_NNCRONTAB_DEFAULT); + break; + } else if( ch == '#' && styler.SafeGetCharAt(i+1) == '(') { + // signals the start of a task... + state = SCE_NNCRONTAB_TASK; + styler.ColourTo(i,SCE_NNCRONTAB_TASK); + } + else if( ch == '\\' && (styler.SafeGetCharAt(i+1) == ' ' || + styler.SafeGetCharAt(i+1) == '\t')) { + // signals the start of an extended comment... + state = SCE_NNCRONTAB_COMMENT; + styler.ColourTo(i,SCE_NNCRONTAB_COMMENT); + } else if( ch == '#' ) { + // signals the start of a plain comment... + state = SCE_NNCRONTAB_COMMENT; + styler.ColourTo(i,SCE_NNCRONTAB_COMMENT); + } else if( ch == ')' && styler.SafeGetCharAt(i+1) == '#') { + // signals the end of a task... + state = SCE_NNCRONTAB_TASK; + styler.ColourTo(i,SCE_NNCRONTAB_TASK); + } else if( ch == '"') { + state = SCE_NNCRONTAB_STRING; + styler.ColourTo(i,SCE_NNCRONTAB_STRING); + } else if( ch == '%') { + // signals environment variables + state = SCE_NNCRONTAB_ENVIRONMENT; + styler.ColourTo(i,SCE_NNCRONTAB_ENVIRONMENT); + } else if( ch == '<' && styler.SafeGetCharAt(i+1) == '%') { + // signals environment variables + state = SCE_NNCRONTAB_ENVIRONMENT; + styler.ColourTo(i,SCE_NNCRONTAB_ENVIRONMENT); + } else if( ch == '*' ) { + // signals an asterisk + // no state jump necessary for this simple case... + styler.ColourTo(i,SCE_NNCRONTAB_ASTERISK); + } else if( isalpha(ch) || ch == '<' ) { + // signals the start of an identifier + bufferCount = 0; + buffer[bufferCount++] = ch; + state = SCE_NNCRONTAB_IDENTIFIER; + } else if( isdigit(ch) ) { + // signals the start of a number + bufferCount = 0; + buffer[bufferCount++] = ch; + state = SCE_NNCRONTAB_NUMBER; + } else { + // style it the default style.. + styler.ColourTo(i,SCE_NNCRONTAB_DEFAULT); + } + break; + + case SCE_NNCRONTAB_COMMENT: + // if we find a newline here, + // we simply go to default state + // else continue to work on it... + if( ch == '\n' || ch == '\r' ) { + state = SCE_NNCRONTAB_DEFAULT; + } else { + styler.ColourTo(i,SCE_NNCRONTAB_COMMENT); + } + break; + + case SCE_NNCRONTAB_TASK: + // if we find a newline here, + // we simply go to default state + // else continue to work on it... + if( ch == '\n' || ch == '\r' ) { + state = SCE_NNCRONTAB_DEFAULT; + } else { + styler.ColourTo(i,SCE_NNCRONTAB_TASK); + } + break; + + case SCE_NNCRONTAB_STRING: + if( ch == '%' ) { + state = SCE_NNCRONTAB_ENVIRONMENT; + insideString = true; + styler.ColourTo(i-1,SCE_NNCRONTAB_STRING); + break; + } + // if we find the end of a string char, we simply go to default state + // else we're still dealing with an string... + if( (ch == '"' && styler.SafeGetCharAt(i-1)!='\\') || + (ch == '\n') || (ch == '\r') ) { + state = SCE_NNCRONTAB_DEFAULT; + } + styler.ColourTo(i,SCE_NNCRONTAB_STRING); + break; + + case SCE_NNCRONTAB_ENVIRONMENT: + // if we find the end of a string char, we simply go to default state + // else we're still dealing with an string... + if( ch == '%' && insideString ) { + state = SCE_NNCRONTAB_STRING; + insideString = false; + break; + } + if( (ch == '%' && styler.SafeGetCharAt(i-1)!='\\') + || (ch == '\n') || (ch == '\r') || (ch == '>') ) { + state = SCE_NNCRONTAB_DEFAULT; + styler.ColourTo(i,SCE_NNCRONTAB_ENVIRONMENT); + break; + } + styler.ColourTo(i+1,SCE_NNCRONTAB_ENVIRONMENT); + break; + + case SCE_NNCRONTAB_IDENTIFIER: + // stay in CONF_IDENTIFIER state until we find a non-alphanumeric + if( isalnum(ch) || (ch == '_') || (ch == '-') || (ch == '/') || + (ch == '$') || (ch == '.') || (ch == '<') || (ch == '>') || + (ch == '@') ) { + buffer[bufferCount++] = ch; + } else { + state = SCE_NNCRONTAB_DEFAULT; + buffer[bufferCount] = '\0'; + + // check if the buffer contains a keyword, + // and highlight it if it is a keyword... + if(section.InList(buffer)) { + styler.ColourTo(i,SCE_NNCRONTAB_SECTION ); + } else if(keyword.InList(buffer)) { + styler.ColourTo(i-1,SCE_NNCRONTAB_KEYWORD ); + } // else if(strchr(buffer,'/') || strchr(buffer,'.')) { + // styler.ColourTo(i-1,SCE_NNCRONTAB_EXTENSION); + // } + else if(modifier.InList(buffer)) { + styler.ColourTo(i-1,SCE_NNCRONTAB_MODIFIER ); + } else { + styler.ColourTo(i-1,SCE_NNCRONTAB_DEFAULT); + } + // push back the faulty character + chNext = styler[i--]; + } + break; + + case SCE_NNCRONTAB_NUMBER: + // stay in CONF_NUMBER state until we find a non-numeric + if( isdigit(ch) /* || ch == '.' */ ) { + buffer[bufferCount++] = ch; + } else { + state = SCE_NNCRONTAB_DEFAULT; + buffer[bufferCount] = '\0'; + // Colourize here... (normal number) + styler.ColourTo(i-1,SCE_NNCRONTAB_NUMBER); + // push back a character + chNext = styler[i--]; + } + break; + } + } + delete []buffer; +} + +static const char * const cronWordListDesc[] = { + "Section keywords and Forth words", + "nnCrontab keywords", + "Modifiers", + 0 +}; + +LexerModule lmNncrontab(SCLEX_NNCRONTAB, ColouriseNncrontabDoc, "nncrontab", 0, cronWordListDesc); diff --git a/scintilla/src/LexCsound.cxx b/scintilla/src/LexCsound.cxx new file mode 100644 index 00000000..fd9d2b40 --- /dev/null +++ b/scintilla/src/LexCsound.cxx @@ -0,0 +1,210 @@ +// Scintilla source code edit control +/** @file LexCsound.cxx + ** Lexer for Csound (Orchestra & Score) + ** Written by Georg Ritter - + **/ +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static inline bool IsAWordChar(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '.' || + ch == '_' || ch == '?'); +} + +static inline bool IsAWordStart(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.' || + ch == '%' || ch == '@' || ch == '$' || ch == '?'); +} + +static inline bool IsCsoundOperator(char ch) { + if (isalnum(ch)) + return false; + // '.' left out as it is used to make up numbers + if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || + ch == '(' || ch == ')' || ch == '=' || ch == '^' || + ch == '[' || ch == ']' || ch == '<' || ch == '&' || + ch == '>' || ch == ',' || ch == '|' || ch == '~' || + ch == '%' || ch == ':') + return true; + return false; +} + +static void ColouriseCsoundDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler) { + + WordList &opcode = *keywordlists[0]; + WordList &headerStmt = *keywordlists[1]; + WordList &otherKeyword = *keywordlists[2]; + + // Do not leak onto next line + if (initStyle == SCE_CSOUND_STRINGEOL) + initStyle = SCE_CSOUND_DEFAULT; + + StyleContext sc(startPos, length, initStyle, styler); + + for (; sc.More(); sc.Forward()) + { + // 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(); + } + continue; + } + } + + // Determine if the current state should terminate. + if (sc.state == SCE_CSOUND_OPERATOR) { + if (!IsCsoundOperator(static_cast(sc.ch))) { + sc.SetState(SCE_CSOUND_DEFAULT); + } + }else if (sc.state == SCE_CSOUND_NUMBER) { + if (!IsAWordChar(sc.ch)) { + sc.SetState(SCE_CSOUND_DEFAULT); + } + } else if (sc.state == SCE_CSOUND_IDENTIFIER) { + if (!IsAWordChar(sc.ch) ) { + char s[100]; + sc.GetCurrent(s, sizeof(s)); + + if (opcode.InList(s)) { + sc.ChangeState(SCE_CSOUND_OPCODE); + } else if (headerStmt.InList(s)) { + sc.ChangeState(SCE_CSOUND_HEADERSTMT); + } else if (otherKeyword.InList(s)) { + sc.ChangeState(SCE_CSOUND_USERKEYWORD); + } else if (s[0] == 'p') { + sc.ChangeState(SCE_CSOUND_PARAM); + } else if (s[0] == 'a') { + sc.ChangeState(SCE_CSOUND_ARATE_VAR); + } else if (s[0] == 'k') { + sc.ChangeState(SCE_CSOUND_KRATE_VAR); + } else if (s[0] == 'i') { // covers both i-rate variables and i-statements + sc.ChangeState(SCE_CSOUND_IRATE_VAR); + } else if (s[0] == 'g') { + sc.ChangeState(SCE_CSOUND_GLOBAL_VAR); + } + sc.SetState(SCE_CSOUND_DEFAULT); + } + } + else if (sc.state == SCE_CSOUND_COMMENT ) { + if (sc.atLineEnd) { + sc.SetState(SCE_CSOUND_DEFAULT); + } + } + else if ((sc.state == SCE_CSOUND_ARATE_VAR) || + (sc.state == SCE_CSOUND_KRATE_VAR) || + (sc.state == SCE_CSOUND_IRATE_VAR)) { + if (!IsAWordChar(sc.ch)) { + sc.SetState(SCE_CSOUND_DEFAULT); + } + } + + // Determine if a new state should be entered. + if (sc.state == SCE_CSOUND_DEFAULT) { + if (sc.ch == ';'){ + sc.SetState(SCE_CSOUND_COMMENT); + } else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) { + sc.SetState(SCE_CSOUND_NUMBER); + } else if (IsAWordStart(sc.ch)) { + sc.SetState(SCE_CSOUND_IDENTIFIER); + } else if (IsCsoundOperator(static_cast(sc.ch))) { + sc.SetState(SCE_CSOUND_OPERATOR); + } else if (sc.ch == 'p') { + sc.SetState(SCE_CSOUND_PARAM); + } else if (sc.ch == 'a') { + sc.SetState(SCE_CSOUND_ARATE_VAR); + } else if (sc.ch == 'k') { + sc.SetState(SCE_CSOUND_KRATE_VAR); + } else if (sc.ch == 'i') { // covers both i-rate variables and i-statements + sc.SetState(SCE_CSOUND_IRATE_VAR); + } else if (sc.ch == 'g') { + sc.SetState(SCE_CSOUND_GLOBAL_VAR); + } + } + } + sc.Complete(); +} + +static void FoldCsoundInstruments(unsigned int startPos, int length, int /* initStyle */, WordList *[], + Accessor &styler) { + unsigned int lengthDoc = 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 stylePrev = 0; + int styleNext = styler.StyleAt(startPos); + for (unsigned int i = startPos; i < lengthDoc; i++) { + char ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + int style = styleNext; + styleNext = styler.StyleAt(i + 1); + bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); + if ((stylePrev != SCE_CSOUND_OPCODE) && (style == SCE_CSOUND_OPCODE)) { + char s[20]; + unsigned int j = 0; + while ((j < (sizeof(s) - 1)) && (iswordchar(styler[i + j]))) { + s[j] = styler[i + j]; + j++; + } + s[j] = '\0'; + + if (strcmp(s, "instr") == 0) + levelCurrent++; + if (strcmp(s, "endin") == 0) + levelCurrent--; + } + + if (atEOL) { + int lev = levelPrev; + if (visibleChars == 0) + lev |= SC_FOLDLEVELWHITEFLAG; + if ((levelCurrent > levelPrev) && (visibleChars > 0)) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelPrev = levelCurrent; + visibleChars = 0; + } + if (!isspacechar(ch)) + visibleChars++; + stylePrev = style; + } + // Fill in the real level of the next line, keeping the current flags as they will be filled in later + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, levelPrev | flagsNext); +} + + +static const char * const csoundWordListDesc[] = { + "Opcodes", + "Header Statements", + "User keywords", + 0 +}; + +LexerModule lmCsound(SCLEX_CSOUND, ColouriseCsoundDoc, "csound", FoldCsoundInstruments, csoundWordListDesc); diff --git a/scintilla/src/LexD.cxx b/scintilla/src/LexD.cxx new file mode 100644 index 00000000..0d6db93c --- /dev/null +++ b/scintilla/src/LexD.cxx @@ -0,0 +1,358 @@ +/** @file LexD.cxx + ** Lexer for D. + ** + ** Copyright (c) 2006 by Waldemar Augustyn + **/ +// Copyright 1998-2005 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +/*/ Nested comments require keeping the value of the nesting level for every + position in the document. But since scintilla always styles line by line, + we only need to store one value per line. The non-negative number indicates + nesting level at the end of the line. +/*/ + +// We use custom qualifiers since it is not clear what D allows. + +static bool IsWordStart(int ch) { + return isascii(ch) && (isalpha(ch) || ch == '_'); +} + +static bool IsWord(int ch) { + return isascii(ch) && (isalnum(ch) || ch == '_'); +} + +static bool IsDoxygen(int ch) { + if (isascii(ch) && islower(ch)) + return true; + if (ch == '$' || ch == '@' || ch == '\\' || + ch == '&' || ch == '#' || ch == '<' || ch == '>' || + ch == '{' || ch == '}' || ch == '[' || ch == ']') + return true; + return false; +} + + +static void ColouriseDoc(unsigned int startPos, int length, int initStyle, + WordList *keywordlists[], Accessor &styler, bool caseSensitive) { + + WordList &keywords = *keywordlists[0]; + WordList &keywords2 = *keywordlists[1]; + WordList &keywords3 = *keywordlists[2]; + WordList &keywords4 = *keywordlists[3]; + + int styleBeforeDCKeyword = SCE_D_DEFAULT; + + StyleContext sc(startPos, length, initStyle, styler); + + int curLine = styler.GetLine(startPos); + int curNcLevel = curLine > 0? styler.GetLineState(curLine-1): 0; + + for (; sc.More(); sc.Forward()) { + + if (sc.atLineStart) { + if (sc.state == SCE_D_STRING) { + // Prevent SCE_D_STRINGEOL from leaking back to previous line which + // ends with a line continuation by locking in the state upto this position. + sc.SetState(SCE_D_STRING); + } + curLine = styler.GetLine(sc.currentPos); + styler.SetLineState(curLine, curNcLevel); + } + + // 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(); + } + continue; + } + } + + // Determine if the current state should terminate. + switch (sc.state) { + case SCE_D_OPERATOR: + sc.SetState(SCE_D_DEFAULT); + break; + case SCE_D_NUMBER: + // We accept almost anything because of hex. and number suffixes + if (!IsWord(sc.ch) && sc.ch != '.') { + sc.SetState(SCE_D_DEFAULT); + } + break; + case SCE_D_IDENTIFIER: + if (!IsWord(sc.ch)) { + char s[1000]; + if (caseSensitive) { + sc.GetCurrent(s, sizeof(s)); + } else { + sc.GetCurrentLowered(s, sizeof(s)); + } + if (keywords.InList(s)) { + sc.ChangeState(SCE_D_WORD); + } else if (keywords2.InList(s)) { + sc.ChangeState(SCE_D_WORD2); + } else if (keywords4.InList(s)) { + sc.ChangeState(SCE_D_TYPEDEF); + } + sc.SetState(SCE_D_DEFAULT); + } + break; + case SCE_D_COMMENT: + if (sc.Match('*', '/')) { + sc.Forward(); + sc.ForwardSetState(SCE_D_DEFAULT); + } + break; + case SCE_D_COMMENTDOC: + if (sc.Match('*', '/')) { + sc.Forward(); + sc.ForwardSetState(SCE_D_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_D_COMMENTDOC; + sc.SetState(SCE_D_COMMENTDOCKEYWORD); + } + } + break; + case SCE_D_COMMENTLINE: + if (sc.atLineStart) { + sc.SetState(SCE_D_DEFAULT); + } + break; + case SCE_D_COMMENTLINEDOC: + if (sc.atLineStart) { + sc.SetState(SCE_D_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_D_COMMENTLINEDOC; + sc.SetState(SCE_D_COMMENTDOCKEYWORD); + } + } + break; + case SCE_D_COMMENTDOCKEYWORD: + if ((styleBeforeDCKeyword == SCE_D_COMMENTDOC) && sc.Match('*', '/')) { + sc.ChangeState(SCE_D_COMMENTDOCKEYWORDERROR); + sc.Forward(); + sc.ForwardSetState(SCE_D_DEFAULT); + } else if (!IsDoxygen(sc.ch)) { + char s[100]; + if (caseSensitive) { + sc.GetCurrent(s, sizeof(s)); + } else { + sc.GetCurrentLowered(s, sizeof(s)); + } + if (!IsASpace(sc.ch) || !keywords3.InList(s + 1)) { + sc.ChangeState(SCE_D_COMMENTDOCKEYWORDERROR); + } + sc.SetState(styleBeforeDCKeyword); + } + break; + case SCE_D_COMMENTNESTED: + if (sc.Match('+', '/')) { + if (curNcLevel > 0) + curNcLevel -= 1; + curLine = styler.GetLine(sc.currentPos); + styler.SetLineState(curLine, curNcLevel); + sc.Forward(); + if (curNcLevel == 0) { + sc.ForwardSetState(SCE_D_DEFAULT); + } + } + else if (sc.Match('/','+')) { + curNcLevel += 1; + curLine = styler.GetLine(sc.currentPos); + styler.SetLineState(curLine, curNcLevel); + sc.Forward(); + } + break; + case SCE_D_STRING: + if (sc.atLineEnd) { + sc.ChangeState(SCE_D_STRINGEOL); + } else if (sc.ch == '\\') { + if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { + sc.Forward(); + } + } else if (sc.ch == '\"') { + sc.ForwardSetState(SCE_D_DEFAULT); + } + break; + case SCE_D_CHARACTER: + if (sc.atLineEnd) { + sc.ChangeState(SCE_D_STRINGEOL); + } else if (sc.ch == '\\') { + if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { + sc.Forward(); + } + } else if (sc.ch == '\'') { + sc.ForwardSetState(SCE_D_DEFAULT); + } + break; + case SCE_D_STRINGEOL: + if (sc.atLineStart) { + sc.SetState(SCE_D_DEFAULT); + } + break; + } + + // Determine if a new state should be entered. + if (sc.state == SCE_D_DEFAULT) { + if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { + sc.SetState(SCE_D_NUMBER); + } else if (IsWordStart(sc.ch)) { + sc.SetState(SCE_D_IDENTIFIER); + } else if (sc.Match('/','+')) { + curNcLevel += 1; + curLine = styler.GetLine(sc.currentPos); + styler.SetLineState(curLine, curNcLevel); + sc.SetState(SCE_D_COMMENTNESTED); + sc.Forward(); + } else if (sc.Match('/', '*')) { + if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style + sc.SetState(SCE_D_COMMENTDOC); + } else { + sc.SetState(SCE_D_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_D_COMMENTLINEDOC); + else + sc.SetState(SCE_D_COMMENTLINE); + } else if (sc.ch == '\"') { + sc.SetState(SCE_D_STRING); + } else if (sc.ch == '\'') { + sc.SetState(SCE_D_CHARACTER); + } else if (isoperator(static_cast(sc.ch))) { + sc.SetState(SCE_D_OPERATOR); + } + } + } + sc.Complete(); +} + +static bool IsStreamCommentStyle(int style) { + return style == SCE_D_COMMENT || + style == SCE_D_COMMENTDOC || + style == SCE_D_COMMENTDOCKEYWORD || + style == SCE_D_COMMENTDOCKEYWORDERROR; +} + +// 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 FoldDoc(unsigned int startPos, int length, int initStyle, Accessor &styler) { + bool foldComment = styler.GetPropertyInt("fold.comment") != 0; + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + bool foldAtElse = styler.GetPropertyInt("lexer.d.fold.at.else", + styler.GetPropertyInt("fold.at.else", 0)) != 0; + unsigned int endPos = startPos + length; + int visibleChars = 0; + int lineCurrent = styler.GetLine(startPos); + int levelCurrent = SC_FOLDLEVELBASE; + if (lineCurrent > 0) + levelCurrent = styler.LevelAt(lineCurrent-1) >> 16; + int levelMinCurrent = levelCurrent; + int levelNext = levelCurrent; + char chNext = 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)) { + levelNext++; + } else if (!IsStreamCommentStyle(styleNext) && !atEOL) { + // Comments don't end at end of line and the next character may be unstyled. + levelNext--; + } + } + if (style == SCE_D_OPERATOR) { + if (ch == '{') { + // Measure the minimum before a '{' to allow + // folding on "} else {" + if (levelMinCurrent > levelNext) { + levelMinCurrent = levelNext; + } + levelNext++; + } else if (ch == '}') { + levelNext--; + } + } + if (atEOL) { + if (foldComment) { // Handle nested comments + int nc; + nc = styler.GetLineState(lineCurrent); + nc -= lineCurrent>0? styler.GetLineState(lineCurrent-1): 0; + levelNext += nc; + } + int levelUse = levelCurrent; + if (foldAtElse) { + levelUse = levelMinCurrent; + } + int lev = levelUse | levelNext << 16; + if (visibleChars == 0 && foldCompact) + lev |= SC_FOLDLEVELWHITEFLAG; + if (levelUse < levelNext) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelCurrent = levelNext; + levelMinCurrent = levelCurrent; + visibleChars = 0; + } + if (!IsASpace(ch)) + visibleChars++; + } +} + +static void FoldDDoc(unsigned int startPos, int length, int initStyle, + WordList *[], Accessor &styler) { + FoldDoc(startPos, length, initStyle, styler); +} + +static const char * const dWordLists[] = { + "Primary keywords and identifiers", + "Secondary keywords and identifiers", + "Documentation comment keywords", + "Type definitions and aliases", + 0, + }; + +static void ColouriseDDoc(unsigned int startPos, int length, + int initStyle, WordList *keywordlists[], Accessor &styler) { + ColouriseDoc(startPos, length, initStyle, keywordlists, styler, true); +} + +LexerModule lmD(SCLEX_D, ColouriseDDoc, "d", FoldDDoc, dWordLists); diff --git a/scintilla/src/LexEScript.cxx b/scintilla/src/LexEScript.cxx new file mode 100644 index 00000000..3e53627e --- /dev/null +++ b/scintilla/src/LexEScript.cxx @@ -0,0 +1,273 @@ +// Scintilla source code edit control +/** @file LexESCRIPT.cxx + ** Lexer for ESCRIPT + **/ +// Copyright 2003 by Patrizio Bekerle (patrizio@bekerle.com) + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + + +static inline bool IsAWordChar(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); +} + +static inline bool IsAWordStart(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '_'); +} + + + +static void ColouriseESCRIPTDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler) { + + WordList &keywords = *keywordlists[0]; + WordList &keywords2 = *keywordlists[1]; + WordList &keywords3 = *keywordlists[2]; + + // Do not leak onto next line + /*if (initStyle == SCE_ESCRIPT_STRINGEOL) + initStyle = SCE_ESCRIPT_DEFAULT;*/ + + StyleContext sc(startPos, length, initStyle, styler); + + bool caseSensitive = styler.GetPropertyInt("escript.case.sensitive", 0) != 0; + + for (; sc.More(); sc.Forward()) { + + /*if (sc.atLineStart && (sc.state == SCE_ESCRIPT_STRING)) { + // Prevent SCE_ESCRIPT_STRINGEOL from leaking back to previous line + sc.SetState(SCE_ESCRIPT_STRING); + }*/ + + // 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(); + } + continue; + } + } + + // Determine if the current state should terminate. + if (sc.state == SCE_ESCRIPT_OPERATOR || sc.state == SCE_ESCRIPT_BRACE) { + sc.SetState(SCE_ESCRIPT_DEFAULT); + } else if (sc.state == SCE_ESCRIPT_NUMBER) { + if (!IsADigit(sc.ch) || sc.ch != '.') { + sc.SetState(SCE_ESCRIPT_DEFAULT); + } + } else if (sc.state == SCE_ESCRIPT_IDENTIFIER) { + if (!IsAWordChar(sc.ch) || (sc.ch == '.')) { + char s[100]; + if (caseSensitive) { + sc.GetCurrent(s, sizeof(s)); + } else { + sc.GetCurrentLowered(s, sizeof(s)); + } + +// sc.GetCurrentLowered(s, sizeof(s)); + + if (keywords.InList(s)) { + sc.ChangeState(SCE_ESCRIPT_WORD); + } else if (keywords2.InList(s)) { + sc.ChangeState(SCE_ESCRIPT_WORD2); + } else if (keywords3.InList(s)) { + sc.ChangeState(SCE_ESCRIPT_WORD3); + // sc.state = SCE_ESCRIPT_IDENTIFIER; + } + sc.SetState(SCE_ESCRIPT_DEFAULT); + } + } else if (sc.state == SCE_ESCRIPT_COMMENT) { + if (sc.Match('*', '/')) { + sc.Forward(); + sc.ForwardSetState(SCE_ESCRIPT_DEFAULT); + } + } else if (sc.state == SCE_ESCRIPT_COMMENTDOC) { + if (sc.Match('*', '/')) { + sc.Forward(); + sc.ForwardSetState(SCE_ESCRIPT_DEFAULT); + } + } else if (sc.state == SCE_ESCRIPT_COMMENTLINE) { + if (sc.atLineEnd) { + sc.SetState(SCE_ESCRIPT_DEFAULT); + } + } else if (sc.state == SCE_ESCRIPT_STRING) { + if (sc.ch == '\\') { + if (sc.chNext == '\"' || sc.chNext == '\\') { + sc.Forward(); + } + } else if (sc.ch == '\"') { + sc.ForwardSetState(SCE_ESCRIPT_DEFAULT); + } + } + + // Determine if a new state should be entered. + if (sc.state == SCE_ESCRIPT_DEFAULT) { + if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { + sc.SetState(SCE_ESCRIPT_NUMBER); + } else if (IsAWordStart(sc.ch) || (sc.ch == '#')) { + sc.SetState(SCE_ESCRIPT_IDENTIFIER); + } else if (sc.Match('/', '*')) { + sc.SetState(SCE_ESCRIPT_COMMENT); + sc.Forward(); // Eat the * so it isn't used for the end of the comment + } else if (sc.Match('/', '/')) { + sc.SetState(SCE_ESCRIPT_COMMENTLINE); + } else if (sc.ch == '\"') { + sc.SetState(SCE_ESCRIPT_STRING); + //} else if (isoperator(static_cast(sc.ch))) { + } else if (sc.ch == '+' || sc.ch == '-' || sc.ch == '*' || sc.ch == '/' || sc.ch == '=' || sc.ch == '<' || sc.ch == '>' || sc.ch == '&' || sc.ch == '|' || sc.ch == '!' || sc.ch == '?' || sc.ch == ':') { + sc.SetState(SCE_ESCRIPT_OPERATOR); + } else if (sc.ch == '{' || sc.ch == '}') { + sc.SetState(SCE_ESCRIPT_BRACE); + } + } + + } + sc.Complete(); +} + + +static int classifyFoldPointESCRIPT(const char* s, const char* prevWord) { + int lev = 0; + if (strcmp(prevWord, "end") == 0) return lev; + if ((strcmp(prevWord, "else") == 0 && strcmp(s, "if") == 0) || strcmp(s, "elseif") == 0) + return -1; + + if (strcmp(s, "for") == 0 || strcmp(s, "foreach") == 0 + || strcmp(s, "program") == 0 || strcmp(s, "function") == 0 + || strcmp(s, "while") == 0 || strcmp(s, "case") == 0 + || strcmp(s, "if") == 0 ) { + lev = 1; + } else if ( strcmp(s, "endfor") == 0 || strcmp(s, "endforeach") == 0 + || strcmp(s, "endprogram") == 0 || strcmp(s, "endfunction") == 0 + || strcmp(s, "endwhile") == 0 || strcmp(s, "endcase") == 0 + || strcmp(s, "endif") == 0 ) { + lev = -1; + } + + return lev; +} + + +static bool IsStreamCommentStyle(int style) { + return style == SCE_ESCRIPT_COMMENT || + style == SCE_ESCRIPT_COMMENTDOC || + style == SCE_ESCRIPT_COMMENTLINE; +} + +static void FoldESCRIPTDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { + //~ bool foldComment = styler.GetPropertyInt("fold.comment") != 0; + // Do not know how to fold the comment at the moment. + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + bool foldComment = true; + unsigned int endPos = startPos + length; + 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; + char prevWord[32] = ""; + + 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)) { + levelCurrent++; + } else if (!IsStreamCommentStyle(styleNext) && !atEOL) { + // Comments don't end at end of line and the next character may be unstyled. + levelCurrent--; + } + } + + if (foldComment && (style == SCE_ESCRIPT_COMMENTLINE)) { + if ((ch == '/') && (chNext == '/')) { + char chNext2 = styler.SafeGetCharAt(i + 2); + if (chNext2 == '{') { + levelCurrent++; + } else if (chNext2 == '}') { + levelCurrent--; + } + } + } + + if (stylePrev == SCE_ESCRIPT_DEFAULT && style == SCE_ESCRIPT_WORD3) + { + // Store last word start point. + lastStart = i; + } + + if (style == SCE_ESCRIPT_WORD3) { + if(iswordchar(ch) && !iswordchar(chNext)) { + char s[32]; + unsigned int j; + for(j = 0; ( j < 31 ) && ( j < i-lastStart+1 ); j++) { + s[j] = static_cast(tolower(styler[lastStart + j])); + } + s[j] = '\0'; + levelCurrent += classifyFoldPointESCRIPT(s, prevWord); + strcpy(prevWord, s); + } + } + if (atEOL) { + int lev = levelPrev; + if (visibleChars == 0 && foldCompact) + lev |= SC_FOLDLEVELWHITEFLAG; + if ((levelCurrent > levelPrev) && (visibleChars > 0)) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelPrev = levelCurrent; + visibleChars = 0; + strcpy(prevWord, ""); + } + + if (!isspacechar(ch)) + visibleChars++; + } + + // Fill in the real level of the next line, keeping the current flags as they will be filled in later + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, levelPrev | flagsNext); +} + + + +static const char * const ESCRIPTWordLists[] = { + "Primary keywords and identifiers", + "Intrinsic functions", + "Extended and user defined functions", + 0, +}; + +LexerModule lmESCRIPT(SCLEX_ESCRIPT, ColouriseESCRIPTDoc, "escript", FoldESCRIPTDoc, ESCRIPTWordLists); diff --git a/scintilla/src/LexEiffel.cxx b/scintilla/src/LexEiffel.cxx new file mode 100644 index 00000000..4f8e7e24 --- /dev/null +++ b/scintilla/src/LexEiffel.cxx @@ -0,0 +1,238 @@ +// Scintilla source code edit control +/** @file LexEiffel.cxx + ** Lexer for Eiffel. + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static inline bool isEiffelOperator(unsigned int ch) { + // '.' left out as it is used to make up numbers + return ch == '*' || ch == '/' || ch == '\\' || ch == '-' || ch == '+' || + ch == '(' || ch == ')' || ch == '=' || + ch == '{' || ch == '}' || ch == '~' || + ch == '[' || ch == ']' || ch == ';' || + ch == '<' || ch == '>' || ch == ',' || + ch == '.' || ch == '^' || ch == '%' || ch == ':' || + ch == '!' || ch == '@' || ch == '?'; +} + +static inline bool IsAWordChar(unsigned int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '_'); +} + +static inline bool IsAWordStart(unsigned int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '_'); +} + +static void ColouriseEiffelDoc(unsigned int startPos, + int length, + int initStyle, + WordList *keywordlists[], + Accessor &styler) { + + WordList &keywords = *keywordlists[0]; + + StyleContext sc(startPos, length, initStyle, styler); + + for (; sc.More(); sc.Forward()) { + + if (sc.state == SCE_EIFFEL_STRINGEOL) { + if (sc.ch != '\r' && sc.ch != '\n') { + sc.SetState(SCE_EIFFEL_DEFAULT); + } + } else if (sc.state == SCE_EIFFEL_OPERATOR) { + sc.SetState(SCE_EIFFEL_DEFAULT); + } else if (sc.state == SCE_EIFFEL_WORD) { + if (!IsAWordChar(sc.ch)) { + char s[100]; + sc.GetCurrentLowered(s, sizeof(s)); + if (!keywords.InList(s)) { + sc.ChangeState(SCE_EIFFEL_IDENTIFIER); + } + sc.SetState(SCE_EIFFEL_DEFAULT); + } + } else if (sc.state == SCE_EIFFEL_NUMBER) { + if (!IsAWordChar(sc.ch)) { + sc.SetState(SCE_EIFFEL_DEFAULT); + } + } else if (sc.state == SCE_EIFFEL_COMMENTLINE) { + if (sc.ch == '\r' || sc.ch == '\n') { + sc.SetState(SCE_EIFFEL_DEFAULT); + } + } else if (sc.state == SCE_EIFFEL_STRING) { + if (sc.ch == '%') { + sc.Forward(); + } else if (sc.ch == '\"') { + sc.Forward(); + sc.SetState(SCE_EIFFEL_DEFAULT); + } + } else if (sc.state == SCE_EIFFEL_CHARACTER) { + if (sc.ch == '\r' || sc.ch == '\n') { + sc.SetState(SCE_EIFFEL_STRINGEOL); + } else if (sc.ch == '%') { + sc.Forward(); + } else if (sc.ch == '\'') { + sc.Forward(); + sc.SetState(SCE_EIFFEL_DEFAULT); + } + } + + if (sc.state == SCE_EIFFEL_DEFAULT) { + if (sc.ch == '-' && sc.chNext == '-') { + sc.SetState(SCE_EIFFEL_COMMENTLINE); + } else if (sc.ch == '\"') { + sc.SetState(SCE_EIFFEL_STRING); + } else if (sc.ch == '\'') { + sc.SetState(SCE_EIFFEL_CHARACTER); + } else if (IsADigit(sc.ch) || (sc.ch == '.')) { + sc.SetState(SCE_EIFFEL_NUMBER); + } else if (IsAWordStart(sc.ch)) { + sc.SetState(SCE_EIFFEL_WORD); + } else if (isEiffelOperator(sc.ch)) { + sc.SetState(SCE_EIFFEL_OPERATOR); + } + } + } + sc.Complete(); +} + +static bool IsEiffelComment(Accessor &styler, int pos, int len) { + return len>1 && styler[pos]=='-' && styler[pos+1]=='-'; +} + +static void FoldEiffelDocIndent(unsigned int startPos, int length, int, + WordList *[], Accessor &styler) { + int lengthDoc = startPos + length; + + // Backtrack to previous line in case need to fix its fold status + int lineCurrent = styler.GetLine(startPos); + if (startPos > 0) { + if (lineCurrent > 0) { + lineCurrent--; + startPos = styler.LineStart(lineCurrent); + } + } + int spaceFlags = 0; + int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsEiffelComment); + char chNext = styler[startPos]; + for (int i = startPos; i < lengthDoc; i++) { + char ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + + if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc)) { + int lev = indentCurrent; + int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsEiffelComment); + if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { + // Only non whitespace lines can be headers + if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) { + lev |= SC_FOLDLEVELHEADERFLAG; + } else if (indentNext & SC_FOLDLEVELWHITEFLAG) { + // Line after is blank so check the next - maybe should continue further? + int spaceFlags2 = 0; + int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsEiffelComment); + if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) { + lev |= SC_FOLDLEVELHEADERFLAG; + } + } + } + indentCurrent = indentNext; + styler.SetLevel(lineCurrent, lev); + lineCurrent++; + } + } +} + +static void FoldEiffelDocKeyWords(unsigned int startPos, int length, int /* initStyle */, WordList *[], + Accessor &styler) { + unsigned int lengthDoc = 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 stylePrev = 0; + int styleNext = styler.StyleAt(startPos); + // lastDeferred should be determined by looking back to last keyword in case + // the "deferred" is on a line before "class" + bool lastDeferred = false; + for (unsigned int i = startPos; i < lengthDoc; i++) { + char ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + int style = styleNext; + styleNext = styler.StyleAt(i + 1); + bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); + if ((stylePrev != SCE_EIFFEL_WORD) && (style == SCE_EIFFEL_WORD)) { + char s[20]; + unsigned int j = 0; + while ((j < (sizeof(s) - 1)) && (iswordchar(styler[i + j]))) { + s[j] = styler[i + j]; + j++; + } + s[j] = '\0'; + + if ( + (strcmp(s, "check") == 0) || + (strcmp(s, "debug") == 0) || + (strcmp(s, "deferred") == 0) || + (strcmp(s, "do") == 0) || + (strcmp(s, "from") == 0) || + (strcmp(s, "if") == 0) || + (strcmp(s, "inspect") == 0) || + (strcmp(s, "once") == 0) + ) + levelCurrent++; + if (!lastDeferred && (strcmp(s, "class") == 0)) + levelCurrent++; + if (strcmp(s, "end") == 0) + levelCurrent--; + lastDeferred = strcmp(s, "deferred") == 0; + } + + if (atEOL) { + int lev = levelPrev; + if (visibleChars == 0) + lev |= SC_FOLDLEVELWHITEFLAG; + if ((levelCurrent > levelPrev) && (visibleChars > 0)) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelPrev = levelCurrent; + visibleChars = 0; + } + if (!isspacechar(ch)) + visibleChars++; + stylePrev = style; + } + // Fill in the real level of the next line, keeping the current flags as they will be filled in later + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, levelPrev | flagsNext); +} + +static const char * const eiffelWordListDesc[] = { + "Keywords", + 0 +}; + +LexerModule lmEiffel(SCLEX_EIFFEL, ColouriseEiffelDoc, "eiffel", FoldEiffelDocIndent, eiffelWordListDesc); +LexerModule lmEiffelkw(SCLEX_EIFFELKW, ColouriseEiffelDoc, "eiffelkw", FoldEiffelDocKeyWords, eiffelWordListDesc); diff --git a/scintilla/src/LexErlang.cxx b/scintilla/src/LexErlang.cxx new file mode 100644 index 00000000..75c85004 --- /dev/null +++ b/scintilla/src/LexErlang.cxx @@ -0,0 +1,527 @@ +// Scintilla source code edit control +/** @file LexErlang.cxx + ** Lexer for Erlang. + ** Written by Peter-Henry Mander, based on Matlab lexer by José Fonseca + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +/* + TODO: + o _Param should be a new lexical type +*/ + +static int is_radix(int radix, int ch) { + int digit; + if ( 16 < radix || 2 > radix ) { + return 0; + } + if ( isdigit(ch) ) { + digit = ch - '0'; + } else if ( isxdigit(ch) ) { + digit = toupper(ch) - 'A' + 10; + } else { + return 0; + } + if ( digit < radix ) { + return 1; + } else { + return 0; + } +} + +typedef enum { + STATE_NULL, + ATOM_UNQUOTED, + ATOM_QUOTED, + ATOM_FUN_NAME, + NODE_NAME_UNQUOTED, + NODE_NAME_QUOTED, + MACRO_START, + MACRO_UNQUOTED, + MACRO_QUOTED, + RECORD_START, + RECORD_UNQUOTED, + RECORD_QUOTED, + NUMERAL_START, + NUMERAL_SIGNED, + NUMERAL_RADIX_LITERAL, + NUMERAL_SPECULATIVE_MANTISSA, + NUMERAL_FLOAT_MANTISSA, + NUMERAL_FLOAT_EXPONENT, + NUMERAL_FLOAT_SIGNED_EXPONENT, + PARSE_ERROR +} atom_parse_state_t; + +static void ColouriseErlangDoc(unsigned int startPos, int length, int initStyle, + WordList *keywordlists[], Accessor &styler) { + + WordList &keywords = *keywordlists[0]; + + styler.StartAt(startPos); + + StyleContext sc(startPos, length, initStyle, styler); + atom_parse_state_t parse_state = STATE_NULL; + int radix_digits = 0; + int exponent_digits = 0; + for (; sc.More(); sc.Forward()) { + if ( STATE_NULL != parse_state ) { + switch (parse_state) { + case STATE_NULL: + sc.SetState(SCE_ERLANG_DEFAULT); + break; + case ATOM_UNQUOTED: + if ( '@' == sc.ch ){ + parse_state = NODE_NAME_UNQUOTED; + } else if ( !isalnum(sc.ch) && sc.ch != '_' ) { + char s[100]; + sc.GetCurrent(s, sizeof(s)); + if (keywords.InList(s)) { + sc.ChangeState(SCE_ERLANG_KEYWORD); + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } else { + if ( '/' == sc.ch ) { + parse_state = ATOM_FUN_NAME; + } else { + sc.ChangeState(SCE_ERLANG_ATOM); + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + } + } + break; + case ATOM_QUOTED: + if ( '@' == sc.ch ){ + parse_state = NODE_NAME_QUOTED; + } else if ( '\'' == sc.ch && '\\' != sc.chPrev ) { + sc.ChangeState(SCE_ERLANG_ATOM); + sc.ForwardSetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case ATOM_FUN_NAME: + if ( !isdigit(sc.ch) ) { + sc.ChangeState(SCE_ERLANG_FUNCTION_NAME); + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case NODE_NAME_QUOTED: + if ( '@' == sc.ch ) { + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } else if ( '\'' == sc.ch && '\\' != sc.chPrev ) { + sc.ChangeState(SCE_ERLANG_NODE_NAME); + sc.ForwardSetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case NODE_NAME_UNQUOTED: + if ( '@' == sc.ch ) { + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } else if ( !isalnum(sc.ch) && sc.ch != '_' ) { + sc.ChangeState(SCE_ERLANG_NODE_NAME); + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case RECORD_START: + if ( '\'' == sc.ch ) { + parse_state = RECORD_QUOTED; + } else if (isalpha(sc.ch) && islower(sc.ch)) { + parse_state = RECORD_UNQUOTED; + } else { // error + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case RECORD_QUOTED: + if ( '\'' == sc.ch && '\\' != sc.chPrev ) { + sc.ChangeState(SCE_ERLANG_RECORD); + sc.ForwardSetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case RECORD_UNQUOTED: + if ( !isalpha(sc.ch) && '_' != sc.ch ) { + sc.ChangeState(SCE_ERLANG_RECORD); + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case MACRO_START: + if ( '\'' == sc.ch ) { + parse_state = MACRO_QUOTED; + } else if (isalpha(sc.ch)) { + parse_state = MACRO_UNQUOTED; + } else { // error + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case MACRO_UNQUOTED: + if ( !isalpha(sc.ch) && '_' != sc.ch ) { + sc.ChangeState(SCE_ERLANG_MACRO); + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case MACRO_QUOTED: + if ( '\'' == sc.ch && '\\' != sc.chPrev ) { + sc.ChangeState(SCE_ERLANG_MACRO); + sc.ForwardSetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case NUMERAL_START: + if ( isdigit(sc.ch) ) { + radix_digits *= 10; + radix_digits += sc.ch - '0'; // Assuming ASCII here! + } else if ( '#' == sc.ch ) { + if ( 2 > radix_digits || 16 < radix_digits) { + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } else { + parse_state = NUMERAL_RADIX_LITERAL; + } + } else if ( '.' == sc.ch && isdigit(sc.chNext)) { + radix_digits = 0; + parse_state = NUMERAL_FLOAT_MANTISSA; + } else if ( 'e' == sc.ch || 'E' == sc.ch ) { + exponent_digits = 0; + parse_state = NUMERAL_FLOAT_EXPONENT; + } else { + radix_digits = 0; + sc.ChangeState(SCE_ERLANG_NUMBER); + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case NUMERAL_RADIX_LITERAL: + if ( !is_radix(radix_digits,sc.ch) ) { + radix_digits = 0; + if ( !isalnum(sc.ch) ) { + sc.ChangeState(SCE_ERLANG_NUMBER); + } + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case NUMERAL_FLOAT_MANTISSA: + if ( 'e' == sc.ch || 'E' == sc.ch ) { + exponent_digits = 0; + parse_state = NUMERAL_FLOAT_EXPONENT; + } else if ( !isdigit(sc.ch) ) { + sc.ChangeState(SCE_ERLANG_NUMBER); + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } + break; + case NUMERAL_FLOAT_EXPONENT: + if ( '-' == sc.ch || '+' == sc.ch ) { + parse_state = NUMERAL_FLOAT_SIGNED_EXPONENT; + } else if ( !isdigit(sc.ch) ) { + if ( 0 < exponent_digits ) { + sc.ChangeState(SCE_ERLANG_NUMBER); + } + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } else { + ++exponent_digits; + } + break; + case NUMERAL_FLOAT_SIGNED_EXPONENT: + if ( !isdigit(sc.ch) ) { + if ( 0 < exponent_digits ) { + sc.ChangeState(SCE_ERLANG_NUMBER); + } + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } else { + ++exponent_digits; + } + break; + case NUMERAL_SIGNED: + if ( !isdigit(sc.ch) ) { + sc.ChangeState(SCE_ERLANG_NUMBER); + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } else if ( '.' == sc.ch ) { + parse_state = NUMERAL_FLOAT_MANTISSA; + } + break; + case NUMERAL_SPECULATIVE_MANTISSA: + if ( !isdigit(sc.ch) ) { + sc.ChangeState(SCE_ERLANG_OPERATOR); + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + } else { + parse_state = NUMERAL_FLOAT_MANTISSA; + } + break; + case PARSE_ERROR: + sc.SetState(SCE_ERLANG_DEFAULT); + parse_state = STATE_NULL; + break; + } + } else if (sc.state == SCE_ERLANG_OPERATOR) { + if (sc.chPrev == '.') { + if (sc.ch == '*' || sc.ch == '/' || sc.ch == '\\' || sc.ch == '^') { + sc.ForwardSetState(SCE_ERLANG_DEFAULT); + } else if (sc.ch == '\'') { + sc.ForwardSetState(SCE_ERLANG_DEFAULT); + } else { + sc.SetState(SCE_ERLANG_DEFAULT); + } + } else { + sc.SetState(SCE_ERLANG_DEFAULT); + } + } else if (sc.state == SCE_ERLANG_VARIABLE) { + if (!isalnum(sc.ch) && sc.ch != '_') { + sc.SetState(SCE_ERLANG_DEFAULT); + } + } else if (sc.state == SCE_ERLANG_STRING) { + if (sc.ch == '\"' && sc.chPrev != '\\') { + sc.ForwardSetState(SCE_ERLANG_DEFAULT); + } + } else if (sc.state == SCE_ERLANG_COMMENT ) { + if (sc.atLineEnd) { + sc.SetState(SCE_ERLANG_DEFAULT); + } + } else if (sc.state == SCE_ERLANG_CHARACTER ) { + if ( sc.chPrev == '\\' ) { + sc.ForwardSetState(SCE_ERLANG_DEFAULT); + } else if ( sc.ch != '\\' ) { + sc.ForwardSetState(SCE_ERLANG_DEFAULT); + } + } + + if (sc.state == SCE_ERLANG_DEFAULT) { + if (sc.ch == '%') { + sc.SetState(SCE_ERLANG_COMMENT); + } else if (sc.ch == '\"') { + sc.SetState(SCE_ERLANG_STRING); + } else if (sc.ch == '#') { + parse_state = RECORD_START; + sc.SetState(SCE_ERLANG_UNKNOWN); + } else if (sc.ch == '?') { + parse_state = MACRO_START; + sc.SetState(SCE_ERLANG_UNKNOWN); + } else if (sc.ch == '$') { + sc.SetState(SCE_ERLANG_CHARACTER); + } else if (sc.ch == '\'') { + parse_state = ATOM_QUOTED; + sc.SetState(SCE_ERLANG_UNKNOWN); + } else if ( isdigit(sc.ch) ) { + parse_state = NUMERAL_START; + radix_digits = sc.ch - '0'; + sc.SetState(SCE_ERLANG_UNKNOWN); + } else if ( '.' == sc.ch ) { + parse_state = NUMERAL_SPECULATIVE_MANTISSA; + sc.SetState(SCE_ERLANG_UNKNOWN); + } else if (isalpha(sc.ch) && isupper(sc.ch)) { + sc.SetState(SCE_ERLANG_VARIABLE); + } else if (isalpha(sc.ch)) { + parse_state = ATOM_UNQUOTED; + sc.SetState(SCE_ERLANG_UNKNOWN); + } else if (isoperator(static_cast(sc.ch)) || sc.ch == '\\') { + sc.SetState(SCE_ERLANG_OPERATOR); + } + } + } + sc.Complete(); +} + +static int ClassifyFoldPointErlang( + Accessor &styler, + int styleNext, + int keyword_start +) { + int lev = 0; + if ( styler.Match(keyword_start,"case") + || ( + styler.Match(keyword_start,"fun") + && SCE_ERLANG_FUNCTION_NAME != styleNext) + || styler.Match(keyword_start,"if") + || styler.Match(keyword_start,"query") + || styler.Match(keyword_start,"receive") + ) { + ++lev; + } else if ( styler.Match(keyword_start,"end") ) { + --lev; + } + return lev; +} + + +static void FoldErlangDoc( + unsigned int startPos, int length, int initStyle, + WordList** /*keywordlists*/, Accessor &styler +) { + unsigned 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.SafeGetCharAt(startPos); + int styleNext = styler.StyleAt(startPos); + int style = initStyle; + int keyword_start = 0; + + bool fold_keywords = true; + bool fold_comments = true; + bool fold_braces = true; + bool fold_function_clauses = false; + bool fold_clauses = false; + + //int clause_level = 0; + + 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 ( (stylePrev != SCE_ERLANG_KEYWORD) && (style == SCE_ERLANG_KEYWORD) ) { + keyword_start = i; + } + if ( fold_keywords ) { + if ( (stylePrev == SCE_ERLANG_KEYWORD) + && (style != SCE_ERLANG_KEYWORD) + && (style != SCE_ERLANG_ATOM) + ) { + levelCurrent += ClassifyFoldPointErlang(styler,styleNext,keyword_start); + } + } + + if ( fold_comments ) { + if (style == SCE_ERLANG_COMMENT) { + if ((ch == '%') && (chNext == '{')) { + levelCurrent++; + } else if ((ch == '%') && (chNext == '}')) { + levelCurrent--; + } + } + } + + if ( fold_function_clauses ) { + if ( (SC_FOLDLEVELBASE == levelCurrent) /*&& (style == SCE_ERLANG_OPERATOR)*/ ) { + if ( (ch == '-') && (chNext == '>')) { + //~ fprintf(stderr,"levelCurrent=%d\n", levelCurrent); + //++clause_level; + //~ if ( 0 < clause_level ) + ++levelCurrent; + } + } + //~ if ( (stylePrev != SCE_ERLANG_RECORD) + //~ && (style != SCE_ERLANG_NUMBER) + //~ && (style != SCE_ERLANG_STRING) + //~ && (style != SCE_ERLANG_COMMENT) + //~ ) { + if ( (SC_FOLDLEVELBASE+1 == levelCurrent) && (ch == '.') ) { + //--clause_level; + //~ if ( 0 == clause_level ) + --levelCurrent; + } + //~ } + } + + if ( fold_clauses ) { + if ( (0 < levelCurrent) && (style == SCE_ERLANG_OPERATOR) ) { + if ((ch == '-') && (chNext == '>')) { + levelCurrent++; + } + if ( (ch == ';') ) { + levelCurrent--; + } + } + if ( (stylePrev != SCE_ERLANG_RECORD) + && (style != SCE_ERLANG_NUMBER) + && (style != SCE_ERLANG_STRING) + && (style != SCE_ERLANG_COMMENT) + ) { + if ( (ch == '.') ) { + levelCurrent--; + } + } + if ( (stylePrev == SCE_ERLANG_KEYWORD) + && (style != SCE_ERLANG_KEYWORD) + && (style != SCE_ERLANG_ATOM) + && ( + styler.Match(keyword_start,"end") // 'end' counted twice if fold_keywords too + || styler.Match(keyword_start,"after") ) + ) { + levelCurrent--; + } + } + + if ( fold_braces ) { + if (style == SCE_ERLANG_OPERATOR) { + if ( (ch == '{') || (ch == '(') || (ch == '[') ) { + levelCurrent++; + } else if ( (ch == '}') || (ch == ')') || (ch == ']') ) { + levelCurrent--; + } + } + } + + if (atEOL) { + int lev = levelPrev; + //~ if (visibleChars == 0 && foldCompact) + //~ lev |= SC_FOLDLEVELWHITEFLAG; + //~ if ((levelCurrent > levelPrev) && (visibleChars > 0)) + if ((levelCurrent > levelPrev)) { + lev |= SC_FOLDLEVELHEADERFLAG; + } + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelPrev = levelCurrent; + //~ visibleChars = 0; + } + //~ if (!isspacechar(ch)) + //~ visibleChars++; + + } + // Fill in the real level of the next line, keeping the current flags as they will be filled in later + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, levelPrev | flagsNext); +} + +static const char * const erlangWordListDesc[] = { + "Keywords", + 0 +}; + +LexerModule lmErlang( + SCLEX_ERLANG, + ColouriseErlangDoc, + "erlang", + FoldErlangDoc, + erlangWordListDesc); + + diff --git a/scintilla/src/LexFlagship.cxx b/scintilla/src/LexFlagship.cxx new file mode 100644 index 00000000..a9e6e011 --- /dev/null +++ b/scintilla/src/LexFlagship.cxx @@ -0,0 +1,231 @@ +// Scintilla source code edit control +/** @file LexFlagShip.cxx + ** Lexer for FlagShip + ** (Syntactically compatible to other XBase dialects, like dBase, Clipper, Fox etc.) + **/ +// Copyright 2005 by Randy Butler +// Copyright 1998-2003 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static bool IsFlagShipComment(Accessor &styler, int pos, int len) { + return len>0 && styler[pos]=='\''; +} + +static inline bool IsTypeCharacter(int ch) { + return ch == '%' || ch == '&' || ch == '@' || ch == '!' || ch == '#' || ch == '$'; +} + +// Extended to accept accented characters +static inline bool IsAWordChar(int ch) { + return ch >= 0x80 || + (isalnum(ch) || ch == '.' || ch == '_'); +} + +static inline bool IsAWordStart(int ch) { + return ch >= 0x80 || + (isalnum(ch) || ch == '_'); +} + +static inline bool IsADateCharacter(const int ch) { + return (ch < 0x80) && + (isalnum(ch) || ch == '|' || ch == '-' || ch == '/' || ch == ':' || ch == ' ' || ch == '\t'); +} + + +static void ColouriseFlagShipDoc(unsigned int startPos, int length, int initStyle, + WordList *keywordlists[], Accessor &styler) { + + //bool FSScriptSyntax = true; + WordList &keywords = *keywordlists[0]; + WordList &keywords2 = *keywordlists[1]; + WordList &keywords3 = *keywordlists[2]; + WordList &keywords4 = *keywordlists[3]; + + styler.StartAt(startPos); + + int visibleChars = 0; + + StyleContext sc(startPos, length, initStyle, styler); + + for (; sc.More(); sc.Forward()) { + + if (sc.state == SCE_FS_OPERATOR) { + sc.SetState(SCE_FS_DEFAULT); + } else if (sc.state == SCE_FS_IDENTIFIER) { + if (!IsAWordChar(sc.ch)) { + char s[100]; + sc.GetCurrentLowered(s, sizeof(s)); + if (keywords.InList(s)) { + sc.ChangeState(SCE_FS_KEYWORD); + } else if (keywords2.InList(s)) { + sc.ChangeState(SCE_FS_KEYWORD2); + } else if (keywords3.InList(s)) { + sc.ChangeState(SCE_FS_KEYWORD3); + } else if (keywords4.InList(s)) { + sc.ChangeState(SCE_FS_KEYWORD4); + }// Else, it is really an identifier... + sc.SetState(SCE_FS_DEFAULT); + } + } else if (sc.state == SCE_FS_NUMBER) { + if (!IsAWordChar(sc.ch)) { + sc.SetState(SCE_FS_DEFAULT); + } + } else if (sc.state == SCE_FS_STRING) { + // VB doubles quotes to preserve them, so just end this string + // state now as a following quote will start again + if (sc.ch == '\"') { + if (tolower(sc.chNext) == 'c') { + sc.Forward(); + } + sc.ForwardSetState(SCE_FS_DEFAULT); + } else if (sc.atLineEnd) { + sc.ChangeState(SCE_FS_STRINGEOL); + sc.ForwardSetState(SCE_FS_DEFAULT); + } + } else if (sc.state == SCE_FS_COMMENT) { + if (sc.Match('*', '/')) { // new code + sc.Forward(); + sc.ForwardSetState(SCE_FS_DEFAULT); + //if (sc.atLineEnd) { // old code + // sc.SetState(SCE_FS_DEFAULT); + } + } else if (sc.state == SCE_FS_COMMENTLINE) { //new code + if (sc.ch == '\r' || sc.ch == '\n') { + sc.SetState(SCE_FS_DEFAULT); + visibleChars = 0; + } + } else if (sc.state == SCE_FS_PREPROCESSOR) { + if (sc.atLineEnd) { + sc.SetState(SCE_FS_DEFAULT); + } + } else if (sc.state == SCE_FS_DATE) { + if (sc.ch == '#' || !IsADateCharacter(sc.chNext)) { + sc.ForwardSetState(SCE_FS_DEFAULT); + } + } + + // Determine if a new state should be entered. + if (sc.state == SCE_FS_DEFAULT) { + if (sc.Match('/', '*')) { // New code + sc.SetState(SCE_FS_COMMENT); + sc.Forward(); // Eat the * so it isn't used for the end of the comment + //if (sc.ch == '\'') { // Old code + // sc.SetState(SCE_FS_COMMENT); // old code + } else if (sc.Match('/', '/')) { // New code + sc.SetState(SCE_FS_COMMENTLINE); + } else if (sc.ch == '\"') { + sc.SetState(SCE_FS_STRING); + } else if (sc.ch == '#' && visibleChars == 0) { + // Preprocessor commands are alone on their line + sc.SetState(SCE_FS_PREPROCESSOR); + } else if (sc.ch == '#') { + int n = 1; + int chSeek = ' '; + while ((n < 100) && (chSeek == ' ' || chSeek == '\t')) { + chSeek = sc.GetRelative(n); + n++; + } + if (IsADigit(chSeek)) { + sc.SetState(SCE_FS_DATE); + } else { + sc.SetState(SCE_FS_OPERATOR); + } + } else if (sc.ch == '&' && tolower(sc.chNext) == 'h') { + sc.SetState(SCE_FS_NUMBER); + } else if (sc.ch == '&' && tolower(sc.chNext) == 'o') { + sc.SetState(SCE_FS_NUMBER); + } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { + sc.SetState(SCE_FS_NUMBER); + } else if (IsAWordStart(sc.ch) || (sc.ch == '[')) { + sc.SetState(SCE_FS_IDENTIFIER); + } else if (isoperator(static_cast(sc.ch)) || (sc.ch == '\\')) { + sc.SetState(SCE_FS_OPERATOR); + } + } + + if (sc.atLineEnd) { + visibleChars = 0; + } + if (!IsASpace(sc.ch)) { + visibleChars++; + } + } + sc.Complete(); +} + +static void FoldFlagShipDoc(unsigned int startPos, int length, int, + WordList *[], Accessor &styler) { + + int endPos = startPos + length; + + // Backtrack to previous line in case need to fix its fold status + int lineCurrent = styler.GetLine(startPos); + if (startPos > 0) { + if (lineCurrent > 0) { + lineCurrent--; + startPos = styler.LineStart(lineCurrent); + } + } + int spaceFlags = 0; + int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsFlagShipComment); + char chNext = styler[startPos]; + for (int i = startPos; i < endPos; i++) { + char ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + + if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) { + int lev = indentCurrent; + int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsFlagShipComment); + if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) { + // Only non whitespace lines can be headers + if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) { + lev |= SC_FOLDLEVELHEADERFLAG; + } else if (indentNext & SC_FOLDLEVELWHITEFLAG) { + // Line after is blank so check the next - maybe should continue further? + int spaceFlags2 = 0; + int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsFlagShipComment); + if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) { + lev |= SC_FOLDLEVELHEADERFLAG; + } + } + } + indentCurrent = indentNext; + styler.SetLevel(lineCurrent, lev); + lineCurrent++; + } + } +} + + +static const char * const FSWordListDesc[] = { + "Keywords", + "functions", + "user2", + "user3", + 0 +}; + +LexerModule lmFlagShip(SCLEX_FLAGSHIP, ColouriseFlagShipDoc, "flagship", FoldFlagShipDoc, FSWordListDesc); + + + + diff --git a/scintilla/src/LexForth.cxx b/scintilla/src/LexForth.cxx new file mode 100644 index 00000000..aa72287f --- /dev/null +++ b/scintilla/src/LexForth.cxx @@ -0,0 +1,352 @@ +// Scintilla source code edit control +/** @file LexCrontab.cxx + ** Lexer to use with extended crontab files used by a powerful + ** Windows scheduler/event monitor/automation manager nnCron. + ** (http://nemtsev.eserv.ru/) + **/ +// Copyright 1998-2001 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +bool is_whitespace(int ch){ + return ch == '\n' || ch == '\r' || ch == '\t' || ch == ' '; +} + +bool is_blank(int ch){ + return ch == '\t' || ch == ' '; +} +//#define FORTH_DEBUG +#ifdef FORTH_DEBUG +static FILE *f_debug; +#define log(x) fputs(f_debug,x); +#else +#define log(x) +#endif + +#define STATE_LOCALE +#define BL ' ' + +static Accessor *st; +static int cur_pos,pos1,pos2,pos0,lengthDoc; +char *buffer; + +char getChar(bool is_bl){ + char ch=st->SafeGetCharAt(cur_pos); + if(is_bl) if(is_whitespace(ch)) ch=BL; + return ch; +} + +char getCharBL(){ + char ch=st->SafeGetCharAt(cur_pos); + return ch; +} +bool is_eol(char ch){ + return ch=='\n' || ch=='\r'; +} + +int parse(char ch, bool skip_eol){ +// pos1 - start pos of word +// pos2 - pos after of word +// pos0 - start pos + char c=0; + int len; + bool is_bl=ch==BL; + pos0=pos1=pos2=cur_pos; + for(;cur_pos9 && base>10) digit-=7; + if(digit<0) return false; + if(digit>=base) return false; + } + return true; +} + +bool is_number(char *s){ + if(strncmp(s,"0x",2)==0) return _is_number(s+2,16); + return _is_number(s,10); +} + +static void ColouriseForthDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) +{ + st=&styler; + cur_pos=startPos; + lengthDoc = startPos + length; + buffer = new char[length]; + +#ifdef FORTH_DEBUG + f_debug=fopen("c:\\sci.log","at"); +#endif + + WordList &control = *keywordLists[0]; + WordList &keyword = *keywordLists[1]; + WordList &defword = *keywordLists[2]; + WordList &preword1 = *keywordLists[3]; + WordList &preword2 = *keywordLists[4]; + WordList &strings = *keywordLists[5]; + + // go through all provided text segment + // using the hand-written state machine shown below + styler.StartAt(startPos); + styler.StartSegment(startPos); + while(parse(BL,true)!=0){ + if(pos0!=pos1){ + styler.ColourTo(pos0,SCE_FORTH_DEFAULT); + styler.ColourTo(pos1-1,SCE_FORTH_DEFAULT); + } + if(strcmp("\\",buffer)==0){ + styler.ColourTo(pos1,SCE_FORTH_COMMENT); + parse(1,false); + styler.ColourTo(pos2,SCE_FORTH_COMMENT); + }else if(strcmp("(",buffer)==0){ + styler.ColourTo(pos1,SCE_FORTH_COMMENT); + parse(')',true); + if(cur_pos +// The License.txt file describes the conditions under which this software may be distributed. +/***************************************/ +#include +#include +#include +#include +#include +/***************************************/ +#include "Platform.h" +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +/***********************************************/ +static inline bool IsAWordChar(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '%'); +} +/**********************************************/ +static inline bool IsAWordStart(const int ch) { + return (ch < 0x80) && (isalnum(ch)); +} +/***************************************/ +inline bool IsABlank(unsigned int ch) { + return (ch == ' ') || (ch == 0x09) || (ch == 0x0b) ; +} +/***************************************/ +inline bool IsALineEnd(char ch) { + return ((ch == '\n') || (ch == '\r')) ; +} +/***************************************/ +unsigned int GetContinuedPos(unsigned int pos, Accessor &styler) { + while (!IsALineEnd(styler.SafeGetCharAt(pos++))) continue; + if (styler.SafeGetCharAt(pos) == '\n') pos++; + while (IsABlank(styler.SafeGetCharAt(pos++))) continue; + char chCur = styler.SafeGetCharAt(pos); + if (chCur == '&') { + while (IsABlank(styler.SafeGetCharAt(++pos))) continue; + return pos; + } else { + return pos; + } +} +/***************************************/ +static void ColouriseFortranDoc(unsigned int startPos, int length, int initStyle, + WordList *keywordlists[], Accessor &styler, bool isFixFormat) { + WordList &keywords = *keywordlists[0]; + WordList &keywords2 = *keywordlists[1]; + WordList &keywords3 = *keywordlists[2]; + /***************************************/ + int posLineStart = 0, numNonBlank = 0, prevState = 0; + int endPos = startPos + length; + /***************************************/ + // backtrack to the nearest keyword + while ((startPos > 1) && (styler.StyleAt(startPos) != SCE_F_WORD)) { + startPos--; + } + startPos = styler.LineStart(styler.GetLine(startPos)); + initStyle = styler.StyleAt(startPos - 1); + StyleContext sc(startPos, endPos-startPos, initStyle, styler); + /***************************************/ + for (; sc.More(); sc.Forward()) { + // remember the start position of the line + if (sc.atLineStart) { + posLineStart = sc.currentPos; + numNonBlank = 0; + sc.SetState(SCE_F_DEFAULT); + } + if (!IsASpaceOrTab(sc.ch)) numNonBlank ++; + /***********************************************/ + // Handle the fix format generically + int toLineStart = sc.currentPos - posLineStart; + if (isFixFormat && (toLineStart < 6 || toLineStart > 72)) { + if (toLineStart == 0 && (tolower(sc.ch) == 'c' || sc.ch == '*') || sc.ch == '!') { + sc.SetState(SCE_F_COMMENT); + while (!sc.atLineEnd && sc.More()) sc.Forward(); // Until line end + } else if (toLineStart > 72) { + sc.SetState(SCE_F_COMMENT); + while (!sc.atLineEnd && sc.More()) sc.Forward(); // Until line end + } else if (toLineStart < 5) { + if (IsADigit(sc.ch)) + sc.SetState(SCE_F_LABEL); + else + sc.SetState(SCE_F_DEFAULT); + } else if (toLineStart == 5) { + if (!IsASpace(sc.ch) && sc.ch != '0') { + sc.SetState(SCE_F_CONTINUATION); + sc.ForwardSetState(prevState); + } else + sc.SetState(SCE_F_DEFAULT); + } + continue; + } + /***************************************/ + // Handle line continuation generically. + if (!isFixFormat && sc.ch == '&') { + char chTemp = ' '; + int j = 1; + while (IsABlank(chTemp) && j<132) { + chTemp = static_cast(sc.GetRelative(j)); + j++; + } + if (chTemp == '!') { + sc.SetState(SCE_F_CONTINUATION); + if (sc.chNext == '!') sc.ForwardSetState(SCE_F_COMMENT); + } else if (chTemp == '\r' || chTemp == '\n') { + int currentState = sc.state; + sc.SetState(SCE_F_CONTINUATION); + sc.ForwardSetState(SCE_F_DEFAULT); + while (IsASpace(sc.ch) && sc.More()) sc.Forward(); + if (sc.ch == '&') { + sc.SetState(SCE_F_CONTINUATION); + sc.Forward(); + } + sc.SetState(currentState); + } + } + /***************************************/ + // Determine if the current state should terminate. + if (sc.state == SCE_F_OPERATOR) { + sc.SetState(SCE_F_DEFAULT); + } else if (sc.state == SCE_F_NUMBER) { + if (!(IsAWordChar(sc.ch) || sc.ch=='\'' || sc.ch=='\"' || sc.ch=='.')) { + sc.SetState(SCE_F_DEFAULT); + } + } else if (sc.state == SCE_F_IDENTIFIER) { + if (!IsAWordChar(sc.ch) || (sc.ch == '%')) { + char s[100]; + sc.GetCurrentLowered(s, sizeof(s)); + if (keywords.InList(s)) { + sc.ChangeState(SCE_F_WORD); + } else if (keywords2.InList(s)) { + sc.ChangeState(SCE_F_WORD2); + } else if (keywords3.InList(s)) { + sc.ChangeState(SCE_F_WORD3); + } + sc.SetState(SCE_F_DEFAULT); + } + } else if (sc.state == SCE_F_COMMENT || sc.state == SCE_F_PREPROCESSOR) { + if (sc.ch == '\r' || sc.ch == '\n') { + sc.SetState(SCE_F_DEFAULT); + } + } else if (sc.state == SCE_F_STRING1) { + prevState = sc.state; + if (sc.ch == '\'') { + if (sc.chNext == '\'') { + sc.Forward(); + } else { + sc.ForwardSetState(SCE_F_DEFAULT); + prevState = SCE_F_DEFAULT; + } + } else if (sc.atLineEnd) { + sc.ChangeState(SCE_F_STRINGEOL); + sc.ForwardSetState(SCE_F_DEFAULT); + } + } else if (sc.state == SCE_F_STRING2) { + prevState = sc.state; + if (sc.atLineEnd) { + sc.ChangeState(SCE_F_STRINGEOL); + sc.ForwardSetState(SCE_F_DEFAULT); + } else if (sc.ch == '\"') { + if (sc.chNext == '\"') { + sc.Forward(); + } else { + sc.ForwardSetState(SCE_F_DEFAULT); + prevState = SCE_F_DEFAULT; + } + } + } else if (sc.state == SCE_F_OPERATOR2) { + if (sc.ch == '.') { + sc.ForwardSetState(SCE_F_DEFAULT); + } + } else if (sc.state == SCE_F_CONTINUATION) { + sc.SetState(SCE_F_DEFAULT); + } else if (sc.state == SCE_F_LABEL) { + if (!IsADigit(sc.ch)) { + sc.SetState(SCE_F_DEFAULT); + } else { + if (isFixFormat && sc.currentPos-posLineStart > 4) + sc.SetState(SCE_F_DEFAULT); + else if (numNonBlank > 5) + sc.SetState(SCE_F_DEFAULT); + } + } + /***************************************/ + // Determine if a new state should be entered. + if (sc.state == SCE_F_DEFAULT) { + if (sc.ch == '!') { + if (sc.chNext == '$') { + sc.SetState(SCE_F_PREPROCESSOR); + } else { + sc.SetState(SCE_F_COMMENT); + } + } else if ((!isFixFormat) && IsADigit(sc.ch) && numNonBlank == 1) { + sc.SetState(SCE_F_LABEL); + } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { + sc.SetState(SCE_F_NUMBER); + } else if ((tolower(sc.ch) == 'b' || tolower(sc.ch) == 'o' || + tolower(sc.ch) == 'z') && (sc.chNext == '\"' || sc.chNext == '\'')) { + sc.SetState(SCE_F_NUMBER); + sc.Forward(); + } else if (sc.ch == '.' && isalpha(sc.chNext)) { + sc.SetState(SCE_F_OPERATOR2); + } else if (IsAWordStart(sc.ch)) { + sc.SetState(SCE_F_IDENTIFIER); + } else if (sc.ch == '\"') { + sc.SetState(SCE_F_STRING2); + } else if (sc.ch == '\'') { + sc.SetState(SCE_F_STRING1); + } else if (isoperator(static_cast(sc.ch))) { + sc.SetState(SCE_F_OPERATOR); + } + } + } + sc.Complete(); +} +/***************************************/ +// To determine the folding level depending on keywords +static int classifyFoldPointFortran(const char* s, const char* prevWord, const char chNextNonBlank) { + int lev = 0; + if ((strcmp(prevWord, "else") == 0 && strcmp(s, "if") == 0) || strcmp(s, "elseif") == 0) + return -1; + if (strcmp(s, "associate") == 0 || strcmp(s, "block") == 0 + || strcmp(s, "blockdata") == 0 || strcmp(s, "select") == 0 + || strcmp(s, "do") == 0 || strcmp(s, "enum") ==0 + || strcmp(s, "function") == 0 || strcmp(s, "interface") == 0 + || strcmp(s, "module") == 0 || strcmp(s, "program") == 0 + || strcmp(s, "subroutine") == 0 || strcmp(s, "then") == 0 + || (strcmp(s, "type") == 0 && chNextNonBlank != '(') ){ + if (strcmp(prevWord, "end") == 0) + lev = 0; + else + lev = 1; + } else if (strcmp(s, "end") == 0 && chNextNonBlank != '=' + || strcmp(s, "endassociate") == 0 || strcmp(s, "endblock") == 0 + || strcmp(s, "endblockdata") == 0 || strcmp(s, "endselect") == 0 + || strcmp(s, "enddo") == 0 || strcmp(s, "endenum") ==0 + || strcmp(s, "endif") == 0 || strcmp(s, "endforall") == 0 + || strcmp(s, "endfunction") == 0 || strcmp(s, "endinterface") == 0 + || strcmp(s, "endmodule") == 0 || strcmp(s, "endprogram") == 0 + || strcmp(s, "endsubroutine") == 0 || strcmp(s, "endtype") == 0 + || strcmp(s, "endwhere") == 0 + || strcmp(s, "procedure") == 0 ) { // Take care of the module procedure statement + lev = -1; + } else if (strcmp(prevWord, "end") == 0 && strcmp(s, "if") == 0){ // end if + lev = 0; + } + return lev; +} +// Folding the code +static void FoldFortranDoc(unsigned int startPos, int length, int initStyle, + Accessor &styler, bool isFixFormat) { + // + // bool foldComment = styler.GetPropertyInt("fold.comment") != 0; + // Do not know how to fold the comment at the moment. + // + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + unsigned 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]; + char chNextNonBlank; + int styleNext = styler.StyleAt(startPos); + int style = initStyle; + /***************************************/ + int lastStart = 0; + char prevWord[32] = ""; + char Label[6] = ""; + // Variables for do label folding. + static int doLabels[100]; + static int posLabel=-1; + /***************************************/ + for (unsigned int i = startPos; i < endPos; i++) { + char ch = chNext; + chNext = styler.SafeGetCharAt(i + 1); + chNextNonBlank = chNext; + unsigned int j=i+1; + while(IsABlank(chNextNonBlank) && j(tolower(styler[lastStart+k])); + } + s[k] = '\0'; + // Handle the forall and where statement and structure. + if (strcmp(s, "forall") == 0 || strcmp(s, "where") == 0) { + if (strcmp(prevWord, "end") != 0) { + j = i + 1; + char chBrace = '(', chSeek = ')', ch1 = styler.SafeGetCharAt(j); + // Find the position of the first ( + while (ch1 != chBrace && j -1) { + levelCurrent--; + posLabel--; + } + } + } + if (atEOL) { + int lev = levelPrev; + if (visibleChars == 0 && foldCompact) + lev |= SC_FOLDLEVELWHITEFLAG; + if ((levelCurrent > levelPrev) && (visibleChars > 0)) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelPrev = levelCurrent; + visibleChars = 0; + strcpy(prevWord, ""); + } + /***************************************/ + if (!isspacechar(ch)) visibleChars++; + } + /***************************************/ + // Fill in the real level of the next line, keeping the current flags as they will be filled in later + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, levelPrev | flagsNext); +} +/***************************************/ +static const char * const FortranWordLists[] = { + "Primary keywords and identifiers", + "Intrinsic functions", + "Extended and user defined functions", + 0, +}; +/***************************************/ +static void ColouriseFortranDocFreeFormat(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler) { + ColouriseFortranDoc(startPos, length, initStyle, keywordlists, styler, false); +} +/***************************************/ +static void ColouriseFortranDocFixFormat(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler) { + ColouriseFortranDoc(startPos, length, initStyle, keywordlists, styler, true); +} +/***************************************/ +static void FoldFortranDocFreeFormat(unsigned int startPos, int length, int initStyle, + WordList *[], Accessor &styler) { + FoldFortranDoc(startPos, length, initStyle,styler, false); +} +/***************************************/ +static void FoldFortranDocFixFormat(unsigned int startPos, int length, int initStyle, + WordList *[], Accessor &styler) { + FoldFortranDoc(startPos, length, initStyle,styler, true); +} +/***************************************/ +LexerModule lmFortran(SCLEX_FORTRAN, ColouriseFortranDocFreeFormat, "fortran", FoldFortranDocFreeFormat, FortranWordLists); +LexerModule lmF77(SCLEX_F77, ColouriseFortranDocFixFormat, "f77", FoldFortranDocFixFormat, FortranWordLists); diff --git a/scintilla/src/LexGAP.cxx b/scintilla/src/LexGAP.cxx new file mode 100644 index 00000000..bec53b7d --- /dev/null +++ b/scintilla/src/LexGAP.cxx @@ -0,0 +1,263 @@ +// Scintilla source code edit control +/** @file LexGAP.cxx + ** Lexer for the GAP language. (The GAP System for Computational Discrete Algebra) + ** http://www.gap-system.org + **/ +// Copyright 2007 by Istvan Szollosi ( szteven gmail com ) +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +static inline bool IsGAPOperator(char ch) { + if (isalnum(ch)) return false; + if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || + ch == '^' || ch == ',' || ch == '!' || ch == '.' || + ch == '=' || ch == '<' || ch == '>' || ch == '(' || + ch == ')' || ch == ';' || ch == '[' || ch == ']' || + ch == '{' || ch == '}' || ch == ':' ) + return true; + return false; +} + +static void GetRange(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(styler[start + i]); + i++; + } + s[i] = '\0'; +} + +static void ColouriseGAPDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { + + WordList &keywords1 = *keywordlists[0]; + WordList &keywords2 = *keywordlists[1]; + WordList &keywords3 = *keywordlists[2]; + WordList &keywords4 = *keywordlists[3]; + + // Do not leak onto next line + if (initStyle == SCE_GAP_STRINGEOL) initStyle = SCE_GAP_DEFAULT; + + StyleContext sc(startPos, length, initStyle, styler); + + for (; sc.More(); sc.Forward()) { + + // Prevent SCE_GAP_STRINGEOL from leaking back to previous line + if ( sc.atLineStart ) { + if (sc.state == SCE_GAP_STRING) sc.SetState(SCE_GAP_STRING); + if (sc.state == SCE_GAP_CHAR) sc.SetState(SCE_GAP_CHAR); + } + + // 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(); + } + continue; + } + } + + // Determine if the current state should terminate + switch (sc.state) { + case SCE_GAP_OPERATOR : + sc.SetState(SCE_GAP_DEFAULT); + break; + + case SCE_GAP_NUMBER : + if (!IsADigit(sc.ch)) { + if (sc.ch == '\\') { + if (!sc.atLineEnd) { + if (!IsADigit(sc.chNext)) { + sc.Forward(); + sc.ChangeState(SCE_GAP_IDENTIFIER); + } + } + } else if (isalpha(sc.ch) || sc.ch == '_') { + sc.ChangeState(SCE_GAP_IDENTIFIER); + } + else sc.SetState(SCE_GAP_DEFAULT); + } + break; + + case SCE_GAP_IDENTIFIER : + if (!(iswordstart(static_cast(sc.ch)) || sc.ch == '$')) { + if (sc.ch == '\\') sc.Forward(); + else { + char s[1000]; + sc.GetCurrent(s, sizeof(s)); + if (keywords1.InList(s)) { + sc.ChangeState(SCE_GAP_KEYWORD); + } else if (keywords2.InList(s)) { + sc.ChangeState(SCE_GAP_KEYWORD2); + } else if (keywords3.InList(s)) { + sc.ChangeState(SCE_GAP_KEYWORD3); + } else if (keywords4.InList(s)) { + sc.ChangeState(SCE_GAP_KEYWORD4); + } + sc.SetState(SCE_GAP_DEFAULT); + } + } + break; + + case SCE_GAP_COMMENT : + if (sc.atLineEnd) { + sc.SetState(SCE_GAP_DEFAULT); + } + break; + + case SCE_GAP_STRING: + if (sc.atLineEnd) { + sc.ChangeState(SCE_GAP_STRINGEOL); + } else if (sc.ch == '\\') { + if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { + sc.Forward(); + } + } else if (sc.ch == '\"') { + sc.ForwardSetState(SCE_GAP_DEFAULT); + } + break; + + case SCE_GAP_CHAR: + if (sc.atLineEnd) { + sc.ChangeState(SCE_GAP_STRINGEOL); + } else if (sc.ch == '\\') { + if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') { + sc.Forward(); + } + } else if (sc.ch == '\'') { + sc.ForwardSetState(SCE_GAP_DEFAULT); + } + break; + + case SCE_GAP_STRINGEOL: + if (sc.atLineStart) { + sc.SetState(SCE_GAP_DEFAULT); + } + break; + } + + // Determine if a new state should be entered + if (sc.state == SCE_GAP_DEFAULT) { + if (IsGAPOperator(static_cast(sc.ch))) { + sc.SetState(SCE_GAP_OPERATOR); + } + else if (IsADigit(sc.ch)) { + sc.SetState(SCE_GAP_NUMBER); + } else if (isalpha(sc.ch) || sc.ch == '_' || sc.ch == '\\' || sc.ch == '$' || sc.ch == '~') { + sc.SetState(SCE_GAP_IDENTIFIER); + if (sc.ch == '\\') sc.Forward(); + } else if (sc.ch == '#') { + sc.SetState(SCE_GAP_COMMENT); + } else if (sc.ch == '\"') { + sc.SetState(SCE_GAP_STRING); + } else if (sc.ch == '\'') { + sc.SetState(SCE_GAP_CHAR); + } + } + + } + sc.Complete(); +} + +static int ClassifyFoldPointGAP(const char* s) { + int level = 0; + if (strcmp(s, "function") == 0 || + strcmp(s, "do") == 0 || + strcmp(s, "if") == 0 || + strcmp(s, "repeat") == 0 ) { + level = 1; + } else if (strcmp(s, "end") == 0 || + strcmp(s, "od") == 0 || + strcmp(s, "fi") == 0 || + strcmp(s, "until") == 0 ) { + level = -1; + } + return level; +} + +static void FoldGAPDoc( unsigned int startPos, int length, int initStyle, WordList** , Accessor &styler) { + unsigned 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 (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 (stylePrev != SCE_GAP_KEYWORD && style == SCE_GAP_KEYWORD) { + // Store last word start point. + lastStart = i; + } + + if (stylePrev == SCE_GAP_KEYWORD) { + if(iswordchar(ch) && !iswordchar(chNext)) { + char s[100]; + GetRange(lastStart, i, styler, s, sizeof(s)); + levelCurrent += ClassifyFoldPointGAP(s); + } + } + + if (atEOL) { + int lev = levelPrev; + if ((levelCurrent > levelPrev) && (visibleChars > 0)) + lev |= SC_FOLDLEVELHEADERFLAG; + if (lev != styler.LevelAt(lineCurrent)) { + styler.SetLevel(lineCurrent, lev); + } + lineCurrent++; + levelPrev = levelCurrent; + visibleChars = 0; + } + + if (!isspacechar(ch)) + visibleChars++; + } + + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, levelPrev | flagsNext); +} + +static const char * const GAPWordListDesc[] = { + "Keywords 1", + "Keywords 2", + "Keywords 3 (unused)", + "Keywords 4 (unused)", + 0 +}; + +LexerModule lmGAP( + SCLEX_GAP, + ColouriseGAPDoc, + "gap", + FoldGAPDoc, + GAPWordListDesc); diff --git a/scintilla/src/LexGen.py b/scintilla/src/LexGen.py new file mode 100644 index 00000000..455d11ef --- /dev/null +++ b/scintilla/src/LexGen.py @@ -0,0 +1,236 @@ +# LexGen.py - implemented 2002 by Neil Hodgson neilh@scintilla.org +# Released to the public domain. + +# Regenerate the Scintilla and SciTE source files that list +# all the lexers and all the properties files. +# Should be run whenever a new lexer is added or removed. +# Requires Python 2.4 or later +# Most files are regenerated in place with templates stored in comments. +# The VS .NET project file is generated into a different file as the +# VS .NET environment will not retain comments when modifying the file. +# The files are copied to a string apart from sections between a +# ++Autogenerated comment and a --Autogenerated comment which is +# generated by the CopyWithInsertion function. After the whole +# string is instantiated, it is compared with the target file and +# if different the file is rewritten. +# Does not regenerate the Visual C++ 6 project files but does the VS .NET +# project file. + +import string +import sys +import os +import glob + +# EOL constants +CR = "\r" +LF = "\n" +CRLF = "\r\n" +if sys.platform == "win32": + NATIVE = CRLF +else: + # Yes, LF is the native EOL even on Mac OS X. CR is just for + # Mac OS <=9 (a.k.a. "Mac Classic") + NATIVE = LF + +# Automatically generated sections contain start and end comments, +# a definition line and the results. +# The results are replaced by regenerating based on the definition line. +# The definition line is a comment prefix followed by "**". +# If there is a digit after the ** then this indicates which list to use +# and the digit and next character are not part of the definition +# Backslash is used as an escape within the definition line. +# The part between \( and \) is repeated for each item in the list. +# \* is replaced by each list item. \t, and \n are tab and newline. +def CopyWithInsertion(input, commentPrefix, retainDefs, eolType, *lists): + copying = 1 + listid = 0 + output = [] + for line in input.splitlines(0): + isStartGenerated = line.startswith(commentPrefix + "++Autogenerated") + if copying and not isStartGenerated: + output.append(line) + if isStartGenerated: + if retainDefs: + output.append(line) + copying = 0 + definition = "" + elif not copying and line.startswith(commentPrefix + "**"): + if retainDefs: + output.append(line) + definition = line[len(commentPrefix + "**"):] + listid = 0 + if definition[0] in string.digits: + listid = int(definition[:1]) + definition = definition[2:] + # Hide double slashes as a control character + definition = definition.replace("\\\\", "\001") + # Do some normal C style transforms + definition = definition.replace("\\n", "\n") + definition = definition.replace("\\t", "\t") + # Get the doubled backslashes back as single backslashes + definition = definition.replace("\001", "\\") + startRepeat = definition.find("\\(") + endRepeat = definition.find("\\)") + intro = definition[:startRepeat] + out = "" + if intro.endswith("\n"): + pos = 0 + else: + pos = len(intro) + out += intro + middle = definition[startRepeat+2:endRepeat] + for i in lists[listid]: + item = middle.replace("\\*", i) + if pos and (pos + len(item) >= 80): + out += "\\\n" + pos = 0 + out += item + pos += len(item) + if item.endswith("\n"): + pos = 0 + outro = definition[endRepeat+2:] + out += outro + out = out.replace("\n", eolType) # correct EOLs in generated content + output.append(out) + elif line.startswith(commentPrefix + "--Autogenerated"): + copying = 1 + if retainDefs: + output.append(line) + output = [line.rstrip(" \t") for line in output] # trim trailing whitespace + return eolType.join(output) + eolType + +def UpdateFile(filename, updated): + """ If the file is different to updated then copy updated + into the file else leave alone so CVS and make don't treat + it as modified. """ + try: + infile = open(filename, "rb") + except IOError: # File is not there yet + out = open(filename, "wb") + out.write(updated) + out.close() + print "New", filename + return + original = infile.read() + infile.close() + if updated != original: + os.unlink(filename) + out = open(filename, "wb") + out.write(updated) + out.close() + print "Changed", filename + #~ else: + #~ print "Unchanged", filename + +def Generate(inpath, outpath, commentPrefix, eolType, *lists): + """Generate 'outpath' from 'inpath'. + + "eolType" indicates the type of EOLs to use in the generated + file. It should be one of following constants: LF, CRLF, + CR, or NATIVE. + """ + #print "generate '%s' -> '%s' (comment prefix: %r, eols: %r)"\ + # % (inpath, outpath, commentPrefix, eolType) + try: + infile = open(inpath, "r") + except IOError: + print "Can not open", inpath + return + original = infile.read() + infile.close() + updated = CopyWithInsertion(original, commentPrefix, + inpath == outpath, eolType, *lists) + UpdateFile(outpath, updated) + +def Regenerate(filename, commentPrefix, eolType, *lists): + """Regenerate the given file. + + "eolType" indicates the type of EOLs to use in the generated + file. It should be one of following constants: LF, CRLF, + CR, or NATIVE. + """ + Generate(filename, filename, commentPrefix, eolType, *lists) + +def FindModules(lexFile): + modules = [] + f = open(lexFile) + for l in f.readlines(): + if l.startswith("LexerModule"): + l = l.replace("(", " ") + modules.append(l.split()[1]) + return modules + +knownIrregularProperties = [ + "fold", + "styling.within.preprocessor", + "tab.timmy.whinge.level", + "asp.default.language", + "html.tags.case.sensitive", + "ps.level", + "ps.tokenize", + "sql.backslash.escapes", + "nsis.uservars", + "nsis.ignorecase" +] + +def FindProperties(lexFile): + properties = set() + f = open(lexFile) + for l in f.readlines(): + if "GetProperty" in l: + l = l.strip() + if not l.startswith("//"): # Drop comments + propertyName = l.split("\"")[1] + if propertyName.lower() == propertyName: + # Only allow lower case property names + if propertyName in knownIrregularProperties or \ + propertyName.startswith("fold.") or \ + propertyName.startswith("lexer."): + properties.add(propertyName) + return properties + +def ciCompare(a,b): + return cmp(a.lower(), b.lower()) + +def RegenerateAll(): + root="../../" + + # Find all the lexer source code files + lexFilePaths = glob.glob(root + "scintilla/src/Lex*.cxx") + lexFiles = [os.path.basename(f)[:-4] for f in lexFilePaths] + print lexFiles + lexerModules = [] + lexerProperties = set() + for lexFile in lexFilePaths: + lexerModules.extend(FindModules(lexFile)) + lexerProperties.update(FindProperties(lexFile)) + lexerModules.sort(ciCompare) + lexerProperties.remove("fold.comment.python") + lexerProperties = list(lexerProperties) + lexerProperties.sort(ciCompare) + + # Find all the SciTE properties files + otherProps = ["abbrev.properties", "Embedded.properties", "SciTEGlobal.properties", "SciTE.properties"] + if os.path.exists(root + "scite"): + propFilePaths = glob.glob(root + "scite/src/*.properties") + propFiles = [os.path.basename(f) for f in propFilePaths if os.path.basename(f) not in otherProps] + propFiles.sort(ciCompare) + print propFiles + + Regenerate(root + "scintilla/src/KeyWords.cxx", "//", NATIVE, lexerModules) + Regenerate(root + "scintilla/win32/makefile", "#", NATIVE, lexFiles) + Regenerate(root + "scintilla/win32/scintilla.mak", "#", NATIVE, lexFiles) + Regenerate(root + "scintilla/win32/scintilla_vc6.mak", "#", NATIVE, lexFiles) + # Use Unix EOLs for gtk Makefiles so they work for Linux users when + # extracted from the Scintilla source ZIP (typically created on + # Windows). + Regenerate(root + "scintilla/gtk/makefile", "#", LF, lexFiles) + Regenerate(root + "scintilla/gtk/scintilla.mak", "#", NATIVE, lexFiles) + Regenerate(root + "scintilla/macosx/makefile", "#", LF, lexFiles) + if os.path.exists(root + "scite"): + Regenerate(root + "scite/win32/makefile", "#", NATIVE, lexFiles, propFiles) + Regenerate(root + "scite/win32/scite.mak", "#", NATIVE, lexFiles, propFiles) + Generate(root + "scite/boundscheck/vcproj.gen", + root + "scite/boundscheck/SciTE.vcproj", "#", NATIVE, lexFiles) + +RegenerateAll() diff --git a/scintilla/src/LexGui4Cli.cxx b/scintilla/src/LexGui4Cli.cxx new file mode 100644 index 00000000..46f78410 --- /dev/null +++ b/scintilla/src/LexGui4Cli.cxx @@ -0,0 +1,314 @@ +// Scintilla source code edit control +// Copyright 1998-2002 by Neil Hodgson +/* +This is the Lexer for Gui4Cli, included in SciLexer.dll +- by d. Keletsekis, 2/10/2003 + +To add to SciLexer.dll: +1. Add the values below to INCLUDE\Scintilla.iface +2. Run the include/HFacer.py script +3. Run the src/lexGen.py script + +val SCE_GC_DEFAULT=0 +val SCE_GC_COMMENTLINE=1 +val SCE_GC_COMMENTBLOCK=2 +val SCE_GC_GLOBAL=3 +val SCE_GC_EVENT=4 +val SCE_GC_ATTRIBUTE=5 +val SCE_GC_CONTROL=6 +val SCE_GC_COMMAND=7 +val SCE_GC_STRING=8 +val SCE_GC_OPERATOR=9 +*/ + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +#define debug Platform::DebugPrintf + +static inline bool IsAWordChar(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch =='\\'); +} + +static inline bool IsAWordStart(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.'); +} + +inline bool isGCOperator(int ch) +{ if (isalnum(ch)) + return false; + // '.' left out as it is used to make up numbers + if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || + ch == '(' || ch == ')' || ch == '=' || ch == '%' || + ch == '[' || ch == ']' || ch == '<' || ch == '>' || + ch == ',' || ch == ';' || ch == ':') + return true; + return false; +} + +#define isSpace(x) ((x)==' ' || (x)=='\t') +#define isNL(x) ((x)=='\n' || (x)=='\r') +#define isSpaceOrNL(x) (isSpace(x) || isNL(x)) +#define BUFFSIZE 500 +#define isFoldPoint(x) ((styler.LevelAt(x) & SC_FOLDLEVELNUMBERMASK) == 1024) + +static void colorFirstWord(WordList *keywordlists[], Accessor &styler, + StyleContext *sc, char *buff, int length, int) +{ + int c = 0; + while (sc->More() && isSpaceOrNL(sc->ch)) + { sc->Forward(); + } + styler.ColourTo(sc->currentPos - 1, sc->state); + + if (!IsAWordChar(sc->ch)) // comment, marker, etc.. + return; + + while (sc->More() && !isSpaceOrNL(sc->ch) && (c < length-1) && !isGCOperator(sc->ch)) + { buff[c] = static_cast(sc->ch); + ++c; sc->Forward(); + } + buff[c] = '\0'; + char *p = buff; + while (*p) // capitalize.. + { if (islower(*p)) *p = static_cast(toupper(*p)); + ++p; + } + + WordList &kGlobal = *keywordlists[0]; // keyword lists set by the user + WordList &kEvent = *keywordlists[1]; + WordList &kAttribute = *keywordlists[2]; + WordList &kControl = *keywordlists[3]; + WordList &kCommand = *keywordlists[4]; + + int state = 0; + // int level = styler.LevelAt(line) & SC_FOLDLEVELNUMBERMASK; + // debug ("line = %d, level = %d", line, level); + + if (kGlobal.InList(buff)) state = SCE_GC_GLOBAL; + else if (kAttribute.InList(buff)) state = SCE_GC_ATTRIBUTE; + else if (kControl.InList(buff)) state = SCE_GC_CONTROL; + else if (kCommand.InList(buff)) state = SCE_GC_COMMAND; + else if (kEvent.InList(buff)) state = SCE_GC_EVENT; + + if (state) + { sc->ChangeState(state); + styler.ColourTo(sc->currentPos - 1, sc->state); + sc->ChangeState(SCE_GC_DEFAULT); + } + else + { sc->ChangeState(SCE_GC_DEFAULT); + styler.ColourTo(sc->currentPos - 1, sc->state); + } +} + +// Main colorizing function called by Scintilla +static void +ColouriseGui4CliDoc(unsigned int startPos, int length, int initStyle, + WordList *keywordlists[], Accessor &styler) +{ + styler.StartAt(startPos); + + int quotestart = 0, oldstate, currentline = styler.GetLine(startPos); + styler.StartSegment(startPos); + bool noforward; + char buff[BUFFSIZE+1]; // buffer for command name + + StyleContext sc(startPos, length, initStyle, styler); + buff[0] = '\0'; // cbuff = 0; + + if (sc.state != SCE_GC_COMMENTBLOCK) // colorize 1st word.. + colorFirstWord(keywordlists, styler, &sc, buff, BUFFSIZE, currentline); + + while (sc.More()) + { noforward = 0; + + switch (sc.ch) + { + case '/': + if (sc.state == SCE_GC_COMMENTBLOCK || sc.state == SCE_GC_STRING) + break; + if (sc.chNext == '/') // line comment + { sc.SetState (SCE_GC_COMMENTLINE); + sc.Forward(); + styler.ColourTo(sc.currentPos, sc.state); + } + else if (sc.chNext == '*') // block comment + { sc.SetState(SCE_GC_COMMENTBLOCK); + sc.Forward(); + styler.ColourTo(sc.currentPos, sc.state); + } + else + styler.ColourTo(sc.currentPos, sc.state); + break; + + case '*': // end of comment block, or operator.. + if (sc.state == SCE_GC_STRING) + break; + if (sc.state == SCE_GC_COMMENTBLOCK && sc.chNext == '/') + { sc.Forward(); + styler.ColourTo(sc.currentPos, sc.state); + sc.ChangeState (SCE_GC_DEFAULT); + } + else + styler.ColourTo(sc.currentPos, sc.state); + break; + + case '\'': case '\"': // strings.. + if (sc.state == SCE_GC_COMMENTBLOCK || sc.state == SCE_GC_COMMENTLINE) + break; + if (sc.state == SCE_GC_STRING) + { if (sc.ch == quotestart) // match same quote char.. + { styler.ColourTo(sc.currentPos, sc.state); + sc.ChangeState(SCE_GC_DEFAULT); + quotestart = 0; + } } + else + { styler.ColourTo(sc.currentPos - 1, sc.state); + sc.ChangeState(SCE_GC_STRING); + quotestart = sc.ch; + } + break; + + case ';': // end of commandline character + if (sc.state != SCE_GC_COMMENTBLOCK && sc.state != SCE_GC_COMMENTLINE && + sc.state != SCE_GC_STRING) + { + styler.ColourTo(sc.currentPos - 1, sc.state); + styler.ColourTo(sc.currentPos, SCE_GC_OPERATOR); + sc.ChangeState(SCE_GC_DEFAULT); + sc.Forward(); + colorFirstWord(keywordlists, styler, &sc, buff, BUFFSIZE, currentline); + noforward = 1; // don't move forward - already positioned at next char.. + } + break; + + case '+': case '-': case '=': case '!': // operators.. + case '<': case '>': case '&': case '|': case '$': + if (sc.state != SCE_GC_COMMENTBLOCK && sc.state != SCE_GC_COMMENTLINE && + sc.state != SCE_GC_STRING) + { + styler.ColourTo(sc.currentPos - 1, sc.state); + styler.ColourTo(sc.currentPos, SCE_GC_OPERATOR); + sc.ChangeState(SCE_GC_DEFAULT); + } + break; + + case '\\': // escape - same as operator, but also mark in strings.. + if (sc.state != SCE_GC_COMMENTBLOCK && sc.state != SCE_GC_COMMENTLINE) + { + oldstate = sc.state; + styler.ColourTo(sc.currentPos - 1, sc.state); + sc.Forward(); // mark also the next char.. + styler.ColourTo(sc.currentPos, SCE_GC_OPERATOR); + sc.ChangeState(oldstate); + } + break; + + case '\n': case '\r': + ++currentline; + if (sc.state == SCE_GC_COMMENTLINE) + { styler.ColourTo(sc.currentPos, sc.state); + sc.ChangeState (SCE_GC_DEFAULT); + } + else if (sc.state != SCE_GC_COMMENTBLOCK) + { colorFirstWord(keywordlists, styler, &sc, buff, BUFFSIZE, currentline); + noforward = 1; // don't move forward - already positioned at next char.. + } + break; + +// case ' ': case '\t': +// default : + } + + if (!noforward) sc.Forward(); + + } + sc.Complete(); +} + +// Main folding function called by Scintilla - (based on props (.ini) files function) +static void FoldGui4Cli(unsigned int startPos, int length, int, + WordList *[], Accessor &styler) +{ + bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + + unsigned int endPos = startPos + length; + int visibleChars = 0; + int lineCurrent = styler.GetLine(startPos); + + char chNext = styler[startPos]; + int styleNext = styler.StyleAt(startPos); + bool headerPoint = false; + + for (unsigned int i = startPos; i < endPos; i++) + { + char ch = chNext; + chNext = styler[i+1]; + + int style = styleNext; + styleNext = styler.StyleAt(i + 1); + bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); + + if (style == SCE_GC_EVENT || style == SCE_GC_GLOBAL) + { headerPoint = true; // fold at events and globals + } + + if (atEOL) + { int lev = SC_FOLDLEVELBASE+1; + + if (headerPoint) + lev = SC_FOLDLEVELBASE; + + if (visibleChars == 0 && foldCompact) + lev |= SC_FOLDLEVELWHITEFLAG; + + if (headerPoint) + lev |= SC_FOLDLEVELHEADERFLAG; + + if (lev != styler.LevelAt(lineCurrent)) // set level, if not already correct + { styler.SetLevel(lineCurrent, lev); + } + + lineCurrent++; // re-initialize our flags + visibleChars = 0; + headerPoint = false; + } + + if (!(isspacechar(ch))) // || (style == SCE_GC_COMMENTLINE) || (style != SCE_GC_COMMENTBLOCK))) + visibleChars++; + } + + int lev = headerPoint ? SC_FOLDLEVELBASE : SC_FOLDLEVELBASE+1; + int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; + styler.SetLevel(lineCurrent, lev | flagsNext); +} + +// I have no idea what these are for.. probably accessible by some message. +static const char * const gui4cliWordListDesc[] = { + "Globals", "Events", "Attributes", "Control", "Commands", + 0 +}; + +// Declare language & pass our function pointers to Scintilla +LexerModule lmGui4Cli(SCLEX_GUI4CLI, ColouriseGui4CliDoc, "gui4cli", FoldGui4Cli, gui4cliWordListDesc); + +#undef debug + + diff --git a/scintilla/src/LexHTML.cxx b/scintilla/src/LexHTML.cxx new file mode 100644 index 00000000..f43a9277 --- /dev/null +++ b/scintilla/src/LexHTML.cxx @@ -0,0 +1,2106 @@ +// Scintilla source code edit control +/** @file LexHTML.cxx + ** Lexer for HTML. + **/ +// Copyright 1998-2005 by Neil Hodgson +// The License.txt file describes the conditions under which this software may be distributed. + +#include +#include +#include +#include +#include + +#include "Platform.h" + +#include "PropSet.h" +#include "Accessor.h" +#include "StyleContext.h" +#include "KeyWords.h" +#include "Scintilla.h" +#include "SciLexer.h" +#include "CharacterSet.h" + +#ifdef SCI_NAMESPACE +using namespace Scintilla; +#endif + +#define SCE_HA_JS (SCE_HJA_START - SCE_HJ_START) +#define SCE_HA_VBS (SCE_HBA_START - SCE_HB_START) +#define SCE_HA_PYTHON (SCE_HPA_START - SCE_HP_START) + +enum script_type { eScriptNone = 0, eScriptJS, eScriptVBS, eScriptPython, eScriptPHP, eScriptXML, eScriptSGML, eScriptSGMLblock }; +enum script_mode { eHtml = 0, eNonHtmlScript, eNonHtmlPreProc, eNonHtmlScriptPreProc }; + +static inline bool IsAWordChar(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_'); +} + +static inline bool IsAWordStart(const int ch) { + return (ch < 0x80) && (isalnum(ch) || ch == '_'); +} + +inline bool IsOperator(int ch) { + if (isascii(ch) && isalnum(ch)) + return false; + // '.' left out as it is used to make up numbers + if (ch == '%' || ch == '^' || ch == '&' || ch == '*' || + ch == '(' || ch == ')' || ch == '-' || ch == '+' || + ch == '=' || ch == '|' || ch == '{' || ch == '}' || + ch == '[' || ch == ']' || ch == ':' || ch == ';' || + ch == '<' || ch == '>' || ch == ',' || ch == '/' || + ch == '?' || ch == '!' || ch == '.' || ch == '~') + return true; + return false; +} + +static inline int MakeLowerCase(int ch) { + if (ch < 'A' || ch > 'Z') + return ch; + else + return ch - 'A' + 'a'; +} + +static void GetTextSegment(Accessor &styler, unsigned int start, unsigned int end, char *s, size_t len) { + size_t i = 0; + for (; (i < end - start + 1) && (i < len-1); i++) { + s[i] = static_cast(MakeLowerCase(styler[start + i])); + } + s[i] = '\0'; +} + +static script_type segIsScriptingIndicator(Accessor &styler, unsigned int start, unsigned int end, script_type prevValue) { + char s[100]; + GetTextSegment(styler, start, end, s, sizeof(s)); + //Platform::DebugPrintf("Scripting indicator [%s]\n", s); + //Don + //if (strstr(s, "src")) // External script + //return eScriptNone; + //nod + if (strstr(s, "vbs")) + return eScriptVBS; + if (strstr(s, "pyth")) + return eScriptPython; + if (strstr(s, "javas")) + return eScriptJS; + if (strstr(s, "jscr")) + return eScriptJS; + if (strstr(s, "php")) + return eScriptPHP; + if (strstr(s, "xml")) { + const char *xml = strstr(s, "xml"); + for (const char *t=s; t= SCE_HP_START) && (state <= SCE_HP_IDENTIFIER)) { + return eScriptPython; + } else if ((state >= SCE_HB_START) && (state <= SCE_HB_STRINGEOL)) { + return eScriptVBS; + } else if ((state >= SCE_HJ_START) && (state <= SCE_HJ_REGEX)) { + return eScriptJS; + } else if ((state >= SCE_HPHP_DEFAULT) && (state <= SCE_HPHP_COMMENTLINE)) { + return eScriptPHP; + } else if ((state >= SCE_H_SGML_DEFAULT) && (state < SCE_H_SGML_BLOCK_DEFAULT)) { + return eScriptSGML; + } else if (state == SCE_H_SGML_BLOCK_DEFAULT) { + return eScriptSGMLblock; + } else { + return eScriptNone; + } +} + +static int statePrintForState(int state, script_mode inScriptType) { + int StateToPrint = state; + + if (state >= SCE_HJ_START) { + if ((state >= SCE_HP_START) && (state <= SCE_HP_IDENTIFIER)) { + StateToPrint = state + ((inScriptType == eNonHtmlScript) ? 0 : SCE_HA_PYTHON); + } else if ((state >= SCE_HB_START) && (state <= SCE_HB_STRINGEOL)) { + StateToPrint = state + ((inScriptType == eNonHtmlScript) ? 0 : SCE_HA_VBS); + } else if ((state >= SCE_HJ_START) && (state <= SCE_HJ_REGEX)) { + StateToPrint = state + ((inScriptType == eNonHtmlScript) ? 0 : SCE_HA_JS); + } + } + + return StateToPrint; +} + +static int stateForPrintState(int StateToPrint) { + int state; + + if ((StateToPrint >= SCE_HPA_START) && (StateToPrint <= SCE_HPA_IDENTIFIER)) { + state = StateToPrint - SCE_HA_PYTHON; + } else if ((StateToPrint >= SCE_HBA_START) && (StateToPrint <= SCE_HBA_STRINGEOL)) { + state = StateToPrint - SCE_HA_VBS; + } else if ((StateToPrint >= SCE_HJA_START) && (StateToPrint <= SCE_HJA_REGEX)) { + state = StateToPrint - SCE_HA_JS; + } else { + state = StateToPrint; + } + + return state; +} + +static inline bool IsNumber(unsigned int start, Accessor &styler) { + return IsADigit(styler[start]) || (styler[start] == '.') || + (styler[start] == '-') || (styler[start] == '#'); +} + +static inline bool isStringState(int state) { + bool bResult; + + switch (state) { + case SCE_HJ_DOUBLESTRING: + case SCE_HJ_SINGLESTRING: + case SCE_HJA_DOUBLESTRING: + case SCE_HJA_SINGLESTRING: + case SCE_HB_STRING: + case SCE_HBA_STRING: + case SCE_HP_STRING: + case SCE_HP_CHARACTER: + case SCE_HP_TRIPLE: + case SCE_HP_TRIPLEDOUBLE: + case SCE_HPA_STRING: + case SCE_HPA_CHARACTER: + case SCE_HPA_TRIPLE: + case SCE_HPA_TRIPLEDOUBLE: + case SCE_HPHP_HSTRING: + case SCE_HPHP_SIMPLESTRING: + case SCE_HPHP_HSTRING_VARIABLE: + case SCE_HPHP_COMPLEX_VARIABLE: + bResult = true; + break; + default : + bResult = false; + break; + } + return bResult; +} + +static inline bool stateAllowsTermination(int state) { + bool allowTermination = !isStringState(state); + if (allowTermination) { + switch (state) { + case SCE_HB_COMMENTLINE: + case SCE_HPHP_COMMENT: + case SCE_HP_COMMENTLINE: + case SCE_HPA_COMMENTLINE: + allowTermination = false; + } + } + return allowTermination; +} + +// not really well done, since it's only comments that should lex the %> and <% +static inline bool isCommentASPState(int state) { + bool bResult; + + switch (state) { + case SCE_HJ_COMMENT: + case SCE_HJ_COMMENTLINE: + case SCE_HJ_COMMENTDOC: + case SCE_HB_COMMENTLINE: + case SCE_HP_COMMENTLINE: + case SCE_HPHP_COMMENT: + case SCE_HPHP_COMMENTLINE: + bResult = true; + break; + default : + bResult = false; + break; + } + return bResult; +} + +static void classifyAttribHTML(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { + bool wordIsNumber = IsNumber(start, styler); + char chAttr = SCE_H_ATTRIBUTEUNKNOWN; + if (wordIsNumber) { + chAttr = SCE_H_NUMBER; + } else { + char s[100]; + GetTextSegment(styler, start, end, s, sizeof(s)); + if (keywords.InList(s)) + chAttr = SCE_H_ATTRIBUTE; + } + if ((chAttr == SCE_H_ATTRIBUTEUNKNOWN) && !keywords) + // No keywords -> all are known + chAttr = SCE_H_ATTRIBUTE; + styler.ColourTo(end, chAttr); +} + +static int classifyTagHTML(unsigned int start, unsigned int end, + WordList &keywords, Accessor &styler, bool &tagDontFold, + bool caseSensitive, bool isXml) { + char s[30 + 2]; + // Copy after the '<' + unsigned int i = 0; + for (unsigned int cPos = start; cPos <= end && i < 30; cPos++) { + char ch = styler[cPos]; + if ((ch != '<') && (ch != '/')) { + s[i++] = caseSensitive ? ch : static_cast(MakeLowerCase(ch)); + } + } + + //The following is only a quick hack, to see if this whole thing would work + //we first need the tagname with a trailing space... + s[i] = ' '; + s[i+1] = '\0'; + + // if the current language is XML, I can fold any tag + // if the current language is HTML, I don't want to fold certain tags (input, meta, etc.) + //...to find it in the list of no-container-tags + tagDontFold = (!isXml) && (NULL != strstr("meta link img area br hr input ",s)); + + //now we can remove the trailing space + s[i] = '\0'; + + bool isScript = false; + char chAttr = SCE_H_TAGUNKNOWN; + if (s[0] == '!') { + chAttr = SCE_H_SGML_DEFAULT; + } else if (s[0] == '/') { // Closing tag + if (keywords.InList(s + 1)) + chAttr = SCE_H_TAG; + } else { + if (keywords.InList(s)) { + chAttr = SCE_H_TAG; + isScript = 0 == strcmp(s, "script"); + } + } + if ((chAttr == SCE_H_TAGUNKNOWN) && !keywords) { + // No keywords -> all are known + chAttr = SCE_H_TAG; + isScript = 0 == strcmp(s, "script"); + } + styler.ColourTo(end, chAttr); + return isScript ? SCE_H_SCRIPT : chAttr; +} + +static void classifyWordHTJS(unsigned int start, unsigned int end, + WordList &keywords, Accessor &styler, script_mode inScriptType) { + char chAttr = SCE_HJ_WORD; + bool wordIsNumber = IsADigit(styler[start]) || (styler[start] == '.'); + if (wordIsNumber) + chAttr = SCE_HJ_NUMBER; + else { + char s[30 + 1]; + unsigned int i = 0; + for (; i < end - start + 1 && i < 30; i++) { + s[i] = styler[start + i]; + } + s[i] = '\0'; + if (keywords.InList(s)) + chAttr = SCE_HJ_KEYWORD; + } + styler.ColourTo(end, statePrintForState(chAttr, inScriptType)); +} + +static int classifyWordHTVB(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, script_mode inScriptType) { + char chAttr = SCE_HB_IDENTIFIER; + bool wordIsNumber = IsADigit(styler[start]) || (styler[start] == '.'); + if (wordIsNumber) + chAttr = SCE_HB_NUMBER; + else { + char s[100]; + GetTextSegment(styler, start, end, s, sizeof(s)); + if (keywords.InList(s)) { + chAttr = SCE_HB_WORD; + if (strcmp(s, "rem") == 0) + chAttr = SCE_HB_COMMENTLINE; + } + } + styler.ColourTo(end, statePrintForState(chAttr, inScriptType)); + if (chAttr == SCE_HB_COMMENTLINE) + return SCE_HB_COMMENTLINE; + else + return SCE_HB_DEFAULT; +} + +static void classifyWordHTPy(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char *prevWord, script_mode inScriptType) { + bool wordIsNumber = IsADigit(styler[start]); + char s[30 + 1]; + unsigned int i = 0; + for (; i < end - start + 1 && i < 30; i++) { + s[i] = styler[start + i]; + } + s[i] = '\0'; + char chAttr = SCE_HP_IDENTIFIER; + if (0 == strcmp(prevWord, "class")) + chAttr = SCE_HP_CLASSNAME; + else if (0 == strcmp(prevWord, "def")) + chAttr = SCE_HP_DEFNAME; + else if (wordIsNumber) + chAttr = SCE_HP_NUMBER; + else if (keywords.InList(s)) + chAttr = SCE_HP_WORD; + styler.ColourTo(end, statePrintForState(chAttr, inScriptType)); + strcpy(prevWord, s); +} + +// Update the word colour to default or keyword +// Called when in a PHP word +static void classifyWordHTPHP(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { + char chAttr = SCE_HPHP_DEFAULT; + bool wordIsNumber = IsADigit(styler[start]) || (styler[start] == '.' && start+1 <= end && IsADigit(styler[start+1])); + if (wordIsNumber) + chAttr = SCE_HPHP_NUMBER; + else { + char s[100]; + GetTextSegment(styler, start, end, s, sizeof(s)); + if (keywords.InList(s)) + chAttr = SCE_HPHP_WORD; + } + styler.ColourTo(end, chAttr); +} + +static bool isWordHSGML(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { + char s[30 + 1]; + unsigned int i = 0; + for (; i < end - start + 1 && i < 30; i++) { + s[i] = styler[start + i]; + } + s[i] = '\0'; + return keywords.InList(s); +} + +static bool isWordCdata(unsigned int start, unsigned int end, Accessor &styler) { + char s[30 + 1]; + unsigned int i = 0; + for (; i < end - start + 1 && i < 30; i++) { + s[i] = styler[start + i]; + } + s[i] = '\0'; + return (0 == strcmp(s, "[CDATA[")); +} + +// Return the first state to reach when entering a scripting language +static int StateForScript(script_type scriptLanguage) { + int Result; + switch (scriptLanguage) { + // Modif by Don + /* + case eScriptVBS: + Result = SCE_HB_START; + break; + */ + case eScriptJS: + Result = SCE_HJ_START; + break; + // Fidom by Don + case eScriptPython: + Result = SCE_HP_START; + break; + case eScriptPHP: + Result = SCE_HPHP_DEFAULT; + break; + case eScriptXML: + Result = SCE_H_TAGUNKNOWN; + break; + case eScriptSGML: + Result = SCE_H_SGML_DEFAULT; + break; + default : + // Modif by Don + //Result = SCE_HJ_START; + Result = SCE_HB_START; + // Fidom by Don + break; + } + return Result; +} + +static inline bool ishtmlwordchar(int ch) { + return !isascii(ch) || + (isalnum(ch) || ch == '.' || ch == '-' || ch == '_' || ch == ':' || ch == '!' || ch == '#'); +} + +static inline bool issgmlwordchar(int ch) { + return !isascii(ch) || + (isalnum(ch) || ch == '.' || ch == '_' || ch == ':' || ch == '!' || ch == '#' || ch == '['); +} + +static inline bool IsPhpWordStart(int ch) { + return (isascii(ch) && (isalpha(ch) || (ch == '_'))) || (ch >= 0x7f); +} + +static inline bool IsPhpWordChar(int ch) { + return IsADigit(ch) || IsPhpWordStart(ch); +} + +static bool InTagState(int state) { + return state == SCE_H_TAG || state == SCE_H_TAGUNKNOWN || + state == SCE_H_SCRIPT || + state == SCE_H_ATTRIBUTE || state == SCE_H_ATTRIBUTEUNKNOWN || + state == SCE_H_NUMBER || state == SCE_H_OTHER || + state == SCE_H_DOUBLESTRING || state == SCE_H_SINGLESTRING; +} + +static bool IsCommentState(const int state) { + return state == SCE_H_COMMENT || state == SCE_H_SGML_COMMENT; +} + +static bool IsScriptCommentState(const int state) { + return state == SCE_HJ_COMMENT || state == SCE_HJ_COMMENTLINE || state == SCE_HJA_COMMENT || + state == SCE_HJA_COMMENTLINE || state == SCE_HB_COMMENTLINE || state == SCE_HBA_COMMENTLINE; +} + +static bool isLineEnd(int ch) { + return ch == '\r' || ch == '\n'; +} + +static bool isOKBeforeRE(int ch) { + return (ch == '(') || (ch == '=') || (ch == ','); +} + +static bool isPHPStringState(int state) { + return + (state == SCE_HPHP_HSTRING) || + (state == SCE_HPHP_SIMPLESTRING) || + (state == SCE_HPHP_HSTRING_VARIABLE) || + (state == SCE_HPHP_COMPLEX_VARIABLE); +} + +static int FindPhpStringDelimiter(char *phpStringDelimiter, const int phpStringDelimiterSize, int i, const int lengthDoc, Accessor &styler) { + int j; + while (i < lengthDoc && (styler[i] == ' ' || styler[i] == '\t')) + i++; + phpStringDelimiter[0] = '\n'; + for (j = i; j < lengthDoc && styler[j] != '\n' && styler[j] != '\r'; j++) { + if (j - i < phpStringDelimiterSize - 2) + phpStringDelimiter[j-i+1] = styler[j]; + else + i++; + } + phpStringDelimiter[j-i+1] = '\0'; + return j; +} + +static void ColouriseHyperTextDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], + Accessor &styler, bool isXml) { + WordList &keywords = *keywordlists[0]; + WordList &keywords2 = *keywordlists[1]; + WordList &keywords3 = *keywordlists[2]; + WordList &keywords4 = *keywordlists[3]; + WordList &keywords5 = *keywordlists[4]; + WordList &keywords6 = *keywordlists[5]; // SGML (DTD) keywords + + // Lexer for HTML requires more lexical states (8 bits worth) than most lexers + styler.StartAt(startPos, static_cast(STYLE_MAX)); + char prevWord[200]; + prevWord[0] = '\0'; + char phpStringDelimiter[200]; // PHP is not limited in length, we are + phpStringDelimiter[0] = '\0'; + int StateToPrint = initStyle; + int state = stateForPrintState(StateToPrint); + + // If inside a tag, it may be a script tag, so reread from the start to ensure any language tags are seen + if (InTagState(state)) { + while ((startPos > 0) && (InTagState(styler.StyleAt(startPos - 1)))) { + startPos--; + length++; + } + state = SCE_H_DEFAULT; + } + // String can be heredoc, must find a delimiter first + while (startPos > 0 && isPHPStringState(state) && state != SCE_HPHP_SIMPLESTRING) { + startPos--; + length++; + state = styler.StyleAt(startPos); + } + styler.StartAt(startPos, static_cast(STYLE_MAX)); + + int lineCurrent = styler.GetLine(startPos); + int lineState; + if (lineCurrent > 0) { + lineState = styler.GetLineState(lineCurrent); + } else { + // Default client and ASP scripting language is JavaScript + lineState = eScriptJS << 8; + // Don + //lineState |= styler.GetPropertyInt("asp.default.language", eScriptJS) << 4; + lineState |= styler.GetPropertyInt("asp.default.language", eScriptVBS) << 4; + //nod + } + script_mode inScriptType = script_mode((lineState >> 0) & 0x03); // 2 bits of scripting mode + bool tagOpened = (lineState >> 2) & 0x01; // 1 bit to know if we are in an opened tag + bool tagClosing = (lineState >> 3) & 0x01; // 1 bit to know if we are in a closing tag + bool tagDontFold = false; //some HTML tags should not be folded + script_type aspScript = script_type((lineState >> 4) & 0x0F); // 4 bits of script name + script_type clientScript = script_type((lineState >> 8) & 0x0F); // 4 bits of script name + int beforePreProc = (lineState >> 12) & 0xFF; // 8 bits of state + + script_type scriptLanguage = ScriptOfState(state); + + const bool foldHTML = styler.GetPropertyInt("fold.html", 0) != 0; + const bool fold = foldHTML && styler.GetPropertyInt("fold", 0); + const bool foldHTMLPreprocessor = foldHTML && styler.GetPropertyInt("fold.html.preprocessor", 1); + const bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; + const bool caseSensitive = styler.GetPropertyInt("html.tags.case.sensitive", 0) != 0; + + const CharacterSet setHTMLWord(CharacterSet::setAlphaNum, ".-_:!#", 0x80, true); + const CharacterSet setTagContinue(CharacterSet::setAlphaNum, ".-_:!#[", 0x80, true); + const CharacterSet setAttributeContinue(CharacterSet::setAlphaNum, ".-_:!#/", 0x80, true); + + int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; + int levelCurrent = levelPrev; + int visibleChars = 0; + + int chPrev = ' '; + int ch = ' '; + int chPrevNonWhite = ' '; + // look back to set chPrevNonWhite properly for better regex colouring + if (scriptLanguage == eScriptJS && startPos > 0) { + int back = startPos; + int style = 0; + while (--back) { + style = styler.StyleAt(back); + if (style < SCE_HJ_DEFAULT || style > SCE_HJ_COMMENTDOC) + // includes SCE_HJ_COMMENT & SCE_HJ_COMMENTLINE + break; + } + if (style == SCE_HJ_SYMBOLS) { + chPrevNonWhite = static_cast(styler.SafeGetCharAt(back)); + } + } + + styler.StartSegment(startPos); + const int lengthDoc = startPos + length; + for (int i = startPos; i < lengthDoc; i++) { + const int chPrev2 = chPrev; + chPrev = ch; + if (!IsASpace(ch) && state != SCE_HJ_COMMENT && + state != SCE_HJ_COMMENTLINE && state != SCE_HJ_COMMENTDOC) + chPrevNonWhite = ch; + ch = static_cast(styler[i]); + int chNext = static_cast(styler.SafeGetCharAt(i + 1)); + const int chNext2 = static_cast(styler.SafeGetCharAt(i + 2)); + + // Handle DBCS codepages + if (styler.IsLeadByte(static_cast(ch))) { + chPrev = ' '; + i += 1; + continue; + } + + if ((!IsASpace(ch) || !foldCompact) && fold) + visibleChars++; + + // decide what is the current state to print (depending of the script tag) + StateToPrint = statePrintForState(state, inScriptType); + + // handle script folding + if (fold) { + switch (scriptLanguage) { + case eScriptJS: + case eScriptPHP: + //not currently supported case eScriptVBS: + + if ((state != SCE_HPHP_COMMENT) && (state != SCE_HPHP_COMMENTLINE) && (state != SCE_HJ_COMMENT) && (state != SCE_HJ_COMMENTLINE) && (state != SCE_HJ_COMMENTDOC) && (!isStringState(state))) { + //Platform::DebugPrintf("state=%d, StateToPrint=%d, initStyle=%d\n", state, StateToPrint, initStyle); + //if ((state == SCE_HPHP_OPERATOR) || (state == SCE_HPHP_DEFAULT) || (state == SCE_HJ_SYMBOLS) || (state == SCE_HJ_START) || (state == SCE_HJ_DEFAULT)) { + if ((ch == '{') || (ch == '}')) { + levelCurrent += (ch == '{') ? 1 : -1; + } + } + break; + case eScriptPython: + if (state != SCE_HP_COMMENTLINE) { + if ((ch == ':') && ((chNext == '\n') || (chNext == '\r' && chNext2 == '\n'))) { + levelCurrent++; + } else if ((ch == '\n') && !((chNext == '\r') && (chNext2 == '\n')) && (chNext != '\n')) { + // check if the number of tabs is lower than the level + int Findlevel = (levelCurrent & ~SC_FOLDLEVELBASE) * 8; + for (int j = 0; Findlevel > 0; j++) { + char chTmp = styler.SafeGetCharAt(i + j + 1); + if (chTmp == '\t') { + Findlevel -= 8; + } else if (chTmp == ' ') { + Findlevel--; + } else { + break; + } + } + + if (Findlevel > 0) { + levelCurrent -= Findlevel / 8; + if (Findlevel % 8) + levelCurrent--; + } + } + } + break; + default: + break; + } + } + + if ((ch == '\r' && chNext != '\n') || (ch == '\n')) { + // Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix) + // Avoid triggering two times on Dos/Win + // New line -> record any line state onto /next/ line + if (fold) { + int lev = levelPrev; + if (visibleChars == 0) + lev |= SC_FOLDLEVELWHITEFLAG; + if ((levelCurrent > levelPrev) && (visibleChars > 0)) + lev |= SC_FOLDLEVELHEADERFLAG; + + styler.SetLevel(lineCurrent, lev); + visibleChars = 0; + levelPrev = levelCurrent; + } + lineCurrent++; + styler.SetLineState(lineCurrent, + ((inScriptType & 0x03) << 0) | + ((tagOpened & 0x01) << 2) | + ((tagClosing & 0x01) << 3) | + ((aspScript & 0x0F) << 4) | + ((clientScript & 0x0F) << 8) | + ((beforePreProc & 0xFF) << 12)); + } + + // generic end of script processing + else if ((inScriptType == eNonHtmlScript) && (ch == '<') && (chNext == '/')) { + // Check if it's the end of the script tag (or any other HTML tag) + switch (state) { + // in these cases, you can embed HTML tags (to confirm !!!!!!!!!!!!!!!!!!!!!!) + case SCE_H_DOUBLESTRING: + case SCE_H_SINGLESTRING: + case SCE_HJ_COMMENT: + case SCE_HJ_COMMENTDOC: + //case SCE_HJ_COMMENTLINE: // removed as this is a common thing done to hide + // the end of script marker from some JS interpreters. + case SCE_HB_COMMENTLINE: + case SCE_HBA_COMMENTLINE: + case SCE_HJ_DOUBLESTRING: + case SCE_HJ_SINGLESTRING: + case SCE_HJ_REGEX: + case SCE_HB_STRING: + case SCE_HBA_STRING: + case SCE_HP_STRING: + case SCE_HP_TRIPLE: + case SCE_HP_TRIPLEDOUBLE: + break; + default : + // check if the closing tag is a script tag + if (state == SCE_HJ_COMMENTLINE || isXml) { + char tag[7]; // room for the