Cleanup
[TortoiseGit.git] / src / Utils / MiscUI / SciEdit.cpp
blobd988c02850151ea9dc96a9ce15418b1acf1b33e9
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2003-2008,2012 - TortoiseSVN
4 // Copyright (C) 2012 - Sven Strickroth <email@cs-ware.de>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "StdAfx.h"
21 #include "LoglistCommonResource.h"
22 #include "..\PathUtils.h"
23 #include "..\UnicodeUtils.h"
24 #include <string>
25 #include "..\registry.h"
26 #include ".\sciedit.h"
27 #include "SysInfo.h"
29 using namespace std;
32 void CSciEditContextMenuInterface::InsertMenuItems(CMenu&, int&) {return;}
33 bool CSciEditContextMenuInterface::HandleMenuItemClick(int, CSciEdit *) {return false;}
36 #define STYLE_ISSUEBOLD 11
37 #define STYLE_ISSUEBOLDITALIC 12
38 #define STYLE_BOLD 14
39 #define STYLE_ITALIC 15
40 #define STYLE_UNDERLINED 16
41 #define STYLE_URL 17
43 #define STYLE_MASK 0x1f
45 #define SCI_ADDWORD 2000
47 struct loc_map {
48 const char * cp;
49 const char * def_enc;
52 struct loc_map enc2locale[] = {
53 {"28591","ISO8859-1"},
54 {"28592","ISO8859-2"},
55 {"28593","ISO8859-3"},
56 {"28594","ISO8859-4"},
57 {"28595","ISO8859-5"},
58 {"28596","ISO8859-6"},
59 {"28597","ISO8859-7"},
60 {"28598","ISO8859-8"},
61 {"28599","ISO8859-9"},
62 {"28605","ISO8859-15"},
63 {"20866","KOI8-R"},
64 {"21866","KOI8-U"},
65 {"1251","microsoft-cp1251"},
66 {"65001","UTF-8"},
70 IMPLEMENT_DYNAMIC(CSciEdit, CWnd)
72 CSciEdit::CSciEdit(void) : m_DirectFunction(NULL)
73 , m_DirectPointer(NULL)
74 , pChecker(NULL)
75 , pThesaur(NULL)
77 m_hModule = ::LoadLibrary(_T("SciLexer.DLL"));
80 CSciEdit::~CSciEdit(void)
82 m_personalDict.Save();
83 if (m_hModule)
84 ::FreeLibrary(m_hModule);
85 if (pChecker)
86 delete pChecker;
87 if (pThesaur)
88 delete pThesaur;
91 void CSciEdit::Init(LONG lLanguage, BOOL bLoadSpellCheck)
93 //Setup the direct access data
94 m_DirectFunction = SendMessage(SCI_GETDIRECTFUNCTION, 0, 0);
95 m_DirectPointer = SendMessage(SCI_GETDIRECTPOINTER, 0, 0);
96 Call(SCI_SETMARGINWIDTHN, 1, 0);
97 Call(SCI_SETUSETABS, 0); //pressing TAB inserts spaces
98 Call(SCI_SETWRAPVISUALFLAGS, SC_WRAPVISUALFLAG_END);
99 Call(SCI_AUTOCSETIGNORECASE, 1);
100 Call(SCI_SETLEXER, SCLEX_CONTAINER);
101 Call(SCI_SETCODEPAGE, SC_CP_UTF8);
102 Call(SCI_AUTOCSETFILLUPS, 0, (LPARAM)"\t([");
103 Call(SCI_AUTOCSETMAXWIDTH, 0);
104 //Set the default windows colors for edit controls
105 Call(SCI_STYLESETFORE, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT));
106 Call(SCI_STYLESETBACK, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOW));
107 Call(SCI_SETSELFORE, TRUE, ::GetSysColor(COLOR_HIGHLIGHTTEXT));
108 Call(SCI_SETSELBACK, TRUE, ::GetSysColor(COLOR_HIGHLIGHT));
109 Call(SCI_SETCARETFORE, ::GetSysColor(COLOR_WINDOWTEXT));
110 Call(SCI_SETMODEVENTMASK, SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT | SC_PERFORMED_UNDO | SC_PERFORMED_REDO);
111 Call(SCI_INDICSETFORE, 1, 0x0000FF);
112 CStringA sWordChars;
113 CStringA sWhiteSpace;
114 for (int i=0; i<255; ++i)
116 if (i == '\r' || i == '\n')
117 continue;
118 else if (i < 0x20 || i == ' ')
119 sWhiteSpace += (char)i;
120 else if (isalnum(i) || i == '\'')
121 sWordChars += (char)i;
123 Call(SCI_SETWORDCHARS, 0, (LPARAM)(LPCSTR)sWordChars);
124 Call(SCI_SETWHITESPACECHARS, 0, (LPARAM)(LPCSTR)sWhiteSpace);
125 // look for dictionary files and use them if found
126 long langId = GetUserDefaultLCID();
128 if(bLoadSpellCheck)
130 if ((lLanguage != 0)||(((DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\Spellchecker"), FALSE))==FALSE))
132 if (!((lLanguage)&&(!LoadDictionaries(lLanguage))))
136 LoadDictionaries(langId);
137 DWORD lid = SUBLANGID(langId);
138 lid--;
139 if (lid > 0)
141 langId = MAKELANGID(PRIMARYLANGID(langId), lid);
143 else if (langId == 1033)
144 langId = 0;
145 else
146 langId = 1033;
147 } while ((langId)&&((pChecker==NULL)||(pThesaur==NULL)));
151 Call(SCI_SETEDGEMODE, EDGE_NONE);
152 Call(SCI_SETWRAPMODE, SC_WRAP_WORD);
153 Call(SCI_ASSIGNCMDKEY, SCK_END, SCI_LINEENDWRAP);
154 Call(SCI_ASSIGNCMDKEY, SCK_END + (SCMOD_SHIFT << 16), SCI_LINEENDWRAPEXTEND);
155 Call(SCI_ASSIGNCMDKEY, SCK_HOME, SCI_HOMEWRAP);
156 Call(SCI_ASSIGNCMDKEY, SCK_HOME + (SCMOD_SHIFT << 16), SCI_HOMEWRAPEXTEND);
157 CRegStdDWORD used2d(L"Software\\TortoiseGit\\ScintillaDirect2D", FALSE);
158 if (SysInfo::Instance().IsWin7OrLater() && DWORD(used2d))
160 Call(SCI_SETTECHNOLOGY, SC_TECHNOLOGY_DIRECTWRITE);
161 Call(SCI_SETBUFFEREDDRAW, 0);
163 Call(SCI_SETFONTQUALITY, SC_EFF_QUALITY_DEFAULT);
167 void CSciEdit::Init(const ProjectProperties& props)
169 Init(props.lProjectLanguage);
170 m_sCommand = CStringA(CUnicodeUtils::GetUTF8(props.sCheckRe));
171 m_sBugID = CStringA(CUnicodeUtils::GetUTF8(props.sBugIDRe));
172 m_sUrl = CStringA(CUnicodeUtils::GetUTF8(props.sUrl));
174 if (props.nLogWidthMarker)
176 Call(SCI_SETWRAPMODE, SC_WRAP_NONE);
177 Call(SCI_SETEDGEMODE, EDGE_LINE);
178 Call(SCI_SETEDGECOLUMN, props.nLogWidthMarker);
180 else
182 Call(SCI_SETEDGEMODE, EDGE_NONE);
183 Call(SCI_SETWRAPMODE, SC_WRAP_WORD);
185 SetText(props.sLogTemplate);
188 BOOL CSciEdit::LoadDictionaries(LONG lLanguageID)
190 //Setup the spell checker and thesaurus
191 TCHAR buf[6];
192 CString sFolder = CPathUtils::GetAppDirectory();
193 CString sFolderUp = CPathUtils::GetAppParentDirectory();
194 CString sFile;
196 GetLocaleInfo(MAKELCID(lLanguageID, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf));
197 sFile = buf;
198 sFile += _T("_");
199 GetLocaleInfo(MAKELCID(lLanguageID, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf));
200 sFile += buf;
201 if (pChecker==NULL)
203 if ((PathFileExists(sFolder + sFile + _T(".aff"))) &&
204 (PathFileExists(sFolder + sFile + _T(".dic"))))
206 pChecker = new Hunspell(CStringA(sFolder + sFile + _T(".aff")), CStringA(sFolder + sFile + _T(".dic")));
208 else if ((PathFileExists(sFolder + _T("dic\\") + sFile + _T(".aff"))) &&
209 (PathFileExists(sFolder + _T("dic\\") + sFile + _T(".dic"))))
211 pChecker = new Hunspell(CStringA(sFolder + _T("dic\\") + sFile + _T(".aff")), CStringA(sFolder + _T("dic\\") + sFile + _T(".dic")));
213 else if ((PathFileExists(sFolderUp + sFile + _T(".aff"))) &&
214 (PathFileExists(sFolderUp + sFile + _T(".dic"))))
216 pChecker = new Hunspell(CStringA(sFolderUp + sFile + _T(".aff")), CStringA(sFolderUp + sFile + _T(".dic")));
218 else if ((PathFileExists(sFolderUp + _T("dic\\") + sFile + _T(".aff"))) &&
219 (PathFileExists(sFolderUp + _T("dic\\") + sFile + _T(".dic"))))
221 pChecker = new Hunspell(CStringA(sFolderUp + _T("dic\\") + sFile + _T(".aff")), CStringA(sFolderUp + _T("dic\\") + sFile + _T(".dic")));
223 else if ((PathFileExists(sFolderUp + _T("Languages\\") + sFile + _T(".aff"))) &&
224 (PathFileExists(sFolderUp + _T("Languages\\") + sFile + _T(".dic"))))
226 pChecker = new Hunspell(CStringA(sFolderUp + _T("Languages\\") + sFile + _T(".aff")), CStringA(sFolderUp + _T("Languages\\") + sFile + _T(".dic")));
229 #if THESAURUS
230 if (pThesaur==NULL)
232 if ((PathFileExists(sFolder + _T("th_") + sFile + _T("_v2.idx"))) &&
233 (PathFileExists(sFolder + _T("th_") + sFile + _T("_v2.dat"))))
235 pThesaur = new MyThes(CStringA(sFolder + sFile + _T("_v2.idx")), CStringA(sFolder + sFile + _T("_v2.dat")));
237 else if ((PathFileExists(sFolder + _T("dic\\th_") + sFile + _T("_v2.idx"))) &&
238 (PathFileExists(sFolder + _T("dic\\th_") + sFile + _T("_v2.dat"))))
240 pThesaur = new MyThes(CStringA(sFolder + _T("dic\\") + sFile + _T("_v2.idx")), CStringA(sFolder + _T("dic\\") + sFile + _T("_v2.dat")));
242 else if ((PathFileExists(sFolderUp + _T("th_") + sFile + _T("_v2.idx"))) &&
243 (PathFileExists(sFolderUp + _T("th_") + sFile + _T("_v2.dat"))))
245 pThesaur = new MyThes(CStringA(sFolderUp + _T("th_") + sFile + _T("_v2.idx")), CStringA(sFolderUp + _T("th_") + sFile + _T("_v2.dat")));
247 else if ((PathFileExists(sFolderUp + _T("dic\\th_") + sFile + _T("_v2.idx"))) &&
248 (PathFileExists(sFolderUp + _T("dic\\th_") + sFile + _T("_v2.dat"))))
250 pThesaur = new MyThes(CStringA(sFolderUp + _T("dic\\th_") + sFile + _T("_v2.idx")), CStringA(sFolderUp + _T("dic\\th_") + sFile + _T("_v2.dat")));
252 else if ((PathFileExists(sFolderUp + _T("Languages\\th_") + sFile + _T("_v2.idx"))) &&
253 (PathFileExists(sFolderUp + _T("Languages\\th_") + sFile + _T("_v2.dat"))))
255 pThesaur = new MyThes(CStringA(sFolderUp + _T("Languages\\th_") + sFile + _T("_v2.idx")), CStringA(sFolderUp + _T("Languages\\th_") + sFile + _T("_v2.dat")));
258 #endif
259 if (pChecker)
261 const char * encoding = pChecker->get_dic_encoding();
262 ATLTRACE(encoding);
263 int n = _countof(enc2locale);
264 m_spellcodepage = 0;
265 for (int i = 0; i < n; i++)
267 if (strcmp(encoding,enc2locale[i].def_enc) == 0)
269 m_spellcodepage = atoi(enc2locale[i].cp);
272 m_personalDict.Init(lLanguageID);
274 if ((pThesaur)||(pChecker))
275 return TRUE;
276 return FALSE;
279 LRESULT CSciEdit::Call(UINT message, WPARAM wParam, LPARAM lParam)
281 ASSERT(::IsWindow(m_hWnd)); //Window must be valid
282 ASSERT(m_DirectFunction); //Direct function must be valid
283 return ((SciFnDirect) m_DirectFunction)(m_DirectPointer, message, wParam, lParam);
286 CString CSciEdit::StringFromControl(const CStringA& text)
288 CString sText;
289 #ifdef UNICODE
290 int codepage = (int)Call(SCI_GETCODEPAGE);
291 int reslen = MultiByteToWideChar(codepage, 0, text, text.GetLength(), 0, 0);
292 MultiByteToWideChar(codepage, 0, text, text.GetLength(), sText.GetBuffer(reslen+1), reslen+1);
293 sText.ReleaseBuffer(reslen);
294 #else
295 sText = text;
296 #endif
297 return sText;
300 CStringA CSciEdit::StringForControl(const CString& text)
302 CStringA sTextA;
303 #ifdef UNICODE
304 int codepage = (int)SendMessage(SCI_GETCODEPAGE);
305 int reslen = WideCharToMultiByte(codepage, 0, text, text.GetLength(), 0, 0, 0, 0);
306 WideCharToMultiByte(codepage, 0, text, text.GetLength(), sTextA.GetBuffer(reslen), reslen, 0, 0);
307 sTextA.ReleaseBuffer(reslen);
308 #else
309 sTextA = text;
310 #endif
311 ATLTRACE("string length %d\n", sTextA.GetLength());
312 return sTextA;
315 void CSciEdit::SetText(const CString& sText)
317 CStringA sTextA = StringForControl(sText);
318 Call(SCI_SETTEXT, 0, (LPARAM)(LPCSTR)sTextA);
320 // Scintilla seems to have problems with strings that
321 // aren't terminated by a newline char. Once that char
322 // is there, it can be removed without problems.
323 // So we add here a newline, then remove it again.
324 Call(SCI_DOCUMENTEND);
325 Call(SCI_NEWLINE);
326 Call(SCI_DELETEBACK);
329 void CSciEdit::InsertText(const CString& sText, bool bNewLine)
331 CStringA sTextA = StringForControl(sText);
332 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)sTextA);
333 if (bNewLine)
334 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)"\n");
337 CString CSciEdit::GetText()
339 LRESULT len = Call(SCI_GETTEXT, 0, 0);
340 CStringA sTextA;
341 Call(SCI_GETTEXT, (WPARAM)(len + 1), (LPARAM)(LPCSTR)sTextA.GetBuffer((int)len + 1));
342 sTextA.ReleaseBuffer();
343 return StringFromControl(sTextA);
346 CString CSciEdit::GetWordUnderCursor(bool bSelectWord)
348 TEXTRANGEA textrange;
349 int pos = (int)Call(SCI_GETCURRENTPOS);
350 textrange.chrg.cpMin = (LONG)Call(SCI_WORDSTARTPOSITION, pos, TRUE);
351 if ((pos == textrange.chrg.cpMin)||(textrange.chrg.cpMin < 0))
352 return CString();
353 textrange.chrg.cpMax = (LONG)Call(SCI_WORDENDPOSITION, textrange.chrg.cpMin, TRUE);
355 char * textbuffer = new char[textrange.chrg.cpMax - textrange.chrg.cpMin + 1];
357 textrange.lpstrText = textbuffer;
358 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
359 if (bSelectWord)
361 Call(SCI_SETSEL, textrange.chrg.cpMin, textrange.chrg.cpMax);
363 CString sRet = StringFromControl(textbuffer);
364 delete [] textbuffer;
365 return sRet;
368 void CSciEdit::SetFont(CString sFontName, int iFontSizeInPoints)
370 Call(SCI_STYLESETFONT, STYLE_DEFAULT, (LPARAM)(LPCSTR)CStringA(sFontName));
371 Call(SCI_STYLESETSIZE, STYLE_DEFAULT, iFontSizeInPoints);
372 Call(SCI_STYLECLEARALL);
374 LPARAM color = (LPARAM)GetSysColor(COLOR_HIGHLIGHT);
375 // set the styles for the bug ID strings
376 Call(SCI_STYLESETBOLD, STYLE_ISSUEBOLD, (LPARAM)TRUE);
377 Call(SCI_STYLESETFORE, STYLE_ISSUEBOLD, color);
378 Call(SCI_STYLESETBOLD, STYLE_ISSUEBOLDITALIC, (LPARAM)TRUE);
379 Call(SCI_STYLESETITALIC, STYLE_ISSUEBOLDITALIC, (LPARAM)TRUE);
380 Call(SCI_STYLESETFORE, STYLE_ISSUEBOLDITALIC, color);
381 Call(SCI_STYLESETHOTSPOT, STYLE_ISSUEBOLDITALIC, (LPARAM)TRUE);
383 // set the formatted text styles
384 Call(SCI_STYLESETBOLD, STYLE_BOLD, (LPARAM)TRUE);
385 Call(SCI_STYLESETITALIC, STYLE_ITALIC, (LPARAM)TRUE);
386 Call(SCI_STYLESETUNDERLINE, STYLE_UNDERLINED, (LPARAM)TRUE);
388 // set the style for URLs
389 Call(SCI_STYLESETFORE, STYLE_URL, color);
390 Call(SCI_STYLESETHOTSPOT, STYLE_URL, (LPARAM)TRUE);
392 Call(SCI_SETHOTSPOTACTIVEUNDERLINE, (LPARAM)TRUE);
395 void CSciEdit::SetAutoCompletionList(const std::set<CString>& list, const TCHAR separator)
397 //copy the auto completion list.
399 //SK: instead of creating a copy of that list, we could accept a pointer
400 //to the list and use that instead. But then the caller would have to make
401 //sure that the list persists over the lifetime of the control!
402 m_autolist.clear();
403 m_autolist = list;
404 m_separator = separator;
407 BOOL CSciEdit::IsMisspelled(const CString& sWord)
409 // convert the string from the control to the encoding of the spell checker module.
410 CStringA sWordA;
411 if (m_spellcodepage)
413 char * buf;
414 buf = sWordA.GetBuffer(sWord.GetLength()*4 + 1);
415 int lengthIncTerminator =
416 WideCharToMultiByte(m_spellcodepage, 0, sWord, -1, buf, sWord.GetLength()*4, NULL, NULL);
417 sWordA.ReleaseBuffer(lengthIncTerminator-1);
419 else
420 sWordA = CStringA(sWord);
421 sWordA.Trim("\'\".,");
422 // words starting with a digit are treated as correctly spelled
423 if (_istdigit(sWord.GetAt(0)))
424 return FALSE;
425 // words in the personal dictionary are correct too
426 if (m_personalDict.FindWord(sWord))
427 return FALSE;
429 // now we actually check the spelling...
430 if (!pChecker->spell(sWordA))
432 // the word is marked as misspelled, we now check whether the word
433 // is maybe a composite identifier
434 // a composite identifier consists of multiple words, with each word
435 // separated by a change in lower to uppercase letters
436 if (sWord.GetLength() > 1)
438 int wordstart = 0;
439 int wordend = 1;
440 while (wordend < sWord.GetLength())
442 while ((wordend < sWord.GetLength())&&(!_istupper(sWord[wordend])))
443 wordend++;
444 if ((wordstart == 0)&&(wordend == sWord.GetLength()))
446 // words in the auto list are also assumed correctly spelled
447 if (m_autolist.find(sWord) != m_autolist.end())
448 return FALSE;
449 return TRUE;
451 sWordA = CStringA(sWord.Mid(wordstart, wordend-wordstart));
452 if ((sWordA.GetLength() > 2)&&(!pChecker->spell(sWordA)))
454 return TRUE;
456 wordstart = wordend;
457 wordend++;
461 return FALSE;
464 void CSciEdit::CheckSpelling()
466 if (pChecker == NULL)
467 return;
469 TEXTRANGEA textrange;
471 LRESULT firstline = Call(SCI_GETFIRSTVISIBLELINE);
472 LRESULT lastline = firstline + Call(SCI_LINESONSCREEN);
473 textrange.chrg.cpMin = (LONG)Call(SCI_POSITIONFROMLINE, firstline);
474 textrange.chrg.cpMax = (LONG)textrange.chrg.cpMin;
475 LRESULT lastpos = Call(SCI_POSITIONFROMLINE, lastline) + Call(SCI_LINELENGTH, lastline);
476 if (lastpos < 0)
477 lastpos = Call(SCI_GETLENGTH)-textrange.chrg.cpMin;
478 while (textrange.chrg.cpMax < lastpos)
480 textrange.chrg.cpMin = (LONG)Call(SCI_WORDSTARTPOSITION, textrange.chrg.cpMax+1, TRUE);
481 if (textrange.chrg.cpMin < textrange.chrg.cpMax)
482 break;
483 textrange.chrg.cpMax = (LONG)Call(SCI_WORDENDPOSITION, textrange.chrg.cpMin, TRUE);
484 if (textrange.chrg.cpMin == textrange.chrg.cpMax)
486 textrange.chrg.cpMax++;
487 continue;
489 ATLASSERT(textrange.chrg.cpMax >= textrange.chrg.cpMin);
490 char * textbuffer = new char[textrange.chrg.cpMax - textrange.chrg.cpMin + 2];
491 SecureZeroMemory(textbuffer, textrange.chrg.cpMax - textrange.chrg.cpMin + 2);
492 textrange.lpstrText = textbuffer;
493 textrange.chrg.cpMax++;
494 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
495 int len = (int)strlen(textrange.lpstrText);
496 if (len == 0)
498 textrange.chrg.cpMax--;
499 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
500 len = (int)strlen(textrange.lpstrText);
501 textrange.chrg.cpMax++;
502 len++;
504 if (len && textrange.lpstrText[len - 1] == '.')
506 // Try to ignore file names from the auto list.
507 // Do do this, for each word ending with '.' we extract next word and check
508 // whether the combined string is present in auto list.
509 TEXTRANGEA twoWords;
510 twoWords.chrg.cpMin = (LONG)textrange.chrg.cpMin;
511 twoWords.chrg.cpMax = (LONG)Call(SCI_WORDENDPOSITION, textrange.chrg.cpMax + 1, TRUE);
512 twoWords.lpstrText = new char[twoWords.chrg.cpMax - twoWords.chrg.cpMin + 1];
513 SecureZeroMemory(twoWords.lpstrText, twoWords.chrg.cpMax - twoWords.chrg.cpMin + 1);
514 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&twoWords);
515 CString sWord = StringFromControl(twoWords.lpstrText);
516 delete [] twoWords.lpstrText;
517 if (m_autolist.find(sWord) != m_autolist.end())
519 //mark word as correct (remove the squiggle line)
520 Call(SCI_STARTSTYLING, twoWords.chrg.cpMin, INDICS_MASK);
521 Call(SCI_SETSTYLING, twoWords.chrg.cpMax - twoWords.chrg.cpMin, 0);
522 textrange.chrg.cpMax = twoWords.chrg.cpMax;
523 delete [] textbuffer;
524 continue;
527 if (len)
528 textrange.lpstrText[len - 1] = 0;
529 textrange.chrg.cpMax--;
530 if (strlen(textrange.lpstrText) > 0)
532 CString sWord = StringFromControl(textrange.lpstrText);
533 if ((GetStyleAt(textrange.chrg.cpMin) != STYLE_URL) && IsMisspelled(sWord))
535 //mark word as misspelled
536 Call(SCI_STARTSTYLING, textrange.chrg.cpMin, INDICS_MASK);
537 Call(SCI_SETSTYLING, textrange.chrg.cpMax - textrange.chrg.cpMin, INDIC1_MASK);
539 else
541 //mark word as correct (remove the squiggle line)
542 Call(SCI_STARTSTYLING, textrange.chrg.cpMin, INDICS_MASK);
543 Call(SCI_SETSTYLING, textrange.chrg.cpMax - textrange.chrg.cpMin, 0);
546 delete [] textbuffer;
550 void CSciEdit::SuggestSpellingAlternatives()
552 if (pChecker == NULL)
553 return;
554 CString word = GetWordUnderCursor(true);
555 Call(SCI_SETCURRENTPOS, Call(SCI_WORDSTARTPOSITION, Call(SCI_GETCURRENTPOS), TRUE));
556 if (word.IsEmpty())
557 return;
558 char ** wlst;
559 int ns = pChecker->suggest(&wlst, CStringA(word));
560 if (ns > 0)
562 CString suggestions;
563 for (int i=0; i < ns; i++)
565 suggestions += CString(wlst[i]) + m_separator;
566 free(wlst[i]);
568 free(wlst);
569 suggestions.TrimRight(m_separator);
570 if (suggestions.IsEmpty())
571 return;
572 Call(SCI_AUTOCSETSEPARATOR, (WPARAM)CStringA(m_separator).GetAt(0));
573 Call(SCI_AUTOCSETDROPRESTOFWORD, 1);
574 Call(SCI_AUTOCSHOW, 0, (LPARAM)(LPCSTR)StringForControl(suggestions));
579 void CSciEdit::DoAutoCompletion(int nMinPrefixLength)
581 if (m_autolist.empty())
582 return;
583 if (Call(SCI_AUTOCACTIVE))
584 return;
585 CString word = GetWordUnderCursor();
586 if (word.GetLength() < nMinPrefixLength)
587 return; //don't auto complete yet, word is too short
588 int pos = (int)Call(SCI_GETCURRENTPOS);
589 if (pos != Call(SCI_WORDENDPOSITION, pos, TRUE))
590 return; //don't auto complete if we're not at the end of a word
591 CString sAutoCompleteList;
593 word.MakeUpper();
594 for (std::set<CString>::const_iterator lowerit = m_autolist.lower_bound(word);
595 lowerit != m_autolist.end(); ++lowerit)
597 int compare = word.CompareNoCase(lowerit->Left(word.GetLength()));
598 if (compare>0)
599 continue;
600 else if (compare == 0)
602 sAutoCompleteList += *lowerit + m_separator;
604 else
606 break;
609 sAutoCompleteList.TrimRight(m_separator);
610 if (sAutoCompleteList.IsEmpty())
611 return;
613 Call(SCI_AUTOCSETSEPARATOR, (WPARAM)CStringA(m_separator).GetAt(0));
614 Call(SCI_AUTOCSHOW, word.GetLength(), (LPARAM)(LPCSTR)StringForControl(sAutoCompleteList));
617 BOOL CSciEdit::OnChildNotify(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pLResult)
619 if (message != WM_NOTIFY)
620 return CWnd::OnChildNotify(message, wParam, lParam, pLResult);
622 LPNMHDR lpnmhdr = (LPNMHDR) lParam;
623 SCNotification * lpSCN = (SCNotification *)lParam;
625 if(lpnmhdr->hwndFrom==m_hWnd)
627 switch(lpnmhdr->code)
629 case SCN_CHARADDED:
631 if ((lpSCN->ch < 32)&&(lpSCN->ch != 13)&&(lpSCN->ch != 10))
632 Call(SCI_DELETEBACK);
633 else
635 DoAutoCompletion(3);
637 return TRUE;
639 break;
640 case SCN_STYLENEEDED:
642 int startstylepos = (int)Call(SCI_GETENDSTYLED);
643 int endstylepos = ((SCNotification *)lpnmhdr)->position;
644 MarkEnteredBugID(startstylepos, endstylepos);
645 StyleEnteredText(startstylepos, endstylepos);
646 StyleURLs(startstylepos, endstylepos);
647 CheckSpelling();
648 WrapLines(startstylepos, endstylepos);
649 return TRUE;
651 break;
652 case SCN_HOTSPOTCLICK:
654 TEXTRANGEA textrange;
655 textrange.chrg.cpMin = lpSCN->position;
656 textrange.chrg.cpMax = lpSCN->position;
657 DWORD style = GetStyleAt(lpSCN->position);
658 while (GetStyleAt(textrange.chrg.cpMin - 1) == style)
659 --textrange.chrg.cpMin;
660 while (GetStyleAt(textrange.chrg.cpMax + 1) == style)
661 ++textrange.chrg.cpMax;
662 ++textrange.chrg.cpMax;
663 char * textbuffer = new char[textrange.chrg.cpMax - textrange.chrg.cpMin + 1];
664 textrange.lpstrText = textbuffer;
665 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
666 CString url;
667 if (style == STYLE_URL)
668 url = StringFromControl(textbuffer);
669 else
671 url = m_sUrl;
672 url.Replace(_T("%BUGID%"), StringFromControl(textbuffer));
674 delete [] textbuffer;
675 if (!url.IsEmpty())
676 ShellExecute(GetParent()->GetSafeHwnd(), _T("open"), url, NULL, NULL, SW_SHOWDEFAULT);
678 break;
681 return CWnd::OnChildNotify(message, wParam, lParam, pLResult);
684 BEGIN_MESSAGE_MAP(CSciEdit, CWnd)
685 ON_WM_KEYDOWN()
686 ON_WM_CONTEXTMENU()
687 END_MESSAGE_MAP()
689 void CSciEdit::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
691 switch (nChar)
693 case (VK_ESCAPE):
695 if ((Call(SCI_AUTOCACTIVE)==0)&&(Call(SCI_CALLTIPACTIVE)==0))
696 ::SendMessage(GetParent()->GetSafeHwnd(), WM_CLOSE, 0, 0);
698 break;
700 CWnd::OnKeyDown(nChar, nRepCnt, nFlags);
703 BOOL CSciEdit::PreTranslateMessage(MSG* pMsg)
705 if (pMsg->message == WM_KEYDOWN)
707 switch (pMsg->wParam)
709 case VK_SPACE:
711 if (GetKeyState(VK_CONTROL) & 0x8000)
713 DoAutoCompletion(1);
714 return TRUE;
717 break;
718 case VK_TAB:
719 // The TAB cannot be handled in OnKeyDown because it is too late by then.
721 if (GetKeyState(VK_CONTROL)&0x8000)
723 //Ctrl-Tab was pressed, this means we should provide the user with
724 //a list of possible spell checking alternatives to the word under
725 //the cursor
726 SuggestSpellingAlternatives();
727 return TRUE;
729 else if (!Call(SCI_AUTOCACTIVE))
731 ::PostMessage(GetParent()->GetSafeHwnd(), WM_NEXTDLGCTL, GetKeyState(VK_SHIFT)&0x8000, 0);
732 return TRUE;
735 break;
738 return CWnd::PreTranslateMessage(pMsg);
741 void CSciEdit::OnContextMenu(CWnd* /*pWnd*/, CPoint point)
743 int anchor = (int)Call(SCI_GETANCHOR);
744 int currentpos = (int)Call(SCI_GETCURRENTPOS);
745 int selstart = (int)Call(SCI_GETSELECTIONSTART);
746 int selend = (int)Call(SCI_GETSELECTIONEND);
747 int pointpos = 0;
748 if ((point.x == -1) && (point.y == -1))
750 CRect rect;
751 GetClientRect(&rect);
752 ClientToScreen(&rect);
753 point = rect.CenterPoint();
754 pointpos = (int)Call(SCI_GETCURRENTPOS);
756 else
758 // change the cursor position to the point where the user
759 // right-clicked.
760 CPoint clientpoint = point;
761 ScreenToClient(&clientpoint);
762 pointpos = (int)Call(SCI_POSITIONFROMPOINT, clientpoint.x, clientpoint.y);
764 CString sMenuItemText;
765 CMenu popup;
766 bool bRestoreCursor = true;
767 if (popup.CreatePopupMenu())
769 bool bCanUndo = !!Call(SCI_CANUNDO);
770 bool bCanRedo = !!Call(SCI_CANREDO);
771 bool bHasSelection = (selend-selstart > 0);
772 bool bCanPaste = !!Call(SCI_CANPASTE);
773 bool bIsReadOnly = !!Call(SCI_GETREADONLY);
774 UINT uEnabledMenu = MF_STRING | MF_ENABLED;
775 UINT uDisabledMenu = MF_STRING | MF_GRAYED;
777 // find the word under the cursor
778 CString sWord;
779 if (pointpos)
781 // setting the cursor clears the selection
782 Call(SCI_SETANCHOR, pointpos);
783 Call(SCI_SETCURRENTPOS, pointpos);
784 sWord = GetWordUnderCursor();
785 // restore the selection
786 Call(SCI_SETSELECTIONSTART, selstart);
787 Call(SCI_SETSELECTIONEND, selend);
789 else
790 sWord = GetWordUnderCursor();
791 CStringA worda = CStringA(sWord);
793 int nCorrections = 1;
794 bool bSpellAdded = false;
795 // check if the word under the cursor is spelled wrong
796 if ((pChecker)&&(!worda.IsEmpty()) && !bIsReadOnly)
798 char ** wlst;
799 // get the spell suggestions
800 int ns = pChecker->suggest(&wlst,worda);
801 if (ns > 0)
803 // add the suggestions to the context menu
804 for (int i=0; i < ns; i++)
806 bSpellAdded = true;
807 CString sug = CString(wlst[i]);
808 popup.InsertMenu((UINT)-1, 0, nCorrections++, sug);
809 free(wlst[i]);
811 free(wlst);
814 // only add a separator if spelling correction suggestions were added
815 if (bSpellAdded)
816 popup.AppendMenu(MF_SEPARATOR);
818 // also allow the user to add the word to the custom dictionary so
819 // it won't show up as misspelled anymore
820 if ((sWord.GetLength()<PDICT_MAX_WORD_LENGTH)&&((pChecker)&&(m_autolist.find(sWord) == m_autolist.end())&&(!pChecker->spell(worda)))&&
821 (!_istdigit(sWord.GetAt(0)))&&(!m_personalDict.FindWord(sWord)) && !bIsReadOnly)
823 sMenuItemText.Format(IDS_SCIEDIT_ADDWORD, sWord);
824 popup.AppendMenu(uEnabledMenu, SCI_ADDWORD, sMenuItemText);
825 // another separator
826 popup.AppendMenu(MF_SEPARATOR);
829 // add the 'default' entries
830 sMenuItemText.LoadString(IDS_SCIEDIT_UNDO);
831 popup.AppendMenu(bCanUndo ? uEnabledMenu : uDisabledMenu, SCI_UNDO, sMenuItemText);
832 sMenuItemText.LoadString(IDS_SCIEDIT_REDO);
833 popup.AppendMenu(bCanRedo ? uEnabledMenu : uDisabledMenu, SCI_REDO, sMenuItemText);
835 popup.AppendMenu(MF_SEPARATOR);
837 sMenuItemText.LoadString(IDS_SCIEDIT_CUT);
838 popup.AppendMenu(bHasSelection ? uEnabledMenu : uDisabledMenu, SCI_CUT, sMenuItemText);
839 sMenuItemText.LoadString(IDS_SCIEDIT_COPY);
840 popup.AppendMenu(bHasSelection ? uEnabledMenu : uDisabledMenu, SCI_COPY, sMenuItemText);
841 sMenuItemText.LoadString(IDS_SCIEDIT_PASTE);
842 popup.AppendMenu(bCanPaste ? uEnabledMenu : uDisabledMenu, SCI_PASTE, sMenuItemText);
844 popup.AppendMenu(MF_SEPARATOR);
846 sMenuItemText.LoadString(IDS_SCIEDIT_SELECTALL);
847 popup.AppendMenu(uEnabledMenu, SCI_SELECTALL, sMenuItemText);
849 popup.AppendMenu(MF_SEPARATOR);
851 sMenuItemText.LoadString(IDS_SCIEDIT_SPLITLINES);
852 popup.AppendMenu(bHasSelection ? uEnabledMenu : uDisabledMenu, SCI_LINESSPLIT, sMenuItemText);
854 popup.AppendMenu(MF_SEPARATOR);
856 int nCustoms = nCorrections;
857 // now add any custom context menus
858 for (INT_PTR handlerindex = 0; handlerindex < m_arContextHandlers.GetCount(); ++handlerindex)
860 CSciEditContextMenuInterface * pHandler = m_arContextHandlers.GetAt(handlerindex);
861 pHandler->InsertMenuItems(popup, nCustoms);
863 if (nCustoms > nCorrections)
865 // custom menu entries present, so add another separator
866 popup.AppendMenu(MF_SEPARATOR);
869 #if THESAURUS
870 // add found thesauri to sub menu's
871 CMenu thesaurs;
872 thesaurs.CreatePopupMenu();
873 int nThesaurs = 0;
874 CPtrArray menuArray;
875 if ((pThesaur)&&(!worda.IsEmpty()))
877 mentry * pmean;
878 worda.MakeLower();
879 int count = pThesaur->Lookup(worda, worda.GetLength(),&pmean);
880 if (count)
882 mentry * pm = pmean;
883 for (int i=0; i < count; i++)
885 CMenu * submenu = new CMenu();
886 menuArray.Add(submenu);
887 submenu->CreateMenu();
888 for (int j=0; j < pm->count; j++)
890 CString sug = CString(pm->psyns[j]);
891 submenu->InsertMenu((UINT)-1, 0, nThesaurs++, sug);
893 thesaurs.InsertMenu((UINT)-1, MF_POPUP, (UINT_PTR)(submenu->m_hMenu), CString(pm->defn));
894 pm++;
897 if ((count > 0)&&(point.x >= 0))
899 #ifdef IDS_SPELLEDIT_THESAURUS
900 sMenuItemText.LoadString(IDS_SPELLEDIT_THESAURUS);
901 popup.InsertMenu((UINT)-1, MF_POPUP, (UINT_PTR)thesaurs.m_hMenu, sMenuItemText);
902 #else
903 popup.InsertMenu((UINT)-1, MF_POPUP, (UINT_PTR)thesaurs.m_hMenu, _T("Thesaurus"));
904 #endif
905 nThesaurs = nCustoms;
907 else
909 sMenuItemText.LoadString(IDS_SPELLEDIT_NOTHESAURUS);
910 popup.AppendMenu(MF_DISABLED | MF_GRAYED | MF_STRING, 0, sMenuItemText);
913 pThesaur->CleanUpAfterLookup(&pmean, count);
915 else
917 sMenuItemText.LoadString(IDS_SPELLEDIT_NOTHESAURUS);
918 popup.AppendMenu(MF_DISABLED | MF_GRAYED | MF_STRING, 0, sMenuItemText);
920 #endif
921 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this, 0);
922 switch (cmd)
924 case 0:
925 break; // no command selected
926 case SCI_SELECTALL:
927 bRestoreCursor = false;
928 // fall through
929 case SCI_UNDO:
930 case SCI_REDO:
931 case SCI_CUT:
932 case SCI_COPY:
933 case SCI_PASTE:
934 Call(cmd);
935 break;
936 case SCI_ADDWORD:
937 m_personalDict.AddWord(sWord);
938 CheckSpelling();
939 break;
940 case SCI_LINESSPLIT:
942 int marker = (int)(Call(SCI_GETEDGECOLUMN) * Call(SCI_TEXTWIDTH, 0, (LPARAM)" "));
943 if (marker)
945 Call(SCI_TARGETFROMSELECTION);
946 Call(SCI_LINESJOIN);
947 Call(SCI_LINESSPLIT, marker);
950 break;
951 default:
952 if (cmd < nCorrections)
954 Call(SCI_SETANCHOR, pointpos);
955 Call(SCI_SETCURRENTPOS, pointpos);
956 GetWordUnderCursor(true);
957 CString temp;
958 popup.GetMenuString(cmd, temp, 0);
959 // setting the cursor clears the selection
960 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)StringForControl(temp));
962 else if (cmd < (nCorrections+nCustoms))
964 for (INT_PTR handlerindex = 0; handlerindex < m_arContextHandlers.GetCount(); ++handlerindex)
966 CSciEditContextMenuInterface * pHandler = m_arContextHandlers.GetAt(handlerindex);
967 if (pHandler->HandleMenuItemClick(cmd, this))
968 break;
971 #if THESAURUS
972 else if (cmd <= (nThesaurs+nCorrections+nCustoms))
974 Call(SCI_SETANCHOR, pointpos);
975 Call(SCI_SETCURRENTPOS, pointpos);
976 GetWordUnderCursor(true);
977 CString temp;
978 thesaurs.GetMenuString(cmd, temp, 0);
979 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)StringForControl(temp));
981 #endif
983 #ifdef THESAURUS
984 for (INT_PTR index = 0; index < menuArray.GetCount(); ++index)
986 CMenu * pMenu = (CMenu*)menuArray[index];
987 delete pMenu;
989 #endif
991 if (bRestoreCursor)
993 // restore the anchor and cursor position
994 Call(SCI_SETCURRENTPOS, currentpos);
995 Call(SCI_SETANCHOR, anchor);
999 bool CSciEdit::StyleEnteredText(int startstylepos, int endstylepos)
1001 bool bStyled = false;
1002 const int line = (int)Call(SCI_LINEFROMPOSITION, startstylepos);
1003 const int line_number_end = (int)Call(SCI_LINEFROMPOSITION, endstylepos);
1004 for (int line_number = line; line_number <= line_number_end; ++line_number)
1006 int offset = (int)Call(SCI_POSITIONFROMLINE, line_number);
1007 int line_len = (int)Call(SCI_LINELENGTH, line_number);
1008 char * linebuffer = new char[line_len+1];
1009 Call(SCI_GETLINE, line_number, (LPARAM)linebuffer);
1010 linebuffer[line_len] = 0;
1011 int start = 0;
1012 int end = 0;
1013 while (FindStyleChars(linebuffer, '*', start, end))
1015 Call(SCI_STARTSTYLING, start+offset, STYLE_MASK);
1016 Call(SCI_SETSTYLING, end-start, STYLE_BOLD);
1017 bStyled = true;
1018 start = end;
1020 start = 0;
1021 end = 0;
1022 while (FindStyleChars(linebuffer, '^', start, end))
1024 Call(SCI_STARTSTYLING, start+offset, STYLE_MASK);
1025 Call(SCI_SETSTYLING, end-start, STYLE_ITALIC);
1026 bStyled = true;
1027 start = end;
1029 start = 0;
1030 end = 0;
1031 while (FindStyleChars(linebuffer, '_', start, end))
1033 Call(SCI_STARTSTYLING, start+offset, STYLE_MASK);
1034 Call(SCI_SETSTYLING, end-start, STYLE_UNDERLINED);
1035 bStyled = true;
1036 start = end;
1038 delete [] linebuffer;
1040 return bStyled;
1043 bool CSciEdit::WrapLines(int startpos, int endpos)
1045 int markerX = (int)(Call(SCI_GETEDGECOLUMN) * Call(SCI_TEXTWIDTH, 0, (LPARAM)" "));
1046 if (markerX)
1048 Call(SCI_SETTARGETSTART, startpos);
1049 Call(SCI_SETTARGETEND, endpos);
1050 Call(SCI_LINESSPLIT, markerX);
1051 return true;
1053 return false;
1056 void CSciEdit::AdvanceUTF8(const char * str, int& pos)
1058 if ((str[pos] & 0xE0)==0xC0)
1060 // utf8 2-byte sequence
1061 pos += 2;
1063 else if ((str[pos] & 0xF0)==0xE0)
1065 // utf8 3-byte sequence
1066 pos += 3;
1068 else if ((str[pos] & 0xF8)==0xF0)
1070 // utf8 4-byte sequence
1071 pos += 4;
1073 else
1074 pos++;
1077 bool CSciEdit::FindStyleChars(const char * line, char styler, int& start, int& end)
1079 int i=0;
1080 int u=0;
1081 while (i < start)
1083 AdvanceUTF8(line, i);
1084 u++;
1087 bool bFoundMarker = false;
1088 CString sULine = CUnicodeUtils::GetUnicode(line);
1089 // find a starting marker
1090 while (line[i] != 0)
1092 if (line[i] == styler)
1094 if ((line[i+1]!=0)&&(IsCharAlphaNumeric(sULine[u+1]))&&
1095 (((u>0)&&(!IsCharAlphaNumeric(sULine[u-1]))) || (u==0)))
1097 start = i+1;
1098 AdvanceUTF8(line, i);
1099 u++;
1100 bFoundMarker = true;
1101 break;
1104 AdvanceUTF8(line, i);
1105 u++;
1107 if (!bFoundMarker)
1108 return false;
1109 // find ending marker
1110 bFoundMarker = false;
1111 while (line[i] != 0)
1113 if (line[i] == styler)
1115 if ((IsCharAlphaNumeric(sULine[u-1]))&&
1116 ((((u+1)<sULine.GetLength())&&(!IsCharAlphaNumeric(sULine[u+1]))) || ((u+1) == sULine.GetLength()))
1119 end = i;
1120 i++;
1121 bFoundMarker = true;
1122 break;
1125 AdvanceUTF8(line, i);
1126 u++;
1128 return bFoundMarker;
1131 BOOL CSciEdit::MarkEnteredBugID(int startstylepos, int endstylepos)
1133 if (m_sCommand.IsEmpty())
1134 return FALSE;
1135 // get the text between the start and end position we have to style
1136 const int line_number = (int)Call(SCI_LINEFROMPOSITION, startstylepos);
1137 int start_pos = (int)Call(SCI_POSITIONFROMLINE, (WPARAM)line_number);
1138 int end_pos = endstylepos;
1140 if (start_pos == end_pos)
1141 return FALSE;
1142 if (start_pos > end_pos)
1144 int switchtemp = start_pos;
1145 start_pos = end_pos;
1146 end_pos = switchtemp;
1149 char * textbuffer = new char[end_pos - start_pos + 2];
1150 TEXTRANGEA textrange;
1151 textrange.lpstrText = textbuffer;
1152 textrange.chrg.cpMin = start_pos;
1153 textrange.chrg.cpMax = end_pos;
1154 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
1155 CStringA msg = CStringA(textbuffer);
1157 Call(SCI_STARTSTYLING, start_pos, STYLE_MASK);
1159 if (!m_sBugID.IsEmpty())
1161 // match with two regex strings (without grouping!)
1164 const tr1::regex regCheck(m_sCommand);
1165 const tr1::regex regBugID(m_sBugID);
1166 const tr1::sregex_iterator end;
1167 string s = msg;
1168 LONG pos = 0;
1169 for (tr1::sregex_iterator it(s.begin(), s.end(), regCheck); it != end; ++it)
1171 // clear the styles up to the match position
1172 Call(SCI_SETSTYLING, it->position(0)-pos, STYLE_DEFAULT);
1173 pos = (LONG)it->position(0);
1175 // (*it)[0] is the matched string
1176 string matchedString = (*it)[0];
1177 for (tr1::sregex_iterator it2(matchedString.begin(), matchedString.end(), regBugID); it2 != end; ++it2)
1179 ATLTRACE(_T("matched id : %s\n"), (*it2)[0].str().c_str());
1181 // bold style up to the id match
1182 ATLTRACE("position = %ld\n", it2->position(0));
1183 if (it2->position(0))
1184 Call(SCI_SETSTYLING, it2->position(0), STYLE_ISSUEBOLD);
1185 // bold and recursive style for the bug ID itself
1186 if ((*it2)[0].str().size())
1187 Call(SCI_SETSTYLING, (*it2)[0].str().size(), STYLE_ISSUEBOLDITALIC);
1189 pos = (LONG)(it->position(0) + matchedString.size());
1191 // bold style for the rest of the string which isn't matched
1192 if (s.size()-pos)
1193 Call(SCI_SETSTYLING, s.size()-pos, STYLE_DEFAULT);
1195 catch (exception) {}
1197 else
1201 const tr1::regex regCheck(m_sCommand);
1202 const tr1::sregex_iterator end;
1203 string s = msg;
1204 LONG pos = 0;
1205 for (tr1::sregex_iterator it(s.begin(), s.end(), regCheck); it != end; ++it)
1207 // clear the styles up to the match position
1208 Call(SCI_SETSTYLING, it->position(0)-pos, STYLE_DEFAULT);
1209 pos = (LONG)it->position(0);
1211 const tr1::smatch match = *it;
1212 // we define group 1 as the whole issue text and
1213 // group 2 as the bug ID
1214 if (match.size() >= 2)
1216 ATLTRACE(_T("matched id : %s\n"), string(match[1]).c_str());
1217 Call(SCI_SETSTYLING, match[1].first-s.begin()-pos, STYLE_ISSUEBOLD);
1218 Call(SCI_SETSTYLING, string(match[1]).size(), STYLE_ISSUEBOLDITALIC);
1219 pos = (LONG)(match[1].second-s.begin());
1223 catch (exception) {}
1225 delete [] textbuffer;
1227 return FALSE;
1230 bool CSciEdit::IsValidURLChar(unsigned char ch)
1232 return isalnum(ch) ||
1233 ch == '_' || ch == '/' || ch == ';' || ch == '?' || ch == '&' || ch == '=' ||
1234 ch == '%' || ch == ':' || ch == '.' || ch == '#' || ch == '-' || ch == '+';
1237 void CSciEdit::StyleURLs(int startstylepos, int endstylepos)
1239 const int line_number = (int)Call(SCI_LINEFROMPOSITION, startstylepos);
1240 startstylepos = (int)Call(SCI_POSITIONFROMLINE, (WPARAM)line_number);
1242 int len = endstylepos - startstylepos + 1;
1243 char* textbuffer = new char[len + 1];
1244 TEXTRANGEA textrange;
1245 textrange.lpstrText = textbuffer;
1246 textrange.chrg.cpMin = startstylepos;
1247 textrange.chrg.cpMax = endstylepos;
1248 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
1249 // we're dealing with utf8 encoded text here, which means one glyph is
1250 // not necessarily one byte/wchar_t
1251 // that's why we use CStringA to still get a correct char index
1252 CStringA msg = textbuffer;
1253 delete [] textbuffer;
1255 int starturl = -1;
1256 for(int i = 0; i <= msg.GetLength(); )
1258 if ((i < len) && IsValidURLChar(msg[i]))
1260 if (starturl < 0)
1261 starturl = i;
1263 else
1265 if ((starturl >= 0) && IsUrl(msg.Mid(starturl, i - starturl)))
1267 ASSERT(startstylepos + i <= endstylepos);
1268 Call(SCI_STARTSTYLING, startstylepos + starturl, STYLE_MASK);
1269 Call(SCI_SETSTYLING, i - starturl, STYLE_URL);
1271 starturl = -1;
1273 AdvanceUTF8(msg, i);
1277 bool CSciEdit::IsUrl(const CStringA& sText)
1279 if (!PathIsURLA(sText))
1280 return false;
1281 if (sText.Find("://")>=0)
1282 return true;
1283 return false;
1286 bool CSciEdit::IsUTF8(LPVOID pBuffer, size_t cb)
1288 if (cb < 2)
1289 return true;
1290 UINT16 * pVal = (UINT16 *)pBuffer;
1291 UINT8 * pVal2 = (UINT8 *)(pVal+1);
1292 // scan the whole buffer for a 0x0000 sequence
1293 // if found, we assume a binary file
1294 for (size_t i=0; i<(cb-2); i=i+2)
1296 if (0x0000 == *pVal++)
1297 return false;
1299 pVal = (UINT16 *)pBuffer;
1300 if (*pVal == 0xFEFF)
1301 return false;
1302 if (cb < 3)
1303 return false;
1304 if (*pVal == 0xBBEF)
1306 if (*pVal2 == 0xBF)
1307 return true;
1309 // check for illegal UTF8 chars
1310 pVal2 = (UINT8 *)pBuffer;
1311 for (size_t i=0; i<cb; ++i)
1313 if ((*pVal2 == 0xC0)||(*pVal2 == 0xC1)||(*pVal2 >= 0xF5))
1314 return false;
1315 pVal2++;
1317 pVal2 = (UINT8 *)pBuffer;
1318 bool bUTF8 = false;
1319 for (size_t i=0; i<(cb-3); ++i)
1321 if ((*pVal2 & 0xE0)==0xC0)
1323 pVal2++;i++;
1324 if ((*pVal2 & 0xC0)!=0x80)
1325 return false;
1326 bUTF8 = true;
1328 if ((*pVal2 & 0xF0)==0xE0)
1330 pVal2++;i++;
1331 if ((*pVal2 & 0xC0)!=0x80)
1332 return false;
1333 pVal2++;i++;
1334 if ((*pVal2 & 0xC0)!=0x80)
1335 return false;
1336 bUTF8 = true;
1338 if ((*pVal2 & 0xF8)==0xF0)
1340 pVal2++;i++;
1341 if ((*pVal2 & 0xC0)!=0x80)
1342 return false;
1343 pVal2++;i++;
1344 if ((*pVal2 & 0xC0)!=0x80)
1345 return false;
1346 pVal2++;i++;
1347 if ((*pVal2 & 0xC0)!=0x80)
1348 return false;
1349 bUTF8 = true;
1351 pVal2++;
1353 if (bUTF8)
1354 return true;
1355 return false;
1358 void CSciEdit::SetAStyle(int style, COLORREF fore, COLORREF back, int size, const char *face)
1360 Call(SCI_STYLESETFORE, style, fore);
1361 Call(SCI_STYLESETBACK, style, back);
1362 if (size >= 1)
1363 Call(SCI_STYLESETSIZE, style, size);
1364 if (face)
1365 Call(SCI_STYLESETFONT, style, reinterpret_cast<LPARAM>(face));
1369 void CSciEdit::SetUDiffStyle()
1371 SetAStyle(STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT), ::GetSysColor(COLOR_WINDOW),
1372 // Reusing TortoiseBlame's setting which already have an user friendly
1373 // pane in TortoiseSVN's Settings dialog, while there is no such
1374 // pane for TortoiseUDiff.
1375 CRegStdDWORD(_T("Software\\TortoiseGit\\BlameFontSize"), 10),
1376 WideToMultibyte(CRegStdString(_T("Software\\TortoiseGit\\BlameFontName"), _T("Courier New"))).c_str());
1378 Call(SCI_SETTABWIDTH, 4);
1379 Call(SCI_SETREADONLY, TRUE);
1380 //LRESULT pix = Call(SCI_TEXTWIDTH, STYLE_LINENUMBER, (LPARAM)"_99999");
1381 //Call(SCI_SETMARGINWIDTHN, 0, pix);
1382 //Call(SCI_SETMARGINWIDTHN, 1);
1383 //Call(SCI_SETMARGINWIDTHN, 2);
1384 //Set the default windows colors for edit controls
1385 Call(SCI_STYLESETFORE, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT));
1386 Call(SCI_STYLESETBACK, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOW));
1387 Call(SCI_SETSELFORE, TRUE, ::GetSysColor(COLOR_HIGHLIGHTTEXT));
1388 Call(SCI_SETSELBACK, TRUE, ::GetSysColor(COLOR_HIGHLIGHT));
1389 Call(SCI_SETCARETFORE, ::GetSysColor(COLOR_WINDOWTEXT));
1391 //SendEditor(SCI_SETREADONLY, FALSE);
1392 Call(SCI_CLEARALL);
1393 Call(EM_EMPTYUNDOBUFFER);
1394 Call(SCI_SETSAVEPOINT);
1395 Call(SCI_CANCEL);
1396 Call(SCI_SETUNDOCOLLECTION, 0);
1398 Call(SCI_SETUNDOCOLLECTION, 1);
1399 Call(SCI_SETWRAPMODE,SC_WRAP_NONE);
1401 //::SetFocus(m_hWndEdit);
1402 Call(EM_EMPTYUNDOBUFFER);
1403 Call(SCI_SETSAVEPOINT);
1404 Call(SCI_GOTOPOS, 0);
1406 Call(SCI_CLEARDOCUMENTSTYLE, 0, 0);
1407 Call(SCI_SETSTYLEBITS, 5, 0);
1409 //SetAStyle(SCE_DIFF_DEFAULT, RGB(0, 0, 0));
1410 SetAStyle(SCE_DIFF_COMMAND, RGB(0x0A, 0x24, 0x36));
1411 SetAStyle(SCE_DIFF_POSITION, RGB(0xFF, 0, 0));
1412 SetAStyle(SCE_DIFF_HEADER, RGB(0x80, 0, 0), RGB(0xFF, 0xFF, 0x80));
1413 SetAStyle(SCE_DIFF_COMMENT, RGB(0, 0x80, 0));
1414 Call(SCI_STYLESETBOLD, SCE_DIFF_COMMENT, TRUE);
1415 SetAStyle(SCE_DIFF_DELETED, ::GetSysColor(COLOR_WINDOWTEXT), RGB(0xFF, 0x80, 0x80));
1416 SetAStyle(SCE_DIFF_ADDED, ::GetSysColor(COLOR_WINDOWTEXT), RGB(0x80, 0xFF, 0x80));
1418 Call(SCI_SETLEXER, SCLEX_DIFF);
1419 Call(SCI_SETKEYWORDS, 0, (LPARAM)"revision");
1420 Call(SCI_COLOURISE, 0, -1);
1423 int CSciEdit::LoadFromFile(CString &filename)
1425 FILE *fp = NULL;
1426 _tfopen_s(&fp, filename, _T("rb"));
1427 if (fp)
1429 //SetTitle();
1430 char data[4096];
1431 size_t lenFile = fread(data, 1, sizeof(data), fp);
1432 bool bUTF8 = IsUTF8(data, lenFile);
1433 while (lenFile > 0)
1435 Call(SCI_ADDTEXT, lenFile,
1436 reinterpret_cast<LPARAM>(static_cast<char *>(data)));
1437 lenFile = fread(data, 1, sizeof(data), fp);
1439 fclose(fp);
1440 Call(SCI_SETCODEPAGE, bUTF8 ? SC_CP_UTF8 : GetACP());
1441 return 0;
1443 else
1444 return -1;