Use the D2D-retain mode if D2D is enabled
[TortoiseGit.git] / src / Utils / MiscUI / SciEdit.cpp
blob6062c2927d6b0b250f1c91f877e867db2c34d8d0
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2012-2014 - TortoiseGit
4 // Copyright (C) 2003-2008,2012-2014 - TortoiseSVN
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"
28 #include "../../TortoiseUDiff/UDiffColors.h"
30 void CSciEditContextMenuInterface::InsertMenuItems(CMenu&, int&) {return;}
31 bool CSciEditContextMenuInterface::HandleMenuItemClick(int, CSciEdit *) {return false;}
32 void CSciEditContextMenuInterface::HandleSnippet(int, const CString &, CSciEdit *) { return; }
35 #define STYLE_ISSUEBOLD 11
36 #define STYLE_ISSUEBOLDITALIC 12
37 #define STYLE_BOLD 14
38 #define STYLE_ITALIC 15
39 #define STYLE_UNDERLINED 16
40 #define STYLE_URL 17
41 #define INDIC_MISSPELLED 18
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)
76 , m_spellcodepage(0)
77 , m_separator(0)
78 , m_typeSeparator(1)
79 , m_bDoStyle(false)
80 , m_nAutoCompleteMinChars(3)
82 m_hModule = ::LoadLibrary(_T("SciLexer_tgit.dll"));
85 CSciEdit::~CSciEdit(void)
87 m_personalDict.Save();
88 if (m_hModule)
89 ::FreeLibrary(m_hModule);
90 if (pChecker)
91 delete pChecker;
92 if (pThesaur)
93 delete pThesaur;
96 static LPBYTE Icon2Image(HICON hIcon)
98 if (hIcon == nullptr)
99 return nullptr;
101 ICONINFO iconInfo;
102 if (!GetIconInfo(hIcon, &iconInfo))
103 return nullptr;
105 BITMAP bm;
106 if (!GetObject(iconInfo.hbmColor, sizeof(BITMAP), &bm))
107 return nullptr;
109 int width = bm.bmWidth;
110 int height = bm.bmHeight;
111 int bytesPerScanLine = (width * 3 + 3) & 0xFFFFFFFC;
112 int size = bytesPerScanLine * height;
113 BITMAPINFO infoheader;
114 infoheader.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
115 infoheader.bmiHeader.biWidth = width;
116 infoheader.bmiHeader.biHeight = height;
117 infoheader.bmiHeader.biPlanes = 1;
118 infoheader.bmiHeader.biBitCount = 24;
119 infoheader.bmiHeader.biCompression = BI_RGB;
120 infoheader.bmiHeader.biSizeImage = size;
122 std::unique_ptr<BYTE> ptrb(new BYTE[(size * 2 + height * width * 4)]);
123 LPBYTE pixelsIconRGB = ptrb.get();
124 LPBYTE alphaPixels = pixelsIconRGB + size;
125 HDC hDC = CreateCompatibleDC(nullptr);
126 HBITMAP hBmpOld = (HBITMAP)SelectObject(hDC, (HGDIOBJ)iconInfo.hbmColor);
127 if (!GetDIBits(hDC, iconInfo.hbmColor, 0, height, (LPVOID)pixelsIconRGB, &infoheader, DIB_RGB_COLORS))
129 DeleteDC(hDC);
130 return nullptr;
133 SelectObject(hDC, hBmpOld);
134 if (!GetDIBits(hDC, iconInfo.hbmMask, 0,height, (LPVOID)alphaPixels, &infoheader, DIB_RGB_COLORS))
136 DeleteDC(hDC);
137 return nullptr;
140 DeleteDC(hDC);
141 UINT* imagePixels = new UINT[height * width];
142 int lsSrc = width * 3;
143 int vsDest = height - 1;
144 for (int y = 0; y < height; y++)
146 int linePosSrc = (vsDest - y) * lsSrc;
147 int linePosDest = y * width;
148 for (int x = 0; x < width; x++)
150 int currentDestPos = linePosDest + x;
151 int currentSrcPos = linePosSrc + x * 3;
152 imagePixels[currentDestPos] = (((UINT)(
154 ((pixelsIconRGB[currentSrcPos + 2] /*Red*/)
155 | (pixelsIconRGB[currentSrcPos + 1] << 8 /*Green*/))
156 | pixelsIconRGB[currentSrcPos] << 16 /*Blue*/
158 | ((alphaPixels[currentSrcPos] ? 0 : 0xff) << 24))) & 0xffffffff);
161 return (LPBYTE)imagePixels;
164 void CSciEdit::Init(LONG lLanguage, BOOL bLoadSpellCheck)
166 //Setup the direct access data
167 m_DirectFunction = SendMessage(SCI_GETDIRECTFUNCTION, 0, 0);
168 m_DirectPointer = SendMessage(SCI_GETDIRECTPOINTER, 0, 0);
169 Call(SCI_SETMARGINWIDTHN, 1, 0);
170 Call(SCI_SETUSETABS, 0); //pressing TAB inserts spaces
171 Call(SCI_SETWRAPVISUALFLAGS, SC_WRAPVISUALFLAG_END);
172 Call(SCI_AUTOCSETIGNORECASE, 1);
173 Call(SCI_SETLEXER, SCLEX_CONTAINER);
174 Call(SCI_SETCODEPAGE, SC_CP_UTF8);
175 Call(SCI_AUTOCSETFILLUPS, 0, (LPARAM)"\t([");
176 Call(SCI_AUTOCSETMAXWIDTH, 0);
177 //Set the default windows colors for edit controls
178 Call(SCI_STYLESETFORE, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT));
179 Call(SCI_STYLESETBACK, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOW));
180 Call(SCI_SETSELFORE, TRUE, ::GetSysColor(COLOR_HIGHLIGHTTEXT));
181 Call(SCI_SETSELBACK, TRUE, ::GetSysColor(COLOR_HIGHLIGHT));
182 Call(SCI_SETCARETFORE, ::GetSysColor(COLOR_WINDOWTEXT));
183 Call(SCI_SETMODEVENTMASK, SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT | SC_PERFORMED_UNDO | SC_PERFORMED_REDO);
184 Call(SCI_INDICSETSTYLE, INDIC_MISSPELLED, INDIC_SQUIGGLE);
185 Call(SCI_INDICSETFORE, INDIC_MISSPELLED, RGB(255,0,0));
186 CStringA sWordChars;
187 CStringA sWhiteSpace;
188 for (int i=0; i<255; ++i)
190 if (i == '\r' || i == '\n')
191 continue;
192 else if (i < 0x20 || i == ' ')
193 sWhiteSpace += (char)i;
194 else if (isalnum(i) || i == '\'' || i == '_' || i == '-')
195 sWordChars += (char)i;
197 Call(SCI_SETWORDCHARS, 0, (LPARAM)(LPCSTR)sWordChars);
198 Call(SCI_SETWHITESPACECHARS, 0, (LPARAM)(LPCSTR)sWhiteSpace);
199 m_bDoStyle = ((DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\StyleCommitMessages"), TRUE))==TRUE;
200 m_nAutoCompleteMinChars = (int)(DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\AutoCompleteMinChars"), 3);
201 // look for dictionary files and use them if found
202 long langId = GetUserDefaultLCID();
204 if(bLoadSpellCheck)
206 if ((lLanguage != 0)||(((DWORD)CRegStdDWORD(_T("Software\\TortoiseGit\\Spellchecker"), FALSE))==FALSE))
208 if (!((lLanguage)&&(!LoadDictionaries(lLanguage))))
212 LoadDictionaries(langId);
213 DWORD lid = SUBLANGID(langId);
214 lid--;
215 if (lid > 0)
217 langId = MAKELANGID(PRIMARYLANGID(langId), lid);
219 else if (langId == 1033)
220 langId = 0;
221 else
222 langId = 1033;
223 } while ((langId)&&((pChecker==NULL)||(pThesaur==NULL)));
227 Call(SCI_SETEDGEMODE, EDGE_NONE);
228 Call(SCI_SETWRAPMODE, SC_WRAP_WORD);
229 Call(SCI_ASSIGNCMDKEY, SCK_END, SCI_LINEENDWRAP);
230 Call(SCI_ASSIGNCMDKEY, SCK_END + (SCMOD_SHIFT << 16), SCI_LINEENDWRAPEXTEND);
231 Call(SCI_ASSIGNCMDKEY, SCK_HOME, SCI_HOMEWRAP);
232 Call(SCI_ASSIGNCMDKEY, SCK_HOME + (SCMOD_SHIFT << 16), SCI_HOMEWRAPEXTEND);
233 CRegStdDWORD used2d(L"Software\\TortoiseGit\\ScintillaDirect2D", FALSE);
234 if (SysInfo::Instance().IsWin7OrLater() && DWORD(used2d))
236 Call(SCI_SETTECHNOLOGY, SC_TECHNOLOGY_DIRECTWRITERETAIN);
237 Call(SCI_SETBUFFEREDDRAW, 0);
242 void CSciEdit::Init(const ProjectProperties& props)
244 Init(props.lProjectLanguage);
245 m_sCommand = CStringA(CUnicodeUtils::GetUTF8(props.GetCheckRe()));
246 m_sBugID = CStringA(CUnicodeUtils::GetUTF8(props.GetBugIDRe()));
247 m_sUrl = CStringA(CUnicodeUtils::GetUTF8(props.sUrl));
249 if (props.nLogWidthMarker)
251 Call(SCI_SETWRAPMODE, SC_WRAP_NONE);
252 Call(SCI_SETEDGEMODE, EDGE_LINE);
253 Call(SCI_SETEDGECOLUMN, props.nLogWidthMarker);
255 else
257 Call(SCI_SETEDGEMODE, EDGE_NONE);
258 Call(SCI_SETWRAPMODE, SC_WRAP_WORD);
262 void CSciEdit::SetIcon(const std::map<int, UINT> &icons)
264 Call(SCI_RGBAIMAGESETWIDTH, 16);
265 Call(SCI_RGBAIMAGESETHEIGHT, 16);
266 for (auto icon : icons)
268 auto hIcon = (HICON)::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(icon.second), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
269 std::unique_ptr<BYTE> bytes(Icon2Image(hIcon));
270 DestroyIcon(hIcon);
271 Call(SCI_REGISTERRGBAIMAGE, icon.first, (LPARAM)bytes.get());
275 BOOL CSciEdit::LoadDictionaries(LONG lLanguageID)
277 //Setup the spell checker and thesaurus
278 TCHAR buf[6] = { 0 };
279 CString sFolder = CPathUtils::GetAppDirectory();
280 CString sFolderUp = CPathUtils::GetAppParentDirectory();
281 CString sFolderAppData = CPathUtils::GetAppDataDirectory();
282 CString sFile;
284 GetLocaleInfo(MAKELCID(lLanguageID, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf));
285 sFile = buf;
286 if (lLanguageID == 2074)
287 sFile += _T("-Latn");
288 sFile += _T("_");
289 GetLocaleInfo(MAKELCID(lLanguageID, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf));
290 sFile += buf;
291 if (pChecker==NULL)
293 if ((PathFileExists(sFolderAppData + _T("dic\\") + sFile + _T(".aff"))) &&
294 (PathFileExists(sFolderAppData + _T("dic\\") + sFile + _T(".dic"))))
296 pChecker = new Hunspell(CStringA(sFolderAppData + _T("dic\\") + sFile + _T(".aff")), CStringA(sFolderAppData + _T("dic\\") + sFile + _T(".dic")));
298 else if ((PathFileExists(sFolder + sFile + _T(".aff"))) &&
299 (PathFileExists(sFolder + sFile + _T(".dic"))))
301 pChecker = new Hunspell(CStringA(sFolder + sFile + _T(".aff")), CStringA(sFolder + sFile + _T(".dic")));
303 else if ((PathFileExists(sFolder + _T("dic\\") + sFile + _T(".aff"))) &&
304 (PathFileExists(sFolder + _T("dic\\") + sFile + _T(".dic"))))
306 pChecker = new Hunspell(CStringA(sFolder + _T("dic\\") + sFile + _T(".aff")), CStringA(sFolder + _T("dic\\") + sFile + _T(".dic")));
308 else if ((PathFileExists(sFolderUp + sFile + _T(".aff"))) &&
309 (PathFileExists(sFolderUp + sFile + _T(".dic"))))
311 pChecker = new Hunspell(CStringA(sFolderUp + sFile + _T(".aff")), CStringA(sFolderUp + sFile + _T(".dic")));
313 else if ((PathFileExists(sFolderUp + _T("dic\\") + sFile + _T(".aff"))) &&
314 (PathFileExists(sFolderUp + _T("dic\\") + sFile + _T(".dic"))))
316 pChecker = new Hunspell(CStringA(sFolderUp + _T("dic\\") + sFile + _T(".aff")), CStringA(sFolderUp + _T("dic\\") + sFile + _T(".dic")));
318 else if ((PathFileExists(sFolderUp + _T("Languages\\") + sFile + _T(".aff"))) &&
319 (PathFileExists(sFolderUp + _T("Languages\\") + sFile + _T(".dic"))))
321 pChecker = new Hunspell(CStringA(sFolderUp + _T("Languages\\") + sFile + _T(".aff")), CStringA(sFolderUp + _T("Languages\\") + sFile + _T(".dic")));
324 #if THESAURUS
325 if (pThesaur==NULL)
327 if ((PathFileExists(sFolderAppData + _T("th_") + sFile + _T("_v2.idx"))) &&
328 (PathFileExists(sFolderAppData + _T("th_") + sFile + _T("_v2.dat"))))
330 pThesaur = new MyThes(CStringA(sFolderAppData + sFile + _T("_v2.idx")), CStringA(sFolderAppData + sFile + _T("_v2.dat")));
332 else if ((PathFileExists(sFolder + _T("th_") + sFile + _T("_v2.idx"))) &&
333 (PathFileExists(sFolder + _T("th_") + sFile + _T("_v2.dat"))))
335 pThesaur = new MyThes(CStringA(sFolder + sFile + _T("_v2.idx")), CStringA(sFolder + sFile + _T("_v2.dat")));
337 else if ((PathFileExists(sFolder + _T("dic\\th_") + sFile + _T("_v2.idx"))) &&
338 (PathFileExists(sFolder + _T("dic\\th_") + sFile + _T("_v2.dat"))))
340 pThesaur = new MyThes(CStringA(sFolder + _T("dic\\") + sFile + _T("_v2.idx")), CStringA(sFolder + _T("dic\\") + sFile + _T("_v2.dat")));
342 else if ((PathFileExists(sFolderUp + _T("th_") + sFile + _T("_v2.idx"))) &&
343 (PathFileExists(sFolderUp + _T("th_") + sFile + _T("_v2.dat"))))
345 pThesaur = new MyThes(CStringA(sFolderUp + _T("th_") + sFile + _T("_v2.idx")), CStringA(sFolderUp + _T("th_") + sFile + _T("_v2.dat")));
347 else if ((PathFileExists(sFolderUp + _T("dic\\th_") + sFile + _T("_v2.idx"))) &&
348 (PathFileExists(sFolderUp + _T("dic\\th_") + sFile + _T("_v2.dat"))))
350 pThesaur = new MyThes(CStringA(sFolderUp + _T("dic\\th_") + sFile + _T("_v2.idx")), CStringA(sFolderUp + _T("dic\\th_") + sFile + _T("_v2.dat")));
352 else if ((PathFileExists(sFolderUp + _T("Languages\\th_") + sFile + _T("_v2.idx"))) &&
353 (PathFileExists(sFolderUp + _T("Languages\\th_") + sFile + _T("_v2.dat"))))
355 pThesaur = new MyThes(CStringA(sFolderUp + _T("Languages\\th_") + sFile + _T("_v2.idx")), CStringA(sFolderUp + _T("Languages\\th_") + sFile + _T("_v2.dat")));
358 #endif
359 if (pChecker)
361 const char * encoding = pChecker->get_dic_encoding();
362 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": %s\n", encoding);
363 int n = _countof(enc2locale);
364 m_spellcodepage = 0;
365 for (int i = 0; i < n; i++)
367 if (strcmp(encoding,enc2locale[i].def_enc) == 0)
369 m_spellcodepage = atoi(enc2locale[i].cp);
372 m_personalDict.Init(lLanguageID);
374 if ((pThesaur)||(pChecker))
375 return TRUE;
376 return FALSE;
379 LRESULT CSciEdit::Call(UINT message, WPARAM wParam, LPARAM lParam)
381 ASSERT(::IsWindow(m_hWnd)); //Window must be valid
382 ASSERT(m_DirectFunction); //Direct function must be valid
383 return ((SciFnDirect) m_DirectFunction)(m_DirectPointer, message, wParam, lParam);
386 CString CSciEdit::StringFromControl(const CStringA& text)
388 CString sText;
389 #ifdef UNICODE
390 int codepage = (int)Call(SCI_GETCODEPAGE);
391 int reslen = MultiByteToWideChar(codepage, 0, text, text.GetLength(), 0, 0);
392 MultiByteToWideChar(codepage, 0, text, text.GetLength(), sText.GetBuffer(reslen+1), reslen+1);
393 sText.ReleaseBuffer(reslen);
394 #else
395 sText = text;
396 #endif
397 return sText;
400 CStringA CSciEdit::StringForControl(const CString& text)
402 CStringA sTextA;
403 #ifdef UNICODE
404 int codepage = (int)SendMessage(SCI_GETCODEPAGE);
405 int reslen = WideCharToMultiByte(codepage, 0, text, text.GetLength(), 0, 0, 0, 0);
406 WideCharToMultiByte(codepage, 0, text, text.GetLength(), sTextA.GetBuffer(reslen), reslen, 0, 0);
407 sTextA.ReleaseBuffer(reslen);
408 #else
409 sTextA = text;
410 #endif
411 ATLTRACE("string length %d\n", sTextA.GetLength());
412 return sTextA;
415 void CSciEdit::SetText(const CString& sText)
417 CStringA sTextA = StringForControl(sText);
418 Call(SCI_SETTEXT, 0, (LPARAM)(LPCSTR)sTextA);
420 // Scintilla seems to have problems with strings that
421 // aren't terminated by a newline char. Once that char
422 // is there, it can be removed without problems.
423 // So we add here a newline, then remove it again.
424 Call(SCI_DOCUMENTEND);
425 Call(SCI_NEWLINE);
426 Call(SCI_DELETEBACK);
429 void CSciEdit::InsertText(const CString& sText, bool bNewLine)
431 CStringA sTextA = StringForControl(sText);
432 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)sTextA);
433 if (bNewLine)
434 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)"\n");
437 CString CSciEdit::GetText()
439 LRESULT len = Call(SCI_GETTEXT, 0, 0);
440 CStringA sTextA;
441 Call(SCI_GETTEXT, (WPARAM)(len + 1), (LPARAM)(LPCSTR)sTextA.GetBuffer((int)len + 1));
442 sTextA.ReleaseBuffer();
443 return StringFromControl(sTextA);
446 CString CSciEdit::GetWordUnderCursor(bool bSelectWord)
448 TEXTRANGEA textrange;
449 int pos = (int)Call(SCI_GETCURRENTPOS);
450 textrange.chrg.cpMin = (LONG)Call(SCI_WORDSTARTPOSITION, pos, TRUE);
451 if ((pos == textrange.chrg.cpMin)||(textrange.chrg.cpMin < 0))
452 return CString();
453 textrange.chrg.cpMax = (LONG)Call(SCI_WORDENDPOSITION, textrange.chrg.cpMin, TRUE);
455 std::unique_ptr<char[]> textbuffer(new char[textrange.chrg.cpMax - textrange.chrg.cpMin + 1]);
456 textrange.lpstrText = textbuffer.get();
457 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
458 if (bSelectWord)
460 Call(SCI_SETSEL, textrange.chrg.cpMin, textrange.chrg.cpMax);
462 CString sRet = StringFromControl(textbuffer.get());
463 return sRet;
466 void CSciEdit::SetFont(CString sFontName, int iFontSizeInPoints)
468 Call(SCI_STYLESETFONT, STYLE_DEFAULT, (LPARAM)(LPCSTR)CUnicodeUtils::GetUTF8(sFontName).GetBuffer());
469 Call(SCI_STYLESETSIZE, STYLE_DEFAULT, iFontSizeInPoints);
470 Call(SCI_STYLECLEARALL);
472 LPARAM color = (LPARAM)GetSysColor(COLOR_HIGHLIGHT);
473 // set the styles for the bug ID strings
474 Call(SCI_STYLESETBOLD, STYLE_ISSUEBOLD, (LPARAM)TRUE);
475 Call(SCI_STYLESETFORE, STYLE_ISSUEBOLD, color);
476 Call(SCI_STYLESETBOLD, STYLE_ISSUEBOLDITALIC, (LPARAM)TRUE);
477 Call(SCI_STYLESETITALIC, STYLE_ISSUEBOLDITALIC, (LPARAM)TRUE);
478 Call(SCI_STYLESETFORE, STYLE_ISSUEBOLDITALIC, color);
479 Call(SCI_STYLESETHOTSPOT, STYLE_ISSUEBOLDITALIC, (LPARAM)TRUE);
481 // set the formatted text styles
482 Call(SCI_STYLESETBOLD, STYLE_BOLD, (LPARAM)TRUE);
483 Call(SCI_STYLESETITALIC, STYLE_ITALIC, (LPARAM)TRUE);
484 Call(SCI_STYLESETUNDERLINE, STYLE_UNDERLINED, (LPARAM)TRUE);
486 // set the style for URLs
487 Call(SCI_STYLESETFORE, STYLE_URL, color);
488 Call(SCI_STYLESETHOTSPOT, STYLE_URL, (LPARAM)TRUE);
490 Call(SCI_SETHOTSPOTACTIVEUNDERLINE, (LPARAM)TRUE);
493 void CSciEdit::SetAutoCompletionList(const std::map<CString, int>& list, TCHAR separator, TCHAR typeSeparator)
495 //copy the auto completion list.
497 //SK: instead of creating a copy of that list, we could accept a pointer
498 //to the list and use that instead. But then the caller would have to make
499 //sure that the list persists over the lifetime of the control!
500 m_autolist.clear();
501 m_autolist = list;
502 m_separator = separator;
503 m_typeSeparator = typeSeparator;
506 BOOL CSciEdit::IsMisspelled(const CString& sWord)
508 // convert the string from the control to the encoding of the spell checker module.
509 CStringA sWordA;
510 if (m_spellcodepage)
512 char * buf;
513 buf = sWordA.GetBuffer(sWord.GetLength()*4 + 1);
514 int lengthIncTerminator =
515 WideCharToMultiByte(m_spellcodepage, 0, sWord, -1, buf, sWord.GetLength()*4, NULL, NULL);
516 if (lengthIncTerminator == 0)
517 return FALSE; // converting to the codepage failed, assume word is spelled correctly
518 sWordA.ReleaseBuffer(lengthIncTerminator-1);
520 else
521 sWordA = CStringA(sWord);
522 sWordA.Trim("\'\".,");
523 // words starting with a digit are treated as correctly spelled
524 if (_istdigit(sWord.GetAt(0)))
525 return FALSE;
526 // words in the personal dictionary are correct too
527 if (m_personalDict.FindWord(sWord))
528 return FALSE;
530 // now we actually check the spelling...
531 if (!pChecker->spell(sWordA))
533 // the word is marked as misspelled, we now check whether the word
534 // is maybe a composite identifier
535 // a composite identifier consists of multiple words, with each word
536 // separated by a change in lower to uppercase letters
537 if (sWord.GetLength() > 1)
539 int wordstart = 0;
540 int wordend = 1;
541 while (wordend < sWord.GetLength())
543 while ((wordend < sWord.GetLength())&&(!_istupper(sWord[wordend])))
544 wordend++;
545 if ((wordstart == 0)&&(wordend == sWord.GetLength()))
547 // words in the auto list are also assumed correctly spelled
548 if (m_autolist.find(sWord) != m_autolist.end())
549 return FALSE;
550 return TRUE;
552 sWordA = CStringA(sWord.Mid(wordstart, wordend-wordstart));
553 if ((sWordA.GetLength() > 2)&&(!pChecker->spell(sWordA)))
555 return TRUE;
557 wordstart = wordend;
558 wordend++;
562 return FALSE;
565 void CSciEdit::CheckSpelling()
567 if (pChecker == NULL)
568 return;
570 TEXTRANGEA textrange;
572 LRESULT firstline = Call(SCI_GETFIRSTVISIBLELINE);
573 LRESULT lastline = firstline + Call(SCI_LINESONSCREEN);
574 textrange.chrg.cpMin = (LONG)Call(SCI_POSITIONFROMLINE, firstline);
575 textrange.chrg.cpMax = (LONG)textrange.chrg.cpMin;
576 LRESULT lastpos = Call(SCI_POSITIONFROMLINE, lastline) + Call(SCI_LINELENGTH, lastline);
577 if (lastpos < 0)
578 lastpos = Call(SCI_GETLENGTH)-textrange.chrg.cpMin;
579 Call(SCI_SETINDICATORCURRENT, INDIC_MISSPELLED);
580 while (textrange.chrg.cpMax < lastpos)
582 textrange.chrg.cpMin = (LONG)Call(SCI_WORDSTARTPOSITION, textrange.chrg.cpMax+1, TRUE);
583 if (textrange.chrg.cpMin < textrange.chrg.cpMax)
584 break;
585 textrange.chrg.cpMax = (LONG)Call(SCI_WORDENDPOSITION, textrange.chrg.cpMin, TRUE);
586 if (textrange.chrg.cpMin == textrange.chrg.cpMax)
588 textrange.chrg.cpMax++;
589 // since Scintilla squiggles to the end of the text even if told to stop one char before it,
590 // we have to clear here the squiggly lines to the end.
591 if (textrange.chrg.cpMin)
592 Call(SCI_INDICATORCLEARRANGE, textrange.chrg.cpMin-1, textrange.chrg.cpMax - textrange.chrg.cpMin + 1);
593 continue;
595 ATLASSERT(textrange.chrg.cpMax >= textrange.chrg.cpMin);
596 std::unique_ptr<char[]> textbuffer(new char[textrange.chrg.cpMax - textrange.chrg.cpMin + 2]);
597 SecureZeroMemory(textbuffer.get(), textrange.chrg.cpMax - textrange.chrg.cpMin + 2);
598 textrange.lpstrText = textbuffer.get();
599 textrange.chrg.cpMax++;
600 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
601 int len = (int)strlen(textrange.lpstrText);
602 if (len == 0)
604 textrange.chrg.cpMax--;
605 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
606 len = (int)strlen(textrange.lpstrText);
607 textrange.chrg.cpMax++;
608 len++;
610 if (len && textrange.lpstrText[len - 1] == '.')
612 // Try to ignore file names from the auto list.
613 // Do do this, for each word ending with '.' we extract next word and check
614 // whether the combined string is present in auto list.
615 TEXTRANGEA twoWords;
616 twoWords.chrg.cpMin = textrange.chrg.cpMin;
617 twoWords.chrg.cpMax = (LONG)Call(SCI_WORDENDPOSITION, textrange.chrg.cpMax + 1, TRUE);
618 std::unique_ptr<char[]> twoWordsBuffer(new char[twoWords.chrg.cpMax - twoWords.chrg.cpMin + 1]);
619 twoWords.lpstrText = twoWordsBuffer.get();
620 SecureZeroMemory(twoWords.lpstrText, twoWords.chrg.cpMax - twoWords.chrg.cpMin + 1);
621 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&twoWords);
622 CString sWord = StringFromControl(twoWords.lpstrText);
623 if (m_autolist.find(sWord) != m_autolist.end())
625 //mark word as correct (remove the squiggle line)
626 Call(SCI_INDICATORCLEARRANGE, twoWords.chrg.cpMin, twoWords.chrg.cpMax - twoWords.chrg.cpMin);
627 textrange.chrg.cpMax = twoWords.chrg.cpMax;
628 continue;
631 if (len)
632 textrange.lpstrText[len - 1] = 0;
633 textrange.chrg.cpMax--;
634 if (strlen(textrange.lpstrText) > 0)
636 CString sWord = StringFromControl(textrange.lpstrText);
637 if ((GetStyleAt(textrange.chrg.cpMin) != STYLE_URL) && IsMisspelled(sWord))
639 //mark word as misspelled
640 Call(SCI_INDICATORFILLRANGE, textrange.chrg.cpMin, textrange.chrg.cpMax - textrange.chrg.cpMin);
642 else
644 //mark word as correct (remove the squiggle line)
645 Call(SCI_INDICATORCLEARRANGE, textrange.chrg.cpMin, textrange.chrg.cpMax - textrange.chrg.cpMin);
646 Call(SCI_INDICATORCLEARRANGE, textrange.chrg.cpMin, textrange.chrg.cpMax - textrange.chrg.cpMin + 1);
652 void CSciEdit::SuggestSpellingAlternatives()
654 if (pChecker == NULL)
655 return;
656 CString word = GetWordUnderCursor(true);
657 Call(SCI_SETCURRENTPOS, Call(SCI_WORDSTARTPOSITION, Call(SCI_GETCURRENTPOS), TRUE));
658 if (word.IsEmpty())
659 return;
660 char ** wlst = nullptr;
661 int ns = pChecker->suggest(&wlst, CStringA(word));
662 if (ns > 0)
664 CString suggestions;
665 for (int i=0; i < ns; i++)
667 suggestions.AppendFormat(_T("%s%c%d%c"), CString(wlst[i]), m_typeSeparator, AUTOCOMPLETE_SPELLING, m_separator);
668 free(wlst[i]);
670 free(wlst);
671 suggestions.TrimRight(m_separator);
672 if (suggestions.IsEmpty())
673 return;
674 Call(SCI_AUTOCSETSEPARATOR, (WPARAM)CStringA(m_separator).GetAt(0));
675 Call(SCI_AUTOCSETTYPESEPARATOR, (WPARAM)m_typeSeparator);
676 Call(SCI_AUTOCSETDROPRESTOFWORD, 1);
677 Call(SCI_AUTOCSHOW, 0, (LPARAM)(LPCSTR)StringForControl(suggestions));
678 return;
680 free(wlst);
683 void CSciEdit::DoAutoCompletion(int nMinPrefixLength)
685 if (m_autolist.empty())
686 return;
687 if (Call(SCI_AUTOCACTIVE))
688 return;
689 CString word = GetWordUnderCursor();
690 if (word.GetLength() < nMinPrefixLength)
691 return; //don't auto complete yet, word is too short
692 int pos = (int)Call(SCI_GETCURRENTPOS);
693 if (pos != Call(SCI_WORDENDPOSITION, pos, TRUE))
694 return; //don't auto complete if we're not at the end of a word
695 CString sAutoCompleteList;
697 std::vector<CString> words;
699 pos = word.Find('-');
701 CString wordLower = word;
702 wordLower.MakeLower();
703 CString wordHigher = word;
704 wordHigher.MakeUpper();
706 words.push_back(wordLower);
707 words.push_back(wordHigher);
709 if (pos >= 0)
711 CString s = wordLower.Left(pos);
712 if (s.GetLength() >= nMinPrefixLength)
713 words.push_back(s);
714 s = wordLower.Mid(pos+1);
715 if (s.GetLength() >= nMinPrefixLength)
716 words.push_back(s);
717 s = wordHigher.Left(pos);
718 if (s.GetLength() >= nMinPrefixLength)
719 words.push_back(wordHigher.Left(pos));
720 s = wordHigher.Mid(pos+1);
721 if (s.GetLength() >= nMinPrefixLength)
722 words.push_back(wordHigher.Mid(pos+1));
725 std::map<CString, int> wordset;
726 for (const auto& w : words)
728 for (auto lowerit = m_autolist.lower_bound(w);
729 lowerit != m_autolist.end(); ++lowerit)
731 int compare = w.CompareNoCase(lowerit->first.Left(w.GetLength()));
732 if (compare>0)
733 continue;
734 else if (compare == 0)
736 wordset.insert(std::make_pair(lowerit->first, lowerit->second));
738 else
740 break;
745 for (const auto& w : wordset)
746 sAutoCompleteList.AppendFormat(_T("%s%c%d%c"), w.first, m_typeSeparator, w.second, m_separator);
748 sAutoCompleteList.TrimRight(m_separator);
749 if (sAutoCompleteList.IsEmpty())
750 return;
752 Call(SCI_AUTOCSETSEPARATOR, (WPARAM)CStringA(m_separator).GetAt(0));
753 Call(SCI_AUTOCSETTYPESEPARATOR, (WPARAM)m_typeSeparator);
754 Call(SCI_AUTOCSHOW, word.GetLength(), (LPARAM)(LPCSTR)StringForControl(sAutoCompleteList));
757 BOOL CSciEdit::OnChildNotify(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pLResult)
759 if (message != WM_NOTIFY)
760 return CWnd::OnChildNotify(message, wParam, lParam, pLResult);
762 LPNMHDR lpnmhdr = (LPNMHDR) lParam;
763 SCNotification * lpSCN = (SCNotification *)lParam;
765 if(lpnmhdr->hwndFrom==m_hWnd)
767 switch(lpnmhdr->code)
769 case SCN_CHARADDED:
771 if ((lpSCN->ch < 32)&&(lpSCN->ch != 13)&&(lpSCN->ch != 10))
772 Call(SCI_DELETEBACK);
773 else
775 DoAutoCompletion(m_nAutoCompleteMinChars);
777 return TRUE;
779 break;
780 case SCN_AUTOCSELECTION:
782 CString text = StringFromControl(lpSCN->text);
783 if (m_autolist[text] == AUTOCOMPLETE_SNIPPET)
785 Call(SCI_AUTOCCANCEL);
786 for (INT_PTR handlerindex = 0; handlerindex < m_arContextHandlers.GetCount(); ++handlerindex)
788 CSciEditContextMenuInterface * pHandler = m_arContextHandlers.GetAt(handlerindex);
789 pHandler->HandleSnippet(m_autolist[text], text, this);
792 return TRUE;
794 case SCN_STYLENEEDED:
796 int startstylepos = (int)Call(SCI_GETENDSTYLED);
797 int endstylepos = ((SCNotification *)lpnmhdr)->position;
798 MarkEnteredBugID(startstylepos, endstylepos);
799 if (m_bDoStyle)
800 StyleEnteredText(startstylepos, endstylepos);
801 StyleURLs(startstylepos, endstylepos);
802 CheckSpelling();
803 WrapLines(startstylepos, endstylepos);
804 return TRUE;
806 break;
807 case SCN_HOTSPOTCLICK:
809 TEXTRANGEA textrange;
810 textrange.chrg.cpMin = lpSCN->position;
811 textrange.chrg.cpMax = lpSCN->position;
812 DWORD style = GetStyleAt(lpSCN->position);
813 while (GetStyleAt(textrange.chrg.cpMin - 1) == style)
814 --textrange.chrg.cpMin;
815 while (GetStyleAt(textrange.chrg.cpMax + 1) == style)
816 ++textrange.chrg.cpMax;
817 ++textrange.chrg.cpMax;
818 std::unique_ptr<char[]> textbuffer(new char[textrange.chrg.cpMax - textrange.chrg.cpMin + 1]);
819 textrange.lpstrText = textbuffer.get();
820 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
821 CString url;
822 if (style == STYLE_URL)
823 url = StringFromControl(textbuffer.get());
824 else
826 url = m_sUrl;
827 url.Replace(L"%BUGID%", StringFromControl(textbuffer.get()));
829 if (!url.IsEmpty())
830 ShellExecute(GetParent()->GetSafeHwnd(), _T("open"), url, NULL, NULL, SW_SHOWDEFAULT);
832 break;
835 return CWnd::OnChildNotify(message, wParam, lParam, pLResult);
838 BEGIN_MESSAGE_MAP(CSciEdit, CWnd)
839 ON_WM_KEYDOWN()
840 ON_WM_CONTEXTMENU()
841 END_MESSAGE_MAP()
843 void CSciEdit::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
845 switch (nChar)
847 case (VK_ESCAPE):
849 if ((Call(SCI_AUTOCACTIVE)==0)&&(Call(SCI_CALLTIPACTIVE)==0))
850 ::SendMessage(GetParent()->GetSafeHwnd(), WM_CLOSE, 0, 0);
852 break;
854 CWnd::OnKeyDown(nChar, nRepCnt, nFlags);
857 BOOL CSciEdit::PreTranslateMessage(MSG* pMsg)
859 if (pMsg->message == WM_KEYDOWN)
861 switch (pMsg->wParam)
863 case VK_SPACE:
865 if (GetKeyState(VK_CONTROL) & 0x8000)
867 DoAutoCompletion(1);
868 return TRUE;
871 break;
872 case VK_TAB:
873 // The TAB cannot be handled in OnKeyDown because it is too late by then.
875 if (GetKeyState(VK_CONTROL)&0x8000)
877 //Ctrl-Tab was pressed, this means we should provide the user with
878 //a list of possible spell checking alternatives to the word under
879 //the cursor
880 SuggestSpellingAlternatives();
881 return TRUE;
883 else if (!Call(SCI_AUTOCACTIVE))
885 ::PostMessage(GetParent()->GetSafeHwnd(), WM_NEXTDLGCTL, GetKeyState(VK_SHIFT)&0x8000, 0);
886 return TRUE;
889 break;
892 return CWnd::PreTranslateMessage(pMsg);
895 void CSciEdit::OnContextMenu(CWnd* /*pWnd*/, CPoint point)
897 int anchor = (int)Call(SCI_GETANCHOR);
898 int currentpos = (int)Call(SCI_GETCURRENTPOS);
899 int selstart = (int)Call(SCI_GETSELECTIONSTART);
900 int selend = (int)Call(SCI_GETSELECTIONEND);
901 int pointpos = 0;
902 if ((point.x == -1) && (point.y == -1))
904 CRect rect;
905 GetClientRect(&rect);
906 ClientToScreen(&rect);
907 point = rect.CenterPoint();
908 pointpos = (int)Call(SCI_GETCURRENTPOS);
910 else
912 // change the cursor position to the point where the user
913 // right-clicked.
914 CPoint clientpoint = point;
915 ScreenToClient(&clientpoint);
916 pointpos = (int)Call(SCI_POSITIONFROMPOINT, clientpoint.x, clientpoint.y);
918 CString sMenuItemText;
919 CMenu popup;
920 bool bRestoreCursor = true;
921 if (popup.CreatePopupMenu())
923 bool bCanUndo = !!Call(SCI_CANUNDO);
924 bool bCanRedo = !!Call(SCI_CANREDO);
925 bool bHasSelection = (selend-selstart > 0);
926 bool bCanPaste = !!Call(SCI_CANPASTE);
927 bool bIsReadOnly = !!Call(SCI_GETREADONLY);
928 UINT uEnabledMenu = MF_STRING | MF_ENABLED;
929 UINT uDisabledMenu = MF_STRING | MF_GRAYED;
931 // find the word under the cursor
932 CString sWord;
933 if (pointpos)
935 // setting the cursor clears the selection
936 Call(SCI_SETANCHOR, pointpos);
937 Call(SCI_SETCURRENTPOS, pointpos);
938 sWord = GetWordUnderCursor();
939 // restore the selection
940 Call(SCI_SETSELECTIONSTART, selstart);
941 Call(SCI_SETSELECTIONEND, selend);
943 else
944 sWord = GetWordUnderCursor();
945 CStringA worda = CStringA(sWord);
947 int nCorrections = 1;
948 bool bSpellAdded = false;
949 // check if the word under the cursor is spelled wrong
950 if ((pChecker)&&(!worda.IsEmpty()) && !bIsReadOnly)
952 char ** wlst = nullptr;
953 // get the spell suggestions
954 int ns = pChecker->suggest(&wlst,worda);
955 if (ns > 0)
957 // add the suggestions to the context menu
958 for (int i=0; i < ns; i++)
960 bSpellAdded = true;
961 CString sug = CString(wlst[i]);
962 popup.InsertMenu((UINT)-1, 0, nCorrections++, sug);
963 free(wlst[i]);
965 free(wlst);
967 else
968 free(wlst);
970 // only add a separator if spelling correction suggestions were added
971 if (bSpellAdded)
972 popup.AppendMenu(MF_SEPARATOR);
974 // also allow the user to add the word to the custom dictionary so
975 // it won't show up as misspelled anymore
976 if ((sWord.GetLength()<PDICT_MAX_WORD_LENGTH)&&((pChecker)&&(m_autolist.find(sWord) == m_autolist.end())&&(!pChecker->spell(worda)))&&
977 (!_istdigit(sWord.GetAt(0)))&&(!m_personalDict.FindWord(sWord)) && !bIsReadOnly)
979 sMenuItemText.Format(IDS_SCIEDIT_ADDWORD, sWord);
980 popup.AppendMenu(uEnabledMenu, SCI_ADDWORD, sMenuItemText);
981 // another separator
982 popup.AppendMenu(MF_SEPARATOR);
985 // add the 'default' entries
986 sMenuItemText.LoadString(IDS_SCIEDIT_UNDO);
987 popup.AppendMenu(bCanUndo ? uEnabledMenu : uDisabledMenu, SCI_UNDO, sMenuItemText);
988 sMenuItemText.LoadString(IDS_SCIEDIT_REDO);
989 popup.AppendMenu(bCanRedo ? uEnabledMenu : uDisabledMenu, SCI_REDO, sMenuItemText);
991 popup.AppendMenu(MF_SEPARATOR);
993 sMenuItemText.LoadString(IDS_SCIEDIT_CUT);
994 popup.AppendMenu(bHasSelection ? uEnabledMenu : uDisabledMenu, SCI_CUT, sMenuItemText);
995 sMenuItemText.LoadString(IDS_SCIEDIT_COPY);
996 popup.AppendMenu(bHasSelection ? uEnabledMenu : uDisabledMenu, SCI_COPY, sMenuItemText);
997 sMenuItemText.LoadString(IDS_SCIEDIT_PASTE);
998 popup.AppendMenu(bCanPaste ? uEnabledMenu : uDisabledMenu, SCI_PASTE, sMenuItemText);
1000 popup.AppendMenu(MF_SEPARATOR);
1002 sMenuItemText.LoadString(IDS_SCIEDIT_SELECTALL);
1003 popup.AppendMenu(uEnabledMenu, SCI_SELECTALL, sMenuItemText);
1005 popup.AppendMenu(MF_SEPARATOR);
1007 sMenuItemText.LoadString(IDS_SCIEDIT_SPLITLINES);
1008 popup.AppendMenu(bHasSelection ? uEnabledMenu : uDisabledMenu, SCI_LINESSPLIT, sMenuItemText);
1010 if (m_arContextHandlers.GetCount() > 0)
1011 popup.AppendMenu(MF_SEPARATOR);
1013 int nCustoms = nCorrections;
1014 // now add any custom context menus
1015 for (INT_PTR handlerindex = 0; handlerindex < m_arContextHandlers.GetCount(); ++handlerindex)
1017 CSciEditContextMenuInterface * pHandler = m_arContextHandlers.GetAt(handlerindex);
1018 pHandler->InsertMenuItems(popup, nCustoms);
1020 #if THESAURUS
1021 if (nCustoms > nCorrections)
1023 // custom menu entries present, so add another separator
1024 popup.AppendMenu(MF_SEPARATOR);
1027 // add found thesauri to sub menu's
1028 CMenu thesaurs;
1029 int nThesaurs = 0;
1030 CPtrArray menuArray;
1031 if (thesaurs.CreatePopupMenu())
1033 if ((pThesaur)&&(!worda.IsEmpty()))
1035 mentry * pmean;
1036 worda.MakeLower();
1037 int count = pThesaur->Lookup(worda, worda.GetLength(),&pmean);
1038 if (count)
1040 mentry * pm = pmean;
1041 for (int i=0; i < count; i++)
1043 CMenu * submenu = new CMenu();
1044 menuArray.Add(submenu);
1045 submenu->CreateMenu();
1046 for (int j=0; j < pm->count; j++)
1048 CString sug = CString(pm->psyns[j]);
1049 submenu->InsertMenu((UINT)-1, 0, nCorrections + nCustoms + (nThesaurs++), sug);
1051 thesaurs.InsertMenu((UINT)-1, MF_POPUP, (UINT_PTR)(submenu->m_hMenu), CString(pm->defn));
1052 pm++;
1055 if ((count > 0)&&(point.x >= 0))
1057 #ifdef IDS_SPELLEDIT_THESAURUS
1058 sMenuItemText.LoadString(IDS_SPELLEDIT_THESAURUS);
1059 popup.InsertMenu((UINT)-1, MF_POPUP, (UINT_PTR)thesaurs.m_hMenu, sMenuItemText);
1060 #else
1061 popup.InsertMenu((UINT)-1, MF_POPUP, (UINT_PTR)thesaurs.m_hMenu, _T("Thesaurus"));
1062 #endif
1063 nThesaurs = nCustoms;
1065 else
1067 sMenuItemText.LoadString(IDS_SPELLEDIT_NOTHESAURUS);
1068 popup.AppendMenu(MF_DISABLED | MF_GRAYED | MF_STRING, 0, sMenuItemText);
1071 pThesaur->CleanUpAfterLookup(&pmean, count);
1073 else
1075 sMenuItemText.LoadString(IDS_SPELLEDIT_NOTHESAURUS);
1076 popup.AppendMenu(MF_DISABLED | MF_GRAYED | MF_STRING, 0, sMenuItemText);
1079 #endif
1080 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this, 0);
1081 switch (cmd)
1083 case 0:
1084 break; // no command selected
1085 case SCI_SELECTALL:
1086 bRestoreCursor = false;
1087 // fall through
1088 case SCI_UNDO:
1089 case SCI_REDO:
1090 case SCI_CUT:
1091 case SCI_COPY:
1092 case SCI_PASTE:
1093 Call(cmd);
1094 break;
1095 case SCI_ADDWORD:
1096 m_personalDict.AddWord(sWord);
1097 CheckSpelling();
1098 break;
1099 case SCI_LINESSPLIT:
1101 int marker = (int)(Call(SCI_GETEDGECOLUMN) * Call(SCI_TEXTWIDTH, 0, (LPARAM)" "));
1102 if (marker)
1104 Call(SCI_TARGETFROMSELECTION);
1105 Call(SCI_LINESJOIN);
1106 Call(SCI_LINESSPLIT, marker);
1109 break;
1110 default:
1111 if (cmd < nCorrections)
1113 Call(SCI_SETANCHOR, pointpos);
1114 Call(SCI_SETCURRENTPOS, pointpos);
1115 GetWordUnderCursor(true);
1116 CString temp;
1117 popup.GetMenuString(cmd, temp, 0);
1118 // setting the cursor clears the selection
1119 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)StringForControl(temp));
1121 else if (cmd < (nCorrections+nCustoms))
1123 for (INT_PTR handlerindex = 0; handlerindex < m_arContextHandlers.GetCount(); ++handlerindex)
1125 CSciEditContextMenuInterface * pHandler = m_arContextHandlers.GetAt(handlerindex);
1126 if (pHandler->HandleMenuItemClick(cmd, this))
1127 break;
1130 #if THESAURUS
1131 else if (cmd <= (nThesaurs+nCorrections+nCustoms))
1133 Call(SCI_SETANCHOR, pointpos);
1134 Call(SCI_SETCURRENTPOS, pointpos);
1135 GetWordUnderCursor(true);
1136 CString temp;
1137 thesaurs.GetMenuString(cmd, temp, 0);
1138 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)StringForControl(temp));
1140 #endif
1142 #ifdef THESAURUS
1143 for (INT_PTR index = 0; index < menuArray.GetCount(); ++index)
1145 CMenu * pMenu = (CMenu*)menuArray[index];
1146 delete pMenu;
1148 #endif
1150 if (bRestoreCursor)
1152 // restore the anchor and cursor position
1153 Call(SCI_SETCURRENTPOS, currentpos);
1154 Call(SCI_SETANCHOR, anchor);
1158 bool CSciEdit::StyleEnteredText(int startstylepos, int endstylepos)
1160 bool bStyled = false;
1161 const int line = (int)Call(SCI_LINEFROMPOSITION, startstylepos);
1162 const int line_number_end = (int)Call(SCI_LINEFROMPOSITION, endstylepos);
1163 for (int line_number = line; line_number <= line_number_end; ++line_number)
1165 int offset = (int)Call(SCI_POSITIONFROMLINE, line_number);
1166 int line_len = (int)Call(SCI_LINELENGTH, line_number);
1167 std::unique_ptr<char[]> linebuffer(new char[line_len+1]);
1168 Call(SCI_GETLINE, line_number, (LPARAM)linebuffer.get());
1169 linebuffer[line_len] = 0;
1170 int start = 0;
1171 int end = 0;
1172 while (FindStyleChars(linebuffer.get(), '*', start, end))
1174 Call(SCI_STARTSTYLING, start+offset, STYLE_MASK);
1175 Call(SCI_SETSTYLING, end-start, STYLE_BOLD);
1176 bStyled = true;
1177 start = end;
1179 start = 0;
1180 end = 0;
1181 while (FindStyleChars(linebuffer.get(), '^', start, end))
1183 Call(SCI_STARTSTYLING, start+offset, STYLE_MASK);
1184 Call(SCI_SETSTYLING, end-start, STYLE_ITALIC);
1185 bStyled = true;
1186 start = end;
1188 start = 0;
1189 end = 0;
1190 while (FindStyleChars(linebuffer.get(), '_', start, end))
1192 Call(SCI_STARTSTYLING, start+offset, STYLE_MASK);
1193 Call(SCI_SETSTYLING, end-start, STYLE_UNDERLINED);
1194 bStyled = true;
1195 start = end;
1198 return bStyled;
1201 bool CSciEdit::WrapLines(int startpos, int endpos)
1203 int markerX = (int)(Call(SCI_GETEDGECOLUMN) * Call(SCI_TEXTWIDTH, 0, (LPARAM)" "));
1204 if (markerX)
1206 Call(SCI_SETTARGETSTART, startpos);
1207 Call(SCI_SETTARGETEND, endpos);
1208 Call(SCI_LINESSPLIT, markerX);
1209 return true;
1211 return false;
1214 void CSciEdit::AdvanceUTF8(const char * str, int& pos)
1216 if ((str[pos] & 0xE0)==0xC0)
1218 // utf8 2-byte sequence
1219 pos += 2;
1221 else if ((str[pos] & 0xF0)==0xE0)
1223 // utf8 3-byte sequence
1224 pos += 3;
1226 else if ((str[pos] & 0xF8)==0xF0)
1228 // utf8 4-byte sequence
1229 pos += 4;
1231 else
1232 pos++;
1235 bool CSciEdit::FindStyleChars(const char * line, char styler, int& start, int& end)
1237 int i=0;
1238 int u=0;
1239 while (i < start)
1241 AdvanceUTF8(line, i);
1242 u++;
1245 bool bFoundMarker = false;
1246 CString sULine = CUnicodeUtils::GetUnicode(line);
1247 // find a starting marker
1248 while (line[i] != 0)
1250 if (line[i] == styler)
1252 if ((line[i+1]!=0)&&(IsCharAlphaNumeric(sULine[u+1]))&&
1253 (((u>0)&&(!IsCharAlphaNumeric(sULine[u-1]))) || (u==0)))
1255 start = i+1;
1256 AdvanceUTF8(line, i);
1257 u++;
1258 bFoundMarker = true;
1259 break;
1262 AdvanceUTF8(line, i);
1263 u++;
1265 if (!bFoundMarker)
1266 return false;
1267 // find ending marker
1268 bFoundMarker = false;
1269 while (line[i] != 0)
1271 if (line[i] == styler)
1273 if ((IsCharAlphaNumeric(sULine[u-1]))&&
1274 ((((u+1)<sULine.GetLength())&&(!IsCharAlphaNumeric(sULine[u+1]))) || ((u+1) == sULine.GetLength()))
1277 end = i;
1278 i++;
1279 bFoundMarker = true;
1280 break;
1283 AdvanceUTF8(line, i);
1284 u++;
1286 return bFoundMarker;
1289 BOOL CSciEdit::MarkEnteredBugID(int startstylepos, int endstylepos)
1291 if (m_sCommand.IsEmpty())
1292 return FALSE;
1293 // get the text between the start and end position we have to style
1294 const int line_number = (int)Call(SCI_LINEFROMPOSITION, startstylepos);
1295 int start_pos = (int)Call(SCI_POSITIONFROMLINE, (WPARAM)line_number);
1296 int end_pos = endstylepos;
1298 if (start_pos == end_pos)
1299 return FALSE;
1300 if (start_pos > end_pos)
1302 int switchtemp = start_pos;
1303 start_pos = end_pos;
1304 end_pos = switchtemp;
1307 std::unique_ptr<char[]> textbuffer(new char[end_pos - start_pos + 2]);
1308 TEXTRANGEA textrange;
1309 textrange.lpstrText = textbuffer.get();
1310 textrange.chrg.cpMin = start_pos;
1311 textrange.chrg.cpMax = end_pos;
1312 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
1313 CStringA msg = CStringA(textbuffer.get());
1315 Call(SCI_STARTSTYLING, start_pos, STYLE_MASK);
1319 if (!m_sBugID.IsEmpty())
1321 // match with two regex strings (without grouping!)
1322 const std::tr1::regex regCheck(m_sCommand);
1323 const std::tr1::regex regBugID(m_sBugID);
1324 const std::tr1::sregex_iterator end;
1325 std::string s = msg;
1326 LONG pos = 0;
1327 // note:
1328 // if start_pos is 0, we're styling from the beginning and let the ^ char match the beginning of the line
1329 // that way, the ^ matches the very beginning of the log message and not the beginning of further lines.
1330 // problem is: this only works *while* entering log messages. If a log message is pasted in whole or
1331 // multiple lines are pasted, start_pos can be 0 and styling goes over multiple lines. In that case, those
1332 // additional line starts also match ^
1333 for (std::tr1::sregex_iterator it(s.begin(), s.end(), regCheck, start_pos != 0 ? std::tr1::regex_constants::match_not_bol : std::tr1::regex_constants::match_default); it != end; ++it)
1335 // clear the styles up to the match position
1336 Call(SCI_SETSTYLING, it->position(0)-pos, STYLE_DEFAULT);
1338 // (*it)[0] is the matched string
1339 std::string matchedString = (*it)[0];
1340 LONG matchedpos = 0;
1341 for (std::tr1::sregex_iterator it2(matchedString.begin(), matchedString.end(), regBugID); it2 != end; ++it2)
1343 ATLTRACE("matched id : %s\n", std::string((*it2)[0]).c_str());
1345 // bold style up to the id match
1346 ATLTRACE("position = %ld\n", it2->position(0));
1347 if (it2->position(0))
1348 Call(SCI_SETSTYLING, it2->position(0) - matchedpos, STYLE_ISSUEBOLD);
1349 // bold and recursive style for the bug ID itself
1350 if ((*it2)[0].str().size())
1351 Call(SCI_SETSTYLING, (*it2)[0].str().size(), STYLE_ISSUEBOLDITALIC);
1352 matchedpos = (LONG)(it2->position(0) + (*it2)[0].str().size());
1354 if ((matchedpos)&&(matchedpos < (LONG)matchedString.size()))
1356 Call(SCI_SETSTYLING, matchedString.size() - matchedpos, STYLE_ISSUEBOLD);
1358 pos = (LONG)(it->position(0) + matchedString.size());
1360 // bold style for the rest of the string which isn't matched
1361 if (s.size()-pos)
1362 Call(SCI_SETSTYLING, s.size()-pos, STYLE_DEFAULT);
1364 else
1366 const std::tr1::regex regCheck(m_sCommand);
1367 const std::tr1::sregex_iterator end;
1368 std::string s = msg;
1369 LONG pos = 0;
1370 for (std::tr1::sregex_iterator it(s.begin(), s.end(), regCheck); it != end; ++it)
1372 // clear the styles up to the match position
1373 if (it->position(0) - pos >= 0)
1374 Call(SCI_SETSTYLING, it->position(0) - pos, STYLE_DEFAULT);
1375 pos = (LONG)it->position(0);
1377 const std::tr1::smatch match = *it;
1378 // we define group 1 as the whole issue text and
1379 // group 2 as the bug ID
1380 if (match.size() >= 2)
1382 ATLTRACE("matched id : %s\n", std::string(match[1]).c_str());
1383 if (match[1].first - s.begin() - pos >= 0)
1384 Call(SCI_SETSTYLING, match[1].first - s.begin() - pos, STYLE_ISSUEBOLD);
1385 Call(SCI_SETSTYLING, std::string(match[1]).size(), STYLE_ISSUEBOLDITALIC);
1386 pos = (LONG)(match[1].second-s.begin());
1391 catch (std::exception) {}
1393 return FALSE;
1396 bool CSciEdit::IsValidURLChar(unsigned char ch)
1398 return isalnum(ch) ||
1399 ch == '_' || ch == '/' || ch == ';' || ch == '?' || ch == '&' || ch == '=' ||
1400 ch == '%' || ch == ':' || ch == '.' || ch == '#' || ch == '-' || ch == '+';
1403 void CSciEdit::StyleURLs(int startstylepos, int endstylepos)
1405 const int line_number = (int)Call(SCI_LINEFROMPOSITION, startstylepos);
1406 startstylepos = (int)Call(SCI_POSITIONFROMLINE, (WPARAM)line_number);
1408 int len = endstylepos - startstylepos + 1;
1409 std::unique_ptr<char[]> textbuffer(new char[len + 1]);
1410 TEXTRANGEA textrange;
1411 textrange.lpstrText = textbuffer.get();
1412 textrange.chrg.cpMin = startstylepos;
1413 textrange.chrg.cpMax = endstylepos;
1414 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
1415 // we're dealing with utf8 encoded text here, which means one glyph is
1416 // not necessarily one byte/wchar_t
1417 // that's why we use CStringA to still get a correct char index
1418 CStringA msg = textbuffer.get();
1420 int starturl = -1;
1421 for(int i = 0; i <= msg.GetLength(); )
1423 if ((i < len) && IsValidURLChar(msg[i]))
1425 if (starturl < 0)
1426 starturl = i;
1428 else
1430 if ((starturl >= 0) && IsUrl(msg.Mid(starturl, i - starturl)))
1432 ASSERT(startstylepos + i <= endstylepos);
1433 Call(SCI_STARTSTYLING, startstylepos + starturl, STYLE_MASK);
1434 Call(SCI_SETSTYLING, i - starturl, STYLE_URL);
1436 starturl = -1;
1438 AdvanceUTF8(msg, i);
1442 bool CSciEdit::IsUrl(const CStringA& sText)
1444 if (!PathIsURLA(sText))
1445 return false;
1446 if (sText.Find("://")>=0)
1447 return true;
1448 return false;
1451 bool CSciEdit::IsUTF8(LPVOID pBuffer, size_t cb)
1453 if (cb < 2)
1454 return true;
1455 UINT16 * pVal = (UINT16 *)pBuffer;
1456 UINT8 * pVal2 = (UINT8 *)(pVal+1);
1457 // scan the whole buffer for a 0x0000 sequence
1458 // if found, we assume a binary file
1459 for (size_t i=0; i<(cb-2); i=i+2)
1461 if (0x0000 == *pVal++)
1462 return false;
1464 pVal = (UINT16 *)pBuffer;
1465 if (*pVal == 0xFEFF)
1466 return false;
1467 if (cb < 3)
1468 return false;
1469 if (*pVal == 0xBBEF)
1471 if (*pVal2 == 0xBF)
1472 return true;
1474 // check for illegal UTF8 chars
1475 pVal2 = (UINT8 *)pBuffer;
1476 for (size_t i=0; i<cb; ++i)
1478 if ((*pVal2 == 0xC0)||(*pVal2 == 0xC1)||(*pVal2 >= 0xF5))
1479 return false;
1480 pVal2++;
1482 pVal2 = (UINT8 *)pBuffer;
1483 bool bUTF8 = false;
1484 for (size_t i=0; i<(cb-3); ++i)
1486 if ((*pVal2 & 0xE0)==0xC0)
1488 pVal2++;i++;
1489 if ((*pVal2 & 0xC0)!=0x80)
1490 return false;
1491 bUTF8 = true;
1493 if ((*pVal2 & 0xF0)==0xE0)
1495 pVal2++;i++;
1496 if ((*pVal2 & 0xC0)!=0x80)
1497 return false;
1498 pVal2++;i++;
1499 if ((*pVal2 & 0xC0)!=0x80)
1500 return false;
1501 bUTF8 = true;
1503 if ((*pVal2 & 0xF8)==0xF0)
1505 pVal2++;i++;
1506 if ((*pVal2 & 0xC0)!=0x80)
1507 return false;
1508 pVal2++;i++;
1509 if ((*pVal2 & 0xC0)!=0x80)
1510 return false;
1511 pVal2++;i++;
1512 if ((*pVal2 & 0xC0)!=0x80)
1513 return false;
1514 bUTF8 = true;
1516 pVal2++;
1518 if (bUTF8)
1519 return true;
1520 return false;
1523 void CSciEdit::SetAStyle(int style, COLORREF fore, COLORREF back, int size, const char *face)
1525 Call(SCI_STYLESETFORE, style, fore);
1526 Call(SCI_STYLESETBACK, style, back);
1527 if (size >= 1)
1528 Call(SCI_STYLESETSIZE, style, size);
1529 if (face)
1530 Call(SCI_STYLESETFONT, style, reinterpret_cast<LPARAM>(face));
1534 void CSciEdit::SetUDiffStyle()
1536 SetAStyle(STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT), ::GetSysColor(COLOR_WINDOW),
1537 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffFontSize", 10),
1538 CUnicodeUtils::StdGetUTF8(CRegStdString(L"Software\\TortoiseGit\\UDiffFontName", L"Courier New")).c_str());
1539 Call(SCI_SETTABWIDTH, CRegStdDWORD(L"Software\\TortoiseGit\\UDiffTabSize", 4));
1541 Call(SCI_SETTABWIDTH, 4);
1542 Call(SCI_SETREADONLY, TRUE);
1543 //LRESULT pix = Call(SCI_TEXTWIDTH, STYLE_LINENUMBER, (LPARAM)"_99999");
1544 //Call(SCI_SETMARGINWIDTHN, 0, pix);
1545 //Call(SCI_SETMARGINWIDTHN, 1);
1546 //Call(SCI_SETMARGINWIDTHN, 2);
1547 //Set the default windows colors for edit controls
1548 Call(SCI_STYLESETFORE, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT));
1549 Call(SCI_STYLESETBACK, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOW));
1550 Call(SCI_SETSELFORE, TRUE, ::GetSysColor(COLOR_HIGHLIGHTTEXT));
1551 Call(SCI_SETSELBACK, TRUE, ::GetSysColor(COLOR_HIGHLIGHT));
1552 Call(SCI_SETCARETFORE, ::GetSysColor(COLOR_WINDOWTEXT));
1554 //SendEditor(SCI_SETREADONLY, FALSE);
1555 Call(SCI_CLEARALL);
1556 Call(EM_EMPTYUNDOBUFFER);
1557 Call(SCI_SETSAVEPOINT);
1558 Call(SCI_CANCEL);
1559 Call(SCI_SETUNDOCOLLECTION, 0);
1561 Call(SCI_SETUNDOCOLLECTION, 1);
1562 Call(SCI_SETWRAPMODE,SC_WRAP_NONE);
1564 //::SetFocus(m_hWndEdit);
1565 Call(EM_EMPTYUNDOBUFFER);
1566 Call(SCI_SETSAVEPOINT);
1567 Call(SCI_GOTOPOS, 0);
1569 Call(SCI_CLEARDOCUMENTSTYLE, 0, 0);
1570 Call(SCI_SETSTYLEBITS, 5, 0);
1572 //SetAStyle(SCE_DIFF_DEFAULT, RGB(0, 0, 0));
1573 SetAStyle(SCE_DIFF_COMMAND,
1574 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeCommandColor", UDIFF_COLORFORECOMMAND),
1575 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackCommandColor", UDIFF_COLORBACKCOMMAND));
1576 SetAStyle(SCE_DIFF_POSITION,
1577 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForePositionColor", UDIFF_COLORFOREPOSITION),
1578 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackPositionColor", UDIFF_COLORBACKPOSITION));
1579 SetAStyle(SCE_DIFF_HEADER,
1580 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeHeaderColor", UDIFF_COLORFOREHEADER),
1581 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackHeaderColor", UDIFF_COLORBACKHEADER));
1582 SetAStyle(SCE_DIFF_COMMENT,
1583 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeCommentColor", UDIFF_COLORFORECOMMENT),
1584 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackCommentColor", UDIFF_COLORBACKCOMMENT));
1585 Call(SCI_STYLESETBOLD, SCE_DIFF_COMMENT, TRUE);
1586 SetAStyle(SCE_DIFF_ADDED,
1587 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeAddedColor", UDIFF_COLORFOREADDED),
1588 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackAddedColor", UDIFF_COLORBACKADDED));
1589 SetAStyle(SCE_DIFF_DELETED,
1590 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeRemovedColor", UDIFF_COLORFOREREMOVED),
1591 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackRemovedColor", UDIFF_COLORBACKREMOVED));
1593 Call(SCI_SETLEXER, SCLEX_DIFF);
1594 Call(SCI_SETKEYWORDS, 0, (LPARAM)"revision");
1595 Call(SCI_COLOURISE, 0, -1);
1598 int CSciEdit::LoadFromFile(CString &filename)
1600 FILE *fp = NULL;
1601 _tfopen_s(&fp, filename, _T("rb"));
1602 if (fp)
1604 //SetTitle();
1605 char data[4096] = { 0 };
1606 size_t lenFile = fread(data, 1, sizeof(data), fp);
1607 bool bUTF8 = IsUTF8(data, lenFile);
1608 while (lenFile > 0)
1610 Call(SCI_ADDTEXT, lenFile,
1611 reinterpret_cast<LPARAM>(static_cast<char *>(data)));
1612 lenFile = fread(data, 1, sizeof(data), fp);
1614 fclose(fp);
1615 Call(SCI_SETCODEPAGE, bUTF8 ? SC_CP_UTF8 : GetACP());
1616 return 0;
1618 else
1619 return -1;
1622 void CSciEdit::RestyleBugIDs()
1624 int endstylepos = (int)Call(SCI_GETLENGTH);
1625 // clear all styles
1626 Call(SCI_STARTSTYLING, 0, STYLE_MASK);
1627 Call(SCI_SETSTYLING, endstylepos, STYLE_DEFAULT);
1628 // style the bug IDs
1629 MarkEnteredBugID(0, endstylepos);