// This file is part of WLangLexer.
// A plugin for Notepad++ - New Plugin Interface for Notepad++ 5.8+
// Copyright (C)2008-2010 Tanguy Pruvot ( tanguy.pruvot@gmail.com )
// WLangLexer is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// WLangLexer is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with WLang. If not, see <http://www.gnu.org/licenses/>.
#define GetWindowInstance(hwnd) ((HMODULE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE))
#include "WLang.h"
#include "LexerBase.h"
using namespace std;
static struct NppData nppData;
using namespace WLang;
//namespace lIface = Npp_ExtLexer_Interface;
namespace pIface = Npp_Plugin_Interface;
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
void WLang::aboutDlg()
{
::MessageBox(nppData._nppHandle,
TEXT("WLanguage Syntax Highlighter v4.1.0.16 for Notepad++ 5.8\n\n")
TEXT("http://www.wdscript.fr/\n\n")
TEXT("by Tanguy PRUVOT, Jan. 2011\n"),
TEXT("About WLangLexer..."),
MB_OK);
}
void WLang::optionsDlg()
{
//HINSTANCE hInstNpp = GetWindowInstance(nppData._nppHandle);
HINSTANCE hInstMod = (HINSTANCE) hModule;
_optionsDlg.init(hInstMod,&nppData);
_optionsDlg.initOptions(&options.fold);
_optionsDlg.Create();
}
void WLang::testDlg() {
//SCN_CALLTIPCLICK
}
#define WLANG_MENUITEMS 4
static const generic_string optionsMenuItem = TEXT("&Options...");
static const generic_string testMenuItem = TEXT("&Test...");
static const generic_string sepMenuItem = TEXT("_");
static const generic_string aboutMenuItem = TEXT("&About...");
static FuncItem pluginMenuItems[WLANG_MENUITEMS];
static int countPluginMenuItems=0;
BOOL APIENTRY DllMain(HANDLE hModule, DWORD reasonForCall, LPVOID /*lpReserved*/)
{
int m=0;
switch (reasonForCall)
{
case DLL_PROCESS_ATTACH:
WLang::hModule = hModule;
// Options
pluginMenuItems[m]._pFunc = optionsDlg;
generic_strncpy_s(pluginMenuItems[m]._itemName, nbChar, optionsMenuItem.c_str(), _TRUNCATE);
// shortcut
pluginMenuItems[m]._pShKey = NULL;
pluginMenuItems[m]._cmdID = 1;
pluginMenuItems[m]._init2Check = false;
m++;
/*
// Test
pluginMenuItems[m]._pFunc = testDlg;
generic_strncpy_s(pluginMenuItems[m]._itemName, nbChar, testMenuItem.c_str(), _TRUNCATE);
pluginMenuItems[m]._pShKey = NULL;
pluginMenuItems[m]._cmdID = NULL;
pluginMenuItems[m]._init2Check = false;
m++;
*/
// separator
pluginMenuItems[m]._pFunc = NULL;
generic_strncpy_s(pluginMenuItems[m]._itemName, nbChar, sepMenuItem.c_str(), _TRUNCATE);
pluginMenuItems[m]._pShKey = NULL;
pluginMenuItems[m]._cmdID = NULL;
pluginMenuItems[m]._init2Check = false;
m++;
// About
pluginMenuItems[m]._pFunc = aboutDlg;
generic_strncpy_s(pluginMenuItems[m]._itemName, nbChar, aboutMenuItem.c_str(), _TRUNCATE);
pluginMenuItems[m]._pShKey = NULL;
pluginMenuItems[m]._cmdID = 2;
pluginMenuItems[m]._init2Check = false;
m++;
countPluginMenuItems = m;
// hmm maybe to remove later.. or now
// lIface::init( "WLang", TEXT("WLangage *Ext"), NULL, NULL );
break;
case DLL_PROCESS_DETACH:
WLang::wl_html_tags.Clear();
WLang::wl_html_attr.Clear();
WLang::wl_wdscript_tags.Clear();
WLang::writeSettings();
break;
}
return TRUE;
}
#define EXT_LEXER_DECL __declspec( dllexport ) __stdcall
extern "C" {
#ifdef UNICODE
__declspec(dllexport) BOOL isUnicode() {
return TRUE;
}
#endif
__declspec(dllexport) const TCHAR * getName() { return PLUGIN_NAME.c_str(); }
__declspec(dllexport) void setInfo(NppData notpadPlusData){
nppData = notpadPlusData;
pIface::setNppInfo(notpadPlusData);
WLang::iniFile[0] = 0;
BOOL result = (BOOL) SendMessage(nppData._nppHandle, NPPM_GETPLUGINSCONFIGDIR, MAX_PATH, (LPARAM) iniFile);
if (!result) { //npp doesnt support config dir or something else went wrong (ie too small buffer)
if (!GetModuleFileName((HMODULE)hModule, iniFile, MAX_PATH))
Error(TEXT("GetModuleFileName"));
PathRemoveFileSpec(iniFile); //path only
lstrcat(iniFile, TEXT("\\")); //append removed backslash
} else {
lstrcat(iniFile, TEXT("\\")); //append backslash as notepad doesnt do this
//It's possible the directory does not yet exist
if (PathFileExists(iniFile) == FALSE) {
if (createDirectory(iniFile) == FALSE) {
MessageBox(nppData._nppHandle, TEXT("WLangLexer\r\n\r\nUnable to create settings directory"), iniFile, MB_OK);
}
}
}
lstrcat(iniFile, TEXT("WLangLexer.ini"));
HANDLE ini = CreateFile(iniFile,0,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if (ini == INVALID_HANDLE_VALUE) { //opening file failed, creating too, disable plugin
MessageBox(nppData._nppHandle, TEXT("WLangLexer\r\n\r\nNo settings were available and unable to create new settingsfile.\r\nThe plugin will not save options!"), iniFile, MB_OK|MB_ICONEXCLAMATION);
} else { //we got our config, lets get profiles
CloseHandle(ini);
}
}
__declspec(dllexport) FuncItem * getFuncsArray(int *nbF)
{
*nbF = countPluginMenuItems;
return pluginMenuItems;
}
__declspec(dllexport) void beNotified(SCNotification * notifyCode) {
/*
* This function gives access to Notepad++'s notification facilities including forwarded
* notifications from Scintilla.
*
* Notifications can be filtered and language specific handlers called using a
* Namespace::Function() call.
*
* To filter a notification to your specific lexer use the lIface::getSCILexerIDByName()
* function and compare that to a value returned from messageProc(SCI_GETLEXER, 0, 0).
*
*/
int currSCILEXERID=0; // External lexers are assigned SCLEX_AUTOMATIC + id by Scintilla.
// ===> Include optional notification handlers in the switch.
switch (notifyCode->nmhdr.code)
{
case SCN_MODIFIED:
pIface::hCurrViewNeedsUpdate();
if (notifyCode->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT | SC_PERFORMED_UNDO | SC_PERFORMED_REDO | SC_MULTILINEUNDOREDO)) {
currSCILEXERID = messageProc(SCI_GETLEXER, 0, 0);
/*
if ( currSCILEXERID > SCLEX_AUTOMATIC ) {
if ( currSCILEXERID == lIface::getSCILexerIDByName("WLang") ) {
WLang::setDocModified( true );
}
}
*/
WLang::setDocModified( true );
}
break;
case NPPN_READY:
pIface::setNppReady();
pIface::hCurrViewNeedsUpdate();
currSCILEXERID = messageProc(SCI_GETLEXER, 0, 0);
/*
if ( currSCILEXERID > SCLEX_AUTOMATIC ) {
if ( currSCILEXERID == lIface::getSCILexerIDByName("WLang") ) {
// Highlighters don't get applied correctly until Npp is ready.
messageProc(SCI_STARTSTYLING, (WPARAM)-1, 0);
}
}
*/
messageProc(SCI_STARTSTYLING, (WPARAM)-1, 0);
break;
case NPPN_WORDSTYLESUPDATED:
/*
* You can use this notification to make sure that style configuration changes to
* highlighter styles take effect without requiring the user to make a doc change.
* Another use is to keep wordlists in memory while your language is active for the
* focused buffer.
*
* To see an example of both of these ideas in action see NppExtLexer_PowerShell.
*
*/
pIface::hCurrViewNeedsUpdate();
currSCILEXERID = messageProc(SCI_GETLEXER, 0, 0);
/*
if ( currSCILEXERID > SCLEX_AUTOMATIC ) {
if ( currSCILEXERID == lIface::getSCILexerIDByName("WLang") ) {
WLang::WORDSTYLESUPDATEDproc();
}
}
*/
break;
case NPPN_LANGCHANGED:
pIface::hCurrViewNeedsUpdate();
currSCILEXERID = messageProc(SCI_GETLEXER, 0, 0);
/*
if ( currSCILEXERID > SCLEX_AUTOMATIC ) {
if ( currSCILEXERID == lIface::getSCILexerIDByName("WLang") ) {
WLang::setLanguageChanged( true );
}
}
*/
break;
case NPPN_BUFFERACTIVATED:
pIface::hCurrViewNeedsUpdate();
currSCILEXERID = messageProc(SCI_GETLEXER, 0, 0);
/*
if ( currSCILEXERID > SCLEX_AUTOMATIC ) {
if ( currSCILEXERID == lIface::getSCILexerIDByName("WLang") ) {
// Make sure highlighters get applied to the whole doc.
WLang::setLanguageChanged( true ); // This flags for a full doc lexing.
messageProc(SCI_STARTSTYLING,(WPARAM) -1, 0);
}
}
*/
break;
case NPPN_FILEOPENED:
pIface::hCurrViewNeedsUpdate();
break;
default:
break;
}
}
__declspec(dllexport) LRESULT messageProc(UINT /*Message*/, WPARAM /*wParam*/, LPARAM /*lParam*/) { return TRUE; }
} // End extern "C"
int EXT_LEXER_DECL GetLexerCount() { return 1; }
void EXT_LEXER_DECL GetLexerName(unsigned int /*index*/, char *name, int buflength)
{
*name = 0;
if (buflength > 0) {
strncpy_s(name, buflength, LEXER_NAME.c_str(), _TRUNCATE);
}
}
void EXT_LEXER_DECL GetLexerStatusText(unsigned int /*Index*/, TCHAR *desc, int buflength)
{
if (buflength > 0) {
generic_strncpy_s(desc, buflength, LEXER_STATUS_TEXT.c_str(), _TRUNCATE);
}
}
LexerFactoryFunction EXT_LEXER_DECL GetLexerFactory(unsigned int index) {
if (index == 0)
return LexerWLang::LexerFactory;
else
return 0;
}
void SCI_METHOD LexerWLang::Lex(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
try {
Accessor astyler(pAccess, &props);
Colourise_Doc(startPos, length, initStyle, keyWordLists, astyler);
astyler.Flush();
} catch (...) {
// Should not throw into caller as may be compiled with different compiler or options
pAccess->SetErrorStatus(SC_STATUS_FAILURE);
}
}
void SCI_METHOD LexerWLang::Fold(unsigned int startPos, int length, int initStyle, IDocument *pAccess) {
try {
Accessor astyler(pAccess, &props);
Fold_Doc(startPos, length, initStyle, astyler);
astyler.Flush();
} catch (...) {
// Should not throw into caller as may be compiled with different compiler or options
pAccess->SetErrorStatus(SC_STATUS_FAILURE);
}
}
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '_');
}
bool WLang::IsEOL(const int ch, const int chNext)
{
return (ch == 13 && chNext == 10) || (ch == 10);
};
// Identify language comment styles (useful for doc folding)
bool WLang::IsCommentStyle(int style)
{
return style == COMMENT ||
style == MULTILINECOMMENT;
}
// This routine is used in identifying successive HashComment lines
bool WLang::IsHashCommentLine(int line, Accessor &styler)
{
char ch, ch2;
int pos = styler.LineStart(line);
int eol_pos = styler.LineStart(line + 1) - 1;
for (int i = pos; i < eol_pos-1; i++) {
ch = styler.SafeGetCharAt( i );
ch2 = styler.SafeGetCharAt( i+1 );
if (ch == '/' && ch2 == '/')
return true;
else if (ch != ' ' && ch != '\t')
return false;
}
return false;
}
void WLang::strrep(char *str, char old, char rep) {
char *pos;
while (true) {
pos = strchr(str, old);
if (pos == NULL) {
break;
}
*pos = rep;
}
}
bool LexerWLang::isInWLang(int state) {
//state = getState(state);
return (state != HTMLATTR
&& state != HTMLTAG
&& state != JAVASCRIPT
&& state != IN_TAG);
}
// <--- Colourise --->
void LexerWLang::Colourise_Doc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler)
{
fullDocProcessing = true;
/* keywordClass/[array] Style Colourise_Doc Switch Case
WordList wl_keywords; // "0" /[0] KEYWORD(15) IDENTIFIER
WordList wl_funcglobales; // "1" /[1] FUNC_GLOBALES(16) IDENTIFIER
WordList wl_varglobales; // "2" /[2] VAR_GLOBALES(17) IDENTIFIER
WordList wl_functions; // "5" /[5] FUNCTIONS(18) IDENTIFIER
WordList wl_functions_us; // "6" /[6] FUNCTIONS_US(19) IDENTIFIER
WordList wl_constants; // "7" /[7] CONSTANTS(20) IDENTIFIER
WordList wl_constants_us; // "8" /[8] CONSTANTS_US(21) IDENTIFIER
*/
WordList &wl_keywords = *keywordlists[0];
WordList &wl_funcglobales = *keywordlists[1];
WordList &wl_varglobales = *keywordlists[2];
WordList &wl_functions = *keywordlists[5];
WordList &wl_functions_us = *keywordlists[6];
WordList &wl_constants = *keywordlists[7];
WordList &wl_constants_us = *keywordlists[8];
updateWordlists(keywordlists);
unsigned int endChkInit = startPos + min(10,length-1);
//int currentLine = styler.GetLine(startPos);
while ((getState(initStyle) == OPERATOR) && startPos < endChkInit) {
startPos++;
initStyle = styler.StyleAt( startPos );
}
StyleContext sc(startPos, length, initStyle, styler);
initStyle = getState(initStyle);
bool bInTag = false; // flag html attributes
bool bWasInTag = false;
bool bInScript = (initStyle == JAVASCRIPT);
bool bInWLang = isInWLang(initStyle);
bool bInHTML = !bInWLang;
int prevWordState = initStyle; // Tracks states for previous non-operator and non-whitespace
std::string lowcase;
int state = initStyle;
for (; sc.More(); sc.Forward()) {
state = getSCState(sc);
switch (state) {
case STRING:
if(sc.ch == '\"') {
sc.ForwardSetState(DEFAULT);
}
break;
case HERESTRING:
while (IsEOL(sc.ch,sc.GetRelative(2)) && sc.More()) {
bInWLang = true;
sc.SetState(DEFAULT);
sc.Forward();
}
sc.SetState(HERESTRING);
if (sc.atLineStart) {
sc.SetState(DEFAULT); //dont colorise last line TABs
while (IsASpaceOrTab(sc.ch) && sc.More()) sc.Forward();
if (sc.Match(']')) {
sc.SetState(OPERATOR);
sc.ForwardSetState(DEFAULT);
} else {
//not the last line, so colorise
sc.ChangeState(HERESTRING);
}
}
break;
case COMMENT:
if (sc.atLineStart) {
sc.SetState(DEFAULT);
}
break;
case MULTILINECOMMENT:
if( sc.Match("-->") ) {
sc.Forward(3);
sc.SetState(DEFAULT);
}
break;
case VARIABLE:
sc.SetState(DEFAULT);
if(!IsAWordChar(sc.ch)) {
sc.SetState(DEFAULT);
}
break;
case NUMBER:
if (!IsADigit(sc.ch,16)) {
sc.SetState(DEFAULT);
}
break;
case IDENTIFIER:
if (!IsAWordChar(sc.ch) || (sc.currentPos+1 == startPos + length)) {
if (IsAWordChar(sc.ch)) {
sc.Forward(); // Checks words at the end of the document.
}
char s[100]={0};
sc.GetCurrent(s, sizeof(s));
Unaccentify(s);
lowcase = s;
if (!options.caseFunc) {
std::transform(lowcase.begin(), lowcase.end(), lowcase.begin(), ::tolower);
}
if (bInWLang && wl_keywords.InList(s)) {
sc.ChangeState(KEYWORD);
} else if (bInWLang && wl_varglobales.InList(s)) {
sc.ChangeState(VAR_GLOBALES);
} else if (bInWLang && wl_funcglobales.InList(lowcase.c_str())) {
sc.ChangeState(FUNC_GLOBALES);
} else if (bInWLang && wl_functions.InList(lowcase.c_str())) {
sc.ChangeState(FUNCTIONS);
} else if (bInWLang && wl_functions_us.InList(lowcase.c_str())) {
sc.ChangeState(FUNCTIONS_US);
} else if (bInWLang && wl_constants.InList(s)) {
sc.ChangeState(CONSTANTS);
} else if (bInWLang && wl_constants_us.InList(s)) {
sc.ChangeState(CONSTANTS_US);
} else if (sc.ch==';' && wl_html_entt.InList(s)) {
sc.ChangeState(HTML_ENTITE);
} else if (bInTag) {
sc.GetCurrentLowered(s, sizeof(s));
if (wl_html_attr.InList(s)) {
sc.ChangeState(HTMLATTR);
sc.SetState(DEFAULT);
} else {
prevWordState = DEFAULT;
sc.ChangeState(DEFAULT);
}
} else {
// Naked strings should be treated as arguments?
prevWordState = DEFAULT;
sc.ChangeState(DEFAULT);
}
sc.SetState(DEFAULT);
}
break;
case MEMBER:
if (sc.atLineEnd || !IsAWordChar(sc.ch)) {
if (sc.ch == '(') {
sc.ChangeState(METHOD);
} else {
sc.ChangeState(PROPERTY);
}
sc.SetState(DEFAULT);
}
break;
case PROPERTY:
if (sc.atLineEnd || !IsAWordChar(sc.ch)) {
if (sc.ch == '(') {
sc.ChangeState(METHOD);
} else {
sc.ChangeState(PROPERTY);
}
sc.SetState(DEFAULT);
}
break;
case PROPERTY2:
if (sc.atLineEnd || !IsAWordChar(sc.ch)) {
sc.SetState(DEFAULT);
}
break;
case OPERATOR:
// 1 symbol only
sc.SetState(DEFAULT);
break;
case HTMLATTR:
bInHTML=true;
sc.SetState(DEFAULT);
break;
case HTMLTAG:
bInHTML=true;
sc.SetState(DEFAULT);
break;
case WDSCRIPTTAG:
sc.SetState(DEFAULT);
break;
case IN_TAG:
bInHTML=true;
if (sc.ch == '>'){
bInTag = false;
sc.SetState(DEFAULT);
}
else if (!IsAWordChar(sc.ch)) {
char s[30];
sc.GetCurrentLowered(s, sizeof(s));
if (wl_html_attr.InList(s)) {
sc.ChangeState(HTMLATTR);
sc.SetState(DEFAULT);
} else {
bInTag=false;
}
}
break;
case UNKNOWNTAG:
if (sc.ch == '/' && sc.chNext == '>') {
sc.ch = '>';
}
if (sc.ch == '>' || isspacechar(sc.ch)) {
bInTag = (sc.ch != '>');
char s[30];
sc.GetCurrentLowered(s, sizeof(s));
if (wl_wdscript_tags.InList(s)) {
sc.ChangeState(WDSCRIPTTAG);
bInWLang = true;
}
else if (wl_html_tags.InList(s)) {
sc.ChangeState(HTMLTAG);
sc.SetState(DEFAULT);
if (!bInScript && _stricmp(s,"script")==0) {
bInScript=true;
sc.SetState(OPERATOR);
} else if (bInScript && _stricmp(s,"/script")==0) {
bInScript=false;
bInHTML=true;
}
if (sc.ch == '>')
bInWLang=false;
}
else {
sc.ChangeState(UNKNOWNTAG);
bInTag=false;
sc.SetState(DEFAULT);
}
}
break;
default:
if (bInScript) {
state = JAVASCRIPT | (wlScriptJS << WLSTATE_SHL_SCRIPT);
sc.ChangeState(state);
if (sc.ch == '<' && sc.chNext =='/') {
sc.SetState(DEFAULT);
}
bInWLang=false;
}
} //switch state
//-------------------------------------------------------
// Reset bInTag (HTML)
if (bInTag)
bInTag = (sc.ch != '>');
// Determine if a new state should be entered.
if (getSCState(sc) == DEFAULT)
{
// Comments
if (sc.Match('/','/') && sc.GetRelative(-1)!=':') {
sc.SetState(COMMENT);
}
// Multiline Comments
else if (sc.Match("<!--")) {
sc.SetState(MULTILINECOMMENT);
}
// Strings
else if (sc.ch == '\"') {
sc.SetState(STRING);
}
// Numerics
else if ((IsADigit(sc.ch) || sc.Match('0','x')) && !isalpha(sc.chPrev)) {
sc.SetState(NUMBER);
if (sc.Match('0','x')) {
sc.Forward(2);
}
}
// Here-Strings
else if(bInWLang && sc.Match('[') && IsEOL(sc.GetRelative(2),sc.GetRelative(3))) {
sc.SetState(OPERATOR);
sc.Forward(2);
sc.ForwardSetState(HERESTRING);
}
// STATIC MEMBERs: start with letters and follow '::'
else if (bInWLang && styler.Match(sc.currentPos - 1, ":") && isalpha(sc.ch)) {
sc.SetState(MEMBER);
}
else if (bInWLang && styler.Match(sc.currentPos - 2, "::") && isalpha(sc.ch)) {
sc.SetState(MEMBER);
}
// MEMBERs: Start with letters, follow ':'
else if (bInWLang && prevWordState != DEFAULT && sc.ch == ':' && isalpha(sc.chNext)) {
sc.SetState(OPERATOR);
sc.ForwardSetState(MEMBER);
}
else if (bInWLang && styler.Match(sc.currentPos - 2, "..") && isalpha(sc.ch)) {
sc.SetState(PROPERTY2);
}
else if (bInWLang && styler.Match(sc.currentPos - 2, ">>") && isalpha(sc.ch)) {
sc.SetState(MEMBER);
}
// html tags
else if (sc.ch == '<' && (isalpha(sc.chNext)||sc.chNext=='/') ) {
sc.SetState(OPERATOR);
sc.ForwardSetState(UNKNOWNTAG);
}
else if (sc.Match("[%")) {
bWasInTag = bInTag;
bInTag = false;
bInWLang=true;
sc.SetState(OPERATOR);
if (sc.Match("[%\\"))
sc.Forward();
sc.Forward(1);
}
else if (sc.Match("%]")) {
sc.SetState(OPERATOR);
sc.Forward(1);
bInTag = bWasInTag;
bInWLang=false;
}
// Operators
else if (setOperator.Contains(sc.ch)) {
sc.SetState(OPERATOR);
}
// All Keyword Identifiers
else if (IsAWordChar(sc.ch)) {
sc.SetState(IDENTIFIER);
}
}
if(!setOperator.Contains(sc.ch) && !IsASpaceOrTab(sc.ch)) {
prevWordState = sc.state;
}
}
// All done
sc.Complete();
// TODO if (bFirstPass) styler.Flush();
}
// <--- Highlight --->
void LexerWLang::Highlight_Doc(unsigned int startPos, int length, int /*initStyle*/, Accessor &styler)
{
// Clear any existing highlights within range & check if we need to draw any highlights.
bool drawHlites = false;
for ( int i = 0; i < INDICMAX; i++ ) {
if ( Hlite[i].Active ) {
drawHlites = true;
}
// Using a zero value param through the accessor will clear an indicator
styler.IndicatorFill( startPos, length -1 , i, NULL );
}
lineState.ClearMultilineState(styler.GetLine(startPos), styler.GetLine(startPos + length));
if ( drawHlites ) {
int currPos;
int currStyle;
int currHlite;
int braceMatchPos; // Used for multiline highlight control.
//int thisLineDiff; // Used for multiline highlight control.
// Draw indicators in range. When modifying pay attention to the placement of
// 'pos=currPos' to save processing time; don't do this when highlights can overlap!
for (unsigned int pos = startPos; pos < (startPos + length); pos++) {
currStyle = styler.StyleAt(pos);
switch (currStyle)
{
case PROPERTY2:
currHlite = INDICPROP2 - INDICBASE;
if ( Hlite[currHlite].Active ) {
// Find the end of the current style and highlight to it
for (currPos = pos + 1; styler.StyleAt(currPos) == currStyle; currPos++);
styler.IndicatorFill(pos, currPos, currHlite, INDICPROP2);
pos = currPos;
}
break;
case PROPERTY:
currHlite = INDICPROP - INDICBASE;
if ( Hlite[currHlite].Active ) {
// Find the end of the current style and highlight to it
for (currPos = pos + 1; styler.StyleAt(currPos) == currStyle; currPos++);
styler.IndicatorFill(pos, currPos, currHlite, INDICPROP);
pos = currPos;
}
break;
case METHOD:
currHlite = INDICMETH - INDICBASE;
if ( Hlite[currHlite].Active ) {
for (currPos = pos + 1; styler.StyleAt(currPos) == currStyle; currPos++);
// Make sure we at least have a matching brace to highlight to
braceMatchPos = messageProc(SCI_BRACEMATCH, currPos, 0);
if (braceMatchPos == -1 ) {
braceMatchPos = pos;
}
braceMatchPos++;
styler.IndicatorFill(pos, braceMatchPos, currHlite, INDICMETH);
}
break;
} // End: switch(currStyle)
} // End: main pos loop
} // End: drawHlites
}
/*
// Nest tracking setup
unsigned int iGroupLevel = 0;
StateNest sn[100]; // how many levels to track (hopefully this is ridiculously high)
unsigned int iNL = 0; // Nested Level Index
// Initialize state nesting
sn[iNL].preNestState = initStyle;
sn[iNL].prevWordState = initStyle;
sn[iNL].GroupLevel = 0;
//{ ...
// Keep track of grouping levels for nest tracking
// Beware of forwarding onto or over group indicators (see STRING cases for example)
if (setGroupStart.Contains(sc.ch)) iGroupLevel++;
if (setGroupEnd.Contains(sc.ch)) iGroupLevel--;
// Process nesting state change
// Sometimes the nest is terminating on the same character that is supposed to terminate the preNestState, since
// we are only using nesting within double quotes it is a fairly easy check
if ( sc.atLineEnd ) {
if ( (iNL >> 0) & 1 ) {
lineState.flagMultilineStyle( styler.GetLine( sc.currentPos ) );
}
if ( iNL == 0 && (! fullDocProcessing ) &&
( lineState.IsMultilineStyle( styler.GetLine( sc.currentPos ) ) ) ) {
lineState.clearMultilineStyle( sc.currentPos );
}
}
if (iNL >> 0) {
switch (sn[iNL].NestedState) {
case VARIABLE:
if (sc.state != VARIABLE) {
sc.SetState(sn[iNL].preNestState);
iNL--;
if (sc.state == STRING && sc.ch == '\"') {
sc.ForwardSetState(sn[iNL].preNestState);
}
}
break;
case EVALUATION:
if (sc.ch == sn[iNL].GroupTerminator && iGroupLevel == sn[iNL].GroupLevel) {
sc.ForwardSetState(sn[iNL].preNestState);
//if (sc.ch == '`') lexer.CaptureEscapeChars(sc);
iNL--;
if (sc.state == STRING && sc.ch == '\"') {
sc.ForwardSetState(DEFAULT);
// Fix for cases when using the previous ForwardSetState bypasses
// GroupTerminators directly after the '\"'
while(sc.ch == sn[iNL].GroupTerminator ||
(iNL == 0 && setOperator.Contains(sc.ch))) {
if (setGroupStart.Contains(sc.ch)) iGroupLevel++;
if (setGroupEnd.Contains(sc.ch)) iGroupLevel--;
sc.SetState(OPERATOR);
sc.ForwardSetState(sn[iNL].preNestState);
}
}
}
break;
}
}
*/
// <--- Fold --->
void LexerWLang::Fold_Doc(unsigned int startPos, int length, int initStyle, Accessor &styler)
{
// 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 {".
/*
Couldn't find any documentation about Notepad++ and .properties, but to be used with editors that
make use of properties files GetPropertyInt is used, but for Notepad++ provide a default value.
*/
// We might not even want folding...
if (!options.fold) return;
//if (styler.GetPropertyInt("fold") == 0) return;
// Initialize fold settings
options.foldComment = styler.GetPropertyInt("fold.comment", options.foldComment) != 0;
options.foldCommentBloc = styler.GetPropertyInt("fold.multilinecomment", options.foldCommentBloc) != 0;
options.foldAtElse = styler.GetPropertyInt("fold.at.else", options.foldAtElse) != 0;
options.foldCompact = styler.GetPropertyInt("fold.compact", options.foldCompact) != 0;
// Initialize values
// 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 {".
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelCurrent = SC_FOLDLEVELBASE;
if (lineCurrent > 1)
levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
int levelMinCurrent = levelCurrent;
int levelNext = levelCurrent;
int styleNext = getState(styler.StyleAt(startPos));
int style = getState(initStyle);
char ch, chNext = styler[startPos];
int stylePrev;
bool atEOL;
styler.SetLevel(lineCurrent, levelCurrent);
// Line Processing
for (unsigned int i = startPos; i < endPos; i++) {
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
stylePrev = style;
style = getState(styleNext);
styleNext = getState(styler.StyleAt(i + 1));
atEOL = (ch == '\n');
// Comment Folding
if (options.foldComment && IsCommentStyle(style) ) {
// Successive single line comment folding
if (atEOL) {
if (options.foldCommentBloc && (stylePrev == COMMENT)) {
if (! IsHashCommentLine(lineCurrent - 1, styler) &&
IsHashCommentLine(lineCurrent + 1, styler)) {
levelNext++;
}
else if (IsHashCommentLine(lineCurrent - 1, styler) &&
!IsHashCommentLine(lineCurrent + 1, styler)) {
levelNext--;
}
}
}
// Multiline comment folding
if (options.foldCommentBloc && (style == MULTILINECOMMENT)) {
if (stylePrev != MULTILINECOMMENT) {
levelNext++;
}
else if (styleNext != MULTILINECOMMENT) {
levelNext--;
}
}
// Manual fold point marker
if (options.foldCommentExplicit) {
if ((ch == '/') && (chNext == '/')) {
char chNext2 = styler.SafeGetCharAt(i + 2);
if (chNext2 == '{') {
levelNext++;
} else if (chNext2 == '}') {
levelNext--;
}
}
}
}
//Here String
if (options.foldHereString) {
if (style == OPERATOR && styleNext == HERESTRING) {
levelNext++;
}
else if (stylePrev == HERESTRING && style != HERESTRING && styleNext != HERESTRING) {
levelNext--;
}
}
//JavaScript
if (options.foldJavaScript) {
if (style == OPERATOR && styleNext == JAVASCRIPT) {
levelNext++;
}
else if (stylePrev == JAVASCRIPT && style != JAVASCRIPT && styleNext != JAVASCRIPT) {
levelNext--;
}
}
// HTML Tag
//if (style == OPERATOR) {
// if ( ch == '<' && chNext != '/' && IsAlpha(chNext)) {
// levelNext++;
// } else if (ch == '<' && chNext == '/') {
// levelNext--;
// }
//}
// Keyword Folding, not working
if (atEOL && stylePrev == KEYWORD) {
// Should be ready to process now; setup the class parms
//StyleContext sc(startPos, endPos, stylePrev, styler);
//char s[30];
//sc.GetCurrentLowered(s, sizeof(s));
//if (wl_foldin.InList(s)) {
// if (levelMinCurrent > levelNext) {
// levelMinCurrent = levelNext;
// }
// levelNext++;
//} else if (wl_foldout.InList(s)) {
// if (levelMinCurrent > levelNext) {
// levelMinCurrent = levelNext;
// }
// levelNext--;
//}
}
// Flag and level controls
if (!IsASpace(ch))
visibleChars++;
if (atEOL) { // || (i == endPos-1)
int levelUse = levelCurrent;
if (options.foldAtElse) {
levelUse = levelMinCurrent;
}
int lev = levelUse | levelNext << 16;
if (visibleChars == 0 && options.foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if (levelUse < levelNext)
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
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);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
// Lexer Helper Functions
//Thanks to joce on #notepad++
void WLang::Unaccentify(char * str)
{
std::string S = str;
static std::map<TCHAR, TCHAR> unaccentMap;
static bool init = false;
int pos=0;
if (!init)
{
unaccentMap.insert(std::pair<TCHAR,TCHAR>('É','E'));
unaccentMap.insert(std::pair<TCHAR,TCHAR>('à','a'));
unaccentMap.insert(std::pair<TCHAR,TCHAR>('â','a'));
unaccentMap.insert(std::pair<TCHAR,TCHAR>('ç','c'));
unaccentMap.insert(std::pair<TCHAR,TCHAR>('é','e'));
unaccentMap.insert(std::pair<TCHAR,TCHAR>('è','e'));
unaccentMap.insert(std::pair<TCHAR,TCHAR>('ê','e'));
unaccentMap.insert(std::pair<TCHAR,TCHAR>('î','i'));
unaccentMap.insert(std::pair<TCHAR,TCHAR>('ï','i'));
unaccentMap.insert(std::pair<TCHAR,TCHAR>('ô','o'));
unaccentMap.insert(std::pair<TCHAR,TCHAR>('ù','u'));
// ....
init = true;
}
std::map<TCHAR, TCHAR>::iterator mapEnd = unaccentMap.end();
for (std::string::iterator it = S.begin(), end = S.end(); it != end; ++it)
{
std::map<TCHAR, TCHAR>::iterator mapIt = unaccentMap.find(it[0]);
if ( mapIt != mapEnd)
{
str[pos] = mapIt->second;
}
pos++;
}
}
void WLang::WordListToLowercase(WordList& list) {
std::string str;
for (int i=0; i<list.len; i++) {
str += list.words[i];
str += '\t';
}
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
list.Set(str.c_str());
}
// Updates wordlists.
void LexerWLang::updateWordlists(WordList * keywordlists[])
{
WordList &wl_funcglobales = *keywordlists[1];
WordList &wl_functions = *keywordlists[5];
WordList &wl_functions_us = *keywordlists[6];
WordList &wl_constants = *keywordlists[7];
WordList &wl_constants_us = *keywordlists[8];
if (wl_wdscript_tags.len) {
if (!options.caseFunc && wl_functions.len && wl_functions.words[0][0] == 'A') {
//Uppercase, we need to update Wordlists...
} else if (!options.caseConst && wl_constants.len && wl_constants.words[0][0] == 'A') {
//Uppercase, we need to update Wordlists...
} else
return;
}
if (!options.langFuncFR) {
wl_functions.Clear();
}
if (!options.langFuncEN) {
wl_functions_us.Clear();
}
if (!options.langConstFR) {
wl_constants.Clear();
}
if (!options.langConstEN) {
wl_constants_us.Clear();
}
const char* wdsctags = "out wdinclude wdscript /out /wdscript\0";
std::string htmltags = "a /a abbr /abbr above acronym /acronym address /address applet /applet array area /area b /b base basefont bdo /bdo bgsound big /big /blink blockquote /blockquote body /body box br big blink button /button caption /caption center /center cite /cite code /code col /col colgroup /colgroup comment /comment dd /dd del /del dfn /dfn dir /dir div /div dl /dl dt /dt em /em embed fieldset /fieldset fig font /font form /form frame frameset /frameset h1 /h1 h2 /h2 h3 /h3 h4 /h4 h5 /h5 h6 /h6 head /head hr html /html i /i iframe /iframe ilayer /ilayer img input ins ins /ins isindex kbd /kbd label /label layer legend /legend li /li link listing /listing map /map marquee /marquee menu /menu meta multicol /multicol nextid nobr /nobr noframes /noframes nolayer /nolayer note /note noscript /noscript object ol /ol option optgroup /optgroup p /p param pre /pre q /q quote range root s /s samp /samp script /script select /select small /small sound spacer span /span sqrt strike /strike strong /strong style /style sub /sub sup /sup table /table tbody /tbody td /td text textarea /textarea tfoot /tfoot th /th thead /thead title /title tr /tr tt /tt u /u ul /ul var /var wbr xmp /xmp\0";
const char* htmltags5 = " article /article aside /aside audio /audio dialog /dialog embed /embed figure /figure footer /footer header /header mark /mark meter /meter nav /nav section /section video /video";
const char* htmlattr = "abbr accept-charset accept accesskey action align alink alt archive axis background behavior below bgcolor border bordercolor cellpadding cellspacing char charoff charset checked cite class classid clear code codebase codetype color cols colspan compact content coords data datetime declare defer dir disabled enctype face for frame frameborder framespacing headers height hidden href hreflang hspace http equiv id ismap label lang language link loop longdesc leftmargin mailto marginheight marginwidth maxlength media method multiple name nohref noresize noshade object onblur onchange onfocus onkeydown onkeypress onkeyup onload onreset onselect onsubmit onunload onclick ondblclick onmousedown onmousemove onmouseout onmouseover onmouseup profile prompt readonly rel rev rows rowspan rules rightmargin scheme scope scrolling selected shape size span src standby start style summary tabindex target text title topmargin type url usemap valign value valuetype version vlink vspace width xmlns";
const char* htmlentt = "aacute acirc acute aelig agrave alefsym alpha amp and ang aring asymp atilde auml bdquo beta brvbar bull cap ccedil cedil cent chi circ clubs cong copy crarr cup curren dagger darr deg delta diams divide eacute ecirc egrave empty emsp ensp epsilon equiv eta eth euml euro exist fnof forall frac12 frac14 frac34 frasl gamma ge gt harr hearts hellip iacute icirc iexcl igrave image infin int iota iquest isin iuml kappa lambda lang laquo larr lceil ldquo le lfloor lowast loz lrm lsaquo lsquo lt macr mdash micro middot minus mu nabla nbsp ndash ne ni not notin nsub ntilde nu oacute ocirc oelig ograve oline omega omicron oplus or ordf ordm oslash otilde otimes ouml para part permil perp phi pi piv plusmn pound prime prod prop psi quot radic rang raquo rarr rceil rdquo real reg rfloor rho rlm rsaquo rsquo sbquo scaron sdot sect shy sigma sigmaf sim spades sub sube sum sup sup1 sup2 sup3 supe szlig tau there4 theta thetasym thinsp thorn tilde times trade uacute uarr ucirc ugrave uml upsih upsilon uuml weierp xi yacute yen yuml zeta zwj zwnj";
htmltags += htmltags5;
wl_wdscript_tags.Set(wdsctags);
wl_html_tags.Set(htmltags.c_str());
wl_html_attr.Set(htmlattr);
wl_html_entt.Set(htmlentt);
if (!options.caseFunc) {
WordListToLowercase(wl_funcglobales);
WordListToLowercase(wl_functions);
WordListToLowercase(wl_functions_us);
}
if (!options.caseConst) {
WordListToLowercase(wl_constants);
WordListToLowercase(wl_constants_us);
}
const char* foldin = "alors then\0";
const char* foldout = "fin end\0";
const char* foldelse = "sinon else\0";
wl_foldin.Set(foldin);
wl_foldout.Set(foldout);
wl_foldelse.Set(foldelse);
}
// Updates highlighters.
void WLang::updateHighlighterStyles()
{
std::vector<Highlighter>::iterator currHlite = Hlite.begin();
for ( currHlite; currHlite < Hlite.end(); currHlite++ ) {
// Check for updates to highlighter styles.
Highlighter tmpHlite;
tmpHlite = currHlite->init();
if ( tmpHlite.StyleChanged ) {
HliteStyleChanged = true;
// Notepad++ and Scintilla will change the colors and styles but not
// over/under and drawing/erasing.
if ( currHlite->Active != tmpHlite.Active ||
( currHlite->Active && ( currHlite->SCI_INDICUNDER != tmpHlite.SCI_INDICUNDER ))) {
*currHlite = tmpHlite;
currHlite->forceReDraw = true;
}
else {
// Otherwise Notepad++ and Scintilla will take care of colouring.
*currHlite = tmpHlite;
}
currHlite->StyleChanged = false;
}
}
}
//*********************************************************************************************
// Notification Handlers.
// This notification handler updates the keyword lists and highlighters and forces a new lexing.
void WLang::WORDSTYLESUPDATEDproc()
{
StylesUpdatedCall = true;
updateHighlighterStyles();
// If another view open with a WLang document we need to update it as well.
int targetView = ( pIface::intCurrView() == MAIN_VIEW ) ? ( SUB_VIEW ) : ( MAIN_VIEW );
int targetIndex = messageProc( NPPM_GETCURRENTDOCINDEX, 0, targetView );
//HWND hTargetView = ( targetView == MAIN_VIEW ) ? ( pIface::hMainView() ) : ( pIface::hSecondView() );
//int targetSCILEXERID = ::SendMessage( hTargetView, SCI_GETLEXER, 0, 0 );
prevHwndFocused = ::GetFocus();
if ( ( targetIndex >= 0 ) ) { // ( targetSCILEXERID == lIface::getSCILexerIDByName("WLang") ) ) {
// The doc in the alternate view is open and needs updating.
processAltView = true;
messageProc( NPPM_ACTIVATEDOC, targetView, targetIndex );
}
else {
// Restart styling for this view only.
messageProc(SCI_STARTSTYLING, (WPARAM) -1, 0);
}
}
void WLang::setDocModified( bool modified ) {
docModified = modified;
};
void WLang::setLanguageChanged( bool changed) {
languageChanged = changed;
};
#define QUOTEME_(x) #x
#define QUOTEME(x) QUOTEME_(x)
void WLang::readSettings() {
#define IniRead(X) options.X = (::GetPrivateProfileInt(TEXT("WLangLexer"), TEXT(QUOTEME(X)), options.X, iniFile) != 0)
IniRead(fold);
IniRead(foldComment);
IniRead(foldCommentBloc);
IniRead(foldCommentExplicit);
IniRead(foldCompact);
IniRead(foldAtElse);
IniRead(foldHereString);
IniRead(foldJavaScript);
IniRead(caseFunc);
IniRead(caseConst);
IniRead(langFuncFR);
IniRead(langConstEN);
IniRead(langFuncFR);
IniRead(langConstEN);
}
void WLang::writeSettings() {
#define IniWrite(X) ::WritePrivateProfileString(TEXT("WLangLexer"), TEXT(QUOTEME(X)), options.X?TEXT("1"):TEXT("0"), WLang::iniFile)
IniWrite(fold);
IniWrite(foldComment);
IniWrite(foldCommentBloc);
IniWrite(foldCommentExplicit);
IniWrite(foldCompact);
IniWrite(foldAtElse);
IniWrite(foldHereString);
IniWrite(foldJavaScript);
IniWrite(caseFunc);
IniWrite(caseConst);
IniWrite(langFuncFR);
IniWrite(langConstEN);
IniWrite(langFuncFR);
IniWrite(langConstEN);
}
//Path processing/file functions
BOOL WLang::createDirectory(LPCTSTR path) {
TCHAR * parsedPath = new TCHAR[MAX_PATH];
BOOL last = FALSE;
DWORD res = 0;
parsedPath[0] = 0;
int i = 0;
LPCTSTR curStringOffset = path;
LPCTSTR prevStringOffset = path;
while(*curStringOffset != 0) {
if ((*curStringOffset == _T('\\')) || (*curStringOffset == _T('/'))) {
if (prevStringOffset != curStringOffset && *prevStringOffset != _T(':') && *prevStringOffset != _T('\\') && *prevStringOffset != _T('/')) { //ignore drivename and doubled separators
last = CreateDirectory(parsedPath, NULL);
res = GetLastError();
}
}
parsedPath[i] = *curStringOffset;
#ifndef UNICODE
//no DBCS checks needed when WCHAR
if (IsDBCSLeadByte(*curStringOffset)) {
i++;
parsedPath[i] = *(curStringOffset + 1);
}
#endif
i++;
parsedPath[i] = 0;
prevStringOffset = curStringOffset;
curStringOffset = CharNext(curStringOffset);
}
delete [] parsedPath;
if (!last && res == ERROR_ALREADY_EXISTS) //dir already exists, so success
return TRUE;
return last;
}
void WLang::Error(LPTSTR lpszFunction) {
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
if (lpszFunction == NULL) {
lpszFunction = TEXT("Unknown function");
}
DWORD dw = GetLastError();
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,NULL,dw,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),(LPTSTR) &lpMsgBuf,0, NULL );
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,(lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
wsprintf((LPTSTR)lpDisplayBuf,TEXT("%s failed with error %d: %s"),lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("WLangLexer Error"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}