Adjust for Scintilla 4.0.3 and fix warnings
[TortoiseGit.git] / src / Utils / MiscUI / SciEdit.cpp
blob307a1db94286c5b6babc7cd116a83c659ae54f75
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2009-2018 - TortoiseGit
4 // Copyright (C) 2003-2008, 2012-2018 - 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 "SmartHandle.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 , m_spellcodepage(0)
75 , m_separator(0)
76 , m_typeSeparator(1)
77 , m_bDoStyle(false)
78 , m_nAutoCompleteMinChars(3)
79 , m_SpellingCache(2000)
80 , m_blockModifiedHandler(false)
82 m_hModule = ::LoadLibrary(L"SciLexer_tgit.dll");
85 CSciEdit::~CSciEdit(void)
87 m_personalDict.Save();
90 static std::unique_ptr<UINT[]> Icon2Image(HICON hIcon)
92 if (hIcon == nullptr)
93 return nullptr;
95 ICONINFO iconInfo;
96 if (!GetIconInfo(hIcon, &iconInfo))
97 return nullptr;
99 BITMAP bm;
100 if (!GetObject(iconInfo.hbmColor, sizeof(BITMAP), &bm))
101 return nullptr;
103 int width = bm.bmWidth;
104 int height = bm.bmHeight;
105 int bytesPerScanLine = (width * 3 + 3) & 0xFFFFFFFC;
106 int size = bytesPerScanLine * height;
107 BITMAPINFO infoheader;
108 infoheader.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
109 infoheader.bmiHeader.biWidth = width;
110 infoheader.bmiHeader.biHeight = height;
111 infoheader.bmiHeader.biPlanes = 1;
112 infoheader.bmiHeader.biBitCount = 24;
113 infoheader.bmiHeader.biCompression = BI_RGB;
114 infoheader.bmiHeader.biSizeImage = size;
116 auto ptrb = std::make_unique<BYTE[]>(size * 2 + height * width * 4);
117 LPBYTE pixelsIconRGB = ptrb.get();
118 LPBYTE alphaPixels = pixelsIconRGB + size;
119 HDC hDC = CreateCompatibleDC(nullptr);
120 SCOPE_EXIT { DeleteDC(hDC); };
121 HBITMAP hBmpOld = (HBITMAP)SelectObject(hDC, (HGDIOBJ)iconInfo.hbmColor);
122 if (!GetDIBits(hDC, iconInfo.hbmColor, 0, height, (LPVOID)pixelsIconRGB, &infoheader, DIB_RGB_COLORS))
123 return nullptr;
125 SelectObject(hDC, hBmpOld);
126 if (!GetDIBits(hDC, iconInfo.hbmMask, 0,height, (LPVOID)alphaPixels, &infoheader, DIB_RGB_COLORS))
127 return nullptr;
129 auto imagePixels = std::make_unique<UINT[]>(height * width);
130 int lsSrc = width * 3;
131 int vsDest = height - 1;
132 for (int y = 0; y < height; y++)
134 int linePosSrc = (vsDest - y) * lsSrc;
135 int linePosDest = y * width;
136 for (int x = 0; x < width; x++)
138 int currentDestPos = linePosDest + x;
139 int currentSrcPos = linePosSrc + x * 3;
140 imagePixels[currentDestPos] = (((UINT)(
142 ((pixelsIconRGB[currentSrcPos + 2] /*Red*/)
143 | (pixelsIconRGB[currentSrcPos + 1] << 8 /*Green*/))
144 | pixelsIconRGB[currentSrcPos] << 16 /*Blue*/
146 | ((alphaPixels[currentSrcPos] ? 0 : 0xff) << 24))) & 0xffffffff);
149 return imagePixels;
152 void CSciEdit::SetColors(bool recolorize)
154 Call(SCI_STYLESETFORE, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT));
155 Call(SCI_STYLESETBACK, STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOW));
156 Call(SCI_SETSELFORE, TRUE, ::GetSysColor(COLOR_HIGHLIGHTTEXT));
157 Call(SCI_SETSELBACK, TRUE, ::GetSysColor(COLOR_HIGHLIGHT));
158 Call(SCI_SETCARETFORE, ::GetSysColor(COLOR_WINDOWTEXT));
160 if (recolorize)
161 Call(SCI_COLOURISE, 0, -1);
164 void CSciEdit::Init(LONG lLanguage)
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 SetColors(false);
179 Call(SCI_SETMODEVENTMASK, SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT | SC_PERFORMED_UNDO | SC_PERFORMED_REDO);
180 Call(SCI_INDICSETSTYLE, INDIC_MISSPELLED, INDIC_SQUIGGLE);
181 Call(SCI_INDICSETFORE, INDIC_MISSPELLED, RGB(255,0,0));
182 CStringA sWordChars;
183 CStringA sWhiteSpace;
184 for (int i=0; i<255; ++i)
186 if (i == '\r' || i == '\n')
187 continue;
188 else if (i < 0x20 || i == ' ')
189 sWhiteSpace += (char)i;
190 else if (isalnum(i) || i == '\'' || i == '_' || i == '-')
191 sWordChars += (char)i;
193 Call(SCI_SETWORDCHARS, 0, (LPARAM)(LPCSTR)sWordChars);
194 Call(SCI_SETWHITESPACECHARS, 0, (LPARAM)(LPCSTR)sWhiteSpace);
195 m_bDoStyle = ((DWORD)CRegStdDWORD(L"Software\\TortoiseGit\\StyleCommitMessages", TRUE)) == TRUE;
196 m_nAutoCompleteMinChars = (int)(DWORD)CRegStdDWORD(L"Software\\TortoiseGit\\AutoCompleteMinChars", 3);
197 // look for dictionary files and use them if found
198 if ((lLanguage >= 0) && (((DWORD)CRegStdDWORD(L"Software\\TortoiseGit\\Spellchecker", TRUE)) == TRUE))
200 if (!lLanguage || (lLanguage && !LoadDictionaries(lLanguage)))
202 long langId = GetUserDefaultLCID();
205 LoadDictionaries(langId);
206 DWORD lid = SUBLANGID(langId);
207 lid--;
208 if (lid > 0)
209 langId = MAKELANGID(PRIMARYLANGID(langId), lid);
210 else if (langId == 1033)
211 langId = 0;
212 else
213 langId = 1033;
214 } while (langId && (!pChecker || !pThesaur));
218 Call(SCI_SETEDGEMODE, EDGE_NONE);
219 Call(SCI_SETWRAPMODE, SC_WRAP_WORD);
220 Call(SCI_ASSIGNCMDKEY, SCK_END, SCI_LINEENDWRAP);
221 Call(SCI_ASSIGNCMDKEY, SCK_END + (SCMOD_SHIFT << 16), SCI_LINEENDWRAPEXTEND);
222 Call(SCI_ASSIGNCMDKEY, SCK_HOME, SCI_HOMEWRAP);
223 Call(SCI_ASSIGNCMDKEY, SCK_HOME + (SCMOD_SHIFT << 16), SCI_HOMEWRAPEXTEND);
224 if (CRegStdDWORD(L"Software\\TortoiseGit\\ScintillaDirect2D", FALSE) != FALSE)
226 // set font quality for the popup window, since that window does not use D2D
227 Call(SCI_SETFONTQUALITY, SC_EFF_QUALITY_LCD_OPTIMIZED);
228 // now enable D2D
229 Call(SCI_SETTECHNOLOGY, SC_TECHNOLOGY_DIRECTWRITERETAIN);
230 Call(SCI_SETBUFFEREDDRAW, 0);
235 void CSciEdit::Init(const ProjectProperties& props)
237 Init(props.lProjectLanguage);
238 m_sCommand = CUnicodeUtils::GetUTF8(props.GetCheckRe());
239 m_sBugID = CUnicodeUtils::GetUTF8(props.GetBugIDRe());
240 m_sUrl = CUnicodeUtils::GetUTF8(props.sUrl);
242 Call(SCI_SETMOUSEDWELLTIME, 333);
244 if (props.nLogWidthMarker)
246 Call(SCI_SETWRAPMODE, SC_WRAP_NONE);
247 Call(SCI_SETEDGEMODE, EDGE_LINE);
248 Call(SCI_SETEDGECOLUMN, props.nLogWidthMarker);
249 Call(SCI_SETSCROLLWIDTHTRACKING, TRUE);
250 Call(SCI_SETSCROLLWIDTH, 1);
252 else
254 Call(SCI_SETEDGEMODE, EDGE_NONE);
255 Call(SCI_SETWRAPMODE, SC_WRAP_WORD);
259 void CSciEdit::SetIcon(const std::map<int, UINT> &icons)
261 int iconWidth = GetSystemMetrics(SM_CXSMICON);
262 int iconHeight = GetSystemMetrics(SM_CYSMICON);
263 Call(SCI_RGBAIMAGESETWIDTH, iconWidth);
264 Call(SCI_RGBAIMAGESETHEIGHT, iconHeight);
265 for (auto icon : icons)
267 auto hIcon = (HICON)::LoadImage(AfxGetInstanceHandle(), MAKEINTRESOURCE(icon.second), IMAGE_ICON, iconWidth, iconHeight, LR_DEFAULTCOLOR);
268 auto bytes = Icon2Image(hIcon);
269 DestroyIcon(hIcon);
270 Call(SCI_REGISTERRGBAIMAGE, icon.first, (LPARAM)bytes.get());
274 BOOL CSciEdit::LoadDictionaries(LONG lLanguageID)
276 //Setup the spell checker and thesaurus
277 TCHAR buf[6] = { 0 };
278 CString sFolderUp = CPathUtils::GetAppParentDirectory();
279 CString sFolderAppData = CPathUtils::GetAppDataDirectory();
280 CString sFile;
282 GetLocaleInfo(MAKELCID(lLanguageID, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf));
283 sFile = buf;
284 if (lLanguageID == 2074)
285 sFile += L"-Latn";
286 sFile += L'_';
287 GetLocaleInfo(MAKELCID(lLanguageID, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf));
288 sFile += buf;
289 if (!pChecker)
291 if ((PathFileExists(sFolderAppData + L"dic\\" + sFile + L".aff")) &&
292 (PathFileExists(sFolderAppData + L"dic\\" + sFile + L".dic")))
294 pChecker = std::make_unique<Hunspell>(CStringA(sFolderAppData + L"dic\\" + sFile + L".aff"), CStringA(sFolderAppData + L"dic\\" + sFile + L".dic"));
296 else if ((PathFileExists(sFolderUp + L"Languages\\" + sFile + L".aff")) &&
297 (PathFileExists(sFolderUp + L"Languages\\" + sFile + L".dic")))
299 pChecker = std::make_unique<Hunspell>(CStringA(sFolderUp + L"Languages\\" + sFile + L".aff"), CStringA(sFolderUp + L"Languages\\" + sFile + L".dic"));
301 if (pChecker)
303 const char* encoding = pChecker->get_dic_encoding();
304 CTraceToOutputDebugString::Instance()(__FUNCTION__ ": %s\n", encoding);
305 m_spellcodepage = 0;
306 for (int i = 0; i < _countof(enc2locale); ++i)
308 if (strcmp(encoding, enc2locale[i].def_enc) == 0)
309 m_spellcodepage = atoi(enc2locale[i].cp);
311 m_personalDict.Init(lLanguageID);
314 #if THESAURUS
315 if (!pThesaur)
317 if ((PathFileExists(sFolderAppData + L"dic\\th_" + sFile + L"_v2.idx")) &&
318 (PathFileExists(sFolderAppData + L"dic\\th_" + sFile + L"_v2.dat")))
320 pThesaur = std::make_unique<MyThes>(CStringA(sFolderAppData + L"dic\\th_" + sFile + L"_v2.idx"), CStringA(sFolderAppData + L"dic\\th_" + sFile + L"_v2.dat"));
322 else if ((PathFileExists(sFolderUp + L"Languages\\th_" + sFile + L"_v2.idx")) &&
323 (PathFileExists(sFolderUp + L"Languages\\th_" + sFile + L"_v2.dat")))
325 pThesaur = std::make_unique<MyThes>(CStringA(sFolderUp + L"Languages\\th_" + sFile + L"_v2.idx"), CStringA(sFolderUp + L"Languages\\th_" + sFile + L"_v2.dat"));
328 #endif
329 if ((pThesaur)||(pChecker))
330 return TRUE;
331 return FALSE;
334 LRESULT CSciEdit::Call(UINT message, WPARAM wParam, LPARAM lParam)
336 ASSERT(::IsWindow(m_hWnd)); //Window must be valid
337 ASSERT(m_DirectFunction); //Direct function must be valid
338 return ((SciFnDirect) m_DirectFunction)(m_DirectPointer, message, wParam, lParam);
341 CString CSciEdit::StringFromControl(const CStringA& text)
343 CString sText;
344 #ifdef UNICODE
345 int codepage = (int)Call(SCI_GETCODEPAGE);
346 int reslen = MultiByteToWideChar(codepage, 0, text, text.GetLength(), 0, 0);
347 MultiByteToWideChar(codepage, 0, text, text.GetLength(), sText.GetBuffer(reslen+1), reslen+1);
348 sText.ReleaseBuffer(reslen);
349 #else
350 sText = text;
351 #endif
352 return sText;
355 CStringA CSciEdit::StringForControl(const CString& text)
357 CStringA sTextA;
358 #ifdef UNICODE
359 int codepage = (int)SendMessage(SCI_GETCODEPAGE);
360 int reslen = WideCharToMultiByte(codepage, 0, text, text.GetLength(), 0, 0, 0, 0);
361 WideCharToMultiByte(codepage, 0, text, text.GetLength(), sTextA.GetBuffer(reslen), reslen, 0, 0);
362 sTextA.ReleaseBuffer(reslen);
363 #else
364 sTextA = text;
365 #endif
366 ATLTRACE("string length %d\n", sTextA.GetLength());
367 return sTextA;
370 void CSciEdit::SetText(const CString& sText)
372 CStringA sTextA = StringForControl(sText);
373 Call(SCI_SETTEXT, 0, (LPARAM)(LPCSTR)sTextA);
375 if (Call(SCI_GETSCROLLWIDTHTRACKING) != 0)
376 Call(SCI_SETSCROLLWIDTH, 1);
378 // Scintilla seems to have problems with strings that
379 // aren't terminated by a newline char. Once that char
380 // is there, it can be removed without problems.
381 // So we add here a newline, then remove it again.
382 Call(SCI_DOCUMENTEND);
383 Call(SCI_NEWLINE);
384 Call(SCI_DELETEBACK);
387 void CSciEdit::InsertText(const CString& sText, bool bNewLine)
389 CStringA sTextA = StringForControl(sText);
390 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)sTextA);
391 if (bNewLine)
392 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)"\n");
395 CString CSciEdit::GetText()
397 auto len = (int)Call(SCI_GETTEXT, 0, 0);
398 CStringA sTextA;
399 Call(SCI_GETTEXT, (WPARAM)(len + 1), (LPARAM)(LPCSTR)CStrBufA(sTextA, len + 1));
400 return StringFromControl(sTextA);
403 CString CSciEdit::GetWordUnderCursor(bool bSelectWord, bool allchars)
405 Sci_TextRange textrange;
406 auto pos = (Sci_Position)Call(SCI_GETCURRENTPOS);
407 textrange.chrg.cpMin = (int)Call(SCI_WORDSTARTPOSITION, pos, TRUE);
408 if ((pos == textrange.chrg.cpMin)||(textrange.chrg.cpMin < 0))
409 return CString();
410 textrange.chrg.cpMax = (int)Call(SCI_WORDENDPOSITION, textrange.chrg.cpMin, TRUE);
412 auto textbuffer = std::make_unique<char[]>(textrange.chrg.cpMax - textrange.chrg.cpMin + 1);
413 textrange.lpstrText = textbuffer.get();
414 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
415 CString sRet = StringFromControl(textbuffer.get());
416 if (m_bDoStyle && !allchars)
418 for (const auto styleindicator : { '*', '_', '^' })
420 if (sRet.IsEmpty())
421 break;
422 if (sRet[sRet.GetLength() - 1] == styleindicator)
424 --textrange.chrg.cpMax;
425 sRet.Truncate(sRet.GetLength() - 1);
427 if (sRet.IsEmpty())
428 break;
429 if (sRet[0] == styleindicator)
431 ++textrange.chrg.cpMin;
432 sRet = sRet.Right(sRet.GetLength() - 1);
436 if (bSelectWord)
437 Call(SCI_SETSEL, textrange.chrg.cpMin, textrange.chrg.cpMax);
438 return sRet;
441 void CSciEdit::SetFont(CString sFontName, int iFontSizeInPoints)
443 Call(SCI_STYLESETFONT, STYLE_DEFAULT, (LPARAM)(LPCSTR)CUnicodeUtils::GetUTF8(sFontName).GetBuffer());
444 Call(SCI_STYLESETSIZE, STYLE_DEFAULT, iFontSizeInPoints);
445 Call(SCI_STYLECLEARALL);
447 LPARAM color = (LPARAM)GetSysColor(COLOR_HOTLIGHT);
448 // set the styles for the bug ID strings
449 Call(SCI_STYLESETBOLD, STYLE_ISSUEBOLD, (LPARAM)TRUE);
450 Call(SCI_STYLESETFORE, STYLE_ISSUEBOLD, color);
451 Call(SCI_STYLESETBOLD, STYLE_ISSUEBOLDITALIC, (LPARAM)TRUE);
452 Call(SCI_STYLESETITALIC, STYLE_ISSUEBOLDITALIC, (LPARAM)TRUE);
453 Call(SCI_STYLESETFORE, STYLE_ISSUEBOLDITALIC, color);
454 Call(SCI_STYLESETHOTSPOT, STYLE_ISSUEBOLDITALIC, (LPARAM)TRUE);
456 // set the formatted text styles
457 Call(SCI_STYLESETBOLD, STYLE_BOLD, (LPARAM)TRUE);
458 Call(SCI_STYLESETITALIC, STYLE_ITALIC, (LPARAM)TRUE);
459 Call(SCI_STYLESETUNDERLINE, STYLE_UNDERLINED, (LPARAM)TRUE);
461 // set the style for URLs
462 Call(SCI_STYLESETFORE, STYLE_URL, color);
463 Call(SCI_STYLESETHOTSPOT, STYLE_URL, (LPARAM)TRUE);
465 Call(SCI_SETHOTSPOTACTIVEUNDERLINE, (LPARAM)TRUE);
468 void CSciEdit::SetAutoCompletionList(std::map<CString, int>&& list, TCHAR separator, TCHAR typeSeparator)
470 //copy the auto completion list.
472 //SK: instead of creating a copy of that list, we could accept a pointer
473 //to the list and use that instead. But then the caller would have to make
474 //sure that the list persists over the lifetime of the control!
475 m_autolist.clear();
476 m_autolist = std::move(list);
477 m_separator = separator;
478 m_typeSeparator = typeSeparator;
481 BOOL CSciEdit::IsMisspelled(const CString& sWord)
483 // convert the string from the control to the encoding of the spell checker module.
484 CStringA sWordA = GetWordForSpellChecker(sWord);
486 // words starting with a digit are treated as correctly spelled
487 if (_istdigit(sWord.GetAt(0)))
488 return FALSE;
489 // words in the personal dictionary are correct too
490 if (m_personalDict.FindWord(sWord))
491 return FALSE;
493 // Check spell checking cache first.
494 const BOOL *cacheResult = m_SpellingCache.try_get(std::wstring(sWord, sWord.GetLength()));
495 if (cacheResult)
496 return *cacheResult;
498 // now we actually check the spelling...
499 BOOL misspelled = !pChecker->spell(sWordA);
500 if (misspelled)
502 // the word is marked as misspelled, we now check whether the word
503 // is maybe a composite identifier
504 // a composite identifier consists of multiple words, with each word
505 // separated by a change in lower to uppercase letters
506 misspelled = FALSE;
507 if (sWord.GetLength() > 1)
509 int wordstart = 0;
510 int wordend = 1;
511 while (wordend < sWord.GetLength())
513 while ((wordend < sWord.GetLength())&&(!_istupper(sWord[wordend])))
514 wordend++;
515 if ((wordstart == 0)&&(wordend == sWord.GetLength()))
517 // words in the auto list are also assumed correctly spelled
518 if (m_autolist.find(sWord) != m_autolist.end())
519 misspelled = FALSE;
520 else
521 misspelled = TRUE;
522 break;
524 sWordA = GetWordForSpellChecker(sWord.Mid(wordstart, wordend - wordstart));
525 if ((sWordA.GetLength() > 2) && (!pChecker->spell(sWordA)))
527 misspelled = TRUE;
528 break;
530 wordstart = wordend;
531 wordend++;
536 // Update cache.
537 m_SpellingCache.insert_or_assign(std::wstring(sWord, sWord.GetLength()), misspelled);
538 return misspelled;
541 void CSciEdit::CheckSpelling(Sci_Position startpos, Sci_Position endpos)
543 if (!pChecker)
544 return;
546 Sci_TextRange textrange;
547 textrange.chrg.cpMin = static_cast<Sci_PositionCR>(startpos);
548 textrange.chrg.cpMax = textrange.chrg.cpMin;
549 auto lastpos = endpos;
550 if (lastpos < 0)
551 lastpos = (int)Call(SCI_GETLENGTH) - textrange.chrg.cpMin;
552 Call(SCI_SETINDICATORCURRENT, INDIC_MISSPELLED);
553 while (textrange.chrg.cpMax < lastpos)
555 textrange.chrg.cpMin = (int)Call(SCI_WORDSTARTPOSITION, textrange.chrg.cpMax+1, TRUE);
556 if (textrange.chrg.cpMin < textrange.chrg.cpMax)
557 break;
558 textrange.chrg.cpMax = (int)Call(SCI_WORDENDPOSITION, textrange.chrg.cpMin, TRUE);
559 if (textrange.chrg.cpMin == textrange.chrg.cpMax)
561 textrange.chrg.cpMax++;
562 // since Scintilla squiggles to the end of the text even if told to stop one char before it,
563 // we have to clear here the squiggly lines to the end.
564 if (textrange.chrg.cpMin)
565 Call(SCI_INDICATORCLEARRANGE, textrange.chrg.cpMin-1, textrange.chrg.cpMax - textrange.chrg.cpMin + 1);
566 continue;
568 ATLASSERT(textrange.chrg.cpMax >= textrange.chrg.cpMin);
569 auto textbuffer = std::make_unique<char[]>(textrange.chrg.cpMax - textrange.chrg.cpMin + 2);
570 SecureZeroMemory(textbuffer.get(), textrange.chrg.cpMax - textrange.chrg.cpMin + 2);
571 textrange.lpstrText = textbuffer.get();
572 textrange.chrg.cpMax++;
573 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
574 auto len = (int)strlen(textrange.lpstrText);
575 if (len == 0)
577 textrange.chrg.cpMax--;
578 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
579 len = (int)strlen(textrange.lpstrText);
580 textrange.chrg.cpMax++;
581 len++;
583 if (len && textrange.lpstrText[len - 1] == '.')
585 // Try to ignore file names from the auto list.
586 // Do do this, for each word ending with '.' we extract next word and check
587 // whether the combined string is present in auto list.
588 Sci_TextRange twoWords;
589 twoWords.chrg.cpMin = textrange.chrg.cpMin;
590 twoWords.chrg.cpMax = (int)Call(SCI_WORDENDPOSITION, textrange.chrg.cpMax + 1, TRUE);
591 auto twoWordsBuffer = std::make_unique<char[]>(twoWords.chrg.cpMax - twoWords.chrg.cpMin + 1);
592 twoWords.lpstrText = twoWordsBuffer.get();
593 SecureZeroMemory(twoWords.lpstrText, twoWords.chrg.cpMax - twoWords.chrg.cpMin + 1);
594 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&twoWords);
595 CString sWord = StringFromControl(twoWords.lpstrText);
596 if (m_autolist.find(sWord) != m_autolist.end())
598 //mark word as correct (remove the squiggle line)
599 Call(SCI_INDICATORCLEARRANGE, twoWords.chrg.cpMin, twoWords.chrg.cpMax - twoWords.chrg.cpMin);
600 textrange.chrg.cpMax = twoWords.chrg.cpMax;
601 continue;
604 if (len)
605 textrange.lpstrText[len - 1] = '\0';
606 textrange.chrg.cpMax--;
607 if (textrange.lpstrText[0])
609 CString sWord = StringFromControl(textrange.lpstrText);
610 if ((GetStyleAt(textrange.chrg.cpMin) != STYLE_URL) && IsMisspelled(sWord))
612 //mark word as misspelled
613 Call(SCI_INDICATORFILLRANGE, textrange.chrg.cpMin, textrange.chrg.cpMax - textrange.chrg.cpMin);
615 else
617 //mark word as correct (remove the squiggle line)
618 Call(SCI_INDICATORCLEARRANGE, textrange.chrg.cpMin, textrange.chrg.cpMax - textrange.chrg.cpMin);
619 Call(SCI_INDICATORCLEARRANGE, textrange.chrg.cpMin, textrange.chrg.cpMax - textrange.chrg.cpMin + 1);
625 void CSciEdit::SuggestSpellingAlternatives()
627 if (!pChecker)
628 return;
629 CString word = GetWordUnderCursor(true);
630 Call(SCI_SETCURRENTPOS, Call(SCI_WORDSTARTPOSITION, Call(SCI_GETCURRENTPOS), TRUE));
631 if (word.IsEmpty())
632 return;
633 char ** wlst = nullptr;
634 int ns = pChecker->suggest(&wlst, GetWordForSpellChecker(word));
635 if (ns > 0)
637 CString suggestions;
638 for (int i=0; i < ns; i++)
640 suggestions.AppendFormat(L"%s%c%d%c", (LPCTSTR)GetWordFromSpellChecker(wlst[i]), m_typeSeparator, AUTOCOMPLETE_SPELLING, m_separator);
641 free(wlst[i]);
643 free(wlst);
644 suggestions.TrimRight(m_separator);
645 if (suggestions.IsEmpty())
646 return;
647 Call(SCI_AUTOCSETSEPARATOR, (WPARAM)CStringA(m_separator).GetAt(0));
648 Call(SCI_AUTOCSETTYPESEPARATOR, (WPARAM)m_typeSeparator);
649 Call(SCI_AUTOCSETDROPRESTOFWORD, 1);
650 Call(SCI_AUTOCSHOW, 0, (LPARAM)(LPCSTR)StringForControl(suggestions));
651 return;
653 free(wlst);
656 void CSciEdit::DoAutoCompletion(Sci_Position nMinPrefixLength)
658 if (m_autolist.empty())
659 return;
660 auto pos = (int)(Sci_Position)Call(SCI_GETCURRENTPOS);
661 if (pos != (int)Call(SCI_WORDENDPOSITION, pos, TRUE))
662 return; // don't auto complete if we're not at the end of a word
663 CString word = GetWordUnderCursor();
664 if (word.GetLength() < nMinPrefixLength)
666 word = GetWordUnderCursor(false, true);
667 if (word.GetLength() < nMinPrefixLength)
668 return; // don't auto complete yet, word is too short
670 CString sAutoCompleteList;
672 for (int i = 0; i < 2; ++i)
674 std::vector<CString> words;
676 pos = word.Find('-');
678 CString wordLower = word;
679 wordLower.MakeLower();
680 CString wordHigher = word;
681 wordHigher.MakeUpper();
683 words.push_back(word);
684 words.push_back(wordLower);
685 words.push_back(wordHigher);
687 if (pos >= 0)
689 CString s = wordLower.Left(pos);
690 if (s.GetLength() >= nMinPrefixLength)
691 words.push_back(s);
692 s = wordLower.Mid(pos + 1);
693 if (s.GetLength() >= nMinPrefixLength)
694 words.push_back(s);
695 s = wordHigher.Left(pos);
696 if (s.GetLength() >= nMinPrefixLength)
697 words.push_back(wordHigher.Left(pos));
698 s = wordHigher.Mid(pos + 1);
699 if (s.GetLength() >= nMinPrefixLength)
700 words.push_back(wordHigher.Mid(pos+1));
703 // note: the m_autolist is case-sensitive because
704 // its contents are also used to mark words in it
705 // as correctly spelled. If it would be case-insensitive,
706 // case spelling mistakes would not show up as misspelled.
707 std::map<CString, int> wordset;
708 for (const auto& w : words)
710 for (auto lowerit = m_autolist.lower_bound(w);
711 lowerit != m_autolist.end(); ++lowerit)
713 int compare = w.CompareNoCase(lowerit->first.Left(w.GetLength()));
714 if (compare > 0)
715 continue;
716 else if (compare == 0)
717 wordset.emplace(lowerit->first, lowerit->second);
718 else
719 break;
723 for (const auto& w : wordset)
724 sAutoCompleteList.AppendFormat(L"%s%c%d%c", (LPCTSTR)w.first, m_typeSeparator, w.second, m_separator);
726 sAutoCompleteList.TrimRight(m_separator);
728 if (i == 0)
730 if (sAutoCompleteList.IsEmpty())
732 // retry with all chars
733 word = GetWordUnderCursor(false, true);
735 else
736 break;
738 if (i == 1)
740 if (sAutoCompleteList.IsEmpty())
741 return;
745 Call(SCI_AUTOCSETSEPARATOR, (WPARAM)CStringA(m_separator).GetAt(0));
746 Call(SCI_AUTOCSETTYPESEPARATOR, (WPARAM)m_typeSeparator);
747 auto sForControl = StringForControl(sAutoCompleteList);
748 Call(SCI_AUTOCSHOW, StringForControl(word).GetLength(), (LPARAM)(LPCSTR)sForControl);
751 BOOL CSciEdit::OnChildNotify(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pLResult)
753 if (message != WM_NOTIFY)
754 return CWnd::OnChildNotify(message, wParam, lParam, pLResult);
756 LPNMHDR lpnmhdr = (LPNMHDR) lParam;
757 SCNotification * lpSCN = (SCNotification *)lParam;
759 if(lpnmhdr->hwndFrom==m_hWnd)
761 switch(lpnmhdr->code)
763 case SCN_CHARADDED:
765 if ((lpSCN->ch < 32)&&(lpSCN->ch != 13)&&(lpSCN->ch != 10))
766 Call(SCI_DELETEBACK);
767 else
768 DoAutoCompletion(m_nAutoCompleteMinChars);
769 return TRUE;
771 break;
772 case SCN_AUTOCSELECTION:
774 CString text = StringFromControl(lpSCN->text);
775 if (m_autolist[text] == AUTOCOMPLETE_SNIPPET)
777 Call(SCI_AUTOCCANCEL);
778 for (INT_PTR handlerindex = 0; handlerindex < m_arContextHandlers.GetCount(); ++handlerindex)
780 CSciEditContextMenuInterface * pHandler = m_arContextHandlers.GetAt(handlerindex);
781 pHandler->HandleSnippet(m_autolist[text], text, this);
784 return TRUE;
786 case SCN_STYLENEEDED:
788 auto startpos = (Sci_Position)Call(SCI_GETENDSTYLED);
789 auto endpos = ((SCNotification*)lpnmhdr)->position;
791 auto startwordpos = (int)Call(SCI_WORDSTARTPOSITION, startpos, true);
792 auto endwordpos = (int)Call(SCI_WORDENDPOSITION, endpos, true);
794 MarkEnteredBugID(startwordpos, endwordpos);
795 if (m_bDoStyle)
796 StyleEnteredText(startwordpos, endwordpos);
798 StyleURLs(startwordpos, endwordpos);
799 CheckSpelling(startwordpos, endwordpos);
801 // Tell scintilla editor that we styled all requested range.
802 Call(SCI_STARTSTYLING, endwordpos);
803 Call(SCI_SETSTYLING, 0, 0);
805 break;
806 case SCN_MODIFIED:
808 if (!m_blockModifiedHandler && (lpSCN->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)))
810 auto firstline = (int)Call(SCI_GETFIRSTVISIBLELINE);
811 auto lastline = firstline + (int)Call(SCI_LINESONSCREEN);
812 auto firstpos = (Sci_Position)Call(SCI_POSITIONFROMLINE, firstline);
813 auto lastpos = (Sci_Position)Call(SCI_GETLINEENDPOSITION, lastline);
814 auto pos1 = lpSCN->position;
815 auto pos2 = pos1 + lpSCN->length;
816 // always use the bigger range
817 firstpos = min(firstpos, pos1);
818 lastpos = max(lastpos, pos2);
820 WrapLines(firstpos, lastpos);
822 break;
824 case SCN_DWELLSTART:
825 case SCN_HOTSPOTCLICK:
827 Sci_TextRange textrange;
828 textrange.chrg.cpMin = static_cast<Sci_PositionCR>(lpSCN->position);
829 textrange.chrg.cpMax = static_cast<Sci_PositionCR>(lpSCN->position);
830 auto style = GetStyleAt(lpSCN->position);
831 if (style != STYLE_ISSUEBOLDITALIC && style != STYLE_URL)
832 break;
833 while (GetStyleAt(textrange.chrg.cpMin - 1) == style)
834 --textrange.chrg.cpMin;
835 while (GetStyleAt(textrange.chrg.cpMax + 1) == style)
836 ++textrange.chrg.cpMax;
837 ++textrange.chrg.cpMax;
838 auto textbuffer = std::make_unique<char[]>(textrange.chrg.cpMax - textrange.chrg.cpMin + 1);
839 textrange.lpstrText = textbuffer.get();
840 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
841 CString url;
842 if (style == STYLE_URL)
844 url = StringFromControl(textbuffer.get());
845 if (url.Find(L'@') > 0 && !PathIsURL(url))
846 url = L"mailto:" + url;
848 else
850 url = m_sUrl;
851 url.Replace(L"%BUGID%", StringFromControl(textbuffer.get()));
853 if (!url.IsEmpty())
855 if (lpnmhdr->code == SCN_HOTSPOTCLICK)
856 ShellExecute(GetParent()->GetSafeHwnd(), L"open", url, nullptr, nullptr, SW_SHOWDEFAULT);
857 else
859 CStringA sTextA = StringForControl(url);
860 Call(SCI_CALLTIPSHOW, lpSCN->position + 3, (LPARAM)(LPCSTR)sTextA);
864 break;
865 case SCN_DWELLEND:
866 Call(SCI_CALLTIPCANCEL);
867 break;
870 return CWnd::OnChildNotify(message, wParam, lParam, pLResult);
873 BEGIN_MESSAGE_MAP(CSciEdit, CWnd)
874 ON_WM_KEYDOWN()
875 ON_WM_CONTEXTMENU()
876 END_MESSAGE_MAP()
878 void CSciEdit::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
880 switch (nChar)
882 case (VK_ESCAPE):
884 if ((Call(SCI_AUTOCACTIVE)==0)&&(Call(SCI_CALLTIPACTIVE)==0))
885 ::SendMessage(GetParent()->GetSafeHwnd(), WM_CLOSE, 0, 0);
887 break;
889 CWnd::OnKeyDown(nChar, nRepCnt, nFlags);
892 BOOL CSciEdit::PreTranslateMessage(MSG* pMsg)
894 if (pMsg->message == WM_KEYDOWN)
896 switch (pMsg->wParam)
898 case VK_SPACE:
900 if ((GetKeyState(VK_CONTROL) & 0x8000) && ((GetKeyState(VK_MENU) & 0x8000) == 0))
902 DoAutoCompletion(1);
903 return TRUE;
906 break;
907 case VK_TAB:
908 // The TAB cannot be handled in OnKeyDown because it is too late by then.
910 if ((GetKeyState(VK_CONTROL) & 0x8000) && ((GetKeyState(VK_MENU) & 0x8000) == 0))
912 //Ctrl-Tab was pressed, this means we should provide the user with
913 //a list of possible spell checking alternatives to the word under
914 //the cursor
915 SuggestSpellingAlternatives();
916 return TRUE;
918 else if (!Call(SCI_AUTOCACTIVE))
920 ::PostMessage(GetParent()->GetSafeHwnd(), WM_NEXTDLGCTL, GetKeyState(VK_SHIFT)&0x8000, 0);
921 return TRUE;
924 break;
927 return CWnd::PreTranslateMessage(pMsg);
930 void CSciEdit::OnContextMenu(CWnd* /*pWnd*/, CPoint point)
932 auto anchor = (Sci_Position)Call(SCI_GETANCHOR);
933 auto currentpos = (Sci_Position)Call(SCI_GETCURRENTPOS);
934 auto selstart = (int)(Sci_Position)Call(SCI_GETSELECTIONSTART);
935 auto selend = (int)(Sci_Position)Call(SCI_GETSELECTIONEND);
936 Sci_Position pointpos = 0;
937 if ((point.x == -1) && (point.y == -1))
939 CRect rect;
940 GetClientRect(&rect);
941 ClientToScreen(&rect);
942 point = rect.CenterPoint();
943 pointpos = (Sci_Position)Call(SCI_GETCURRENTPOS);
945 else
947 // change the cursor position to the point where the user
948 // right-clicked.
949 CPoint clientpoint = point;
950 ScreenToClient(&clientpoint);
951 pointpos = (Sci_Position)Call(SCI_POSITIONFROMPOINT, clientpoint.x, clientpoint.y);
953 CString sMenuItemText;
954 CMenu popup;
955 bool bRestoreCursor = true;
956 if (popup.CreatePopupMenu())
958 bool bCanUndo = !!Call(SCI_CANUNDO);
959 bool bCanRedo = !!Call(SCI_CANREDO);
960 bool bHasSelection = (selend-selstart > 0);
961 bool bCanPaste = !!Call(SCI_CANPASTE);
962 bool bIsReadOnly = !!Call(SCI_GETREADONLY);
963 UINT uEnabledMenu = MF_STRING | MF_ENABLED;
964 UINT uDisabledMenu = MF_STRING | MF_GRAYED;
966 // find the word under the cursor
967 CString sWord;
968 if (pointpos)
970 // setting the cursor clears the selection
971 Call(SCI_SETANCHOR, pointpos);
972 Call(SCI_SETCURRENTPOS, pointpos);
973 sWord = GetWordUnderCursor();
974 // restore the selection
975 Call(SCI_SETSELECTIONSTART, selstart);
976 Call(SCI_SETSELECTIONEND, selend);
978 else
979 sWord = GetWordUnderCursor();
980 CStringA worda = GetWordForSpellChecker(sWord);
982 int nCorrections = 1;
983 bool bSpellAdded = false;
984 // check if the word under the cursor is spelled wrong
985 if ((pChecker)&&(!worda.IsEmpty()) && !bIsReadOnly)
987 char ** wlst = nullptr;
988 // get the spell suggestions
989 int ns = pChecker->suggest(&wlst,worda);
990 if (ns > 0)
992 // add the suggestions to the context menu
993 for (int i=0; i < ns; i++)
995 bSpellAdded = true;
996 CString sug = GetWordFromSpellChecker(wlst[i]);
997 popup.InsertMenu((UINT)-1, 0, nCorrections++, sug);
998 free(wlst[i]);
1000 free(wlst);
1002 else
1003 free(wlst);
1005 // only add a separator if spelling correction suggestions were added
1006 if (bSpellAdded)
1007 popup.AppendMenu(MF_SEPARATOR);
1009 // also allow the user to add the word to the custom dictionary so
1010 // it won't show up as misspelled anymore
1011 if ((sWord.GetLength()<PDICT_MAX_WORD_LENGTH)&&((pChecker)&&(m_autolist.find(sWord) == m_autolist.end())&&(!pChecker->spell(worda)))&&
1012 (!_istdigit(sWord.GetAt(0)))&&(!m_personalDict.FindWord(sWord)) && !bIsReadOnly)
1014 sMenuItemText.Format(IDS_SCIEDIT_ADDWORD, (LPCTSTR)sWord);
1015 popup.AppendMenu(uEnabledMenu, SCI_ADDWORD, sMenuItemText);
1016 // another separator
1017 popup.AppendMenu(MF_SEPARATOR);
1020 // add the 'default' entries
1021 sMenuItemText.LoadString(IDS_SCIEDIT_UNDO);
1022 popup.AppendMenu(bCanUndo ? uEnabledMenu : uDisabledMenu, SCI_UNDO, sMenuItemText);
1023 sMenuItemText.LoadString(IDS_SCIEDIT_REDO);
1024 popup.AppendMenu(bCanRedo ? uEnabledMenu : uDisabledMenu, SCI_REDO, sMenuItemText);
1026 popup.AppendMenu(MF_SEPARATOR);
1028 sMenuItemText.LoadString(IDS_SCIEDIT_CUT);
1029 popup.AppendMenu(!bIsReadOnly && bHasSelection ? uEnabledMenu : uDisabledMenu, SCI_CUT, sMenuItemText);
1030 sMenuItemText.LoadString(IDS_SCIEDIT_COPY);
1031 popup.AppendMenu(bHasSelection ? uEnabledMenu : uDisabledMenu, SCI_COPY, sMenuItemText);
1032 sMenuItemText.LoadString(IDS_SCIEDIT_PASTE);
1033 popup.AppendMenu(bCanPaste ? uEnabledMenu : uDisabledMenu, SCI_PASTE, sMenuItemText);
1035 popup.AppendMenu(MF_SEPARATOR);
1037 sMenuItemText.LoadString(IDS_SCIEDIT_SELECTALL);
1038 popup.AppendMenu(uEnabledMenu, SCI_SELECTALL, sMenuItemText);
1040 if (!bIsReadOnly && Call(SCI_GETEDGECOLUMN))
1042 popup.AppendMenu(MF_SEPARATOR);
1044 sMenuItemText.LoadString(IDS_SCIEDIT_SPLITLINES);
1045 popup.AppendMenu(bHasSelection ? uEnabledMenu : uDisabledMenu, SCI_LINESSPLIT, sMenuItemText);
1048 if (m_arContextHandlers.GetCount() > 0)
1049 popup.AppendMenu(MF_SEPARATOR);
1051 int nCustoms = nCorrections;
1052 // now add any custom context menus
1053 for (INT_PTR handlerindex = 0; handlerindex < m_arContextHandlers.GetCount(); ++handlerindex)
1055 CSciEditContextMenuInterface * pHandler = m_arContextHandlers.GetAt(handlerindex);
1056 pHandler->InsertMenuItems(popup, nCustoms);
1058 #if THESAURUS
1059 // add found thesauri to sub menu's
1060 CMenu thesaurs;
1061 int nThesaurs = 0;
1062 CPtrArray menuArray;
1063 if (thesaurs.CreatePopupMenu())
1065 if ((nCustoms > nCorrections || m_arContextHandlers.IsEmpty()) && !bIsReadOnly)
1066 popup.AppendMenu(MF_SEPARATOR);
1067 if (pThesaur && !worda.IsEmpty() && !bIsReadOnly)
1069 mentry * pmean;
1070 worda.MakeLower();
1071 int count = pThesaur->Lookup(worda, worda.GetLength(),&pmean);
1072 if (count)
1074 mentry * pm = pmean;
1075 for (int i=0; i < count; i++)
1077 CMenu * submenu = new CMenu();
1078 menuArray.Add(submenu);
1079 submenu->CreateMenu();
1080 for (int j=0; j < pm->count; j++)
1082 CString sug = CString(pm->psyns[j]);
1083 submenu->InsertMenu((UINT)-1, 0, nCorrections + nCustoms + (nThesaurs++), sug);
1085 thesaurs.InsertMenu((UINT)-1, MF_POPUP, (UINT_PTR)(submenu->m_hMenu), CString(pm->defn));
1086 pm++;
1089 if ((count > 0)&&(point.x >= 0))
1091 #ifdef IDS_SPELLEDIT_THESAURUS
1092 sMenuItemText.LoadString(IDS_SPELLEDIT_THESAURUS);
1093 popup.InsertMenu((UINT)-1, MF_POPUP, (UINT_PTR)thesaurs.m_hMenu, sMenuItemText);
1094 #else
1095 popup.InsertMenu((UINT)-1, MF_POPUP, (UINT_PTR)thesaurs.m_hMenu, L"Thesaurus");
1096 #endif
1097 nThesaurs = nCustoms;
1099 else
1101 sMenuItemText.LoadString(IDS_SPELLEDIT_NOTHESAURUS);
1102 popup.AppendMenu(MF_DISABLED | MF_GRAYED | MF_STRING, 0, sMenuItemText);
1105 pThesaur->CleanUpAfterLookup(&pmean, count);
1107 else if (!bIsReadOnly)
1109 sMenuItemText.LoadString(IDS_SPELLEDIT_NOTHESAURUS);
1110 popup.AppendMenu(MF_DISABLED | MF_GRAYED | MF_STRING, 0, sMenuItemText);
1113 #endif
1114 int cmd = popup.TrackPopupMenu(TPM_RETURNCMD | TPM_LEFTALIGN | TPM_NONOTIFY, point.x, point.y, this);
1115 switch (cmd)
1117 case 0:
1118 break; // no command selected
1119 case SCI_SELECTALL:
1120 bRestoreCursor = false;
1121 // fall through
1122 case SCI_UNDO:
1123 case SCI_REDO:
1124 case SCI_CUT:
1125 case SCI_COPY:
1126 case SCI_PASTE:
1127 Call(cmd);
1128 break;
1129 case SCI_ADDWORD:
1130 m_personalDict.AddWord(sWord);
1131 CheckSpelling((Sci_Position)Call(SCI_POSITIONFROMLINE, (int)Call(SCI_GETFIRSTVISIBLELINE)), (Sci_Position)Call(SCI_POSITIONFROMLINE, (int)Call(SCI_GETFIRSTVISIBLELINE) + (int)Call(SCI_LINESONSCREEN)));
1132 break;
1133 case SCI_LINESSPLIT:
1135 auto marker = (int)(Call(SCI_GETEDGECOLUMN) * (int)Call(SCI_TEXTWIDTH, 0, (LPARAM)" "));
1136 if (marker)
1138 m_blockModifiedHandler = true;
1139 SCOPE_EXIT{ m_blockModifiedHandler = false; };
1140 Call(SCI_TARGETFROMSELECTION);
1141 Call(SCI_LINESJOIN);
1142 Call(SCI_LINESSPLIT, marker);
1145 break;
1146 default:
1147 if (cmd < nCorrections)
1149 Call(SCI_SETANCHOR, pointpos);
1150 Call(SCI_SETCURRENTPOS, pointpos);
1151 GetWordUnderCursor(true);
1152 CString temp;
1153 popup.GetMenuString(cmd, temp, 0);
1154 // setting the cursor clears the selection
1155 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)StringForControl(temp));
1157 else if (cmd < (nCorrections+nCustoms))
1159 for (INT_PTR handlerindex = 0; handlerindex < m_arContextHandlers.GetCount(); ++handlerindex)
1161 CSciEditContextMenuInterface * pHandler = m_arContextHandlers.GetAt(handlerindex);
1162 if (pHandler->HandleMenuItemClick(cmd, this))
1163 break;
1166 #if THESAURUS
1167 else if (cmd <= (nThesaurs+nCorrections+nCustoms))
1169 Call(SCI_SETANCHOR, pointpos);
1170 Call(SCI_SETCURRENTPOS, pointpos);
1171 GetWordUnderCursor(true);
1172 CString temp;
1173 thesaurs.GetMenuString(cmd, temp, 0);
1174 Call(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)StringForControl(temp));
1176 #endif
1178 #ifdef THESAURUS
1179 for (INT_PTR index = 0; index < menuArray.GetCount(); ++index)
1181 CMenu * pMenu = (CMenu*)menuArray[index];
1182 delete pMenu;
1184 #endif
1186 if (bRestoreCursor)
1188 // restore the anchor and cursor position
1189 Call(SCI_SETCURRENTPOS, currentpos);
1190 Call(SCI_SETANCHOR, anchor);
1194 bool CSciEdit::StyleEnteredText(Sci_Position startstylepos, Sci_Position endstylepos)
1196 bool bStyled = false;
1197 const auto line = (int)Call(SCI_LINEFROMPOSITION, startstylepos);
1198 const auto line_number_end = (int)Call(SCI_LINEFROMPOSITION, endstylepos);
1199 for (auto line_number = line; line_number <= line_number_end; ++line_number)
1201 auto offset = (Sci_Position)Call(SCI_POSITIONFROMLINE, line_number);
1202 auto line_len = (int)Call(SCI_LINELENGTH, line_number);
1203 auto linebuffer = std::make_unique<char[]>(line_len + 1);
1204 Call(SCI_GETLINE, line_number, (LPARAM)linebuffer.get());
1205 linebuffer[line_len] = '\0';
1206 Sci_Position start = 0;
1207 Sci_Position end = 0;
1208 while (FindStyleChars(linebuffer.get(), '*', start, end))
1210 Call(SCI_STARTSTYLING, start + offset, STYLE_BOLD);
1211 Call(SCI_SETSTYLING, end-start, STYLE_BOLD);
1212 bStyled = true;
1213 start = end;
1215 start = 0;
1216 end = 0;
1217 while (FindStyleChars(linebuffer.get(), '^', start, end))
1219 Call(SCI_STARTSTYLING, start + offset, STYLE_ITALIC);
1220 Call(SCI_SETSTYLING, end-start, STYLE_ITALIC);
1221 bStyled = true;
1222 start = end;
1224 start = 0;
1225 end = 0;
1226 while (FindStyleChars(linebuffer.get(), '_', start, end))
1228 Call(SCI_STARTSTYLING, start + offset, STYLE_UNDERLINED);
1229 Call(SCI_SETSTYLING, end-start, STYLE_UNDERLINED);
1230 bStyled = true;
1231 start = end;
1234 return bStyled;
1237 bool CSciEdit::WrapLines(Sci_Position startpos, Sci_Position endpos)
1239 auto markerX = (Sci_Position)(Call(SCI_GETEDGECOLUMN) * (int)Call(SCI_TEXTWIDTH, 0, (LPARAM)" "));
1240 if (markerX)
1242 Call(SCI_SETTARGETSTART, startpos);
1243 Call(SCI_SETTARGETEND, endpos);
1244 Call(SCI_LINESSPLIT, markerX);
1245 return true;
1247 return false;
1250 void CSciEdit::AdvanceUTF8(const char * str, int& pos)
1252 if ((str[pos] & 0xE0)==0xC0)
1254 // utf8 2-byte sequence
1255 pos += 2;
1257 else if ((str[pos] & 0xF0)==0xE0)
1259 // utf8 3-byte sequence
1260 pos += 3;
1262 else if ((str[pos] & 0xF8)==0xF0)
1264 // utf8 4-byte sequence
1265 pos += 4;
1267 else
1268 pos++;
1271 bool CSciEdit::FindStyleChars(const char* line, char styler, Sci_Position& start, Sci_Position& end)
1273 int i=0;
1274 int u=0;
1275 while (i < start)
1277 AdvanceUTF8(line, i);
1278 u++;
1281 bool bFoundMarker = false;
1282 CString sULine = CUnicodeUtils::GetUnicode(line);
1283 // find a starting marker
1284 while (line[i] != 0)
1286 if (line[i] == styler)
1288 if ((line[i+1]!=0)&&(IsCharAlphaNumeric(sULine[u+1]))&&
1289 (((u>0)&&(!IsCharAlphaNumeric(sULine[u-1]))) || (u==0)))
1291 start = i+1;
1292 AdvanceUTF8(line, i);
1293 u++;
1294 bFoundMarker = true;
1295 break;
1298 AdvanceUTF8(line, i);
1299 u++;
1301 if (!bFoundMarker)
1302 return false;
1303 // find ending marker
1304 bFoundMarker = false;
1305 while (line[i])
1307 if (line[i] == styler)
1309 if ((IsCharAlphaNumeric(sULine[u-1]))&&
1310 ((((u+1)<sULine.GetLength())&&(!IsCharAlphaNumeric(sULine[u+1]))) || ((u+1) == sULine.GetLength()))
1313 end = i;
1314 i++;
1315 bFoundMarker = true;
1316 break;
1319 AdvanceUTF8(line, i);
1320 u++;
1322 return bFoundMarker;
1325 BOOL CSciEdit::MarkEnteredBugID(Sci_Position startstylepos, Sci_Position endstylepos)
1327 if (m_sCommand.IsEmpty())
1328 return FALSE;
1329 // get the text between the start and end position we have to style
1330 const auto line_number = (int)Call(SCI_LINEFROMPOSITION, startstylepos);
1331 auto start_pos = (Sci_Position)Call(SCI_POSITIONFROMLINE, (WPARAM)line_number);
1332 auto end_pos = endstylepos;
1334 if (start_pos == end_pos)
1335 return FALSE;
1336 if (start_pos > end_pos)
1338 auto switchtemp = start_pos;
1339 start_pos = end_pos;
1340 end_pos = switchtemp;
1343 auto textbuffer = std::make_unique<char[]>(end_pos - start_pos + 2);
1344 Sci_TextRange textrange;
1345 textrange.lpstrText = textbuffer.get();
1346 textrange.chrg.cpMin = static_cast<Sci_PositionCR>(start_pos);
1347 textrange.chrg.cpMax = static_cast<Sci_PositionCR>(end_pos);
1348 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
1349 CStringA msg = CStringA(textbuffer.get());
1351 Call(SCI_STARTSTYLING, start_pos, STYLE_MASK);
1355 if (!m_sBugID.IsEmpty())
1357 // match with two regex strings (without grouping!)
1358 const std::regex regCheck(m_sCommand);
1359 const std::regex regBugID(m_sBugID);
1360 const std::sregex_iterator end;
1361 std::string s = msg;
1362 LONG pos = 0;
1363 // note:
1364 // if start_pos is 0, we're styling from the beginning and let the ^ char match the beginning of the line
1365 // that way, the ^ matches the very beginning of the log message and not the beginning of further lines.
1366 // problem is: this only works *while* entering log messages. If a log message is pasted in whole or
1367 // multiple lines are pasted, start_pos can be 0 and styling goes over multiple lines. In that case, those
1368 // additional line starts also match ^
1369 for (std::sregex_iterator it(s.cbegin(), s.cend(), regCheck, start_pos != 0 ? std::regex_constants::match_not_bol : std::regex_constants::match_default); it != end; ++it)
1371 // clear the styles up to the match position
1372 Call(SCI_SETSTYLING, it->position(0)-pos, STYLE_DEFAULT);
1374 // (*it)[0] is the matched string
1375 std::string matchedString = (*it)[0];
1376 LONG matchedpos = 0;
1377 for (std::sregex_iterator it2(matchedString.cbegin(), matchedString.cend(), regBugID); it2 != end; ++it2)
1379 ATLTRACE("matched id : %s\n", std::string((*it2)[0]).c_str());
1381 // bold style up to the id match
1382 ATLTRACE("position = %ld\n", it2->position(0));
1383 if (it2->position(0))
1384 Call(SCI_SETSTYLING, it2->position(0) - matchedpos, STYLE_ISSUEBOLD);
1385 // bold and recursive style for the bug ID itself
1386 if ((*it2)[0].str().size())
1387 Call(SCI_SETSTYLING, (*it2)[0].str().size(), STYLE_ISSUEBOLDITALIC);
1388 matchedpos = (LONG)(it2->position(0) + (*it2)[0].str().size());
1390 if ((matchedpos)&&(matchedpos < (LONG)matchedString.size()))
1392 Call(SCI_SETSTYLING, matchedString.size() - matchedpos, STYLE_ISSUEBOLD);
1394 pos = (LONG)(it->position(0) + matchedString.size());
1396 // bold style for the rest of the string which isn't matched
1397 if (s.size()-pos)
1398 Call(SCI_SETSTYLING, s.size()-pos, STYLE_DEFAULT);
1400 else
1402 const std::regex regCheck(m_sCommand);
1403 const std::sregex_iterator end;
1404 std::string s = msg;
1405 LONG pos = 0;
1406 for (std::sregex_iterator it(s.cbegin(), s.cend(), regCheck); it != end; ++it)
1408 // clear the styles up to the match position
1409 if (it->position(0) - pos >= 0)
1410 Call(SCI_SETSTYLING, it->position(0) - pos, STYLE_DEFAULT);
1411 pos = (LONG)it->position(0);
1413 const std::smatch match = *it;
1414 // we define group 1 as the whole issue text and
1415 // group 2 as the bug ID
1416 if (match.size() >= 2)
1418 ATLTRACE("matched id : %s\n", std::string(match[1]).c_str());
1419 if (match[1].first - s.cbegin() - pos >= 0)
1420 Call(SCI_SETSTYLING, match[1].first - s.cbegin() - pos, STYLE_ISSUEBOLD);
1421 Call(SCI_SETSTYLING, std::string(match[1]).size(), STYLE_ISSUEBOLDITALIC);
1422 pos = (LONG)(match[1].second - s.cbegin());
1427 catch (std::exception&) {}
1429 return FALSE;
1432 //similar code in AppUtils.cpp
1433 bool CSciEdit::IsValidURLChar(unsigned char ch)
1435 return isalnum(ch) ||
1436 ch == '_' || ch == '/' || ch == ';' || ch == '?' || ch == '&' || ch == '=' ||
1437 ch == '%' || ch == ':' || ch == '.' || ch == '#' || ch == '-' || ch == '+' ||
1438 ch == '|' || ch == '>' || ch == '<' || ch == '!' || ch == '@' || ch == '~';
1441 //similar code in AppUtils.cpp
1442 void CSciEdit::StyleURLs(Sci_Position startstylepos, Sci_Position endstylepos)
1444 const auto line_number = (int)Call(SCI_LINEFROMPOSITION, startstylepos);
1445 startstylepos = (Sci_Position)Call(SCI_POSITIONFROMLINE, (WPARAM)line_number);
1447 auto len = endstylepos - startstylepos + 1;
1448 auto textbuffer = std::make_unique<char[]>(len + 1);
1449 Sci_TextRange textrange;
1450 textrange.lpstrText = textbuffer.get();
1451 textrange.chrg.cpMin = static_cast<Sci_PositionCR>(startstylepos);
1452 textrange.chrg.cpMax = static_cast<Sci_PositionCR>(endstylepos);
1453 Call(SCI_GETTEXTRANGE, 0, (LPARAM)&textrange);
1454 // we're dealing with utf8 encoded text here, which means one glyph is
1455 // not necessarily one byte/wchar_t
1456 // that's why we use CStringA to still get a correct char index
1457 CStringA msg = textbuffer.get();
1459 int starturl = -1;
1460 for (int i = 0; i <= msg.GetLength(); AdvanceUTF8(msg, i))
1462 if ((i < len) && IsValidURLChar(msg[i]))
1464 if (starturl < 0)
1465 starturl = i;
1467 else
1469 if (starturl >= 0)
1471 bool strip = true;
1472 if (msg[starturl] == '<' && i < len) // try to detect and do not strip URLs put within <>
1474 while (starturl <= i && msg[starturl] == '<') // strip leading '<'
1475 ++starturl;
1476 strip = false;
1477 i = starturl;
1478 while (i < len && msg[i] != '\r' && msg[i] != '\n' && msg[i] != '>') // find first '>' or new line after resetting i to start position
1479 AdvanceUTF8(msg, i);
1482 int skipTrailing = 0;
1483 while (strip && i - skipTrailing - 1 > starturl && (msg[i - skipTrailing - 1] == '.' || msg[i - skipTrailing - 1] == '-' || msg[i - skipTrailing - 1] == '?' || msg[i - skipTrailing - 1] == ';' || msg[i - skipTrailing - 1] == ':' || msg[i - skipTrailing - 1] == '>' || msg[i - skipTrailing - 1] == '<' || msg[i - skipTrailing - 1] == '!'))
1484 ++skipTrailing;
1486 if (!IsUrlOrEmail(msg.Mid(starturl, i - starturl - skipTrailing)))
1488 starturl = -1;
1489 continue;
1492 ASSERT(startstylepos + i - skipTrailing <= endstylepos);
1493 Call(SCI_STARTSTYLING, startstylepos + starturl, STYLE_URL);
1494 Call(SCI_SETSTYLING, i - starturl - skipTrailing, STYLE_URL);
1496 starturl = -1;
1501 bool CSciEdit::IsUrlOrEmail(const CStringA& sText)
1503 if (!PathIsURLA(sText))
1505 auto atpos = sText.Find('@');
1506 if (atpos <= 0)
1507 return false;
1508 if (sText.Find('.', atpos) <= atpos + 1) // a dot must follow after the @, but not directly after it
1509 return false;
1510 if (sText.Find(':', atpos) < 0) // do not detect git@example.com:something as an email address
1511 return true;
1512 return false;
1514 for (const CStringA& prefix : { "http://", "https://", "git://", "ftp://", "file://", "mailto:" })
1516 if (strncmp(sText, prefix, prefix.GetLength()) == 0 && sText.GetLength() != prefix.GetLength())
1517 return true;
1519 return false;
1522 CStringA CSciEdit::GetWordForSpellChecker(const CString& sWord)
1524 // convert the string from the control to the encoding of the spell checker module.
1525 CStringA sWordA;
1526 if (m_spellcodepage)
1528 char * buf = sWordA.GetBuffer(sWord.GetLength() * 4 + 1);
1529 int lengthIncTerminator = WideCharToMultiByte(m_spellcodepage, 0, sWord, -1, buf, sWord.GetLength() * 4, nullptr, nullptr);
1530 if (lengthIncTerminator == 0)
1531 return ""; // converting to the codepage failed
1532 sWordA.ReleaseBuffer(lengthIncTerminator - 1);
1534 else
1535 sWordA = CStringA(sWord);
1537 sWordA.Trim("\'\".,");
1539 if (m_bDoStyle)
1541 for (const auto styleindicator : { '*', '_', '^' })
1543 if (sWordA.IsEmpty())
1544 break;
1545 if (sWordA[sWordA.GetLength() - 1] == styleindicator)
1546 sWordA.Truncate(sWordA.GetLength() - 1);
1547 if (sWordA.IsEmpty())
1548 break;
1549 if (sWordA[0] == styleindicator)
1550 sWordA = sWordA.Right(sWordA.GetLength() - 1);
1554 return sWordA;
1557 CString CSciEdit::GetWordFromSpellChecker(const CStringA& sWordA)
1559 CString sWord;
1560 if (m_spellcodepage)
1562 wchar_t * buf = sWord.GetBuffer(sWordA.GetLength() * 2);
1563 int lengthIncTerminator = MultiByteToWideChar(m_spellcodepage, 0, sWordA, -1, buf, sWordA.GetLength() * 2);
1564 if (lengthIncTerminator == 0)
1565 return L"";
1566 sWord.ReleaseBuffer(lengthIncTerminator - 1);
1568 else
1569 sWord = CString(sWordA);
1571 sWord.Trim(L"\'\".,");
1573 return sWord;
1576 bool CSciEdit::IsUTF8(LPVOID pBuffer, size_t cb)
1578 if (cb < 2)
1579 return true;
1580 UINT16 * pVal = (UINT16 *)pBuffer;
1581 UINT8 * pVal2 = (UINT8 *)(pVal+1);
1582 // scan the whole buffer for a 0x0000 sequence
1583 // if found, we assume a binary file
1584 for (size_t i=0; i<(cb-2); i=i+2)
1586 if (0x0000 == *pVal++)
1587 return false;
1589 pVal = (UINT16 *)pBuffer;
1590 if (*pVal == 0xFEFF)
1591 return false;
1592 if (cb < 3)
1593 return false;
1594 if (*pVal == 0xBBEF)
1596 if (*pVal2 == 0xBF)
1597 return true;
1599 // check for illegal UTF8 chars
1600 pVal2 = (UINT8 *)pBuffer;
1601 for (size_t i=0; i<cb; ++i)
1603 if ((*pVal2 == 0xC0)||(*pVal2 == 0xC1)||(*pVal2 >= 0xF5))
1604 return false;
1605 pVal2++;
1607 pVal2 = (UINT8 *)pBuffer;
1608 bool bUTF8 = false;
1609 for (size_t i=0; i<(cb-3); ++i)
1611 if ((*pVal2 & 0xE0)==0xC0)
1613 pVal2++;i++;
1614 if ((*pVal2 & 0xC0)!=0x80)
1615 return false;
1616 bUTF8 = true;
1618 if ((*pVal2 & 0xF0)==0xE0)
1620 pVal2++;i++;
1621 if ((*pVal2 & 0xC0)!=0x80)
1622 return false;
1623 pVal2++;i++;
1624 if ((*pVal2 & 0xC0)!=0x80)
1625 return false;
1626 bUTF8 = true;
1628 if ((*pVal2 & 0xF8)==0xF0)
1630 pVal2++;i++;
1631 if ((*pVal2 & 0xC0)!=0x80)
1632 return false;
1633 pVal2++;i++;
1634 if ((*pVal2 & 0xC0)!=0x80)
1635 return false;
1636 pVal2++;i++;
1637 if ((*pVal2 & 0xC0)!=0x80)
1638 return false;
1639 bUTF8 = true;
1641 pVal2++;
1643 if (bUTF8)
1644 return true;
1645 return false;
1648 void CSciEdit::SetAStyle(int style, COLORREF fore, COLORREF back, int size, const char *face)
1650 Call(SCI_STYLESETFORE, style, fore);
1651 Call(SCI_STYLESETBACK, style, back);
1652 if (size >= 1)
1653 Call(SCI_STYLESETSIZE, style, size);
1654 if (face)
1655 Call(SCI_STYLESETFONT, style, reinterpret_cast<LPARAM>(face));
1658 void CSciEdit::SetUDiffStyle()
1660 m_bDoStyle = false;
1661 SetAStyle(STYLE_DEFAULT, ::GetSysColor(COLOR_WINDOWTEXT), ::GetSysColor(COLOR_WINDOW),
1662 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffFontSize", 10),
1663 CUnicodeUtils::StdGetUTF8(CRegStdString(L"Software\\TortoiseGit\\UDiffFontName", L"Consolas")).c_str());
1664 Call(SCI_SETTABWIDTH, CRegStdDWORD(L"Software\\TortoiseGit\\UDiffTabSize", 4));
1666 Call(SCI_SETREADONLY, TRUE);
1667 //LRESULT pix = Call(SCI_TEXTWIDTH, STYLE_LINENUMBER, (LPARAM)"_99999");
1668 //Call(SCI_SETMARGINWIDTHN, 0, pix);
1669 //Call(SCI_SETMARGINWIDTHN, 1);
1670 //Call(SCI_SETMARGINWIDTHN, 2);
1671 //Set the default windows colors for edit controls
1672 SetColors(false);
1674 //SendEditor(SCI_SETREADONLY, FALSE);
1675 Call(SCI_CLEARALL);
1676 Call(EM_EMPTYUNDOBUFFER);
1677 Call(SCI_SETSAVEPOINT);
1678 Call(SCI_CANCEL);
1679 Call(SCI_SETUNDOCOLLECTION, 0);
1681 Call(SCI_SETUNDOCOLLECTION, 1);
1682 Call(SCI_SETWRAPMODE,SC_WRAP_NONE);
1684 //::SetFocus(m_hWndEdit);
1685 Call(EM_EMPTYUNDOBUFFER);
1686 Call(SCI_SETSAVEPOINT);
1687 Call(SCI_GOTOPOS, 0);
1689 Call(SCI_CLEARDOCUMENTSTYLE, 0, 0);
1691 HIGHCONTRAST highContrast = { 0 };
1692 highContrast.cbSize = sizeof(HIGHCONTRAST);
1693 if (SystemParametersInfo(SPI_GETHIGHCONTRAST, 0, &highContrast, 0) == TRUE && (highContrast.dwFlags & HCF_HIGHCONTRASTON))
1695 Call(SCI_SETLEXER, SCLEX_NULL);
1696 return;
1699 //SetAStyle(SCE_DIFF_DEFAULT, RGB(0, 0, 0));
1700 SetAStyle(SCE_DIFF_COMMAND,
1701 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeCommandColor", UDIFF_COLORFORECOMMAND),
1702 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackCommandColor", UDIFF_COLORBACKCOMMAND));
1703 SetAStyle(SCE_DIFF_POSITION,
1704 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForePositionColor", UDIFF_COLORFOREPOSITION),
1705 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackPositionColor", UDIFF_COLORBACKPOSITION));
1706 SetAStyle(SCE_DIFF_HEADER,
1707 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeHeaderColor", UDIFF_COLORFOREHEADER),
1708 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackHeaderColor", UDIFF_COLORBACKHEADER));
1709 SetAStyle(SCE_DIFF_COMMENT,
1710 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeCommentColor", UDIFF_COLORFORECOMMENT),
1711 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackCommentColor", UDIFF_COLORBACKCOMMENT));
1712 Call(SCI_STYLESETBOLD, SCE_DIFF_COMMENT, TRUE);
1713 SetAStyle(SCE_DIFF_ADDED,
1714 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeAddedColor", UDIFF_COLORFOREADDED),
1715 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackAddedColor", UDIFF_COLORBACKADDED));
1716 SetAStyle(SCE_DIFF_DELETED,
1717 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffForeRemovedColor", UDIFF_COLORFOREREMOVED),
1718 CRegStdDWORD(L"Software\\TortoiseGit\\UDiffBackRemovedColor", UDIFF_COLORBACKREMOVED));
1720 Call(SCI_SETLEXER, SCLEX_DIFF);
1721 Call(SCI_SETKEYWORDS, 0, (LPARAM)"revision");
1722 Call(SCI_COLOURISE, 0, -1);
1725 int CSciEdit::LoadFromFile(CString &filename)
1727 CAutoFILE fp = _wfsopen(filename, L"rb", _SH_DENYWR);
1728 if (!fp)
1729 return -1;
1731 char data[4096] = { 0 };
1732 size_t lenFile = fread(data, 1, sizeof(data), fp);
1733 bool bUTF8 = IsUTF8(data, lenFile);
1734 while (lenFile > 0)
1736 Call(SCI_ADDTEXT, lenFile, reinterpret_cast<LPARAM>(static_cast<char *>(data)));
1737 lenFile = fread(data, 1, sizeof(data), fp);
1739 Call(SCI_SETCODEPAGE, bUTF8 ? SC_CP_UTF8 : GetACP());
1740 return 0;
1743 void CSciEdit::RestyleBugIDs()
1745 auto endstylepos = (int)Call(SCI_GETLENGTH);
1746 // clear all styles
1747 Call(SCI_STARTSTYLING, 0, STYLE_MASK);
1748 Call(SCI_SETSTYLING, endstylepos, STYLE_DEFAULT);
1749 // style the bug IDs
1750 MarkEnteredBugID(0, endstylepos);
1753 ULONG CSciEdit::GetGestureStatus(CPoint /*ptTouch*/)
1755 return 0;