From 7f2f649c171d8230e33209011aee6f20df94d753 Mon Sep 17 00:00:00 2001 From: "METANEOCORTEX\\Kotti" Date: Wed, 18 Nov 2026 18:17:49 +0100 Subject: [PATCH 1/3] Extract Find/Replace and consolidate editor helpers Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../architecture/codebase-and-conventions.md | 10 +- agent-trail/open-questions.md | 2 +- other_sln/Notepad3DLL.vcxproj | 2 + other_sln/Notepad3DLL.vcxproj.filters | 6 + src/Config/Config.cpp | 1 + src/Edit.c | 2484 +-------------- src/Edit.h | 28 +- src/FindReplace.c | 2656 +++++++++++++++++ src/FindReplace.h | 53 + src/Helpers.c | 154 +- src/Helpers.h | 4 +- src/Notepad3.c | 624 ++-- src/Notepad3.h | 9 +- src/Notepad3.vcxproj | 4 +- src/Notepad3.vcxproj.filters | 12 +- src/Notepad3Util.c | 349 --- src/Notepad3Util.h | 50 - src/TypeDefs.h | 4 +- 18 files changed, 3140 insertions(+), 3312 deletions(-) create mode 100644 src/FindReplace.c create mode 100644 src/FindReplace.h delete mode 100644 src/Notepad3Util.c delete mode 100644 src/Notepad3Util.h diff --git a/agent-trail/architecture/codebase-and-conventions.md b/agent-trail/architecture/codebase-and-conventions.md index 017d249f50..73887de9a8 100644 --- a/agent-trail/architecture/codebase-and-conventions.md +++ b/agent-trail/architecture/codebase-and-conventions.md @@ -10,9 +10,9 @@ Notepad3 is a Windows-only Win32 C/C++ text editor built on Scintilla/Lexilla, d | File | Purpose | |---|---| -| `src\Notepad3.c/h` | `wWinMain`, `MainWndProc`, global state structs (`Globals`, `Settings`, `Settings2`, `Flags`, `Paths`), and `MsgCommand()` | -| `src\Notepad3Util.c/h` | Bitmap/toolbar helpers, word-wrap configuration, middle-click auto-scroll | -| `src\Edit.c/h` | Find/replace (PCRE2), encoding, clipboard, indent, sort, bookmarks, folding, autocomplete | +| `src\Notepad3.c/h` | `wWinMain`, `MainWndProc`, global state, `MsgCommand()`, toolbar setup, word-wrap configuration, middle-click auto-scroll | +| `src\Edit.c/h` | Encoding, clipboard, indent, sort, bookmarks, folding, autocomplete, URL/color highlighting | +| `src\FindReplace.c/h` | Find/Replace dialog, search state, PCRE2-backed matching, replacement, occurrence marking | | `src\Styles.c/h` | Scintilla styling, lexer selection, themes, margins | | `src\Dialogs.c/h` | Dialogs and DPI-aware UI | | `src\Config\Config.cpp/h` | INI load/save and MRU | @@ -79,13 +79,13 @@ Before an approved vendored-library change, consult the [Lexilla patch registry] ### Find/Replace dialog text limits -- `CB_LIMITTEXT` (`FNDRPL_BUFFER`) does not apply to `WM_SETTEXT`; bound text before calling `ComboBox_SetText*`, or an oversized value freezes the single-line combo edit (see the `bFindReplCopySelOrClip` block in `EditFindReplaceDlgProc`, `src\Edit.c`). +- `CB_LIMITTEXT` (`FNDRPL_BUFFER`) does not apply to `WM_SETTEXT`; bound text before calling `ComboBox_SetText*`, or an oversized value freezes the single-line combo edit (see the `bFindReplCopySelOrClip` block in `EditFindReplaceDlgProc`, `src\FindReplace.c`). - `ComboBox_SetText*` fires `CBN_EDITCHANGE` synchronously; reset one-shot flags before calling it. - `_FindInTarget` has an 8192-byte `chFind` buffer; a longer pattern makes `WideCharToMultiByte` fail (`len` = -1) and Scintilla reports "not found". ### Find/Replace dialog placement -- For live recreation, capture the old screen rectangle and restore against its monitor. [`SetDlgPos`](../../src/Dialogs.c#L6157) is for owner-relative settings and clamps to the owner's monitor; [`_RestoreFindReplaceDlgPosition`](../../src/Edit.c#L6807) uses the old rectangle's monitor and fits the dialog again after any DPI resize. +- For live recreation, capture the old screen rectangle and restore against its monitor. [`SetDlgPos`](../../src/Dialogs.c#L6157) is for owner-relative settings and clamps to the owner's monitor; [`_RestoreFindReplaceDlgPosition`](../../src/FindReplace.c#L828) uses the old rectangle's monitor and fits the dialog again after any DPI resize. ### Dynamic string/path buffer lifetime diff --git a/agent-trail/open-questions.md b/agent-trail/open-questions.md index 50071be686..84ce5bfeae 100644 --- a/agent-trail/open-questions.md +++ b/agent-trail/open-questions.md @@ -13,5 +13,5 @@ Add one bullet per finding: `- : — + @@ -526,6 +527,7 @@ + diff --git a/other_sln/Notepad3DLL.vcxproj.filters b/other_sln/Notepad3DLL.vcxproj.filters index 01a9bc9d19..0bacbf1c53 100644 --- a/other_sln/Notepad3DLL.vcxproj.filters +++ b/other_sln/Notepad3DLL.vcxproj.filters @@ -51,6 +51,9 @@ Source Files + + Source Files + Source Files @@ -413,6 +416,9 @@ Header Files + + Header Files + Header Files diff --git a/src/Config/Config.cpp b/src/Config/Config.cpp index d888aa7052..4c0bda3107 100644 --- a/src/Config/Config.cpp +++ b/src/Config/Config.cpp @@ -55,6 +55,7 @@ extern "C" { #include "Styles.h" #include "Dialogs.h" #include "Encoding.h" +#include "FindReplace.h" #include "Notepad3.h" #include "MuiLanguage.h" #include "DynStrg.h" diff --git a/src/Edit.c b/src/Edit.c index 39c0376326..6a797b23ab 100644 --- a/src/Edit.c +++ b/src/Edit.c @@ -36,6 +36,7 @@ #include "uthash/utlist.h" #include "tinyexprcpp/tinyexpr_cif.h" #include "Encoding.h" +#include "FindReplace.h" #include "MuiLanguage.h" #include "Notepad3.h" #include "Config/Config.h" @@ -50,11 +51,6 @@ #define LCMAP_TITLECASE 0x00000300 // Title Case Letters bit mask #endif -static bool s_bSwitchedFindReplace = false; - -static int s_xFindReplaceDlgSave; -static int s_yFindReplaceDlgSave; - static char DelimChars[ANSI_CHAR_BUFFER] = { '\0' }; static char DelimCharsAccel[ANSI_CHAR_BUFFER] = { '\0' }; static char WordCharsDefault[ANSI_CHAR_BUFFER] = { '\0' }; @@ -157,155 +153,6 @@ enum SortOrderMask { }; -//============================================================================= -// -// Delay Message Queue Handling (TODO: MultiThreading) -// - -static CmdMessageQueue_t* MessageQueue = NULL; - -// ---------------------------------------------------------------------------- - -static int msgcmp(void* mqc1, void* mqc2) -{ - const CmdMessageQueue_t* const pMQC1 = (CmdMessageQueue_t*)mqc1; - const CmdMessageQueue_t* const pMQC2 = (CmdMessageQueue_t*)mqc2; - - if ((pMQC1->cmd == pMQC2->cmd) - && (pMQC1->hwnd == pMQC2->hwnd) - && (pMQC1->wparam == pMQC2->wparam) - && (pMQC1->lparam == pMQC2->lparam) - ) { - return 0; - } - return 1; -} - -static LONG64 sortcmp(void *mqc1, void *mqc2) { - const CmdMessageQueue_t *const pMQC1 = (CmdMessageQueue_t *)mqc1; - const CmdMessageQueue_t *const pMQC2 = (CmdMessageQueue_t *)mqc2; - return (pMQC1->delay - pMQC2->delay); -} -// ---------------------------------------------------------------------------- - - - -#define _MQ_TIMER_CYCLE (USER_TIMER_MINIMUM << 1) -#define _MQ_STD (_MQ_TIMER_CYCLE << 2) -#define _MQ_ms2cycl(T) (((T) + USER_TIMER_MINIMUM) / _MQ_TIMER_CYCLE) -#define _MQ_ASAP 0 - -static void _MQ_AppendCmd(CmdMessageQueue_t* const pMsgQCmd, int cycles) -{ - if (!pMsgQCmd) { return; } - - cycles = clampi(cycles, 0, _MQ_ms2cycl(60000)); - - CmdMessageQueue_t* pmqc = NULL; - DL_SEARCH(MessageQueue, pmqc, pMsgQCmd, msgcmp); - - if (!pmqc) { // NOT found, create new one - pmqc = AllocMem(sizeof(CmdMessageQueue_t), HEAP_ZERO_MEMORY); - if (pmqc) { - *pmqc = *pMsgQCmd; - pmqc->delay = cycles; - DL_APPEND(MessageQueue, pmqc); - } - } else { - if ((pmqc->delay > 0) && (cycles > 0)) { - pmqc->delay = (pmqc->delay + cycles) >> 1; // median delay - } else { - pmqc->delay = cycles; - } - } - if (0 == cycles) { - PostMessage(pMsgQCmd->hwnd, pMsgQCmd->cmd, pMsgQCmd->wparam, pMsgQCmd->lparam); - } - //~DL_SORT(MessageQueue, sortcmp); // next scheduled first -} -// ---------------------------------------------------------------------------- - -/* not used yet -static void _MQ_DropAll() { - CmdMessageQueue_t *pmqc = NULL; - DL_FOREACH(MessageQueue, pmqc) { - pmqc->delay = -1; - } -} -*/ -// ---------------------------------------------------------------------------- - - -// ---------------------------------------------------------------------------- -// -// called by MarkAll Timer -// -// TIMERPROC -static void CALLBACK MQ_ExecuteNext(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) -{ - UNREFERENCED_PARAMETER(hwnd); // must be main wnd - UNREFERENCED_PARAMETER(uMsg); // must be WM_TIMER - UNREFERENCED_PARAMETER(idEvent); // must be pTimerIdentifier - UNREFERENCED_PARAMETER(dwTime); // This is the value returned by the GetTickCoun(t)) function - - CmdMessageQueue_t *pmqc; - DL_FOREACH(MessageQueue, pmqc) { - if (pmqc->delay >= 0) { - --(pmqc->delay); - } - if (pmqc->delay == 0) { - if (IsWindow(pmqc->hwnd)) { - PostMessage(pmqc->hwnd, pmqc->cmd, pmqc->wparam, pmqc->lparam); - } - } - } -} - - -//============================================================================= -// -// EditReplaceSelection() -// - -void DuplicateEFR(LPEDITFINDREPLACE dst, CLPCEDITFINDREPLACE src) -{ - dst->fuFlags = src->fuFlags; - dst->bTransformBS = src->bTransformBS; - dst->bFindClose = src->bFindClose; - dst->bReplaceClose = src->bReplaceClose; - dst->bNoFindWrap = src->bNoFindWrap; - dst->bRegExprSearch = src->bRegExprSearch; - dst->bWildcardSearch = src->bWildcardSearch; - dst->bMarkOccurences = src->bMarkOccurences; - dst->bInstantIncrementalSearch = src->bInstantIncrementalSearch; - dst->bHideNonMatchedLines = src->bHideNonMatchedLines; - dst->bStateChanged = src->bStateChanged; - dst->hwnd = src->hwnd; - if (!(dst->chFindPattern)) { - dst->chFindPattern = StrgCreate(StrgGet(src->chFindPattern)); - } - else { - StrgReset(dst->chFindPattern, StrgGet(src->chFindPattern)); - } - if (!(dst->chReplaceTemplate)) { - dst->chReplaceTemplate = StrgCreate(StrgGet(src->chReplaceTemplate)); - } - else { - StrgReset(dst->chReplaceTemplate, StrgGet(src->chReplaceTemplate)); - } -} - - -void ReleaseEFR(LPEDITFINDREPLACE efr) -{ - StrgDestroy(efr->chFindPattern); - efr->chFindPattern = NULL; - StrgDestroy(efr->chReplaceTemplate); - efr->chReplaceTemplate = NULL; -} -// -------------------------------------------------------------------------- - - //============================================================================= // // EditReplaceSelection() @@ -416,6 +263,17 @@ void EditInitWordDelimiter(HWND hwnd) MultiByteToWideChar(Encoding_SciCP, 0, WhiteSpaceCharsAccelerated, -1, W_WhiteSpaceCharsAccelerated, (int)COUNTOF(W_WhiteSpaceCharsAccelerated)); } +bool EditContainsWordDelimiter(LPCSTR text, size_t length) +{ + const char* const delims = Settings.AccelWordNavigation ? DelimCharsAccel : DelimChars; + for (size_t i = 0; i < length && text[i]; ++i) { + if (StrChrIA(delims, text[i])) { + return true; + } + } + return false; +} + //============================================================================= // @@ -6294,2176 +6152,65 @@ void EditGetExcerpt(HWND hwnd, LPWSTR lpszExcerpt, DWORD cchExcerpt) //============================================================================= // -// _SyncBoolOpt() / _SyncFlagOpt() - take a dialog check-box state over into the F/R data -// -static void _SyncBoolOpt(HWND hwnd, int idButton, bool* const pbOpt, bool* const pbChanged) -{ - bool const bChecked = IsButtonChecked(hwnd, idButton); - if (bChecked != *pbOpt) { - *pbOpt = bChecked; - *pbChanged = true; - } -} - -static void _SyncFlagOpt(HWND hwnd, int idButton, UINT* const puFlags, const UINT flag, bool* const pbChanged) -{ - bool const bChecked = IsButtonChecked(hwnd, idButton); - if (bChecked != ((*puFlags & flag) != 0)) { - *puFlags = bChecked ? (*puFlags | flag) : (*puFlags & ~flag); - *pbChanged = true; - } -} - - -//============================================================================= -// -// _SetSearchFlags() -// -static void _SetSearchFlags(HWND hwnd, LPEDITFINDREPLACE lpefr) -{ - if (hwnd && lpefr) { - - bool bIsFindDlg = (GetDlgItem(Globals.hwndDlgFindReplace, IDC_REPLACE) == NULL); - - HSTRINGW hstr = StrgCreate(NULL); - - ComboBox_GetTextHW(hwnd, IDC_FINDTEXT, hstr); - if (StringCchCompareX(StrgGet(hstr), StrgGet(lpefr->chFindPattern)) != 0) { - StrgReset(lpefr->chFindPattern, StrgGet(hstr)); - lpefr->bStateChanged = true; - } - - StrgReset(hstr, L""); - - ComboBox_GetTextHW(hwnd, IDC_REPLACETEXT, hstr); - if (StringCchCompareX(StrgGet(hstr), StrgGet(lpefr->chReplaceTemplate)) != 0) { - StrgReset(lpefr->chReplaceTemplate, StrgGet(hstr)); - lpefr->bStateChanged = true; - } - - StrgDestroy(hstr); - - _SyncFlagOpt(hwnd, IDC_FINDCASE, &lpefr->fuFlags, SCFIND_MATCHCASE, &lpefr->bStateChanged); - _SyncFlagOpt(hwnd, IDC_FINDWORD, &lpefr->fuFlags, SCFIND_WHOLEWORD, &lpefr->bStateChanged); - - if (IsDialogControlEnabled(hwnd, IDC_FINDTRANSFORMBS)) { - _SyncBoolOpt(hwnd, IDC_FINDTRANSFORMBS, &lpefr->bTransformBS, &lpefr->bStateChanged); - } - - _SyncFlagOpt(hwnd, IDC_FINDSTART, &lpefr->fuFlags, SCFIND_WORDSTART, &lpefr->bStateChanged); - - // regular expression option and its search flag change together - bool const bRegExChecked = IsButtonChecked(hwnd, IDC_FINDREGEXP); - if (bRegExChecked != lpefr->bRegExprSearch) { - lpefr->bRegExprSearch = bRegExChecked; - lpefr->fuFlags = bRegExChecked ? (lpefr->fuFlags | SCFIND_REGEXP) : (lpefr->fuFlags & ~(UINT)SCFIND_REGEXP); - lpefr->bStateChanged = true; - } - - if (IsDialogControlEnabled(hwnd, IDC_DOT_MATCH_ALL)) { - _SyncFlagOpt(hwnd, IDC_DOT_MATCH_ALL, &lpefr->fuFlags, SCFIND_DOT_MATCH_ALL, &lpefr->bStateChanged); - } - - // force consistency - if (lpefr->bRegExprSearch) { - CheckDlgButton(hwnd, IDC_WILDCARDSEARCH, BST_UNCHECKED); - } - bool const bWildcardChecked = IsButtonChecked(hwnd, IDC_WILDCARDSEARCH); - if (bWildcardChecked != lpefr->bWildcardSearch) { - lpefr->bWildcardSearch = bWildcardChecked; - lpefr->bStateChanged = true; - } - if (bWildcardChecked) { - if (!(lpefr->fuFlags & SCFIND_REGEXP)) { - lpefr->fuFlags |= SCFIND_REGEXP; // wild-card search based on RegExpr - lpefr->bStateChanged = true; - } - } else if ((lpefr->fuFlags & SCFIND_REGEXP) && !lpefr->bRegExprSearch) { - lpefr->fuFlags &= ~(UINT)SCFIND_REGEXP; - lpefr->bStateChanged = true; - } - - _SyncBoolOpt(hwnd, IDC_NOWRAP, &lpefr->bNoFindWrap, &lpefr->bStateChanged); - _SyncBoolOpt(hwnd, IDC_ALL_OCCURRENCES, &lpefr->bMarkOccurences, &lpefr->bStateChanged); - _SyncBoolOpt(hwnd, IDC_INST_INCR_SEARCH, &lpefr->bInstantIncrementalSearch, &lpefr->bStateChanged); - - // close dialog after find resp. replace - _SyncBoolOpt(hwnd, IDC_FINDCLOSE, bIsFindDlg ? &lpefr->bFindClose : &lpefr->bReplaceClose, &lpefr->bStateChanged); - } -} - - -// Wildcard search uses the regexp engine to perform a simple search with * ? as wildcards -// instead of more advanced and user-unfriendly RegExpr syntax -// for speed, we only need POSIX syntax here -static void _EscapeWildcards(wchar_t* wchFind, size_t cch, LPEDITFINDREPLACE lpefr) -{ - wchar_t* const wchWildcardEscaped = AllocMem(((cch<<1) + 1) * sizeof(wchar_t), HEAP_ZERO_MEMORY); - if (wchWildcardEscaped) { - - size_t iSource = 0; - size_t iDest = 0; - - lpefr->fuFlags |= SCFIND_REGEXP; - - bool bEsc = false; - while ((iSource < cch) && (wchFind[iSource] != L'\0')) { - wchar_t c = wchFind[iSource]; - if (c == L'*' && !bEsc) { - wchWildcardEscaped[iDest++] = L'.'; - } else if (c == L'?' && !bEsc) { - c = L'.'; - } else if (c == L'\\' && !bEsc) { - bEsc = true; - } - else if ( - (c == L'^' || - c == L'$' || - c == L'(' || - c == L')' || - c == L'[' || - c == L']' || - c == L'{' || - c == L'}' || - //~c == L'.' || - c == L'+' || - c == L'|' - ) ) { - if (!bEsc) { - wchWildcardEscaped[iDest++] = L'\\'; - } else { - bEsc = false; - } - } else if (bEsc) { - //~wchWildcardEscaped[iDest++] = L'\\'; ~ don't esc' backslash here - bEsc = false; - } - wchWildcardEscaped[iDest++] = c; - ++iSource; - } - - StringCchCopyN(wchFind, cch, wchWildcardEscaped, (cch << 1) + 1); - FreeMem(wchWildcardEscaped); - } -} - - -//============================================================================= -// -// _EditGetFindStrg() +// EditClearAllBookMarks() // -static LPCWSTR _EditGetFindStrg(HWND hwnd, const LPEDITFINDREPLACE lpefr, bool bFillEmpty) +void EditClearAllBookMarks(HWND hwnd) { UNREFERENCED_PARAMETER(hwnd); - - if (!lpefr) { - return NULL; - } - - static HSTRINGW hfind = NULL; - // TODO: StrgDestroy(hfind); - - if (!hfind) { - hfind = StrgCreate(NULL); - } - - // 1st: try last used pattern - if (StrgIsEmpty(lpefr->chFindPattern) && bFillEmpty) { - StrgReset(hfind, GetFindPattern()); - } else { - StrgReset(hfind, StrgGet(lpefr->chFindPattern)); - } - - // 2nd: try get clipboard content - if (StrgIsEmpty(hfind) && bFillEmpty && Settings.SearchByClipboardIfEmpty) { - LPWSTR const buf = StrgWriteAccessBuf(hfind, FNDRPL_BUFFER); - EditGetClipboardW(buf, StrgGetAllocLength(hfind)); - StrgSanitize(hfind); - } - - // 3nd: try get most recently used find pattern - if (StrgIsEmpty(hfind) && bFillEmpty) { - LPWSTR const buf = StrgWriteAccessBuf(hfind, FNDRPL_BUFFER); - MRU_Enum(Globals.pMRUfind, 0, buf, (int)StrgGetAllocLength(hfind)); - StrgSanitize(hfind); - } - - // 4th: return if still empty - if (StrgIsEmpty(hfind)) { - //~StrgDestroy(hfind); - static for speed - return NULL; - } - - // ensure to F/R-dialog data structure consistency - StrgReset(lpefr->chFindPattern, StrgGet(hfind)); - SetFindPattern(StrgGet(hfind)); - - if (lpefr->bWildcardSearch) { - // _EscapeWildcards can expand each char to two (e.g. '|' -> '\|', '*' -> '.*'), - // so ensure the buffer holds at least 2× the current content length. - size_t const expandCap = (StrgGetLength(hfind) * 2) + 2; - LPWSTR const buf = StrgWriteAccessBuf(hfind, max(expandCap, (size_t)FNDRPL_BUFFER)); - _EscapeWildcards(buf, StrgGetAllocLength(hfind), lpefr); - StrgSanitize(hfind); - } - - bool const bIsRegEx = (lpefr->fuFlags & SCFIND_REGEXP); - if (lpefr->bTransformBS || bIsRegEx) { - LPWSTR const buf = StrgWriteAccessBuf(hfind, FNDRPL_BUFFER); - TransformBackslashesW(buf, bIsRegEx, CP_UTF8, NULL); - StrgSanitize(hfind); - } - - return StrgGet(hfind); -} - - -//============================================================================= -// -// _GetReplaceString() -// -static char* _GetReplaceString(HWND hwnd, CLPCEDITFINDREPLACE lpefr, int* iReplaceMsg) -{ - char* pszReplace = NULL; // replace text of arbitrary size - if (Settings.ReplaceByClipboardTag && (StrCmpW(StrgGet(lpefr->chReplaceTemplate), L"^c")) == 0) - { - *iReplaceMsg = SciCall_GetChangeHistory() ? SCI_REPLACETARGETMINIMAL : SCI_REPLACETARGET; - pszReplace = EditGetClipboardText(hwnd, true, NULL, NULL); - } - else { - int const cch = max_i(StrgLengthAsUTF8(lpefr->chReplaceTemplate), 255) + 1; - pszReplace = (char*)AllocMem(cch, HEAP_ZERO_MEMORY); - if (pszReplace) { - StrgGetAsUTF8(lpefr->chReplaceTemplate, pszReplace, cch); - bool const bIsRegEx = (lpefr->fuFlags & SCFIND_REGEXP); - if (lpefr->bTransformBS || bIsRegEx) { - TransformBackslashesA(pszReplace, bIsRegEx, CP_UTF8, iReplaceMsg); - } - } - } - return pszReplace; // transfer ownership -} - - -//============================================================================= -// -// _FindInTarget() -// -// ONIG_MISMATCH -#define NOT_FOUND ((DocPos)(-1LL)) - -static DocPos _FindInTarget(LPCWSTR wchFind, int sFlags, - DocPos* begin, DocPos* end, bool bForceNext, FR_UPD_MODES fMode) -{ - static char chFind[8192] = { '\0' }; // max find buffer - - // mark-all and replace-all call this once per match with the same pattern: convert it only when it changed - static WCHAR s_wchLastFind[COUNTOF(chFind)] = { L'\0' }; - static UINT s_cpLastFind = 0; // code page of the pattern in chFind, 0 if chFind is not backed by s_wchLastFind - - DocPos iPos = NOT_FOUND; - - if (StrIsEmpty(wchFind)) { - return iPos; - } - - // remember original target range - DocPos const saveTargetBeg = SciCall_GetTargetStart(); - DocPos const saveTargetEnd = SciCall_GetTargetEnd(); - - DocPos const start = *begin; - DocPos const stop = *end; - bool const bFindNext = (start <= stop); // else find previous - - DocPos len = 0; - if ((s_cpLastFind == (UINT)Encoding_SciCP) && (wcscmp(wchFind, s_wchLastFind) == 0)) { // exact (ordinal) comparison - len = (DocPos)strlen(chFind); - } else { - len = (DocPos)(WideCharToMultiByte(Encoding_SciCP, 0, wchFind, -1, chFind, COUNTOF(chFind), NULL, NULL) - 1); - bool const bRemember = (len >= 0) && SUCCEEDED(StringCchCopyW(s_wchLastFind, COUNTOF(s_wchLastFind), wchFind)); - s_cpLastFind = bRemember ? (UINT)Encoding_SciCP : 0; - } - - // Clear any lingering regex-warning status so the post-call state reflects - // this search only. Without this, a stale SC_STATUS_WARN_REGEX from an - // earlier _FindInTarget call could leak into the next caller's Sci_ConsumeRegexWarnStatus. - SciCall_SetStatus(SC_STATUS_OK); - - SciCall_SetSearchFlags(sFlags); - SciCall_SetTargetRange(start, stop); - iPos = SciCall_SearchInTarget(len, chFind); - - // Bail out before the retry loop if the regex engine flagged an invalid - // pattern — every subsequent SearchInTarget would just re-set the warning. - // Status stays raised for the caller to consume via Sci_ConsumeRegexWarnStatus. - if ((sFlags & SCFIND_REGEXP) && SciCall_GetStatus() == SC_STATUS_WARN_REGEX) { - SciCall_SetTargetRange(saveTargetBeg, saveTargetEnd); - return NOT_FOUND; - } - -#if 1 - // handle next in case of zero-length-matches or invalid position (regex) ! - bool const bZeroLenMatch = ((iPos == start) && (start == SciCall_GetTargetEnd())); - bool bValidPos = !(bForceNext && bZeroLenMatch) && Sci_IsPosValid(iPos); - while (!bValidPos) { - DocPos const newStart = (bFindNext ? SciCall_PositionAfter(iPos) : SciCall_PositionBefore(iPos)); - bool const bProceed = (bFindNext ? (newStart < stop) : (newStart > stop)) && (newStart != iPos); - if (bProceed) { - SciCall_SetTargetRange(newStart, stop); - iPos = SciCall_SearchInTarget(len, chFind); // not found if beyond stop - } - else { - iPos = NOT_FOUND; // already at document begin, end or stuck => not found - } - bValidPos = Sci_IsPosValid(iPos); // NOT_FOUND is a valid pos - } -#else - // handle next in case of zero-length-matches (regex) ! - if (iPos == start) { - DocPos const nstop = SciCall_GetTargetEnd(); - if ((start == nstop) && bForceNext) { - DocPos const new_start = (bFindNext ? SciCall_PositionAfter(start) : SciCall_PositionBefore(start)); - bool const bProceed = (bFindNext ? (new_start < stop) : (new_start > stop)); - if ((new_start != start) && bProceed) { - SciCall_SetTargetRange(new_start, stop); - iPos = SciCall_SearchInTarget(len - 1, chFind); - } else { - iPos = (DocPos)-1LL; // already at document begin or end => not found - } - } - } -#endif - - if (iPos >= 0) { - if (fMode != FRMOD_IGNORE) { - Globals.FindReplaceMatchFoundState = bFindNext ? - ((fMode == FRMOD_WRAPED) ? NXT_WRP_FND : NXT_FND) : - ((fMode == FRMOD_WRAPED) ? PRV_WRP_FND : PRV_FND); + int const bitmask = OCCURRENCE_MARKER_BITMASK(); + DocLn const line = SciCall_MarkerNext(0, bitmask); + if (line >= 0) { + // 1st press: clear all occurrences marker + for (int m = MARKER_NP3_1; m < MARKER_NP3_BOOKMARK; ++m) { + SciCall_MarkerDeleteAll(m); } - // found in range, set begin and end of finding - *begin = SciCall_GetTargetStart(); - *end = SciCall_GetTargetEnd(); } else { - if (fMode != FRMOD_IGNORE) { - Globals.FindReplaceMatchFoundState = (fMode != FRMOD_WRAPED) ? (bFindNext ? NXT_NOT_FND : PRV_NOT_FND) : FND_NOP; - } + // if no occurrences marker found + SciCall_MarkerDeleteAll(MARKER_NP3_BOOKMARK); } - - SciCall_SetTargetRange(saveTargetBeg, saveTargetEnd); // restore original target range - - return iPos; } //============================================================================= // -// _FindHasMatch() +// EditToggleView() // -typedef enum { MATCH = 0, NO_MATCH = 1, INVALID = 2 } RegExResult_t; - -static RegExResult_t _FindHasMatch(HWND hwnd, const LPEDITFINDREPLACE lpefr, DocPos iStartPos, bool bMarkAll) +void EditToggleView(HWND hwnd) { - if (StrgIsEmpty(lpefr->chFindPattern)) { - return NO_MATCH; - } - int const sFlags = (int)(lpefr->fuFlags); - DocPos const iStart = iStartPos; - DocPos const iTextEnd = Sci_GetDocEndPosition(); + if (Settings.FocusViewMarkerMode & FVMM_FOLD) { - DocPos start = iStart; - DocPos end = iTextEnd; + BeginWaitCursorUID(true, IDS_MUI_SB_TOGGLE_VIEW); - LPCWSTR wchFind = _EditGetFindStrg(hwnd, lpefr, false); - DocPos const iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_IGNORE); - bool const bRegexInvalid = (sFlags & SCFIND_REGEXP) && Sci_ConsumeRegexWarnStatus(); + FocusedView.HideNonMatchedLines = !FocusedView.HideNonMatchedLines; // toggle - if (bMarkAll) { - EditClearAllOccurrenceMarkers(hwnd); - if (iPos >= 0) { - EditMarkAll(wchFind, (int)(lpefr->fuFlags), 0, iTextEnd, false); - if (FocusedView.HideNonMatchedLines) { - EditFoldMarkedLineRange(lpefr->hwnd, true); + if (FocusedView.HideNonMatchedLines) { + EditFoldMarkedLineRange(hwnd, true); + if (Settings.FocusViewMarkerMode & (FVMM_MARGIN | FVMM_LN_BACKGR)) { + EditBookMarkLineRange(hwnd); } } else { - if (FocusedView.HideNonMatchedLines) { - EditFoldMarkedLineRange(lpefr->hwnd, false); - } + EditFoldMarkedLineRange(hwnd, false); } - } - return ((iPos >= 0) ? MATCH : (bRegexInvalid ? INVALID : NO_MATCH)); -} - - -//============================================================================= -// -// _DelayMarkAll() -// -// -static void _DelayMarkAll(int delay) -{ - CmdMessageQueue_t mqc = MQ_WM_CMD_INIT(Globals.hwndDlgFindReplace, IDT_TIMER_CALLBACK_MRKALL, 0LL); - _MQ_AppendCmd(&mqc, _MQ_ms2cycl(delay)); -} - -//============================================================================= - -static bool s_SaveMarkOccurrences = false; -static bool s_SaveMarkMatchVisible = false; -//============================================================================= -// -// EditBoxForPasteFixes() -// Single-line EDIT's default WM_PASTE truncates at the first line break; -// EM_REPLACESEL inserts multi-line clipboard text unchanged. -// -static LRESULT CALLBACK EditBoxForPasteFixes(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, - UINT_PTR uIdSubclass, DWORD_PTR dwRefData) -{ - UNREFERENCED_PARAMETER(dwRefData); - - switch (uMsg) { - case WM_PASTE: { - // copy first: EM_REPLACESEL synchronously triggers the incremental search, - // which must not run while the clipboard is held open - WCHAR wchBuffer[FNDRPL_BUFFER] = { L'\0' }; - EditGetClipboardW(wchBuffer, COUNTOF(wchBuffer)); - if (StrIsNotEmpty(wchBuffer)) { - SendMessage(hwnd, EM_REPLACESEL, (WPARAM)TRUE, (LPARAM)wchBuffer); - return 0; - } - } break; + UpdateDocumentReadOnlyState(); + SciCall_ScrollCaret(); - case WM_NCDESTROY: - RemoveWindowSubclass(hwnd, EditBoxForPasteFixes, uIdSubclass); - break; + EndWaitCursor(); - default: - break; + } else if (Settings.FocusViewMarkerMode & (FVMM_MARGIN | FVMM_LN_BACKGR)) { + EditBookMarkLineRange(hwnd); } - return DefSubclassProc(hwnd, uMsg, wParam, lParam); } //============================================================================= // -// _ShowZeroLengthCallTip() +// EditSelectWordAtPos() // -static void _ShowZeroLengthCallTip(DocPos iPosition) +void EditSelectWordAtPos(const DocPos iPos, const bool bForceWord) { - char chZeroLenCT[80] = { '\0' }; - GetLngStringW2MB(IDS_MUI_ZERO_LEN_MATCH, chZeroLenCT, COUNTOF(chZeroLenCT)); - SciCall_CallTipShow(iPosition, chZeroLenCT); -} - - -//============================================================================= -// -// _EnableFRDlgCtrls() -// -static bool _EnableFRDlgCtrls(HWND hwnd) { - - bool const bEmptyFnd = ComboBox_GetTextLengthEx(hwnd, IDC_FINDTEXT) == 0 /*|| ComboBox_GetCurSelEx(hwnd, IDC_FINDTEXT) != CB_ERR)*/; - bool const bEmptyRpl = ComboBox_GetTextLengthEx(hwnd, IDC_REPLACETEXT) == 0 /*|| ComboBox_GetCurSelEx(hwnd, IDC_REPLACETEXT) != CB_ERR)*/; - bool const bEmptySel = (SciCall_IsSelectionEmpty() || Sci_IsMultiOrRectangleSelection()); - - DialogEnableControl(hwnd, IDOK, !bEmptyFnd); - DialogEnableControl(hwnd, IDC_FINDPREV, !bEmptyFnd); - DialogEnableControl(hwnd, IDC_REPLACE, !bEmptyFnd); - DialogEnableControl(hwnd, IDC_REPLACEALL, !bEmptyFnd); - DialogEnableControl(hwnd, IDC_REPLACEINSEL, !bEmptyFnd && !bEmptySel); - DialogEnableControl(hwnd, IDC_SWAPSTRG, !bEmptyFnd || !bEmptyRpl); - - return !bEmptyFnd; -} - - -//============================================================================= -// -// _AddPatternToComboMRU() -// Insert pszItem at the top of a CBS_DROPDOWN combo's list without touching -// its edit field (no CBN_EDITCHANGE side-effects). -// -static void _AddPatternToComboMRU(HWND hwnd, int nIDDlgItem, LPCWSTR pszItem) -{ - if (StrIsEmpty(pszItem)) { return; } - HWND const hwndCtl = GetDlgItem(hwnd, nIDDlgItem); - int const idx = (int)SendMessage(hwndCtl, CB_FINDSTRINGEXACT, (WPARAM)(-1), (LPARAM)pszItem); - if (idx != CB_ERR) { - SendMessage(hwndCtl, CB_DELETESTRING, (WPARAM)idx, 0); - } - SendMessage(hwndCtl, CB_INSERTSTRING, 0, (LPARAM)pszItem); -} - - -//============================================================================= -// -// EditFindReplaceDlgProc() -// -typedef struct { - LPEDITFINDREPLACE pEfrData; - const FindReplaceDlgRestore* pRestore; -} FindReplaceDlgInit; - -static void _RestoreFindReplaceDlgPosition(HWND hwnd, const RECT* pPreviousRect) -{ - MONITORINFO mi = { sizeof(mi) }; - if (IsRectEmpty(pPreviousRect) || - !GetMonitorInfo(MonitorFromRect(pPreviousRect, MONITOR_DEFAULTTONEAREST), &mi)) { - return; - } - - // The first move can resize the dialog via WM_DPICHANGED. Fit it again using the new size. - for (int i = 0; i < 2; ++i) { - RECT rc; - if (!GetWindowRect(hwnd, &rc)) { - return; - } - LONG const x = max_l(mi.rcWork.left, min_l(pPreviousRect->left, mi.rcWork.right - (rc.right - rc.left))); - LONG const y = max_l(mi.rcWork.top, min_l(pPreviousRect->top, mi.rcWork.bottom - (rc.bottom - rc.top))); - if (rc.left == x && rc.top == y) { - break; - } - SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); - } -} - -extern int g_flagMatchText; - -// TODO: §§§ get rid of this buffer -static WCHAR s_wchBufIn[FNDRPL_BUFFER] = { L'\0' }; // tmp working buffer -static WCHAR s_wchBufOut[FNDRPL_BUFFER] = { L'\0' }; // tmp working buffer - - -static INT_PTR CALLBACK EditFindReplaceDlgProc(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) -{ - static LPEDITFINDREPLACE s_pEfrData = NULL; - - static bool s_bIsReplaceDlg = false; - static bool s_bRestoreFocusedView = false; - - static UINT_PTR pTimerIdentifier = 0; - - static DocPos s_InitialSearchStart = 0; - static DocPos s_InitialAnchorPos = 0; - static DocPos s_InitialCaretPos = 0; - static DocLn s_InitialTopLine = -1; - -#define SET_INITIAL_ANCHORS() {\ - s_InitialTopLine = -1;\ - s_InitialCaretPos = SciCall_GetCurrentPos();\ - s_InitialAnchorPos = SciCall_GetAnchor();\ - s_InitialSearchStart = SciCall_GetSelectionStart(); \ - } - - static RegExResult_t s_anyMatch = NO_MATCH; - - static HBRUSH hBrushRed; - static HBRUSH hBrushGreen; - static HBRUSH hBrushBlue; - - switch (umsg) { - case WM_INITDIALOG: { - - const FindReplaceDlgInit* const pInit = (const FindReplaceDlgInit*)lParam; - s_pEfrData = pInit->pEfrData; - s_bRestoreFocusedView = pInit->pRestore && pInit->pRestore->bFocusedView; - - Globals.hwndDlgFindReplace = hwnd; - s_bIsReplaceDlg = (GetDlgItem(hwnd, IDC_REPLACETEXT) != NULL); - - // clear cmd line stuff - g_flagMatchText = 0; - - SetDialogIconNP3(hwnd); - InitWindowCommon(hwnd, true); - -#ifdef D_NP3_WIN10_DARK_MODE - if (UseDarkMode()) { - int const ctlx[] = { IDOK, IDCANCEL, IDC_FINDPREV, IDC_REPLACE, IDC_REPLACEALL, - IDC_REPLACEINSEL, IDC_SWAPSTRG, IDC_TOGGLE_VISIBILITY - }; - for (int i = 0; i < COUNTOF(ctlx); ++i) { - SetExplorerTheme(GetDlgItem(hwnd, ctlx[i])); - } - int const ctl[] = { IDC_FINDCASE, IDC_FINDWORD, IDC_FINDSTART, IDC_FINDTRANSFORMBS, IDC_FINDESCCTRLCHR, IDC_REPLESCCTRLCHR, - IDC_FINDREGEXP, IDC_DOT_MATCH_ALL, IDC_NOWRAP, IDC_FINDCLOSE, - IDC_ALL_OCCURRENCES, IDC_INST_INCR_SEARCH, IDC_WILDCARDSEARCH, IDC_TRANSPARENT, IDC_STATIC, IDC_STATIC2 - }; - for (int i = 0; i < COUNTOF(ctl); ++i) { - SetWindowTheme(GetDlgItem(hwnd, ctl[i]), L"", L""); // remove theme for BS_AUTORADIOBUTTON - } - //SetExplorerTheme(GetDlgItem(hwnd, IDC_RESIZEGRIP)); - } -#endif - - pTimerIdentifier = SetTimer(hwnd, 0, _MQ_TIMER_CYCLE, MQ_ExecuteNext); - - SET_INITIAL_ANCHORS() - s_InitialTopLine = SciCall_GetFirstVisibleLine(); - - EditSetCaretToSelectionStart(); // avoid search text selection jumps to next match (before ResizeDlg_InitX()) - - Globals.iReplacedOccurrences = 0; - Globals.FindReplaceMatchFoundState = FND_NOP; - - s_SaveMarkOccurrences = s_bSwitchedFindReplace ? s_SaveMarkOccurrences : Settings.MarkOccurrences; - s_SaveMarkMatchVisible = s_bSwitchedFindReplace ? s_SaveMarkMatchVisible : Settings.MarkOccurrencesMatchVisible; - // switch off normal mark occurrences - Settings.MarkOccurrences = false; - Settings.MarkOccurrencesMatchVisible = false; - EnableCmd(GetMenu(Globals.hwndMain), IDM_VIEW_MARKOCCUR_ONOFF, false); - - SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_LIMITTEXT, FNDRPL_BUFFER, 0); - SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_SETEXTENDEDUI, true, 0); - - // Load MRUs - for (int i = 0; i < MRU_Count(Globals.pMRUfind); i++) { - MRU_Enum(Globals.pMRUfind, i, s_wchBufOut, COUNTOF(s_wchBufOut)); - SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_ADDSTRING, 0, (LPARAM)s_wchBufOut); - } - - COMBOBOXINFO cbInfoF = { sizeof(COMBOBOXINFO) }; - GetComboBoxInfo(GetDlgItem(hwnd, IDC_FINDTEXT), &cbInfoF); - if (cbInfoF.hwndItem) { - SetWindowSubclass(cbInfoF.hwndItem, EditBoxForPasteFixes, 0, 0); - SHAutoComplete(cbInfoF.hwndItem, SHACF_FILESYS_ONLY | SHACF_AUTOAPPEND_FORCE_OFF | SHACF_AUTOSUGGEST_FORCE_OFF); - } - - if (s_bIsReplaceDlg) { - - SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_LIMITTEXT, FNDRPL_BUFFER, 0); - SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_SETEXTENDEDUI, true, 0); - - // Load MRUs - for (int i = 0; i < MRU_Count(Globals.pMRUreplace); i++) { - MRU_Enum(Globals.pMRUreplace, i, s_wchBufOut, COUNTOF(s_wchBufOut)); - SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_ADDSTRING, 0, (LPARAM)s_wchBufOut); - } - - COMBOBOXINFO cbInfoR = { sizeof(COMBOBOXINFO) }; - GetComboBoxInfo(GetDlgItem(hwnd, IDC_REPLACETEXT), &cbInfoR); - if (cbInfoR.hwndItem) { - SetWindowSubclass(cbInfoR.hwndItem, EditBoxForPasteFixes, 0, 0); - SHAutoComplete(cbInfoR.hwndItem, SHACF_FILESYS_ONLY | SHACF_AUTOAPPEND_FORCE_OFF | SHACF_AUTOSUGGEST_FORCE_OFF); - } - } - - // Initialize all checkboxes BEFORE setting combobox text. - // Setting combobox text triggers CBN_EDITCHANGE synchronously, - // which calls _SetSearchFlags() that reads checkbox states. - // Checkboxes must reflect s_pEfrData values at that point. - CheckDlgButton(hwnd, IDC_FINDREGEXP, SetBtn(s_pEfrData->bRegExprSearch)); - - bool const bDotMatchAll = (s_pEfrData->fuFlags & SCFIND_DOT_MATCH_ALL) != 0; - CheckDlgButton(hwnd, IDC_DOT_MATCH_ALL, SetBtn(s_pEfrData->bRegExprSearch && bDotMatchAll)); - DialogEnableControl(hwnd, IDC_DOT_MATCH_ALL, s_pEfrData->bRegExprSearch); - - if (s_pEfrData->bRegExprSearch) { - s_pEfrData->bWildcardSearch = false; - } - if (s_pEfrData->bWildcardSearch) { - CheckDlgButton(hwnd, IDC_WILDCARDSEARCH, BST_CHECKED); - CheckDlgButton(hwnd, IDC_FINDREGEXP, BST_UNCHECKED); - } - - // transform BS handled by regex (wild-card search based on): - CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, SetBtn(s_pEfrData->bTransformBS || s_pEfrData->bRegExprSearch || s_pEfrData->bWildcardSearch)); - DialogEnableControl(hwnd, IDC_FINDTRANSFORMBS, !(s_pEfrData->bRegExprSearch || s_pEfrData->bWildcardSearch)); - - CheckDlgButton(hwnd, IDC_ALL_OCCURRENCES, SetBtn(s_pEfrData->bMarkOccurences)); - if (!s_pEfrData->bMarkOccurences) { - EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); - } - - CheckDlgButton(hwnd, IDC_INST_INCR_SEARCH, SetBtn(s_pEfrData->bInstantIncrementalSearch)); - - CheckDlgButton(hwnd, IDC_FINDCASE, SetBtn(s_pEfrData->fuFlags & SCFIND_MATCHCASE)); - CheckDlgButton(hwnd, IDC_FINDWORD, SetBtn(s_pEfrData->fuFlags & SCFIND_WHOLEWORD)); - CheckDlgButton(hwnd, IDC_FINDSTART, SetBtn(s_pEfrData->fuFlags & SCFIND_WORDSTART)); - CheckDlgButton(hwnd, IDC_NOWRAP, SetBtn(s_pEfrData->bNoFindWrap)); - - if (s_bIsReplaceDlg) { - CheckDlgButton(hwnd, IDC_FINDCLOSE, SetBtn(s_pEfrData->bReplaceClose)); - } else { - CheckDlgButton(hwnd, IDC_FINDCLOSE, SetBtn(s_pEfrData->bFindClose)); - } - - CheckDlgButton(hwnd, IDC_TRANSPARENT, SetBtn(Settings.FindReplaceTransparentMode)); - - // Now set combobox text — CBN_EDITCHANGE will fire and call - // _SetSearchFlags(), which can now read the correct checkbox states. - if (pInit->pRestore) { - // Restore both fields before edit notifications can sync the partially initialized dialog. - s_pEfrData = NULL; - ComboBox_SetTextHW(hwnd, IDC_FINDTEXT, pInit->pEfrData->chFindPattern); - if (s_bIsReplaceDlg) { - ComboBox_SetTextHW(hwnd, IDC_REPLACETEXT, pInit->pEfrData->chReplaceTemplate); - } - s_pEfrData = pInit->pEfrData; - } else if (!GetWindowTextLengthW(GetDlgItem(hwnd, IDC_FINDTEXT))) { - if (StrgIsNotEmpty(s_pEfrData->chFindPattern)) { - ComboBox_SetTextHW(hwnd, IDC_FINDTEXT, s_pEfrData->chFindPattern); - } - else if (MRU_Count(Globals.pMRUfind)) { - MRU_Enum(Globals.pMRUfind, 0, s_wchBufOut, COUNTOF(s_wchBufOut)); - ComboBox_SetTextW(hwnd, IDC_FINDTEXT, s_wchBufOut); - } - else { - ComboBox_SetTextW(hwnd, IDC_FINDTEXT, NULL); - } - } - - if (s_bIsReplaceDlg && !pInit->pRestore) { - if (!GetWindowTextLengthW(GetDlgItem(hwnd, IDC_REPLACETEXT))) { - if (StrgIsNotEmpty(s_pEfrData->chReplaceTemplate)) { - ComboBox_SetTextHW(hwnd, IDC_REPLACETEXT, s_pEfrData->chReplaceTemplate); - } - else if (MRU_Count(Globals.pMRUreplace)) { - MRU_Enum(Globals.pMRUreplace, 0, s_wchBufOut, COUNTOF(s_wchBufOut)); - ComboBox_SetTextW(hwnd, IDC_REPLACETEXT, s_wchBufOut); - } - else { - ComboBox_SetTextW(hwnd, IDC_REPLACETEXT, NULL); - } - } - } - - if (s_bSwitchedFindReplace) { - // restore from prev Dlg - SetDlgPos(hwnd, s_xFindReplaceDlgSave, s_yFindReplaceDlgSave); - s_bSwitchedFindReplace = false; - } - else if (pInit->pRestore) { - _RestoreFindReplaceDlgPosition(hwnd, &pInit->pRestore->windowRect); - } - else { - if (Settings.FindReplaceDlgPosX == CW_USEDEFAULT || Settings.FindReplaceDlgPosY == CW_USEDEFAULT) { - CenterDlgInParent(hwnd, false); - } - else { - SetDlgPos(hwnd, Settings.FindReplaceDlgPosX, Settings.FindReplaceDlgPosY); - } - } - - WCHAR wchMenuBuf[80] = {L'\0'}; - HMENU hmenu = GetSystemMenu(hwnd, FALSE); - - GetLngString(IDS_MUI_SAVEPOS, wchMenuBuf, COUNTOF(wchMenuBuf)); - InsertMenu(hmenu, 0, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_SAVEPOS, wchMenuBuf); - GetLngString(IDS_MUI_RESETPOS, wchMenuBuf, COUNTOF(wchMenuBuf)); - InsertMenu(hmenu, 1, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_RESETPOS, wchMenuBuf); - InsertMenu(hmenu, 2, MF_BYPOSITION | MF_SEPARATOR, 0, NULL); - GetLngString(IDS_MUI_CLEAR_FIND_HISTORY, wchMenuBuf, COUNTOF(wchMenuBuf)); - InsertMenu(hmenu, 3, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_CLEAR_FIND_HISTORY, wchMenuBuf); - GetLngString(IDS_MUI_CLEAR_REPL_HISTORY, wchMenuBuf, COUNTOF(wchMenuBuf)); - InsertMenu(hmenu, 4, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_CLEAR_REPL_HISTORY, wchMenuBuf); - InsertMenu(hmenu, 5, MF_BYPOSITION | MF_SEPARATOR, 0, NULL); - GetLngString(IDS_MUI_SEARCHCLIPIFEMPTY, wchMenuBuf, COUNTOF(wchMenuBuf)); - InsertMenu(hmenu, 6, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_SEARCHCLIPIFEMPTY, wchMenuBuf); - GetLngString(IDS_MUI_REPLCLIPTAG, wchMenuBuf, COUNTOF(wchMenuBuf)); - InsertMenu(hmenu, 7, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_REPLCLIPTAG, wchMenuBuf); - InsertMenu(hmenu, 8, MF_BYPOSITION | MF_SEPARATOR, 0, NULL); - - CheckCmd(hmenu, IDS_MUI_SEARCHCLIPIFEMPTY, Settings.SearchByClipboardIfEmpty); - CheckCmd(hmenu, IDS_MUI_REPLCLIPTAG, Settings.ReplaceByClipboardTag); - - - hBrushRed = CreateSolidBrush(rgbRedColorRef); - hBrushGreen = CreateSolidBrush(rgbGreenColorRef); - hBrushBlue = CreateSolidBrush(rgbBlueColorRef); - - s_anyMatch = NO_MATCH; - - _SetSearchFlags(hwnd, s_pEfrData); // sync - s_pEfrData->bStateChanged = true; // force update - - DialogEnableControl(hwnd, IDC_TOGGLE_VISIBILITY, s_pEfrData->bMarkOccurences); - - _DelayMarkAll(_MQ_STD); - - PostMessage(hwnd, WM_THEMECHANGED, 0, 0); - } - return TRUE; // (!) further processing - - case WM_ENABLE: - // modal child dialog should disable main window too - EnableWindow(Globals.hwndMain, (BOOL)wParam); - return TRUE; - - case WM_CLOSE: - // Language switching needs the modeless dialog destroyed before the resource DLL is unloaded. - DestroyWindow(hwnd); - return TRUE; - - case WM_DESTROY: { - - KillTimer(hwnd, pTimerIdentifier); - pTimerIdentifier = 0; - - _SetSearchFlags(hwnd, s_pEfrData); // sync - DuplicateEFR(&(Settings.EFR_Data), s_pEfrData); - - if (!s_bSwitchedFindReplace) { - if (s_anyMatch == MATCH) { - // Save MRUs - if (StrgIsNotEmpty(s_pEfrData->chFindPattern)) { - MRU_Add(Globals.pMRUfind, StrgGet(s_pEfrData->chFindPattern), 0, -1, -1, NULL); - SetFindPattern(StrgGet(s_pEfrData->chFindPattern)); - } - //~if (StrgIsNotEmpty(s_pEfrData->chReplaceTemplate)) { - MRU_Add(Globals.pMRUreplace, StrgGet(s_pEfrData->chReplaceTemplate), 0, -1, -1, NULL); - //~} - } - - Globals.iReplacedOccurrences = 0; - Globals.FindReplaceMatchFoundState = FND_NOP; - - Settings.MarkOccurrences = s_SaveMarkOccurrences; - Settings.MarkOccurrencesMatchVisible = s_SaveMarkMatchVisible; - EnableCmd(GetMenu(Globals.hwndMain), IDM_VIEW_MARKOCCUR_ONOFF, true); - - if (FocusedView.HideNonMatchedLines) { - EditToggleView(s_pEfrData->hwnd); - } - - if (IsMarkOccurrencesEnabled()) { - MarkAllOccurrences(_MQ_STD, true); - } else { - EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); - } - - if (s_InitialTopLine >= 0) { - SciCall_SetFirstVisibleLine(s_InitialTopLine); - s_InitialTopLine = -1; // reset - } else { - if (s_anyMatch == NO_MATCH) { - EditSetSelectionEx(s_InitialAnchorPos, s_InitialCaretPos, -1, -1); - } else { - Sci_ScrollSelectionToView(); - } - } - - CmdMessageQueue_t* pmqc = NULL; - CmdMessageQueue_t* dummy; - DL_FOREACH_SAFE(MessageQueue, pmqc, dummy) { - DL_DELETE(MessageQueue, pmqc); - FreeMem(pmqc); - } - } - - DeleteObject(hBrushRed); - DeleteObject(hBrushGreen); - DeleteObject(hBrushBlue); - GetSystemMenu(hwnd, TRUE); - - s_pEfrData = NULL; - Globals.hwndDlgFindReplace = NULL; - } - return FALSE; - - - case WM_DPICHANGED: - UpdateWindowLayoutForDPI(hwnd, (RECT*)lParam, LOWORD(wParam)); - return TRUE; // further processing - - -#ifdef D_NP3_WIN10_DARK_MODE - - case WM_CTLCOLORDLG: - case WM_CTLCOLORBTN: - //~case WM_CTLCOLOREDIT: - //~case WM_CTLCOLORLISTBOX: - case WM_CTLCOLORSTATIC: - return SetDarkModeCtlColors((HDC)wParam, UseDarkMode()); - break; - - case WM_SETTINGCHANGE: - if (IsDarkModeSupported() && IsColorSchemeChangeMessage(lParam)) { - SendMessage(hwnd, WM_THEMECHANGED, 0, 0); - } - break; - - case WM_THEMECHANGED: - if (IsDarkModeSupported()) { - bool const darkModeEnabled = CheckDarkModeEnabled(); - AllowDarkModeForWindowEx(hwnd, darkModeEnabled); - RefreshTitleBarThemeColor(hwnd); - int const ctlx[] = { IDOK, IDCANCEL, IDC_FINDPREV, IDC_REPLACE, IDC_SWAPSTRG, - IDC_REPLACEALL, IDC_REPLACEINSEL, IDC_TOGGLE_VISIBILITY - }; - for (int i = 0; i < COUNTOF(ctlx); ++i) { - HWND const hBtn = GetDlgItem(hwnd, ctlx[i]); - AllowDarkModeForWindowEx(hBtn, darkModeEnabled); - SendMessage(hBtn, WM_THEMECHANGED, 0, 0); - } - UpdateWindowEx(hwnd); - } - break; - -#endif - - case WM_CTLCOLOREDIT: - case WM_CTLCOLORLISTBOX: { - if (!s_pEfrData) { - return false; - } - HWND hCheck = (HWND)lParam; - HDC hDC = (HDC)wParam; - - HWND hComboBox = GetDlgItem(hwnd, IDC_FINDTEXT); - COMBOBOXINFO ci = { sizeof(COMBOBOXINFO) }; - GetComboBoxInfo(hComboBox, &ci); - - //if (hCheck == ci.hwndItem || hCheck == ci.hwndList) - if (hCheck == ci.hwndItem) { - SetBkMode(hDC, TRANSPARENT); - INT_PTR hBrush; - switch (s_anyMatch) { - case MATCH: - //SetTextColor(hDC, green); - SetBkColor(hDC, rgbGreenColorRef); - hBrush = (INT_PTR)hBrushGreen; - break; - case NO_MATCH: - //SetTextColor(hDC, blue); - SetBkColor(hDC, rgbBlueColorRef); - hBrush = (INT_PTR)hBrushBlue; - break; - case INVALID: - default: - //SetTextColor(hDC, red); - SetBkColor(hDC, rgbRedColorRef); - hBrush = (INT_PTR)hBrushRed; - break; - } - return hBrush; - } - } -#ifdef D_NP3_WIN10_DARK_MODE - return SetDarkModeCtlColors((HDC)wParam, UseDarkMode()); -#else - return FALSE; -#endif - - - case WM_ACTIVATE: { - if (!s_pEfrData) { - return false; - } - - switch (LOWORD(wParam)) { - case WA_INACTIVE: - SetWindowTransparentMode(hwnd, Settings.FindReplaceTransparentMode, Settings2.FindReplaceOpacityLevel); - break; - - case WA_CLICKACTIVE: - // mouse click activation - case WA_ACTIVE: - SetWindowTransparentMode(hwnd, false, 100); - - // selection changed ? - if ((SciCall_GetCurrentPos() != s_InitialCaretPos) || - (SciCall_GetAnchor() != s_InitialAnchorPos)) { - EditSetCaretToSelectionStart(); - s_InitialAnchorPos = SciCall_GetAnchor(); - s_InitialCaretPos = SciCall_GetCurrentPos(); - s_InitialTopLine = SciCall_GetFirstVisibleLine(); - s_InitialSearchStart = s_InitialCaretPos; - if (s_pEfrData) { - s_pEfrData->bStateChanged = true; - } - } - - bool const bEnableReplInSel = !(SciCall_IsSelectionEmpty() || Sci_IsMultiOrRectangleSelection()); - DialogEnableControl(hwnd, IDC_REPLACEINSEL, bEnableReplInSel); - - _DelayMarkAll(_MQ_STD); - - if (!SciCall_IsSelectionEmpty()) { - Sci_ScrollSelectionToView(); - } - /// don't do: ///~SendWMCommandEx(hwnd, IDC_FINDTEXT, CBN_EDITCHANGE); - break; - - default: - break; - } - } - return false; - - - case WM_COMMAND: { - if (!s_pEfrData) { - return FALSE; - } - - switch (LOWORD(wParam)) { - - case IDC_DOC_MODIFIED: - s_InitialSearchStart = SciCall_GetSelectionStart(); - s_InitialTopLine = -1; // reset - s_pEfrData->bStateChanged = true; - _DelayMarkAll(_MQ_STD); - break; - - - case IDC_FINDTEXT: - case IDC_REPLACETEXT: { - - bool bFndPatternChanged = s_pEfrData->bStateChanged; - - switch (HIWORD(wParam)) { - - case CBN_EDITUPDATE: - if (SendDlgItemMessage(hwnd, LOWORD(wParam), CB_GETDROPPEDSTATE, 0, 0)) { - //~SendDlgItemMessage(hwnd, LOWORD(wParam), CB_SETCURSEL, (WPARAM)-1, 0); // clear - SendDlgItemMessage(hwnd, LOWORD(wParam), CB_SHOWDROPDOWN, 0, 0); // hide - } - break; - - //~case CBN_SELCHANGE: - case CBN_CLOSEUP: { - int const cursel = (int)SendDlgItemMessage(hwnd, LOWORD(wParam), CB_GETCURSEL, 0, 0); - if (cursel >= 0) { - SendDlgItemMessage(hwnd, LOWORD(wParam), CB_SETCURSEL, (WPARAM)cursel, 0); - } - } - // [fallthrough] - case CBN_SELENDOK: - case CBN_EDITCHANGE: - bFndPatternChanged = (LOWORD(wParam) == IDC_FINDTEXT); - break; - - case CBN_KILLFOCUS: - case CBN_SELENDCANCEL: - default: - break; - } - - if (Globals.bFindReplCopySelOrClip) { - // reset first: setting the combo text below re-enters this handler (CBN_EDITCHANGE) - Globals.bFindReplCopySelOrClip = false; - char* lpszSelection = NULL; - DocPos const cchSelection = SciCall_GetSelText(NULL); - // WM_SETTEXT ignores CB_LIMITTEXT: an oversized selection freezes the combo's edit control - if ((cchSelection > 0) && (cchSelection <= FNDRPL_BUFFER) && (LOWORD(wParam) != IDC_REPLACETEXT)) { - lpszSelection = AllocMem((cchSelection + 1), HEAP_ZERO_MEMORY); - SciCall_GetSelText(lpszSelection); - } else { // no (usable) selection - // nothing is selected in the editor: - // if first time you bring up find/replace dialog, - // use most recent search pattern to find box - // in case of no history: paste clipboard - LPCWSTR wchFind = _EditGetFindStrg(Globals.hwndEdit, s_pEfrData, true); - if (StrIsNotEmpty(wchFind)) { - int const size = WideCharToMultiByte(Encoding_SciCP, 0, wchFind, -1, NULL, 0, NULL, NULL); - lpszSelection = AllocMem(size * sizeof(CHAR), HEAP_ZERO_MEMORY); - WideCharToMultiByte(Encoding_SciCP, 0, wchFind, -1, lpszSelection, size, NULL, NULL); - } - } - if (lpszSelection) { - ComboBox_SetTextMB2W(hwnd, IDC_FINDTEXT, lpszSelection); - FreeMem(lpszSelection); - lpszSelection = NULL; - bFndPatternChanged = true; - } - s_InitialTopLine = -1; // reset - - } // Globals.bFindReplCopySelOrClip - - _SetSearchFlags(hwnd, s_pEfrData); - SetFindPattern(StrgGet(s_pEfrData->chFindPattern)); - - // ------------------------ - - if (!(bFndPatternChanged || s_pEfrData->bStateChanged)) { - break; // return - } - // ------------------------ - - EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); - - if (_EnableFRDlgCtrls(hwnd)) { - EditSetSelectionEx(s_InitialAnchorPos, s_InitialCaretPos, -1, -1); - } - - DocPos start = s_InitialSearchStart; - DocPos end = Sci_GetDocEndPosition(); - - LPCWSTR wchFind = _EditGetFindStrg(s_pEfrData->hwnd, s_pEfrData, false); - DocPos const iPos = _FindInTarget(wchFind, (int)(s_pEfrData->fuFlags), &start, &end, false, FRMOD_NORM); - - if (s_pEfrData->bInstantIncrementalSearch) { - if (iPos >= 0) { - if (s_bIsReplaceDlg) { - SciCall_ScrollRange(end, iPos); - } - else { - EditSetSelectionEx(end, iPos, -1, -1); - } - if (iPos == end) { - _ShowZeroLengthCallTip(iPos); - } - } - else { - if (s_bIsReplaceDlg) { - SciCall_ScrollRange(s_InitialAnchorPos, s_InitialCaretPos); - } - if (s_InitialTopLine >= 0) { - SciCall_SetFirstVisibleLine(s_InitialTopLine); - } - } - } - _DelayMarkAll(_MQ_STD); - } - break; - - case IDT_TIMER_CALLBACK_MRKALL: { - bool const bRestoreFocusedView = s_bRestoreFocusedView; - s_bRestoreFocusedView = false; - static wchar_t s_lastFind[FNDRPL_BUFFER] = { L'\0' }; - bool const bRefreshMarks = s_pEfrData->bMarkOccurences && - (s_pEfrData->bStateChanged || (StringCchCompareX(s_lastFind, StrgGet(s_pEfrData->chFindPattern)) != 0)); - if (bRefreshMarks) { - StringCchCopyW(s_lastFind, COUNTOF(s_lastFind), StrgGet(s_pEfrData->chFindPattern)); - } - s_anyMatch = _FindHasMatch(s_pEfrData->hwnd, s_pEfrData, 0, bRefreshMarks); - InvalidateRect(GetDlgItem(hwnd, IDC_FINDTEXT), NULL, TRUE); // coloring - if (bRefreshMarks) { - if (bRestoreFocusedView && s_anyMatch == MATCH && (Settings.FocusViewMarkerMode & FVMM_FOLD)) { - // Fold the rebuilt matches without re-running Focused View's bookmark action. - FocusedView.HideNonMatchedLines = true; - EditFoldMarkedLineRange(s_pEfrData->hwnd, true); - UpdateDocumentReadOnlyState(); - } else if (FocusedView.HideNonMatchedLines) { - EditToggleView(s_pEfrData->hwnd); - } - } else if (!s_pEfrData->bMarkOccurences && s_pEfrData->bStateChanged) { - if (FocusedView.HideNonMatchedLines) { - SendWMCommand(hwnd, IDC_TOGGLE_VISIBILITY); - } else { - EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); - InvalidateRect(GetDlgItem(hwnd, IDC_FINDTEXT), NULL, TRUE); - } - } - s_pEfrData->bStateChanged = false; - } - break; - - case IDC_ALL_OCCURRENCES: { - _SetSearchFlags(hwnd, s_pEfrData); - - if (IsButtonChecked(hwnd, IDC_ALL_OCCURRENCES)) { - DialogEnableControl(hwnd, IDC_TOGGLE_VISIBILITY, true); - _DelayMarkAll(_MQ_STD); - } else { // switched OFF - DialogEnableControl(hwnd, IDC_TOGGLE_VISIBILITY, false); - if (FocusedView.HideNonMatchedLines) { - EditToggleView(s_pEfrData->hwnd); - } - EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); - InvalidateRect(GetDlgItem(hwnd, IDC_FINDTEXT), NULL, TRUE); - } - } - break; - - case IDC_INST_INCR_SEARCH: - _SetSearchFlags(hwnd, s_pEfrData); - _DelayMarkAll(_MQ_STD); - break; - - case IDC_TOGGLE_VISIBILITY: - if (s_pEfrData) { - s_bRestoreFocusedView = false; - EditToggleView(s_pEfrData->hwnd); - if (!FocusedView.HideNonMatchedLines) { - s_pEfrData->bStateChanged = true; - s_InitialTopLine = -1; // reset - EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); - _DelayMarkAll(_MQ_STD); - } - } - break; - - case IDC_FINDREGEXP: - if (IsButtonChecked(hwnd, IDC_FINDREGEXP)) { - DialogEnableControl(hwnd, IDC_DOT_MATCH_ALL, true); - // Can not use wild-card search together with RegExp - CheckDlgButton(hwnd, IDC_WILDCARDSEARCH, BST_UNCHECKED); - // transform BS handled by regex - CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, BST_CHECKED); - DialogEnableControl(hwnd, IDC_FINDTRANSFORMBS, false); - } else { // unchecked - DialogEnableControl(hwnd, IDC_DOT_MATCH_ALL, false); - DialogEnableControl(hwnd, IDC_FINDTRANSFORMBS, true); - CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, SetBtn(s_pEfrData->bTransformBS)); - } - _SetSearchFlags(hwnd, s_pEfrData); - _DelayMarkAll(_MQ_STD); - break; - - case IDC_DOT_MATCH_ALL: - _SetSearchFlags(hwnd, s_pEfrData); - _DelayMarkAll(_MQ_STD); - break; - - case IDC_WILDCARDSEARCH: { - if (IsButtonChecked(hwnd, IDC_WILDCARDSEARCH)) { - // Can not use wild-card search together with RegExp - CheckDlgButton(hwnd, IDC_FINDREGEXP, BST_UNCHECKED); - DialogEnableControl(hwnd, IDC_DOT_MATCH_ALL, false); - // transform BS handled by regex (wild-card search based on): - CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, BST_CHECKED); - DialogEnableControl(hwnd, IDC_FINDTRANSFORMBS, false); - } else { // unchecked - DialogEnableControl(hwnd, IDC_FINDTRANSFORMBS, true); - CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, SetBtn(s_pEfrData->bTransformBS)); - } - _SetSearchFlags(hwnd, s_pEfrData); - _DelayMarkAll(_MQ_STD); - } - break; - - case IDC_FINDTRANSFORMBS: { - _SetSearchFlags(hwnd, s_pEfrData); - _DelayMarkAll(_MQ_STD); - } - break; - - case IDC_FINDCASE: - _SetSearchFlags(hwnd, s_pEfrData); - _DelayMarkAll(_MQ_STD); - break; - - case IDC_FINDWORD: - _SetSearchFlags(hwnd, s_pEfrData); - _DelayMarkAll(_MQ_STD); - break; - - case IDC_FINDSTART: - _SetSearchFlags(hwnd, s_pEfrData); - _DelayMarkAll(_MQ_STD); - break; - - case IDC_TRANSPARENT: - Settings.FindReplaceTransparentMode = IsButtonChecked(hwnd, IDC_TRANSPARENT); - break; - - case IDC_REPLACE: - case IDC_REPLACEALL: - case IDC_REPLACEINSEL: - Globals.iReplacedOccurrences = 0; - case IDOK: - case IDC_FINDPREV: - case IDACC_SELTONEXT: - case IDACC_SELTOPREV: - case IDMSG_SWITCHTOFIND: - case IDMSG_SWITCHTOREPLACE: { - - if ((!s_bIsReplaceDlg && LOWORD(wParam) == IDMSG_SWITCHTOREPLACE) || - (s_bIsReplaceDlg && LOWORD(wParam) == IDMSG_SWITCHTOFIND)) { - GetDlgPos(hwnd, &s_xFindReplaceDlgSave, &s_yFindReplaceDlgSave); - s_bSwitchedFindReplace = true; - } - - if (!s_bSwitchedFindReplace && !_EnableFRDlgCtrls(hwnd)) { - return true; - } - - _SetSearchFlags(hwnd, s_pEfrData); - - if (s_bSwitchedFindReplace) { - // Reload MRUs - SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_RESETCONTENT, 0, 0); - SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_RESETCONTENT, 0, 0); - - for (int i = 0; i < MRU_Count(Globals.pMRUfind); i++) { - MRU_Enum(Globals.pMRUfind, i, s_wchBufOut, COUNTOF(s_wchBufOut)); - SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_ADDSTRING, 0, (LPARAM)s_wchBufOut); - } - for (int i = 0; i < MRU_Count(Globals.pMRUreplace); i++) { - MRU_Enum(Globals.pMRUreplace, i, s_wchBufOut, COUNTOF(s_wchBufOut)); - SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_ADDSTRING, 0, (LPARAM)s_wchBufOut); - } - ComboBox_SetTextHW(hwnd, IDC_FINDTEXT, s_pEfrData->chFindPattern); - ComboBox_SetTextHW(hwnd, IDC_REPLACETEXT, s_pEfrData->chReplaceTemplate); - } - else { - // Save MRUs - if (StrgIsNotEmpty(s_pEfrData->chFindPattern)) { - MRU_Add(Globals.pMRUfind, StrgGet(s_pEfrData->chFindPattern), 0, -1, -1, NULL); - SetFindPattern(StrgGet(s_pEfrData->chFindPattern)); - } - MRU_Add(Globals.pMRUreplace, StrgGet(s_pEfrData->chReplaceTemplate), 0, -1, -1, NULL); - // Immediately reflect used patterns in dropdown (without touching the edit field) - _AddPatternToComboMRU(hwnd, IDC_FINDTEXT, StrgGet(s_pEfrData->chFindPattern)); - if (s_bIsReplaceDlg) { - _AddPatternToComboMRU(hwnd, IDC_REPLACETEXT, StrgGet(s_pEfrData->chReplaceTemplate)); - } - } - - if (!s_bSwitchedFindReplace) { - SendMessage(hwnd, WM_NEXTDLGCTL, (WPARAM)(GetFocus()), 1); - } - - bool bFound = false; - - switch (LOWORD(wParam)) { - case IDOK: // find next - case IDACC_SELTONEXT: - if (s_bIsReplaceDlg) { - Globals.bReplaceInitialized = true; - } - bFound = EditFindNext(s_pEfrData->hwnd, s_pEfrData, (LOWORD(wParam) == IDACC_SELTONEXT), IsKeyDown(VK_F3), true); - SET_INITIAL_ANCHORS() - break; - - case IDC_FINDPREV: // find previous - case IDACC_SELTOPREV: - if (s_bIsReplaceDlg) { - Globals.bReplaceInitialized = true; - } - bFound = EditFindPrev(s_pEfrData->hwnd, s_pEfrData, (LOWORD(wParam) == IDACC_SELTOPREV), IsKeyDown(VK_F3), true); - SET_INITIAL_ANCHORS() - break; - - case IDC_REPLACE: { - Globals.bReplaceInitialized = true; - bFound = EditReplace(s_pEfrData->hwnd, s_pEfrData); - } - break; - - case IDC_REPLACEALL: - Globals.bReplaceInitialized = true; - bFound = EditReplaceAll(s_pEfrData->hwnd, s_pEfrData, true); - break; - - case IDC_REPLACEINSEL: - if (!SciCall_IsSelectionEmpty()) { - Globals.bReplaceInitialized = true; - bFound = EditReplaceAllInSelection(s_pEfrData->hwnd, s_pEfrData, true); - } - break; - } - - if (bFound && !s_bIsReplaceDlg && (s_pEfrData->bFindClose)) { - //~EndDialog(hwnd, LOWORD(wParam)); ~ (!) not running on own message loop - DestroyWindow(hwnd); - } - else if (bFound && s_bIsReplaceDlg && s_pEfrData->bReplaceClose) { - //~EndDialog(hwnd, LOWORD(wParam)); ~ (!) not running on own message loop - DestroyWindow(hwnd); - } - } - _DelayMarkAll(_MQ_STD); - break; - - - case IDCANCEL: - //~EndDialog(hwnd, IDCANCEL); ~ (!) not running on own message loop - DestroyWindow(hwnd); - break; - - case IDC_FINDESCCTRLCHR: - case IDC_REPLESCCTRLCHR: { - UINT const ctrl_id = (LOWORD(wParam) == IDC_FINDESCCTRLCHR) ? IDC_FINDTEXT : IDC_REPLACETEXT; - GetDlgItemTextW(hwnd, ctrl_id, s_wchBufIn, COUNTOF(s_wchBufIn)); - size_t const inLen = StringCchLen(s_wchBufIn, 0); - if (SlashCtrlW(s_wchBufOut, COUNTOF(s_wchBufOut), s_wchBufIn) == inLen) { - UnSlashCtrlW(s_wchBufOut); - } - SetDlgItemTextW(hwnd, ctrl_id, s_wchBufOut); - if ((ctrl_id == IDC_FINDTEXT) && (inLen != StringCchLen(s_wchBufOut, 0))) { - Globals.FindReplaceMatchFoundState = FND_NOP; - _SetSearchFlags(hwnd, s_pEfrData); - _DelayMarkAll(_MQ_ASAP); - } - } - break; - - case IDC_SWAPSTRG: { - GetDlgItemTextW(hwnd, IDC_FINDTEXT, s_wchBufOut, COUNTOF(s_wchBufOut)); - GetDlgItemTextW(hwnd, IDC_REPLACETEXT, s_wchBufIn, COUNTOF(s_wchBufIn)); - SetDlgItemTextW(hwnd, IDC_FINDTEXT, s_wchBufIn); - SetDlgItemTextW(hwnd, IDC_REPLACETEXT, s_wchBufOut); - if (StringCchCompareX(s_wchBufIn, s_wchBufOut) != 0) { - Globals.FindReplaceMatchFoundState = FND_NOP; - _SetSearchFlags(hwnd, s_pEfrData); - _DelayMarkAll(_MQ_ASAP); - } - } - break; - - case IDACC_FIND: - PostWMCommand(GetParent(hwnd), IDM_EDIT_FIND); - break; - - case IDACC_REPLACE: - PostWMCommand(GetParent(hwnd), IDM_EDIT_REPLACE); - break; - - case IDACC_SAVEPOS: - GetDlgPos(hwnd, &Settings.FindReplaceDlgPosX, &Settings.FindReplaceDlgPosY); - break; - - case IDACC_RESETPOS: - CenterDlgInParent(hwnd, false); - Settings.FindReplaceDlgPosX = Settings.FindReplaceDlgPosY = CW_USEDEFAULT; - break; - - case IDACC_CLEAR_FIND_HISTORY: - MRU_Empty(Globals.pMRUfind, false, Globals.bCanSaveIniFile); - if (s_pEfrData) { - StrgEmpty(s_pEfrData->chFindPattern, false); - } - SetFindPattern(NULL); - while ((int)SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_DELETESTRING, 0, 0) > 0) {}; - SetDlgItemText(hwnd, IDC_FINDTEXT, L""); - break; - - case IDACC_CLEAR_REPL_HISTORY: - MRU_Empty(Globals.pMRUreplace, false, Globals.bCanSaveIniFile); - if (s_pEfrData) { - StrgEmpty(s_pEfrData->chReplaceTemplate, false); - } - while ((int)SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_DELETESTRING, 0, 0) > 0) {}; - SetDlgItemText(hwnd, IDC_REPLACETEXT, L""); - break; - - case IDACC_SEARCHCLIPIFEMPTY: - Settings.SearchByClipboardIfEmpty = !Settings.SearchByClipboardIfEmpty; - CheckCmd(GetSystemMenu(hwnd, FALSE), IDS_MUI_SEARCHCLIPIFEMPTY, Settings.SearchByClipboardIfEmpty); - break; - - case IDACC_REPLCLIPTAG: - Settings.ReplaceByClipboardTag = !Settings.ReplaceByClipboardTag; - CheckCmd(GetSystemMenu(hwnd, FALSE), IDS_MUI_REPLCLIPTAG, Settings.ReplaceByClipboardTag); - break; - - case IDACC_FINDNEXT: - PostWMCommand(hwnd, IDOK); - break; - - case IDACC_FINDPREV: - PostWMCommand(hwnd, IDC_FINDPREV); - break; - - case IDACC_REPLACENEXT: - if (s_bIsReplaceDlg) { - PostWMCommand(hwnd, IDC_REPLACE); - } - break; - - case IDACC_SAVEFIND: - Globals.FindReplaceMatchFoundState = FND_NOP; - SendWMCommand(Globals.hwndMain, IDM_EDIT_SAVEFIND); - ComboBox_SetTextHW(hwnd, IDC_FINDTEXT, s_pEfrData->chFindPattern); - CheckDlgButton(hwnd, IDC_FINDREGEXP, BST_UNCHECKED); - CheckDlgButton(hwnd, IDC_DOT_MATCH_ALL, BST_UNCHECKED); - CheckDlgButton(hwnd, IDC_WILDCARDSEARCH, BST_UNCHECKED); - CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, BST_UNCHECKED); - PostMessage(hwnd, WM_NEXTDLGCTL, (WPARAM)(GetDlgItem(hwnd, IDC_FINDTEXT)), 1); - break; - - case IDACC_VIEWSCHEMECONFIG: - PostWMCommand(GetParent(hwnd), IDM_VIEW_SCHEMECONFIG); - break; - - default: - return FALSE; - } - - } // WM_COMMAND: - return TRUE; - - - case WM_SYSCOMMAND: - if (wParam == IDS_MUI_SAVEPOS) { - PostWMCommand(hwnd, IDACC_SAVEPOS); - return TRUE; - } else if (wParam == IDS_MUI_RESETPOS) { - PostWMCommand(hwnd, IDACC_RESETPOS); - return TRUE; - } else if (wParam == IDS_MUI_CLEAR_FIND_HISTORY) { - PostWMCommand(hwnd, IDACC_CLEAR_FIND_HISTORY); - return TRUE; - } else if (wParam == IDS_MUI_CLEAR_REPL_HISTORY) { - PostWMCommand(hwnd, IDACC_CLEAR_REPL_HISTORY); - return TRUE; - } else if (wParam == IDS_MUI_SEARCHCLIPIFEMPTY) { - PostWMCommand(hwnd, IDACC_SEARCHCLIPIFEMPTY); - return TRUE; - } else if (wParam == IDS_MUI_REPLCLIPTAG) { - PostWMCommand(hwnd, IDACC_REPLCLIPTAG); - return TRUE; - } - break; - - case WM_NOTIFY: { - LPNMHDR pnmhdr = (LPNMHDR)lParam; - switch (pnmhdr->code) { - case NM_CLICK: - case NM_RETURN: - switch (pnmhdr->idFrom) { - case IDC_TOGGLEFINDREPLACE: - if (s_bIsReplaceDlg) { - PostWMCommand(GetParent(hwnd), IDM_EDIT_FIND); - } else { - PostWMCommand(GetParent(hwnd), IDM_EDIT_REPLACE); - } - break; - case IDC_FINDESCCTRLCHR: - SendWMCommand(hwnd, IDC_FINDESCCTRLCHR); - break; - case IDC_REPLESCCTRLCHR: - SendWMCommand(hwnd, IDC_REPLESCCTRLCHR); - break; - case IDC_BACKSLASHHELP: - // Display help messages in the find/replace windows - DisplayHelpDlgLng(hwnd, IDS_MUI_BACKSLASHHELP); - break; - case IDC_REGEXPHELP: - DisplayHelpDlgLng(hwnd, IDS_MUI_REGEXPHELP); - break; - case IDC_WILDCARDHELP: - DisplayHelpDlgLng(hwnd, IDS_MUI_WILDCARDHELP); - break; - default: - break; - } - break; - - default: - return false; - } - } - break; - - default: - break; - - } // switch(umsg) - - return FALSE; // message handled -} - - -//============================================================================= -// -// EditFindReplaceDlg() -// -HWND EditFindReplaceDlg(HWND hwnd, LPEDITFINDREPLACE lpefr, bool bReplace, const FindReplaceDlgRestore* pRestore) -{ - lpefr->hwnd = hwnd; - FindReplaceDlgInit const init = { lpefr, pRestore }; - HWND hDlg = CreateThemedDialogParam(Globals.hLngResContainer, - (bReplace) ? MAKEINTRESOURCEW(IDD_MUI_REPLACE) : MAKEINTRESOURCEW(IDD_MUI_FIND), - GetParent(hwnd), - EditFindReplaceDlgProc, - (LPARAM)&init); - - if (IS_VALID_HANDLE(hDlg)) { - ShowWindow(hDlg, SW_SHOW); - if (pRestore) { - _EnableFRDlgCtrls(hDlg); - } - UpdateStatusbar(true); - } - return hDlg; -} - - -//============================================================================= -// -// EditFindNext() -// -bool EditFindNext(HWND hwnd, const LPEDITFINDREPLACE lpefr, bool bExtendSelection, bool bFocusWnd, bool bFillEmpty) -{ - bool bSuppressNotFound = false; - bool bFoundWrapAround = false; - - if (bFocusWnd) { - SetFocus(hwnd); - } - - LPCWSTR wchFind = _EditGetFindStrg(hwnd, lpefr, bFillEmpty); - - if (StrIsEmpty(wchFind)) { - return false; - } - int const sFlags = (int)(lpefr->fuFlags); - bool const bIsRegExpr = (sFlags & SCFIND_REGEXP); - - DocPos const iDocEndPos = Sci_GetDocEndPosition(); - - EditSetCaretToSelectionEnd(); // fluent switch between Prev/Next - DocPos const curPos = SciCall_GetCurrentPos(); - DocPos start = (curPos < iDocEndPos) ? curPos : 0; - - DocPos end = iDocEndPos; - - Sci_CallTipCancelEx(); - - DocPos iPos = _FindInTarget(wchFind, sFlags, &start, &end, true, FRMOD_NORM); - - if (bIsRegExpr && Sci_ConsumeRegexWarnStatus()) { - InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.MsgInvalidRegex, IDS_MUI_REGEX_INVALID); - bSuppressNotFound = true; - } else if ((iPos < 0LL) && (start >= 0LL) && !bExtendSelection) { - UpdateStatusbar(false); - if (!lpefr->bNoFindWrap && !bSuppressNotFound) { - Globals.iSelectionMarkNumber = 0; - DocPos const _start = start; - //DocPos const _end = end; - end = min_p(start, iDocEndPos); - start = 0LL; - iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_WRAPED); - - if ((iPos < 0LL) || (end == _start)) { - if (bIsRegExpr && Sci_ConsumeRegexWarnStatus()) { - InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.MsgInvalidRegex, IDS_MUI_REGEX_INVALID); - bSuppressNotFound = true; - } - } else { - LONG const result = InfoBoxLng(MB_OKCANCEL, Constants.SuppressKey.MsgFindWrap1, IDS_MUI_FIND_WRAPFW); - if (!IsYesOkay(result)) { - iPos = NOT_FOUND; - bSuppressNotFound = true; - } - bFoundWrapAround = (INFOBOX_MODE(result) != 0); - } - } - } - - if (iPos < 0LL) { - if (!bSuppressNotFound) { - InfoBoxLng(MB_OK, Constants.SuppressKey.MsgNotFound, IDS_MUI_NOTFOUND); - } - return false; - } - - if (bExtendSelection) { - DocPos const iSelPos = SciCall_GetCurrentPos(); - DocPos const iSelAnchor = SciCall_GetAnchor(); - EditSetSelectionEx(min_p(iSelAnchor, iSelPos), end, -1, -1); - } else { - EditSetSelectionEx(iPos, end, -1, -1); - } - - if (!Globals.iSelectionMarkNumber && lpefr->bMarkOccurences) { - _FindHasMatch(hwnd, lpefr, 0, true); - } - else { - ++Globals.iSelectionMarkNumber; - } - - if (iPos == end) { - _ShowZeroLengthCallTip(iPos); - } - if ((iPos+1) == end) { - char const p = SciCall_GetCharAt(iPos); - char const e = SciCall_GetCharAt(end); - if (p == 0x0d && e == 0x0a) { - _ShowZeroLengthCallTip(iPos); - } - } - if (bFoundWrapAround) { - ShowWrapAroundCallTip(true); - } - - return true; -} - - -//============================================================================= -// -// EditFindPrev() -// -bool EditFindPrev(HWND hwnd, LPEDITFINDREPLACE lpefr, bool bExtendSelection, bool bFocusWnd, bool bFillEmpty) -{ - bool bSuppressNotFound = false; - bool bFoundWrapAround = false; - - if (bFocusWnd) { - SetFocus(hwnd); - } - - LPCWSTR wchFind = _EditGetFindStrg(hwnd, lpefr, bFillEmpty); - - if (StrIsEmpty(wchFind)) { - return false; - } - int const sFlags = (int)(lpefr->fuFlags); - bool const bIsRegExpr = (sFlags & SCFIND_REGEXP); - - DocPos const iDocEndPos = Sci_GetDocEndPosition(); - - EditSetCaretToSelectionStart(); // fluent switch between Next/Prev - DocPos const curPos = SciCall_GetCurrentPos(); - DocPos start = (curPos > 0) ? (SciCall_IsSelectionEmpty() ? curPos : SciCall_PositionBefore(curPos)) : SciCall_PositionBefore(iDocEndPos); - DocPos end = 0LL; - - Sci_CallTipCancelEx(); - - DocPos iPos = _FindInTarget(wchFind, sFlags, &start, &end, true, FRMOD_NORM); - - if (bIsRegExpr && Sci_ConsumeRegexWarnStatus()) { - InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.MsgInvalidRegex, IDS_MUI_REGEX_INVALID); - bSuppressNotFound = true; - } else if ((iPos < 0LL) && (start <= iDocEndPos) && !bExtendSelection) { - UpdateStatusbar(false); - if (!lpefr->bNoFindWrap && !bSuppressNotFound) { - Globals.iSelectionMarkNumber = Globals.iMarkOccurrencesCount + 1; - DocPos const _start = start; - //DocPos const _end = end; - end = max_p(start, 0LL); - start = iDocEndPos; - iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_WRAPED); - - if ((iPos < 0LL) || (start == _start)) { - if (bIsRegExpr && Sci_ConsumeRegexWarnStatus()) { - InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.MsgInvalidRegex, IDS_MUI_REGEX_INVALID); - bSuppressNotFound = true; - } - } else { - LONG const result = InfoBoxLng(MB_OKCANCEL, Constants.SuppressKey.MsgFindWrap2, IDS_MUI_FIND_WRAPRE); - if (!IsYesOkay(result)) { - iPos = NOT_FOUND; - bSuppressNotFound = true; - } - bFoundWrapAround = (INFOBOX_MODE(result) != 0); - } - } - } - - if (iPos < 0LL) { - if (!bSuppressNotFound) { - InfoBoxLng(MB_OK, Constants.SuppressKey.MsgNotFound, IDS_MUI_NOTFOUND); - } - return false; - } - - if (bExtendSelection) { - DocPos const iSelPos = SciCall_GetCurrentPos(); - DocPos const iSelAnchor = SciCall_GetAnchor(); - EditSetSelectionEx(max_p(iSelPos, iSelAnchor), iPos, -1, -1); - } else { - EditSetSelectionEx(end, iPos, -1, -1); - } - - if (!Globals.iSelectionMarkNumber && lpefr->bMarkOccurences) { - _FindHasMatch(hwnd, lpefr, 0, true); - } - else { - --Globals.iSelectionMarkNumber; - } - - if (iPos == end) { - _ShowZeroLengthCallTip(iPos); - } - if ((iPos + 1) == end) { - char const p = SciCall_GetCharAt(iPos); - char const e = SciCall_GetCharAt(end); - if (p == 0x0d && e == 0x0a) { - _ShowZeroLengthCallTip(iPos); - } - } - if (bFoundWrapAround) { - ShowWrapAroundCallTip(false); - } - - return true; -} - - -//============================================================================= -// -// EditMarkAllOccurrences() -// -void EditMarkAllOccurrences(HWND hwnd, bool bForceClear) -{ - if (bForceClear) { - EditClearAllOccurrenceMarkers(hwnd); - } - - if (!IsMarkOccurrencesEnabled()) { - return; - } - - int const searchFlags = GetMarkAllOccSearchFlags(); - - if (Settings.MarkOccurrencesMatchVisible) { - - // get visible lines for update - DocLn const iStartLine = SciCall_DocLineFromVisible(SciCall_GetFirstVisibleLine()); - DocLn const iEndLine = min_ln((iStartLine + SciCall_LinesOnScreen()), Sci_GetLastDocLineNumber()); - DocPos const iPosStart = SciCall_PositionFromLine(iStartLine); - DocPos const iPosEnd = SciCall_GetLineEndPosition(iEndLine); - - // !!! don't clear all marks, else this method is re-called - // !!! on UpdateUI notification on drawing indicator mark - EditMarkAll(NULL, searchFlags, iPosStart, iPosEnd, false); - } else { - EditMarkAll(NULL, searchFlags, 0, Sci_GetDocEndPosition(), false); - } -} - - -//============================================================================= -// -// EditSelectionMultiSelectAll() -// -void EditSelectionMultiSelectAll() -{ - if (SciCall_GetSelText(NULL) > 0) { - SciCall_TargetWholeDocument(); - SciCall_SetSearchFlags(GetMarkAllOccSearchFlags()); - SciCall_MultipleSelectAddEach(); - SciCall_SetMainSelection(0); - if (SciCall_GetSelectionNAnchor(0) > SciCall_GetSelectionNCaret(0)) { - SciCall_SwapMainAnchorCaret(); - } - Sci_ScrollSelectionToView(); - } -} - - -//============================================================================= -// -// EditSelectionMultiSelectAllEx() -// -void EditSelectionMultiSelectAllEx(HWND hwnd, CLPCEDITFINDREPLACE edFndRpl) -{ - EDITFINDREPLACE efr = INIT_EFR_DATA; - DuplicateEFR(&efr, edFndRpl); - - if (IsWindow(Globals.hwndDlgFindReplace)) { - _SetSearchFlags(Globals.hwndDlgFindReplace, &efr); - } else { - efr.fuFlags = GetMarkAllOccSearchFlags(); - } - - LPCWSTR wchFind = _EditGetFindStrg(hwnd, &efr, false); - - if (StrIsNotEmpty(wchFind)) { - UndoTransActionBegin(); - EditMarkAll(wchFind, efr.fuFlags, 0, Sci_GetDocEndPosition(), true); - EndUndoTransAction(); - } - ReleaseEFR(&efr); -} - - -//============================================================================= -// -// EditReplace() -// -bool EditReplace(HWND hwnd, LPEDITFINDREPLACE lpefr) -{ - int iReplaceMsg = SciCall_GetChangeHistory() ? SCI_REPLACETARGETMINIMAL : SCI_REPLACETARGET; - DocPos const selBeg = SciCall_GetSelectionStart(); - DocPos const selEnd = SciCall_GetSelectionEnd(); - - // redo find to get group ranges filled - DocPos start = (SciCall_IsSelectionEmpty() ? SciCall_GetCurrentPos() : selBeg); - DocPos end = Sci_GetDocEndPosition(); - DocPos _start = start; - Globals.iReplacedOccurrences = 0; - - LPCWSTR wchFind = _EditGetFindStrg(hwnd, lpefr, false); - - if (StrIsEmpty(wchFind)) { - return false; - } - - char* const pszReplace = _GetReplaceString(hwnd, lpefr, &iReplaceMsg); - if (!pszReplace) { - return false; // recoding of clipboard canceled - } - - int const sFlags = (int)(lpefr->fuFlags); - DocPos const iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_NORM); - - // w/o selection, replacement string is put into current position - // but this maybe not intended here - if (SciCall_IsSelectionEmpty()) { - if ((iPos < 0LL) || (_start != start) || (_start != end)) { - // empty-replace was not intended - FreeMem(pszReplace); - if (iPos < 0LL) { - return EditFindNext(hwnd, lpefr, false, false, false); - } - EditSetSelectionEx(start, end, -1, -1); - return true; - } - } - // if selection is is not equal current find, set selection - else if ((selBeg != start) || (selEnd != end)) { - FreeMem(pszReplace); - SciCall_SetCurrentPos(selBeg); - return EditFindNext(hwnd, lpefr, false, false, false); - } - - UndoTransActionBegin(); - - SciCall_TargetFromSelection(); - DocPos const posTargetStart = SciCall_GetTargetStart(); - Sci_ReplaceTargetEx(iReplaceMsg, -1, pszReplace); - // move caret behind replacement - if (SCI_REPLACETARGETMINIMAL == iReplaceMsg) { - SciCall_SetCurrentPos(posTargetStart + strlen(pszReplace)); - } - else { - SciCall_SetCurrentPos(SciCall_GetTargetEnd()); - } - - Globals.iReplacedOccurrences = 1; - - EndUndoTransAction(); - - FreeMem(pszReplace); - - return EditFindNext(hwnd, lpefr, false, false, false); -} - - - -//============================================================================= -// -// EditReplaceAllInRange() -// -// -DocPosU EditReplaceAllInRange(HWND hwnd, LPEDITFINDREPLACE lpefr, DocPos iStartPos, DocPos iEndPos, DocPos *enlargement) -{ - if (iStartPos > iEndPos) { - swapos(&iStartPos, &iEndPos); - } - DocPos const iOrigEndPos = iEndPos; // remember - - LPCWSTR wchFind = _EditGetFindStrg(hwnd, lpefr, false); - - if (StrIsEmpty(wchFind)) { - return 0; - } - - int const sFlags = (int)(lpefr->fuFlags); - bool const bIsRegExpr = (sFlags & SCFIND_REGEXP); - bool const bRegexStartOfLine = bIsRegExpr && (wchFind[0] == L'^'); - - // SCI_REPLACETARGET or SCI_REPLACETARGETRE - int iReplaceMsg = SCI_REPLACETARGET; - char* const pszReplace = _GetReplaceString(hwnd, lpefr, &iReplaceMsg); - if (!pszReplace) { - return 0; // recoding of clipboard canceled - } - - DocPos const _saveTargetBeg_ = SciCall_GetTargetStart(); - DocPos const _saveTargetEnd_ = SciCall_GetTargetEnd(); - - DocPos start = iStartPos; - DocPos end = iEndPos; - DocPos iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_NORM); - - if (bIsRegExpr && Sci_ConsumeRegexWarnStatus()) { - InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.MsgInvalidRegex, IDS_MUI_REGEX_INVALID); - return 0; - } - - DocPosU iCount = 0; - LimitNotifyEvents(); - UndoTransActionBegin(); - - while ((iPos >= 0LL) && (start <= iEndPos)) { - DocLn const lnCnt = bRegexStartOfLine ? SciCall_GetLineCount() : 0; - SciCall_SetTargetRange(iPos, end); - DocPos const replLen = Sci_ReplaceTargetEx(iReplaceMsg, -1, pszReplace); - ++iCount; - // start next search behind replacement - if (SCI_REPLACETARGETMINIMAL == iReplaceMsg) { - DocPos const replLength = strlen(pszReplace); - iStartPos = iPos + replLength; - iEndPos += replLength - (end - iPos); - } - else { - iStartPos = SciCall_GetTargetEnd(); - if (bRegexStartOfLine && (SciCall_GetLineCount() == lnCnt) && (Sci_GetLineStartPosition(iStartPos) == iStartPos)) { - iStartPos = SciCall_PositionAfter(iStartPos); - } - iEndPos += replLen - (end - iPos); - } - start = iStartPos; - end = iEndPos; - iPos = (start <= end) ? _FindInTarget(wchFind, sFlags, &start, &end, true, FRMOD_NORM) : NOT_FOUND; - } - - EndUndoTransAction(); - - FreeMem(pszReplace); - - *enlargement = (iEndPos - iOrigEndPos); - SciCall_SetTargetRange(_saveTargetBeg_, _saveTargetEnd_ + *enlargement); //restore - - RestoreNotifyEvents(); - - return iCount; -} - - -//============================================================================= -// -// EditReplaceAll() -// -bool EditReplaceAll(HWND hwnd, LPEDITFINDREPLACE lpefr, bool bShowInfo) -{ - DocPos const start = 0; - DocPos const end = Sci_GetDocEndPosition(); - DocPos enlargement = 0; - - BeginWaitCursorUID(true, IDS_MUI_SB_REPLACE_ALL); - Globals.iReplacedOccurrences = EditReplaceAllInRange(hwnd, lpefr, start, end, &enlargement); - EndWaitCursor(); - - WCHAR wchOcc[64] = { L'\0' }; - StringCchPrintf(wchOcc, COUNTOF(wchOcc), DOCPOSFMTW, Globals.iReplacedOccurrences); - FormatNumberStr(wchOcc, COUNTOF(wchOcc), 0); - - if (bShowInfo) { - if (Globals.iReplacedOccurrences) { - InfoBoxLng(MB_OK, Constants.SuppressKey.MsgReplaceCount, IDS_MUI_REPLCOUNT, wchOcc); - } else { - InfoBoxLng(MB_OK, Constants.SuppressKey.MsgNotFound, IDS_MUI_NOTFOUND); - } - } - - return (bool)Globals.iReplacedOccurrences; -} - - -//============================================================================= -// -// EditReplaceAllInSelection() -// -bool EditReplaceAllInSelection(HWND hwnd, LPEDITFINDREPLACE lpefr, bool bShowInfo) -{ - if (Sci_IsMultiOrRectangleSelection()) { - InfoBoxLng(MB_ICONWARNING, NULL, IDS_MUI_SELRECTORMULTI); - return false; - } - - const DocPos start = SciCall_GetSelectionStart(); - const DocPos end = SciCall_GetSelectionEnd(); - const DocPos currPos = SciCall_GetCurrentPos(); - const DocPos anchorPos = SciCall_GetAnchor(); - DocPos enlargement = 0; - - BeginWaitCursorUID(true, IDS_MUI_SB_REPLACE_ALL); - Globals.iReplacedOccurrences = EditReplaceAllInRange(hwnd, lpefr, start, end, &enlargement); - EndWaitCursor(); - - if (Globals.iReplacedOccurrences) { - if (currPos < anchorPos) { - SciCall_SetSel(anchorPos + enlargement, currPos); - } else { - SciCall_SetSel(anchorPos, currPos + enlargement); - } - if (bShowInfo) { - WCHAR wchOcc[64] = { L'\0' }; - StringCchPrintf(wchOcc, COUNTOF(wchOcc), DOCPOSFMTW, Globals.iReplacedOccurrences); - FormatNumberStr(wchOcc, COUNTOF(wchOcc), 0); - InfoBoxLng(MB_OK, Constants.SuppressKey.MsgReplaceCount, IDS_MUI_REPLCOUNT, wchOcc); - } - } - else if (bShowInfo) { - InfoBoxLng(MB_OK, Constants.SuppressKey.MsgNotFound, IDS_MUI_NOTFOUND); - } - - return (bool)Globals.iReplacedOccurrences; -} - - - -//============================================================================= -// -// EditClearAllOccurrenceMarkers() -// -void EditClearAllOccurrenceMarkers(HWND hwnd) -{ - UNREFERENCED_PARAMETER(hwnd); - - LimitNotifyEvents(); - - SciCall_SetIndicatorCurrent(INDIC_NP3_MARK_OCCURANCE); - SciCall_IndicatorClearRange(0, Sci_GetDocEndPosition()); - - SciCall_MarkerDeleteAll(MARKER_NP3_OCCURRENCE); - - Globals.iSelectionMarkNumber = Globals.iMarkOccurrencesCount = 0; - - RestoreNotifyEvents(); -} - - -//============================================================================= -// -// EditClearAllBookMarks() -// -void EditClearAllBookMarks(HWND hwnd) -{ - UNREFERENCED_PARAMETER(hwnd); - int const bitmask = OCCURRENCE_MARKER_BITMASK(); - DocLn const line = SciCall_MarkerNext(0, bitmask); - if (line >= 0) { - // 1st press: clear all occurrences marker - for (int m = MARKER_NP3_1; m < MARKER_NP3_BOOKMARK; ++m) { - SciCall_MarkerDeleteAll(m); - } - } else { - // if no occurrences marker found - SciCall_MarkerDeleteAll(MARKER_NP3_BOOKMARK); - } -} - - -//============================================================================= -// -// EditToggleView() -// -void EditToggleView(HWND hwnd) -{ - if (Settings.FocusViewMarkerMode & FVMM_FOLD) { - - BeginWaitCursorUID(true, IDS_MUI_SB_TOGGLE_VIEW); - - FocusedView.HideNonMatchedLines = !FocusedView.HideNonMatchedLines; // toggle - - if (FocusedView.HideNonMatchedLines) { - EditFoldMarkedLineRange(hwnd, true); - if (Settings.FocusViewMarkerMode & (FVMM_MARGIN | FVMM_LN_BACKGR)) { - EditBookMarkLineRange(hwnd); - } - } else { - EditFoldMarkedLineRange(hwnd, false); - } - - UpdateDocumentReadOnlyState(); - SciCall_ScrollCaret(); - - EndWaitCursor(); - - } else if (Settings.FocusViewMarkerMode & (FVMM_MARGIN | FVMM_LN_BACKGR)) { - EditBookMarkLineRange(hwnd); - } -} - - -//============================================================================= -// -// EditSelectWordAtPos() -// -void EditSelectWordAtPos(const DocPos iPos, const bool bForceWord) -{ - DocPos iWordStart = SciCall_WordStartPosition(iPos, true); - DocPos iWordEnd = SciCall_WordEndPosition(iPos, true); + DocPos iWordStart = SciCall_WordStartPosition(iPos, true); + DocPos iWordEnd = SciCall_WordEndPosition(iPos, true); if ((iWordStart == iWordEnd) && bForceWord) { // we are in whitespace salad... iWordStart = SciCall_WordEndPosition(iPos, false); @@ -8477,153 +6224,6 @@ void EditSelectWordAtPos(const DocPos iPos, const bool bForceWord) } -//============================================================================= -// -// EditAddSearchFlags() -// -int EditAddSearchFlags(int flags, bool bRegEx, bool bWordStart, bool bMatchCase, bool bMatchWords, bool bDotMatchAll) -{ - flags |= (bRegEx ? SCFIND_REGEXP : 0); - flags |= (bWordStart ? SCFIND_WORDSTART : 0); - flags |= (bMatchWords ? SCFIND_WHOLEWORD : 0); - flags |= (bMatchCase ? SCFIND_MATCHCASE : 0); - flags |= (bDotMatchAll ? SCFIND_DOT_MATCH_ALL : 0); - return flags; -} - - -//============================================================================= -// -// EditMarkAll() -// Mark all occurrences of the matching text in range (by Aleksandar Lekov) -// -void EditMarkAll(LPCWSTR wchFind, int sFlags, DocPos rangeStart, DocPos rangeEnd, bool bMultiSel) -{ - char chText[FNDRPL_BUFFER] = { L'\0' }; - WCHAR wchText[FNDRPL_BUFFER] = { L'\0' }; - - DocPos iFindLength = 0; - - LimitNotifyEvents(); - - if (StrIsEmpty(wchFind)) { - - WideCharToMultiByte(Encoding_SciCP, 0, wchFind, -1, chText, COUNTOF(chText), NULL, NULL); - - if (SciCall_IsSelectionEmpty()) { - // nothing selected, get word under caret if flagged - if (Settings.MarkOccurrencesCurrentWord && (sFlags & SCFIND_WHOLEWORD)) { - DocPos const iCurPos = SciCall_GetCurrentPos(); - DocPos iWordStart = SciCall_WordStartPosition(iCurPos, true); - DocPos iWordEnd = SciCall_WordEndPosition(iCurPos, true); - if (iWordStart == iWordEnd) { - goto observe; - } - iFindLength = (iWordEnd - iWordStart); - - StringCchCopyNA(chText, COUNTOF(chText), SciCall_GetRangePointer(iWordStart, iFindLength), iFindLength); - - } else { - goto observe; // no pattern, no selection and no word mark chosen - } - } else { // we have a selection - - if (Sci_IsMultiSelection()) { - goto observe; - } - - // get current selection - DocPos const iSelStart = SciCall_GetSelectionStart(); - DocPos const iSelEnd = SciCall_GetSelectionEnd(); - //DocPos const iSelCount = (iSelEnd - iSelStart); - - // if multiple lines are selected exit - if (SciCall_LineFromPosition(iSelStart) != SciCall_LineFromPosition(iSelEnd)) { - goto observe; - } - - DocPosU const iSelLen = SciCall_GetSelText(NULL); - if (iSelLen >= COUNTOF(chText)) { - goto observe; - } - - iFindLength = SciCall_GetSelText(chText); - chText[iFindLength] = '\0'; - - // exit if selection is not a word and Match whole words only is enabled - if (sFlags & SCFIND_WHOLEWORD) { - DocPosU iSelStart2 = 0; - const char* delims = (Settings.AccelWordNavigation ? DelimCharsAccel : DelimChars); - while ((iSelStart2 <= iSelLen) && chText[iSelStart2]) { - if (StrChrIA(delims, chText[iSelStart2])) { - goto observe; - } - ++iSelStart2; - } - } - } - - MultiByteToWideChar(Encoding_SciCP, 0, chText, (int)iFindLength, wchText, (int)COUNTOF(wchText)); - - } else { - StringCchCopy(wchText, COUNTOF(wchText), wchFind); - } - - if (StrIsNotEmpty(wchText)) { - - if (bMultiSel) { - SciCall_ClearSelections(); - } - DocPos const iSelStart = SciCall_GetSelectionStart(); - DocPos const iSelEnd = SciCall_GetSelectionEnd(); - - DocPos const iTextEnd = Sci_GetDocEndPosition(); - rangeStart = max_p(0, rangeStart); - rangeEnd = min_p(rangeEnd, iTextEnd); - - DocPos start = rangeStart; - DocPos end = rangeEnd; - DocPos iPos = _FindInTarget(wchText, sFlags, &start, &end, false, FRMOD_NORM); - - if (!bMultiSel) { - SciCall_SetIndicatorCurrent(INDIC_NP3_MARK_OCCURANCE); // once: doc-change notifications are disabled (LimitNotifyEvents) - } - - DocPosU count = 0; - DocPosU found = 0; - while ((iPos >= 0LL) && (start <= rangeEnd)) { - - if (bMultiSel) { - if (count) { - SciCall_AddSelection(end, iPos); - } else { - SciCall_SetSelection(end, iPos); - } - } else { - // mark this match if not done before - SciCall_IndicatorFillRange(iPos, (end - start)); - SciCall_MarkerAdd(SciCall_LineFromPosition(iPos), MARKER_NP3_OCCURRENCE); - } - ++count; - if (!found && ((iSelStart <= end) && (start <= iSelEnd))) { - // intersect = (max_p(iSelStart, start) < min_p(iSelEnd, end)) - found = count; - } - start = end; - end = rangeEnd; - iPos = _FindInTarget(wchText, sFlags, &start, &end, true, FRMOD_NORM); - }; - Globals.iSelectionMarkNumber = found; - Globals.iMarkOccurrencesCount = count; - assert(!bMultiSel || (SciCall_GetSelections() == count)); - } - -observe: - - RestoreNotifyEvents(); -} - - //============================================================================= // // EditCheckNewLineInACFillUps() @@ -8930,7 +6530,7 @@ static void _UpdateIndicators(const int indicator, const int indicator2nd, do { DocPos const start_m = start; DocPos const end_m = end; - DocPos const iPos = _FindInTarget(regExpr, SCFIND_REGEXP, &start, &end, true, FRMOD_IGNORE); + DocPos const iPos = EditFindInTarget(regExpr, SCFIND_REGEXP, &start, &end, true); if (iPos < 0) { if (bClearGaps) { diff --git a/src/Edit.h b/src/Edit.h index 38f6112da2..d0bb60bd5b 100644 --- a/src/Edit.h +++ b/src/Edit.h @@ -21,11 +21,9 @@ #include "SciCall.h" #include "TypeDefs.h" -void DuplicateEFR(LPEDITFINDREPLACE dst, CLPCEDITFINDREPLACE src); -void ReleaseEFR(LPEDITFINDREPLACE efr); - void EditReplaceSelection(const char* text, bool bForceSel); void EditInitWordDelimiter(HWND hwnd); +bool EditContainsWordDelimiter(LPCSTR text, size_t length); void EditSetNewText(HWND hwnd, const char* lpstrText, DocPosU lenText, bool bClearUndoHistory, bool bReload); bool EditConvertText(HWND hwnd, cpi_enc_t encSource, cpi_enc_t encDest); bool EditSetNewEncoding(HWND hwnd, cpi_enc_t iNewEncoding,bool bSupressWarning); @@ -100,18 +98,6 @@ void EditFixPositions(); void EditEnsureConsistentLineEndings(HWND hwnd); void EditGetExcerpt(HWND hwnd,LPWSTR lpszExcerpt,DWORD cchExcerpt); -typedef struct { - RECT windowRect; - bool bFocusedView; -} FindReplaceDlgRestore; - -HWND EditFindReplaceDlg(HWND hwnd, LPEDITFINDREPLACE lpefr, bool bReplace, const FindReplaceDlgRestore* pRestore); -bool EditFindNext(HWND hwnd, const LPEDITFINDREPLACE lpefr, bool bExtendSelection, bool bFocusWnd, bool bFillEmpty); -bool EditFindPrev(HWND hwnd, const LPEDITFINDREPLACE lpefr, bool bExtendSelection, bool bFocusWnd, bool bFillEmpty); -bool EditReplace(HWND hwnd, LPEDITFINDREPLACE lpefr); -DocPosU EditReplaceAllInRange(HWND hwnd, LPEDITFINDREPLACE lpefr, DocPos iStartPos, DocPos iEndPos, DocPos *enlargement); -bool EditReplaceAll(HWND hwnd, LPEDITFINDREPLACE lpefr, bool); -bool EditReplaceAllInSelection(HWND hwnd, LPEDITFINDREPLACE lpefr, bool); bool EditLinenumDlg(HWND hwnd); bool EditModifyLinesDlg(HWND hwnd, PENCLOSESELDATA pEnclData); bool EditEncloseSelectionDlg(HWND hwnd, PENCLOSESELDATA pEnclData); @@ -123,12 +109,9 @@ void EditPrintSetup(HWND hwnd); void EditPrintInit(); bool EditSetDocumentBuffer(const char* lpstrText, DocPosU lenText, bool reload); void EditMatchBrace(HWND hwnd); -void EditClearAllOccurrenceMarkers(HWND hwnd); void EditClearAllBookMarks(HWND hwnd); void EditToggleView(HWND hwnd); void EditSelectWordAtPos(const DocPos iPos, const bool bForceWord); -int EditAddSearchFlags(int flags, bool bRegEx, bool bWordStart, bool bMatchCase, bool bMatchWords, bool bDotMatchAll); -void EditMarkAll(LPCWSTR wchFind, int sFlags, DocPos rangeStart, DocPos rangeEnd, bool bMultiSel); void EditUpdateVisibleIndicators(); void EditUpdateIndicators(DocPos startPos, DocPos endPos, bool bClearOnly); void EditReducedWordSeparatorSet(HWND hwnd, bool); @@ -141,12 +124,9 @@ void EditBookmarkPrevious(HWND hwnd, const DocLn iLine); void EditBookmarkToggle(HWND hwnd, const DocLn ln, const int modifiers); void EditBookmarkResetNavigation(void); void EditBookmarkAdjustNavigation(const DocLn modLine, const DocLn linesAdded); -void EditMarkAllOccurrences(HWND hwnd, bool bForceClear); void EditFoldMarkedLineRange(HWND hwnd, bool bHideLines); void EditBookMarkLineRange(HWND hwnd); void EditDeleteMarkerInSelection(); -void EditSelectionMultiSelectAll(); -void EditSelectionMultiSelectAllEx(HWND hwnd, CLPCEDITFINDREPLACE edFndRpl); // // Folding Functions @@ -172,12 +152,6 @@ void EditFoldCmdKey(FOLD_MOVE move, FOLD_ACTION action); #define NP3_BRACES_TO_MATCH "()[]{}" -inline int GetMarkAllOccSearchFlags() -{ - return EditAddSearchFlags(0, false, false, Settings.MarkOccurrencesMatchCase, - Settings.MarkOccurrencesCurrentWord || Settings.MarkOccurrencesMatchWholeWords, false); -} - #endif //_NP3_EDIT_H_ /// End of Edit.h /// diff --git a/src/FindReplace.c b/src/FindReplace.c new file mode 100644 index 0000000000..f349356373 --- /dev/null +++ b/src/FindReplace.c @@ -0,0 +1,2656 @@ +// encoding: UTF-8 +/****************************************************************************** +* * +* * +* Notepad3 * +* * +* FindReplace.c * +* Find/Replace and occurrence matching * +* Based on code from Notepad2, (c) Florian Balmer 1996-2011 * +* * +* (c) Rizonesoft 2008-2026 * +* https://rizonesoft.com * +* * +* * +*******************************************************************************/ + + +#include "Helpers.h" + +#include +#include +#include + +#include "Dialogs.h" +#include "Edit.h" +#include "Encoding.h" +#include "FindReplace.h" +#include "MuiLanguage.h" +#include "Notepad3.h" +#include "Styles.h" +#include "Config/Config.h" +#include "DarkMode/DarkMode.h" +#include "uthash/utlist.h" + +//============================================================================= + +static bool s_bSwitchedFindReplace = false; + +static int s_xFindReplaceDlgSave; +static int s_yFindReplaceDlgSave; + +static HSTRINGW s_hstrCurrentFindPattern = NULL; +static EDITFINDREPLACE s_FindReplaceData = INIT_EFR_DATA; + +static void DuplicateEFR(LPEDITFINDREPLACE dst, CLPCEDITFINDREPLACE src); +static void EditMarkAll(LPCWSTR wchFind, int sFlags, DocPos rangeStart, DocPos rangeEnd, bool bMultiSel); +static void _TransformReplaceBackslashes(LPSTR pszInput, bool bRegEx, int* iReplaceMsg); +void FindReplaceInit(void) +{ + s_hstrCurrentFindPattern = StrgCreate(NULL); +} + +void FindReplaceRelease(void) +{ + StrgDestroy(s_hstrCurrentFindPattern); + ReleaseEFR(&s_FindReplaceData); +} + +bool IsFindPatternEmpty(void) +{ + return StrgIsEmpty(s_hstrCurrentFindPattern); +} + +//============================================================================= +// +// GetFindPattern() +// +LPCWSTR GetFindPattern(void) +{ + return StrgGet(s_hstrCurrentFindPattern); +} + +//============================================================================= +// +// SetFindPattern() +// +void SetFindPattern(LPCWSTR wchFindPattern) +{ + StrgReset(s_hstrCurrentFindPattern, StrIsNotEmpty(wchFindPattern) ? wchFindPattern : L""); +} + +//============================================================================= +// +// SetFindPatternMB() +// +static void SetFindPatternMB(LPCSTR chFindPattern) +{ + StrgResetFromUTF8(s_hstrCurrentFindPattern, !StrIsEmptyA(chFindPattern) ? chFindPattern : ""); +} + +//============================================================================= +// +// LengthOfFindPattern() +// +size_t LengthOfFindPattern(void) +{ + return StrgGetLength(s_hstrCurrentFindPattern); +} + +//============================================================================= +// +// FindReplacePrepare() +// +LPEDITFINDREPLACE FindReplacePrepare(void) +{ + // init find pattern with current + if (!IsFindPatternEmpty()) { + StrgReset(Settings.EFR_Data.chFindPattern, GetFindPattern()); + } + // copy settings to working data + DuplicateEFR(&s_FindReplaceData, &(Settings.EFR_Data)); + + if (g_flagMatchText) { // cmd line + if (g_flagMatchText & 4) { + s_FindReplaceData.fuFlags = (SCFIND_REGEXP | SCFIND_POSIX); + } else { + // /m without R flag: force text mode (clear regex flags) - fixes #5060 + s_FindReplaceData.fuFlags &= ~(SCFIND_REGEXP | SCFIND_POSIX); + } + if (g_flagMatchText & 8) { + s_FindReplaceData.fuFlags |= SCFIND_MATCHCASE; + } + if (g_flagMatchText & 16) { + s_FindReplaceData.fuFlags |= SCFIND_DOT_MATCH_ALL; + } + if (g_flagMatchText & 32) { + s_FindReplaceData.bTransformBS = true; + } + s_FindReplaceData.bRegExprSearch = (s_FindReplaceData.fuFlags & SCFIND_REGEXP); + s_FindReplaceData.bWildcardSearch = false; + s_FindReplaceData.bReplaceClose = false; + } + return &s_FindReplaceData; +} + + +//============================================================================= +// +// FindReplaceUseSelection() +// +LPEDITFINDREPLACE FindReplaceUseSelection(void) +{ + if (SciCall_IsSelectionEmpty()) { + EditSelectWordAtPos(SciCall_GetCurrentPos(), true); + } + + size_t const cchSelection = SciCall_GetSelText(NULL); + + if (0 < cchSelection) { + char* const szSelection = AllocMem((cchSelection + 1), HEAP_ZERO_MEMORY); + if (szSelection) { + SciCall_GetSelText(szSelection); + + SetFindPatternMB(szSelection); + LPEDITFINDREPLACE const lpefr = FindReplacePrepare(); + StrgReset(lpefr->chFindPattern, GetFindPattern()); + + FreeMem(szSelection); + return lpefr; + } + } + return NULL; +} + + +static void DuplicateEFR(LPEDITFINDREPLACE dst, CLPCEDITFINDREPLACE src) +{ + dst->fuFlags = src->fuFlags; + dst->bTransformBS = src->bTransformBS; + dst->bFindClose = src->bFindClose; + dst->bReplaceClose = src->bReplaceClose; + dst->bNoFindWrap = src->bNoFindWrap; + dst->bRegExprSearch = src->bRegExprSearch; + dst->bWildcardSearch = src->bWildcardSearch; + dst->bMarkOccurences = src->bMarkOccurences; + dst->bInstantIncrementalSearch = src->bInstantIncrementalSearch; + dst->bHideNonMatchedLines = src->bHideNonMatchedLines; + dst->bStateChanged = src->bStateChanged; + dst->hwnd = src->hwnd; + if (!(dst->chFindPattern)) { + dst->chFindPattern = StrgCreate(StrgGet(src->chFindPattern)); + } + else { + StrgReset(dst->chFindPattern, StrgGet(src->chFindPattern)); + } + if (!(dst->chReplaceTemplate)) { + dst->chReplaceTemplate = StrgCreate(StrgGet(src->chReplaceTemplate)); + } + else { + StrgReset(dst->chReplaceTemplate, StrgGet(src->chReplaceTemplate)); + } +} + + +void ReleaseEFR(LPEDITFINDREPLACE efr) +{ + StrgDestroy(efr->chFindPattern); + efr->chFindPattern = NULL; + StrgDestroy(efr->chReplaceTemplate); + efr->chReplaceTemplate = NULL; +} + + +//============================================================================= +// +// Delay Message Queue Handling (TODO: MultiThreading) +// + +static CmdMessageQueue_t* MessageQueue = NULL; + +// ---------------------------------------------------------------------------- + +static int msgcmp(void* mqc1, void* mqc2) +{ + const CmdMessageQueue_t* const pMQC1 = (CmdMessageQueue_t*)mqc1; + const CmdMessageQueue_t* const pMQC2 = (CmdMessageQueue_t*)mqc2; + + if ((pMQC1->cmd == pMQC2->cmd) + && (pMQC1->hwnd == pMQC2->hwnd) + && (pMQC1->wparam == pMQC2->wparam) + && (pMQC1->lparam == pMQC2->lparam) + ) { + return 0; + } + return 1; +} + +static LONG64 sortcmp(void *mqc1, void *mqc2) { + const CmdMessageQueue_t *const pMQC1 = (CmdMessageQueue_t *)mqc1; + const CmdMessageQueue_t *const pMQC2 = (CmdMessageQueue_t *)mqc2; + return (pMQC1->delay - pMQC2->delay); +} +// ---------------------------------------------------------------------------- + + + +#define _MQ_TIMER_CYCLE (USER_TIMER_MINIMUM << 1) +#define _MQ_STD (_MQ_TIMER_CYCLE << 2) +#define _MQ_ms2cycl(T) (((T) + USER_TIMER_MINIMUM) / _MQ_TIMER_CYCLE) +#define _MQ_ASAP 0 + +static void _MQ_AppendCmd(CmdMessageQueue_t* const pMsgQCmd, int cycles) +{ + if (!pMsgQCmd) { return; } + + cycles = clampi(cycles, 0, _MQ_ms2cycl(60000)); + + CmdMessageQueue_t* pmqc = NULL; + DL_SEARCH(MessageQueue, pmqc, pMsgQCmd, msgcmp); + + if (!pmqc) { // NOT found, create new one + pmqc = AllocMem(sizeof(CmdMessageQueue_t), HEAP_ZERO_MEMORY); + if (pmqc) { + *pmqc = *pMsgQCmd; + pmqc->delay = cycles; + DL_APPEND(MessageQueue, pmqc); + } + } else { + if ((pmqc->delay > 0) && (cycles > 0)) { + pmqc->delay = (pmqc->delay + cycles) >> 1; // median delay + } else { + pmqc->delay = cycles; + } + } + if (0 == cycles) { + PostMessage(pMsgQCmd->hwnd, pMsgQCmd->cmd, pMsgQCmd->wparam, pMsgQCmd->lparam); + } + //~DL_SORT(MessageQueue, sortcmp); // next scheduled first +} +// ---------------------------------------------------------------------------- + +/* not used yet +static void _MQ_DropAll() { + CmdMessageQueue_t *pmqc = NULL; + DL_FOREACH(MessageQueue, pmqc) { + pmqc->delay = -1; + } +} +*/ +// ---------------------------------------------------------------------------- + + +// ---------------------------------------------------------------------------- +// +// called by MarkAll Timer +// +// TIMERPROC +static void CALLBACK MQ_ExecuteNext(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) +{ + UNREFERENCED_PARAMETER(hwnd); // must be main wnd + UNREFERENCED_PARAMETER(uMsg); // must be WM_TIMER + UNREFERENCED_PARAMETER(idEvent); // must be pTimerIdentifier + UNREFERENCED_PARAMETER(dwTime); // This is the value returned by the GetTickCoun(t)) function + + CmdMessageQueue_t *pmqc; + DL_FOREACH(MessageQueue, pmqc) { + if (pmqc->delay >= 0) { + --(pmqc->delay); + } + if (pmqc->delay == 0) { + if (IsWindow(pmqc->hwnd)) { + PostMessage(pmqc->hwnd, pmqc->cmd, pmqc->wparam, pmqc->lparam); + } + } + } +} + + + +//============================================================================= +// +// _SyncBoolOpt() / _SyncFlagOpt() - take a dialog check-box state over into the F/R data +// +static void _SyncBoolOpt(HWND hwnd, int idButton, bool* const pbOpt, bool* const pbChanged) +{ + bool const bChecked = IsButtonChecked(hwnd, idButton); + if (bChecked != *pbOpt) { + *pbOpt = bChecked; + *pbChanged = true; + } +} + +static void _SyncFlagOpt(HWND hwnd, int idButton, UINT* const puFlags, const UINT flag, bool* const pbChanged) +{ + bool const bChecked = IsButtonChecked(hwnd, idButton); + if (bChecked != ((*puFlags & flag) != 0)) { + *puFlags = bChecked ? (*puFlags | flag) : (*puFlags & ~flag); + *pbChanged = true; + } +} + + +//============================================================================= +// +// _SetSearchFlags() +// +static void _SetSearchFlags(HWND hwnd, LPEDITFINDREPLACE lpefr) +{ + if (hwnd && lpefr) { + + bool bIsFindDlg = (GetDlgItem(Globals.hwndDlgFindReplace, IDC_REPLACE) == NULL); + + HSTRINGW hstr = StrgCreate(NULL); + + ComboBox_GetTextHW(hwnd, IDC_FINDTEXT, hstr); + if (StringCchCompareX(StrgGet(hstr), StrgGet(lpefr->chFindPattern)) != 0) { + StrgReset(lpefr->chFindPattern, StrgGet(hstr)); + lpefr->bStateChanged = true; + } + + StrgReset(hstr, L""); + + ComboBox_GetTextHW(hwnd, IDC_REPLACETEXT, hstr); + if (StringCchCompareX(StrgGet(hstr), StrgGet(lpefr->chReplaceTemplate)) != 0) { + StrgReset(lpefr->chReplaceTemplate, StrgGet(hstr)); + lpefr->bStateChanged = true; + } + + StrgDestroy(hstr); + + _SyncFlagOpt(hwnd, IDC_FINDCASE, &lpefr->fuFlags, SCFIND_MATCHCASE, &lpefr->bStateChanged); + _SyncFlagOpt(hwnd, IDC_FINDWORD, &lpefr->fuFlags, SCFIND_WHOLEWORD, &lpefr->bStateChanged); + + if (IsDialogControlEnabled(hwnd, IDC_FINDTRANSFORMBS)) { + _SyncBoolOpt(hwnd, IDC_FINDTRANSFORMBS, &lpefr->bTransformBS, &lpefr->bStateChanged); + } + + _SyncFlagOpt(hwnd, IDC_FINDSTART, &lpefr->fuFlags, SCFIND_WORDSTART, &lpefr->bStateChanged); + + // regular expression option and its search flag change together + bool const bRegExChecked = IsButtonChecked(hwnd, IDC_FINDREGEXP); + if (bRegExChecked != lpefr->bRegExprSearch) { + lpefr->bRegExprSearch = bRegExChecked; + lpefr->fuFlags = bRegExChecked ? (lpefr->fuFlags | SCFIND_REGEXP) : (lpefr->fuFlags & ~(UINT)SCFIND_REGEXP); + lpefr->bStateChanged = true; + } + + if (IsDialogControlEnabled(hwnd, IDC_DOT_MATCH_ALL)) { + _SyncFlagOpt(hwnd, IDC_DOT_MATCH_ALL, &lpefr->fuFlags, SCFIND_DOT_MATCH_ALL, &lpefr->bStateChanged); + } + + // force consistency + if (lpefr->bRegExprSearch) { + CheckDlgButton(hwnd, IDC_WILDCARDSEARCH, BST_UNCHECKED); + } + bool const bWildcardChecked = IsButtonChecked(hwnd, IDC_WILDCARDSEARCH); + if (bWildcardChecked != lpefr->bWildcardSearch) { + lpefr->bWildcardSearch = bWildcardChecked; + lpefr->bStateChanged = true; + } + if (bWildcardChecked) { + if (!(lpefr->fuFlags & SCFIND_REGEXP)) { + lpefr->fuFlags |= SCFIND_REGEXP; // wild-card search based on RegExpr + lpefr->bStateChanged = true; + } + } else if ((lpefr->fuFlags & SCFIND_REGEXP) && !lpefr->bRegExprSearch) { + lpefr->fuFlags &= ~(UINT)SCFIND_REGEXP; + lpefr->bStateChanged = true; + } + + _SyncBoolOpt(hwnd, IDC_NOWRAP, &lpefr->bNoFindWrap, &lpefr->bStateChanged); + _SyncBoolOpt(hwnd, IDC_ALL_OCCURRENCES, &lpefr->bMarkOccurences, &lpefr->bStateChanged); + _SyncBoolOpt(hwnd, IDC_INST_INCR_SEARCH, &lpefr->bInstantIncrementalSearch, &lpefr->bStateChanged); + + // close dialog after find resp. replace + _SyncBoolOpt(hwnd, IDC_FINDCLOSE, bIsFindDlg ? &lpefr->bFindClose : &lpefr->bReplaceClose, &lpefr->bStateChanged); + } +} + + +// Wildcard search uses the regexp engine to perform a simple search with * ? as wildcards +// instead of more advanced and user-unfriendly RegExpr syntax +// for speed, we only need POSIX syntax here +static void _EscapeWildcards(wchar_t* wchFind, size_t cch, LPEDITFINDREPLACE lpefr) +{ + wchar_t* const wchWildcardEscaped = AllocMem(((cch<<1) + 1) * sizeof(wchar_t), HEAP_ZERO_MEMORY); + if (wchWildcardEscaped) { + + size_t iSource = 0; + size_t iDest = 0; + + lpefr->fuFlags |= SCFIND_REGEXP; + + bool bEsc = false; + while ((iSource < cch) && (wchFind[iSource] != L'\0')) { + wchar_t c = wchFind[iSource]; + if (c == L'*' && !bEsc) { + wchWildcardEscaped[iDest++] = L'.'; + } else if (c == L'?' && !bEsc) { + c = L'.'; + } else if (c == L'\\' && !bEsc) { + bEsc = true; + } + else if ( + (c == L'^' || + c == L'$' || + c == L'(' || + c == L')' || + c == L'[' || + c == L']' || + c == L'{' || + c == L'}' || + //~c == L'.' || + c == L'+' || + c == L'|' + ) ) { + if (!bEsc) { + wchWildcardEscaped[iDest++] = L'\\'; + } else { + bEsc = false; + } + } else if (bEsc) { + //~wchWildcardEscaped[iDest++] = L'\\'; ~ don't esc' backslash here + bEsc = false; + } + wchWildcardEscaped[iDest++] = c; + ++iSource; + } + + StringCchCopyN(wchFind, cch, wchWildcardEscaped, (cch << 1) + 1); + FreeMem(wchWildcardEscaped); + } +} + + +//============================================================================= +// +// _EditGetFindStrg() +// +static LPCWSTR _EditGetFindStrg(HWND hwnd, const LPEDITFINDREPLACE lpefr, bool bFillEmpty) +{ + UNREFERENCED_PARAMETER(hwnd); + + if (!lpefr) { + return NULL; + } + + static HSTRINGW hfind = NULL; + // TODO: StrgDestroy(hfind); + + if (!hfind) { + hfind = StrgCreate(NULL); + } + + // 1st: try last used pattern + if (StrgIsEmpty(lpefr->chFindPattern) && bFillEmpty) { + StrgReset(hfind, GetFindPattern()); + } else { + StrgReset(hfind, StrgGet(lpefr->chFindPattern)); + } + + // 2nd: try get clipboard content + if (StrgIsEmpty(hfind) && bFillEmpty && Settings.SearchByClipboardIfEmpty) { + LPWSTR const buf = StrgWriteAccessBuf(hfind, FNDRPL_BUFFER); + EditGetClipboardW(buf, StrgGetAllocLength(hfind)); + StrgSanitize(hfind); + } + + // 3nd: try get most recently used find pattern + if (StrgIsEmpty(hfind) && bFillEmpty) { + LPWSTR const buf = StrgWriteAccessBuf(hfind, FNDRPL_BUFFER); + MRU_Enum(Globals.pMRUfind, 0, buf, (int)StrgGetAllocLength(hfind)); + StrgSanitize(hfind); + } + + // 4th: return if still empty + if (StrgIsEmpty(hfind)) { + //~StrgDestroy(hfind); - static for speed + return NULL; + } + + // ensure to F/R-dialog data structure consistency + StrgReset(lpefr->chFindPattern, StrgGet(hfind)); + SetFindPattern(StrgGet(hfind)); + + if (lpefr->bWildcardSearch) { + // _EscapeWildcards can expand each char to two (e.g. '|' -> '\|', '*' -> '.*'), + // so ensure the buffer holds at least 2× the current content length. + size_t const expandCap = (StrgGetLength(hfind) * 2) + 2; + LPWSTR const buf = StrgWriteAccessBuf(hfind, max(expandCap, (size_t)FNDRPL_BUFFER)); + _EscapeWildcards(buf, StrgGetAllocLength(hfind), lpefr); + StrgSanitize(hfind); + } + + bool const bIsRegEx = (lpefr->fuFlags & SCFIND_REGEXP); + if (lpefr->bTransformBS || bIsRegEx) { + LPWSTR const buf = StrgWriteAccessBuf(hfind, FNDRPL_BUFFER); + if (!bIsRegEx) { UnSlashW(buf, CP_UTF8); } + StrgSanitize(hfind); + } + + return StrgGet(hfind); +} + + +//============================================================================= +// +// _GetReplaceString() +// +static char* _GetReplaceString(HWND hwnd, CLPCEDITFINDREPLACE lpefr, int* iReplaceMsg) +{ + char* pszReplace = NULL; // replace text of arbitrary size + if (Settings.ReplaceByClipboardTag && (StrCmpW(StrgGet(lpefr->chReplaceTemplate), L"^c")) == 0) + { + *iReplaceMsg = SciCall_GetChangeHistory() ? SCI_REPLACETARGETMINIMAL : SCI_REPLACETARGET; + pszReplace = EditGetClipboardText(hwnd, true, NULL, NULL); + } + else { + int const cch = max_i(StrgLengthAsUTF8(lpefr->chReplaceTemplate), 255) + 1; + pszReplace = (char*)AllocMem(cch, HEAP_ZERO_MEMORY); + if (pszReplace) { + StrgGetAsUTF8(lpefr->chReplaceTemplate, pszReplace, cch); + bool const bIsRegEx = (lpefr->fuFlags & SCFIND_REGEXP); + if (lpefr->bTransformBS || bIsRegEx) { + _TransformReplaceBackslashes(pszReplace, bIsRegEx, iReplaceMsg); + } + } + } + return pszReplace; // transfer ownership +} + + +//============================================================================= +// +// _FindInTarget() +// +// ONIG_MISMATCH +#define NOT_FOUND ((DocPos)(-1LL)) + +typedef enum { FRMOD_IGNORE = 0, FRMOD_NORM, FRMOD_WRAPED } FR_UPD_MODES; + +static DocPos _FindInTarget(LPCWSTR wchFind, int sFlags, + DocPos* begin, DocPos* end, bool bForceNext, FR_UPD_MODES fMode) +{ + static char chFind[8192] = { '\0' }; // max find buffer + + // mark-all and replace-all call this once per match with the same pattern: convert it only when it changed + static WCHAR s_wchLastFind[COUNTOF(chFind)] = { L'\0' }; + static UINT s_cpLastFind = 0; // code page of the pattern in chFind, 0 if chFind is not backed by s_wchLastFind + + DocPos iPos = NOT_FOUND; + + if (StrIsEmpty(wchFind)) { + return iPos; + } + + // remember original target range + DocPos const saveTargetBeg = SciCall_GetTargetStart(); + DocPos const saveTargetEnd = SciCall_GetTargetEnd(); + + DocPos const start = *begin; + DocPos const stop = *end; + bool const bFindNext = (start <= stop); // else find previous + + DocPos len = 0; + if ((s_cpLastFind == (UINT)Encoding_SciCP) && (wcscmp(wchFind, s_wchLastFind) == 0)) { // exact (ordinal) comparison + len = (DocPos)strlen(chFind); + } else { + len = (DocPos)(WideCharToMultiByte(Encoding_SciCP, 0, wchFind, -1, chFind, COUNTOF(chFind), NULL, NULL) - 1); + bool const bRemember = (len >= 0) && SUCCEEDED(StringCchCopyW(s_wchLastFind, COUNTOF(s_wchLastFind), wchFind)); + s_cpLastFind = bRemember ? (UINT)Encoding_SciCP : 0; + } + + // Clear any lingering regex-warning status so the post-call state reflects + // this search only. Without this, a stale SC_STATUS_WARN_REGEX from an + // earlier _FindInTarget call could leak into the next caller's Sci_ConsumeRegexWarnStatus. + SciCall_SetStatus(SC_STATUS_OK); + + SciCall_SetSearchFlags(sFlags); + SciCall_SetTargetRange(start, stop); + iPos = SciCall_SearchInTarget(len, chFind); + + // Bail out before the retry loop if the regex engine flagged an invalid + // pattern — every subsequent SearchInTarget would just re-set the warning. + // Status stays raised for the caller to consume via Sci_ConsumeRegexWarnStatus. + if ((sFlags & SCFIND_REGEXP) && SciCall_GetStatus() == SC_STATUS_WARN_REGEX) { + SciCall_SetTargetRange(saveTargetBeg, saveTargetEnd); + return NOT_FOUND; + } + +#if 1 + // handle next in case of zero-length-matches or invalid position (regex) ! + bool const bZeroLenMatch = ((iPos == start) && (start == SciCall_GetTargetEnd())); + bool bValidPos = !(bForceNext && bZeroLenMatch) && Sci_IsPosValid(iPos); + while (!bValidPos) { + DocPos const newStart = (bFindNext ? SciCall_PositionAfter(iPos) : SciCall_PositionBefore(iPos)); + bool const bProceed = (bFindNext ? (newStart < stop) : (newStart > stop)) && (newStart != iPos); + if (bProceed) { + SciCall_SetTargetRange(newStart, stop); + iPos = SciCall_SearchInTarget(len, chFind); // not found if beyond stop + } + else { + iPos = NOT_FOUND; // already at document begin, end or stuck => not found + } + bValidPos = Sci_IsPosValid(iPos); // NOT_FOUND is a valid pos + } +#else + // handle next in case of zero-length-matches (regex) ! + if (iPos == start) { + DocPos const nstop = SciCall_GetTargetEnd(); + if ((start == nstop) && bForceNext) { + DocPos const new_start = (bFindNext ? SciCall_PositionAfter(start) : SciCall_PositionBefore(start)); + bool const bProceed = (bFindNext ? (new_start < stop) : (new_start > stop)); + if ((new_start != start) && bProceed) { + SciCall_SetTargetRange(new_start, stop); + iPos = SciCall_SearchInTarget(len - 1, chFind); + } else { + iPos = (DocPos)-1LL; // already at document begin or end => not found + } + } + } +#endif + + if (iPos >= 0) { + if (fMode != FRMOD_IGNORE) { + Globals.FindReplaceMatchFoundState = bFindNext ? + ((fMode == FRMOD_WRAPED) ? NXT_WRP_FND : NXT_FND) : + ((fMode == FRMOD_WRAPED) ? PRV_WRP_FND : PRV_FND); + } + // found in range, set begin and end of finding + *begin = SciCall_GetTargetStart(); + *end = SciCall_GetTargetEnd(); + } else { + if (fMode != FRMOD_IGNORE) { + Globals.FindReplaceMatchFoundState = (fMode != FRMOD_WRAPED) ? (bFindNext ? NXT_NOT_FND : PRV_NOT_FND) : FND_NOP; + } + } + + SciCall_SetTargetRange(saveTargetBeg, saveTargetEnd); // restore original target range + + return iPos; +} + +DocPos EditFindInTarget(LPCWSTR wchFind, int sFlags, DocPos* begin, DocPos* end, bool bForceNext) +{ + return _FindInTarget(wchFind, sFlags, begin, end, bForceNext, FRMOD_IGNORE); +} + + +//============================================================================= +// +// _FindHasMatch() +// +typedef enum { MATCH = 0, NO_MATCH = 1, INVALID = 2 } RegExResult_t; + +static RegExResult_t _FindHasMatch(HWND hwnd, const LPEDITFINDREPLACE lpefr, DocPos iStartPos, bool bMarkAll) +{ + if (StrgIsEmpty(lpefr->chFindPattern)) { + return NO_MATCH; + } + int const sFlags = (int)(lpefr->fuFlags); + DocPos const iStart = iStartPos; + DocPos const iTextEnd = Sci_GetDocEndPosition(); + + DocPos start = iStart; + DocPos end = iTextEnd; + + LPCWSTR wchFind = _EditGetFindStrg(hwnd, lpefr, false); + DocPos const iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_IGNORE); + bool const bRegexInvalid = (sFlags & SCFIND_REGEXP) && Sci_ConsumeRegexWarnStatus(); + + if (bMarkAll) { + EditClearAllOccurrenceMarkers(hwnd); + if (iPos >= 0) { + EditMarkAll(wchFind, (int)(lpefr->fuFlags), 0, iTextEnd, false); + if (FocusedView.HideNonMatchedLines) { + EditFoldMarkedLineRange(lpefr->hwnd, true); + } + } else { + if (FocusedView.HideNonMatchedLines) { + EditFoldMarkedLineRange(lpefr->hwnd, false); + } + } + } + return ((iPos >= 0) ? MATCH : (bRegexInvalid ? INVALID : NO_MATCH)); +} + + +//============================================================================= +// +// _DelayMarkAll() +// +// +static void _DelayMarkAll(int delay) +{ + CmdMessageQueue_t mqc = MQ_WM_CMD_INIT(Globals.hwndDlgFindReplace, IDT_TIMER_CALLBACK_MRKALL, 0LL); + _MQ_AppendCmd(&mqc, _MQ_ms2cycl(delay)); +} + +//============================================================================= + +static bool s_SaveMarkOccurrences = false; +static bool s_SaveMarkMatchVisible = false; + +//============================================================================= +// +// EditBoxForPasteFixes() +// Single-line EDIT's default WM_PASTE truncates at the first line break; +// EM_REPLACESEL inserts multi-line clipboard text unchanged. +// +static LRESULT CALLBACK EditBoxForPasteFixes(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, + UINT_PTR uIdSubclass, DWORD_PTR dwRefData) +{ + UNREFERENCED_PARAMETER(dwRefData); + + switch (uMsg) { + case WM_PASTE: { + // copy first: EM_REPLACESEL synchronously triggers the incremental search, + // which must not run while the clipboard is held open + WCHAR wchBuffer[FNDRPL_BUFFER] = { L'\0' }; + EditGetClipboardW(wchBuffer, COUNTOF(wchBuffer)); + if (StrIsNotEmpty(wchBuffer)) { + SendMessage(hwnd, EM_REPLACESEL, (WPARAM)TRUE, (LPARAM)wchBuffer); + return 0; + } + } break; + + case WM_NCDESTROY: + RemoveWindowSubclass(hwnd, EditBoxForPasteFixes, uIdSubclass); + break; + + default: + break; + } + return DefSubclassProc(hwnd, uMsg, wParam, lParam); +} + + +//============================================================================= +// +// _ShowZeroLengthCallTip() +// +static void _ShowZeroLengthCallTip(DocPos iPosition) +{ + char chZeroLenCT[80] = { '\0' }; + GetLngStringW2MB(IDS_MUI_ZERO_LEN_MATCH, chZeroLenCT, COUNTOF(chZeroLenCT)); + SciCall_CallTipShow(iPosition, chZeroLenCT); +} + + +//============================================================================= +// +// _EnableFRDlgCtrls() +// +static bool _EnableFRDlgCtrls(HWND hwnd) { + + bool const bEmptyFnd = ComboBox_GetTextLengthEx(hwnd, IDC_FINDTEXT) == 0 /*|| ComboBox_GetCurSelEx(hwnd, IDC_FINDTEXT) != CB_ERR)*/; + bool const bEmptyRpl = ComboBox_GetTextLengthEx(hwnd, IDC_REPLACETEXT) == 0 /*|| ComboBox_GetCurSelEx(hwnd, IDC_REPLACETEXT) != CB_ERR)*/; + bool const bEmptySel = (SciCall_IsSelectionEmpty() || Sci_IsMultiOrRectangleSelection()); + + DialogEnableControl(hwnd, IDOK, !bEmptyFnd); + DialogEnableControl(hwnd, IDC_FINDPREV, !bEmptyFnd); + DialogEnableControl(hwnd, IDC_REPLACE, !bEmptyFnd); + DialogEnableControl(hwnd, IDC_REPLACEALL, !bEmptyFnd); + DialogEnableControl(hwnd, IDC_REPLACEINSEL, !bEmptyFnd && !bEmptySel); + DialogEnableControl(hwnd, IDC_SWAPSTRG, !bEmptyFnd || !bEmptyRpl); + + return !bEmptyFnd; +} + + +//============================================================================= +// +// _AddPatternToComboMRU() +// Insert pszItem at the top of a CBS_DROPDOWN combo's list without touching +// its edit field (no CBN_EDITCHANGE side-effects). +// +static void _AddPatternToComboMRU(HWND hwnd, int nIDDlgItem, LPCWSTR pszItem) +{ + if (StrIsEmpty(pszItem)) { return; } + HWND const hwndCtl = GetDlgItem(hwnd, nIDDlgItem); + int const idx = (int)SendMessage(hwndCtl, CB_FINDSTRINGEXACT, (WPARAM)(-1), (LPARAM)pszItem); + if (idx != CB_ERR) { + SendMessage(hwndCtl, CB_DELETESTRING, (WPARAM)idx, 0); + } + SendMessage(hwndCtl, CB_INSERTSTRING, 0, (LPARAM)pszItem); +} + + +//============================================================================= +// +// EditFindReplaceDlgProc() +// +typedef struct { + LPEDITFINDREPLACE pEfrData; + const FindReplaceDlgRestore* pRestore; +} FindReplaceDlgInit; + +static void _RestoreFindReplaceDlgPosition(HWND hwnd, const RECT* pPreviousRect) +{ + MONITORINFO mi = { sizeof(mi) }; + if (IsRectEmpty(pPreviousRect) || + !GetMonitorInfo(MonitorFromRect(pPreviousRect, MONITOR_DEFAULTTONEAREST), &mi)) { + return; + } + + // The first move can resize the dialog via WM_DPICHANGED. Fit it again using the new size. + for (int i = 0; i < 2; ++i) { + RECT rc; + if (!GetWindowRect(hwnd, &rc)) { + return; + } + LONG const x = max_l(mi.rcWork.left, min_l(pPreviousRect->left, mi.rcWork.right - (rc.right - rc.left))); + LONG const y = max_l(mi.rcWork.top, min_l(pPreviousRect->top, mi.rcWork.bottom - (rc.bottom - rc.top))); + if (rc.left == x && rc.top == y) { + break; + } + SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); + } +} + + +// TODO: §§§ get rid of this buffer +static WCHAR s_wchBufIn[FNDRPL_BUFFER] = { L'\0' }; // tmp working buffer +static WCHAR s_wchBufOut[FNDRPL_BUFFER] = { L'\0' }; // tmp working buffer + + +static INT_PTR CALLBACK EditFindReplaceDlgProc(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) +{ + static LPEDITFINDREPLACE s_pEfrData = NULL; + + static bool s_bIsReplaceDlg = false; + static bool s_bRestoreFocusedView = false; + + static UINT_PTR pTimerIdentifier = 0; + + static DocPos s_InitialSearchStart = 0; + static DocPos s_InitialAnchorPos = 0; + static DocPos s_InitialCaretPos = 0; + static DocLn s_InitialTopLine = -1; + +#define SET_INITIAL_ANCHORS() {\ + s_InitialTopLine = -1;\ + s_InitialCaretPos = SciCall_GetCurrentPos();\ + s_InitialAnchorPos = SciCall_GetAnchor();\ + s_InitialSearchStart = SciCall_GetSelectionStart(); \ + } + + static RegExResult_t s_anyMatch = NO_MATCH; + + static HBRUSH hBrushRed; + static HBRUSH hBrushGreen; + static HBRUSH hBrushBlue; + + switch (umsg) { + case WM_INITDIALOG: { + + const FindReplaceDlgInit* const pInit = (const FindReplaceDlgInit*)lParam; + s_pEfrData = pInit->pEfrData; + s_bRestoreFocusedView = pInit->pRestore && pInit->pRestore->bFocusedView; + + Globals.hwndDlgFindReplace = hwnd; + s_bIsReplaceDlg = (GetDlgItem(hwnd, IDC_REPLACETEXT) != NULL); + + // clear cmd line stuff + g_flagMatchText = 0; + + SetDialogIconNP3(hwnd); + InitWindowCommon(hwnd, true); + +#ifdef D_NP3_WIN10_DARK_MODE + if (UseDarkMode()) { + int const ctlx[] = { IDOK, IDCANCEL, IDC_FINDPREV, IDC_REPLACE, IDC_REPLACEALL, + IDC_REPLACEINSEL, IDC_SWAPSTRG, IDC_TOGGLE_VISIBILITY + }; + for (int i = 0; i < COUNTOF(ctlx); ++i) { + SetExplorerTheme(GetDlgItem(hwnd, ctlx[i])); + } + int const ctl[] = { IDC_FINDCASE, IDC_FINDWORD, IDC_FINDSTART, IDC_FINDTRANSFORMBS, IDC_FINDESCCTRLCHR, IDC_REPLESCCTRLCHR, + IDC_FINDREGEXP, IDC_DOT_MATCH_ALL, IDC_NOWRAP, IDC_FINDCLOSE, + IDC_ALL_OCCURRENCES, IDC_INST_INCR_SEARCH, IDC_WILDCARDSEARCH, IDC_TRANSPARENT, IDC_STATIC, IDC_STATIC2 + }; + for (int i = 0; i < COUNTOF(ctl); ++i) { + SetWindowTheme(GetDlgItem(hwnd, ctl[i]), L"", L""); // remove theme for BS_AUTORADIOBUTTON + } + //SetExplorerTheme(GetDlgItem(hwnd, IDC_RESIZEGRIP)); + } +#endif + + pTimerIdentifier = SetTimer(hwnd, 0, _MQ_TIMER_CYCLE, MQ_ExecuteNext); + + SET_INITIAL_ANCHORS() + s_InitialTopLine = SciCall_GetFirstVisibleLine(); + + EditSetCaretToSelectionStart(); // avoid search text selection jumps to next match (before ResizeDlg_InitX()) + + Globals.iReplacedOccurrences = 0; + Globals.FindReplaceMatchFoundState = FND_NOP; + + s_SaveMarkOccurrences = s_bSwitchedFindReplace ? s_SaveMarkOccurrences : Settings.MarkOccurrences; + s_SaveMarkMatchVisible = s_bSwitchedFindReplace ? s_SaveMarkMatchVisible : Settings.MarkOccurrencesMatchVisible; + // switch off normal mark occurrences + Settings.MarkOccurrences = false; + Settings.MarkOccurrencesMatchVisible = false; + EnableCmd(GetMenu(Globals.hwndMain), IDM_VIEW_MARKOCCUR_ONOFF, false); + + SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_LIMITTEXT, FNDRPL_BUFFER, 0); + SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_SETEXTENDEDUI, true, 0); + + // Load MRUs + for (int i = 0; i < MRU_Count(Globals.pMRUfind); i++) { + MRU_Enum(Globals.pMRUfind, i, s_wchBufOut, COUNTOF(s_wchBufOut)); + SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_ADDSTRING, 0, (LPARAM)s_wchBufOut); + } + + COMBOBOXINFO cbInfoF = { sizeof(COMBOBOXINFO) }; + GetComboBoxInfo(GetDlgItem(hwnd, IDC_FINDTEXT), &cbInfoF); + if (cbInfoF.hwndItem) { + SetWindowSubclass(cbInfoF.hwndItem, EditBoxForPasteFixes, 0, 0); + SHAutoComplete(cbInfoF.hwndItem, SHACF_FILESYS_ONLY | SHACF_AUTOAPPEND_FORCE_OFF | SHACF_AUTOSUGGEST_FORCE_OFF); + } + + if (s_bIsReplaceDlg) { + + SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_LIMITTEXT, FNDRPL_BUFFER, 0); + SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_SETEXTENDEDUI, true, 0); + + // Load MRUs + for (int i = 0; i < MRU_Count(Globals.pMRUreplace); i++) { + MRU_Enum(Globals.pMRUreplace, i, s_wchBufOut, COUNTOF(s_wchBufOut)); + SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_ADDSTRING, 0, (LPARAM)s_wchBufOut); + } + + COMBOBOXINFO cbInfoR = { sizeof(COMBOBOXINFO) }; + GetComboBoxInfo(GetDlgItem(hwnd, IDC_REPLACETEXT), &cbInfoR); + if (cbInfoR.hwndItem) { + SetWindowSubclass(cbInfoR.hwndItem, EditBoxForPasteFixes, 0, 0); + SHAutoComplete(cbInfoR.hwndItem, SHACF_FILESYS_ONLY | SHACF_AUTOAPPEND_FORCE_OFF | SHACF_AUTOSUGGEST_FORCE_OFF); + } + } + + // Initialize all checkboxes BEFORE setting combobox text. + // Setting combobox text triggers CBN_EDITCHANGE synchronously, + // which calls _SetSearchFlags() that reads checkbox states. + // Checkboxes must reflect s_pEfrData values at that point. + CheckDlgButton(hwnd, IDC_FINDREGEXP, SetBtn(s_pEfrData->bRegExprSearch)); + + bool const bDotMatchAll = (s_pEfrData->fuFlags & SCFIND_DOT_MATCH_ALL) != 0; + CheckDlgButton(hwnd, IDC_DOT_MATCH_ALL, SetBtn(s_pEfrData->bRegExprSearch && bDotMatchAll)); + DialogEnableControl(hwnd, IDC_DOT_MATCH_ALL, s_pEfrData->bRegExprSearch); + + if (s_pEfrData->bRegExprSearch) { + s_pEfrData->bWildcardSearch = false; + } + if (s_pEfrData->bWildcardSearch) { + CheckDlgButton(hwnd, IDC_WILDCARDSEARCH, BST_CHECKED); + CheckDlgButton(hwnd, IDC_FINDREGEXP, BST_UNCHECKED); + } + + // transform BS handled by regex (wild-card search based on): + CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, SetBtn(s_pEfrData->bTransformBS || s_pEfrData->bRegExprSearch || s_pEfrData->bWildcardSearch)); + DialogEnableControl(hwnd, IDC_FINDTRANSFORMBS, !(s_pEfrData->bRegExprSearch || s_pEfrData->bWildcardSearch)); + + CheckDlgButton(hwnd, IDC_ALL_OCCURRENCES, SetBtn(s_pEfrData->bMarkOccurences)); + if (!s_pEfrData->bMarkOccurences) { + EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); + } + + CheckDlgButton(hwnd, IDC_INST_INCR_SEARCH, SetBtn(s_pEfrData->bInstantIncrementalSearch)); + + CheckDlgButton(hwnd, IDC_FINDCASE, SetBtn(s_pEfrData->fuFlags & SCFIND_MATCHCASE)); + CheckDlgButton(hwnd, IDC_FINDWORD, SetBtn(s_pEfrData->fuFlags & SCFIND_WHOLEWORD)); + CheckDlgButton(hwnd, IDC_FINDSTART, SetBtn(s_pEfrData->fuFlags & SCFIND_WORDSTART)); + CheckDlgButton(hwnd, IDC_NOWRAP, SetBtn(s_pEfrData->bNoFindWrap)); + + if (s_bIsReplaceDlg) { + CheckDlgButton(hwnd, IDC_FINDCLOSE, SetBtn(s_pEfrData->bReplaceClose)); + } else { + CheckDlgButton(hwnd, IDC_FINDCLOSE, SetBtn(s_pEfrData->bFindClose)); + } + + CheckDlgButton(hwnd, IDC_TRANSPARENT, SetBtn(Settings.FindReplaceTransparentMode)); + + // Now set combobox text — CBN_EDITCHANGE will fire and call + // _SetSearchFlags(), which can now read the correct checkbox states. + if (pInit->pRestore) { + // Restore both fields before edit notifications can sync the partially initialized dialog. + s_pEfrData = NULL; + ComboBox_SetTextHW(hwnd, IDC_FINDTEXT, pInit->pEfrData->chFindPattern); + if (s_bIsReplaceDlg) { + ComboBox_SetTextHW(hwnd, IDC_REPLACETEXT, pInit->pEfrData->chReplaceTemplate); + } + s_pEfrData = pInit->pEfrData; + } else if (!GetWindowTextLengthW(GetDlgItem(hwnd, IDC_FINDTEXT))) { + if (StrgIsNotEmpty(s_pEfrData->chFindPattern)) { + ComboBox_SetTextHW(hwnd, IDC_FINDTEXT, s_pEfrData->chFindPattern); + } + else if (MRU_Count(Globals.pMRUfind)) { + MRU_Enum(Globals.pMRUfind, 0, s_wchBufOut, COUNTOF(s_wchBufOut)); + ComboBox_SetTextW(hwnd, IDC_FINDTEXT, s_wchBufOut); + } + else { + ComboBox_SetTextW(hwnd, IDC_FINDTEXT, NULL); + } + } + + if (s_bIsReplaceDlg && !pInit->pRestore) { + if (!GetWindowTextLengthW(GetDlgItem(hwnd, IDC_REPLACETEXT))) { + if (StrgIsNotEmpty(s_pEfrData->chReplaceTemplate)) { + ComboBox_SetTextHW(hwnd, IDC_REPLACETEXT, s_pEfrData->chReplaceTemplate); + } + else if (MRU_Count(Globals.pMRUreplace)) { + MRU_Enum(Globals.pMRUreplace, 0, s_wchBufOut, COUNTOF(s_wchBufOut)); + ComboBox_SetTextW(hwnd, IDC_REPLACETEXT, s_wchBufOut); + } + else { + ComboBox_SetTextW(hwnd, IDC_REPLACETEXT, NULL); + } + } + } + + if (s_bSwitchedFindReplace) { + // restore from prev Dlg + SetDlgPos(hwnd, s_xFindReplaceDlgSave, s_yFindReplaceDlgSave); + s_bSwitchedFindReplace = false; + } + else if (pInit->pRestore) { + _RestoreFindReplaceDlgPosition(hwnd, &pInit->pRestore->windowRect); + } + else { + if (Settings.FindReplaceDlgPosX == CW_USEDEFAULT || Settings.FindReplaceDlgPosY == CW_USEDEFAULT) { + CenterDlgInParent(hwnd, false); + } + else { + SetDlgPos(hwnd, Settings.FindReplaceDlgPosX, Settings.FindReplaceDlgPosY); + } + } + + WCHAR wchMenuBuf[80] = {L'\0'}; + HMENU hmenu = GetSystemMenu(hwnd, FALSE); + + GetLngString(IDS_MUI_SAVEPOS, wchMenuBuf, COUNTOF(wchMenuBuf)); + InsertMenu(hmenu, 0, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_SAVEPOS, wchMenuBuf); + GetLngString(IDS_MUI_RESETPOS, wchMenuBuf, COUNTOF(wchMenuBuf)); + InsertMenu(hmenu, 1, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_RESETPOS, wchMenuBuf); + InsertMenu(hmenu, 2, MF_BYPOSITION | MF_SEPARATOR, 0, NULL); + GetLngString(IDS_MUI_CLEAR_FIND_HISTORY, wchMenuBuf, COUNTOF(wchMenuBuf)); + InsertMenu(hmenu, 3, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_CLEAR_FIND_HISTORY, wchMenuBuf); + GetLngString(IDS_MUI_CLEAR_REPL_HISTORY, wchMenuBuf, COUNTOF(wchMenuBuf)); + InsertMenu(hmenu, 4, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_CLEAR_REPL_HISTORY, wchMenuBuf); + InsertMenu(hmenu, 5, MF_BYPOSITION | MF_SEPARATOR, 0, NULL); + GetLngString(IDS_MUI_SEARCHCLIPIFEMPTY, wchMenuBuf, COUNTOF(wchMenuBuf)); + InsertMenu(hmenu, 6, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_SEARCHCLIPIFEMPTY, wchMenuBuf); + GetLngString(IDS_MUI_REPLCLIPTAG, wchMenuBuf, COUNTOF(wchMenuBuf)); + InsertMenu(hmenu, 7, MF_BYPOSITION | MF_STRING | MF_ENABLED, IDS_MUI_REPLCLIPTAG, wchMenuBuf); + InsertMenu(hmenu, 8, MF_BYPOSITION | MF_SEPARATOR, 0, NULL); + + CheckCmd(hmenu, IDS_MUI_SEARCHCLIPIFEMPTY, Settings.SearchByClipboardIfEmpty); + CheckCmd(hmenu, IDS_MUI_REPLCLIPTAG, Settings.ReplaceByClipboardTag); + + + hBrushRed = CreateSolidBrush(rgbRedColorRef); + hBrushGreen = CreateSolidBrush(rgbGreenColorRef); + hBrushBlue = CreateSolidBrush(rgbBlueColorRef); + + s_anyMatch = NO_MATCH; + + _SetSearchFlags(hwnd, s_pEfrData); // sync + s_pEfrData->bStateChanged = true; // force update + + DialogEnableControl(hwnd, IDC_TOGGLE_VISIBILITY, s_pEfrData->bMarkOccurences); + + _DelayMarkAll(_MQ_STD); + + PostMessage(hwnd, WM_THEMECHANGED, 0, 0); + } + return TRUE; // (!) further processing + + case WM_ENABLE: + // modal child dialog should disable main window too + EnableWindow(Globals.hwndMain, (BOOL)wParam); + return TRUE; + + case WM_CLOSE: + // Language switching needs the modeless dialog destroyed before the resource DLL is unloaded. + DestroyWindow(hwnd); + return TRUE; + + case WM_DESTROY: { + + KillTimer(hwnd, pTimerIdentifier); + pTimerIdentifier = 0; + + _SetSearchFlags(hwnd, s_pEfrData); // sync + DuplicateEFR(&(Settings.EFR_Data), s_pEfrData); + + if (!s_bSwitchedFindReplace) { + if (s_anyMatch == MATCH) { + // Save MRUs + if (StrgIsNotEmpty(s_pEfrData->chFindPattern)) { + MRU_Add(Globals.pMRUfind, StrgGet(s_pEfrData->chFindPattern), 0, -1, -1, NULL); + SetFindPattern(StrgGet(s_pEfrData->chFindPattern)); + } + //~if (StrgIsNotEmpty(s_pEfrData->chReplaceTemplate)) { + MRU_Add(Globals.pMRUreplace, StrgGet(s_pEfrData->chReplaceTemplate), 0, -1, -1, NULL); + //~} + } + + Globals.iReplacedOccurrences = 0; + Globals.FindReplaceMatchFoundState = FND_NOP; + + Settings.MarkOccurrences = s_SaveMarkOccurrences; + Settings.MarkOccurrencesMatchVisible = s_SaveMarkMatchVisible; + EnableCmd(GetMenu(Globals.hwndMain), IDM_VIEW_MARKOCCUR_ONOFF, true); + + if (FocusedView.HideNonMatchedLines) { + EditToggleView(s_pEfrData->hwnd); + } + + if (IsMarkOccurrencesEnabled()) { + MarkAllOccurrences(_MQ_STD, true); + } else { + EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); + } + + if (s_InitialTopLine >= 0) { + SciCall_SetFirstVisibleLine(s_InitialTopLine); + s_InitialTopLine = -1; // reset + } else { + if (s_anyMatch == NO_MATCH) { + EditSetSelectionEx(s_InitialAnchorPos, s_InitialCaretPos, -1, -1); + } else { + Sci_ScrollSelectionToView(); + } + } + + CmdMessageQueue_t* pmqc = NULL; + CmdMessageQueue_t* dummy; + DL_FOREACH_SAFE(MessageQueue, pmqc, dummy) { + DL_DELETE(MessageQueue, pmqc); + FreeMem(pmqc); + } + } + + DeleteObject(hBrushRed); + DeleteObject(hBrushGreen); + DeleteObject(hBrushBlue); + GetSystemMenu(hwnd, TRUE); + + s_pEfrData = NULL; + Globals.hwndDlgFindReplace = NULL; + } + return FALSE; + + + case WM_DPICHANGED: + UpdateWindowLayoutForDPI(hwnd, (RECT*)lParam, LOWORD(wParam)); + return TRUE; // further processing + + +#ifdef D_NP3_WIN10_DARK_MODE + + case WM_CTLCOLORDLG: + case WM_CTLCOLORBTN: + //~case WM_CTLCOLOREDIT: + //~case WM_CTLCOLORLISTBOX: + case WM_CTLCOLORSTATIC: + return SetDarkModeCtlColors((HDC)wParam, UseDarkMode()); + break; + + case WM_SETTINGCHANGE: + if (IsDarkModeSupported() && IsColorSchemeChangeMessage(lParam)) { + SendMessage(hwnd, WM_THEMECHANGED, 0, 0); + } + break; + + case WM_THEMECHANGED: + if (IsDarkModeSupported()) { + bool const darkModeEnabled = CheckDarkModeEnabled(); + AllowDarkModeForWindowEx(hwnd, darkModeEnabled); + RefreshTitleBarThemeColor(hwnd); + int const ctlx[] = { IDOK, IDCANCEL, IDC_FINDPREV, IDC_REPLACE, IDC_SWAPSTRG, + IDC_REPLACEALL, IDC_REPLACEINSEL, IDC_TOGGLE_VISIBILITY + }; + for (int i = 0; i < COUNTOF(ctlx); ++i) { + HWND const hBtn = GetDlgItem(hwnd, ctlx[i]); + AllowDarkModeForWindowEx(hBtn, darkModeEnabled); + SendMessage(hBtn, WM_THEMECHANGED, 0, 0); + } + UpdateWindowEx(hwnd); + } + break; + +#endif + + case WM_CTLCOLOREDIT: + case WM_CTLCOLORLISTBOX: { + if (!s_pEfrData) { + return false; + } + HWND hCheck = (HWND)lParam; + HDC hDC = (HDC)wParam; + + HWND hComboBox = GetDlgItem(hwnd, IDC_FINDTEXT); + COMBOBOXINFO ci = { sizeof(COMBOBOXINFO) }; + GetComboBoxInfo(hComboBox, &ci); + + //if (hCheck == ci.hwndItem || hCheck == ci.hwndList) + if (hCheck == ci.hwndItem) { + SetBkMode(hDC, TRANSPARENT); + INT_PTR hBrush; + switch (s_anyMatch) { + case MATCH: + //SetTextColor(hDC, green); + SetBkColor(hDC, rgbGreenColorRef); + hBrush = (INT_PTR)hBrushGreen; + break; + case NO_MATCH: + //SetTextColor(hDC, blue); + SetBkColor(hDC, rgbBlueColorRef); + hBrush = (INT_PTR)hBrushBlue; + break; + case INVALID: + default: + //SetTextColor(hDC, red); + SetBkColor(hDC, rgbRedColorRef); + hBrush = (INT_PTR)hBrushRed; + break; + } + return hBrush; + } + } +#ifdef D_NP3_WIN10_DARK_MODE + return SetDarkModeCtlColors((HDC)wParam, UseDarkMode()); +#else + return FALSE; +#endif + + + case WM_ACTIVATE: { + if (!s_pEfrData) { + return false; + } + + switch (LOWORD(wParam)) { + case WA_INACTIVE: + SetWindowTransparentMode(hwnd, Settings.FindReplaceTransparentMode, Settings2.FindReplaceOpacityLevel); + break; + + case WA_CLICKACTIVE: + // mouse click activation + case WA_ACTIVE: + SetWindowTransparentMode(hwnd, false, 100); + + // selection changed ? + if ((SciCall_GetCurrentPos() != s_InitialCaretPos) || + (SciCall_GetAnchor() != s_InitialAnchorPos)) { + EditSetCaretToSelectionStart(); + s_InitialAnchorPos = SciCall_GetAnchor(); + s_InitialCaretPos = SciCall_GetCurrentPos(); + s_InitialTopLine = SciCall_GetFirstVisibleLine(); + s_InitialSearchStart = s_InitialCaretPos; + if (s_pEfrData) { + s_pEfrData->bStateChanged = true; + } + } + + bool const bEnableReplInSel = !(SciCall_IsSelectionEmpty() || Sci_IsMultiOrRectangleSelection()); + DialogEnableControl(hwnd, IDC_REPLACEINSEL, bEnableReplInSel); + + _DelayMarkAll(_MQ_STD); + + if (!SciCall_IsSelectionEmpty()) { + Sci_ScrollSelectionToView(); + } + /// don't do: ///~SendWMCommandEx(hwnd, IDC_FINDTEXT, CBN_EDITCHANGE); + break; + + default: + break; + } + } + return false; + + + case WM_COMMAND: { + if (!s_pEfrData) { + return FALSE; + } + + switch (LOWORD(wParam)) { + + case IDC_DOC_MODIFIED: + s_InitialSearchStart = SciCall_GetSelectionStart(); + s_InitialTopLine = -1; // reset + s_pEfrData->bStateChanged = true; + _DelayMarkAll(_MQ_STD); + break; + + + case IDC_FINDTEXT: + case IDC_REPLACETEXT: { + + bool bFndPatternChanged = s_pEfrData->bStateChanged; + + switch (HIWORD(wParam)) { + + case CBN_EDITUPDATE: + if (SendDlgItemMessage(hwnd, LOWORD(wParam), CB_GETDROPPEDSTATE, 0, 0)) { + //~SendDlgItemMessage(hwnd, LOWORD(wParam), CB_SETCURSEL, (WPARAM)-1, 0); // clear + SendDlgItemMessage(hwnd, LOWORD(wParam), CB_SHOWDROPDOWN, 0, 0); // hide + } + break; + + //~case CBN_SELCHANGE: + case CBN_CLOSEUP: { + int const cursel = (int)SendDlgItemMessage(hwnd, LOWORD(wParam), CB_GETCURSEL, 0, 0); + if (cursel >= 0) { + SendDlgItemMessage(hwnd, LOWORD(wParam), CB_SETCURSEL, (WPARAM)cursel, 0); + } + } + // [fallthrough] + case CBN_SELENDOK: + case CBN_EDITCHANGE: + bFndPatternChanged = (LOWORD(wParam) == IDC_FINDTEXT); + break; + + case CBN_KILLFOCUS: + case CBN_SELENDCANCEL: + default: + break; + } + + if (Globals.bFindReplCopySelOrClip) { + // reset first: setting the combo text below re-enters this handler (CBN_EDITCHANGE) + Globals.bFindReplCopySelOrClip = false; + char* lpszSelection = NULL; + DocPos const cchSelection = SciCall_GetSelText(NULL); + // WM_SETTEXT ignores CB_LIMITTEXT: an oversized selection freezes the combo's edit control + if ((cchSelection > 0) && (cchSelection <= FNDRPL_BUFFER) && (LOWORD(wParam) != IDC_REPLACETEXT)) { + lpszSelection = AllocMem((cchSelection + 1), HEAP_ZERO_MEMORY); + SciCall_GetSelText(lpszSelection); + } else { // no (usable) selection + // nothing is selected in the editor: + // if first time you bring up find/replace dialog, + // use most recent search pattern to find box + // in case of no history: paste clipboard + LPCWSTR wchFind = _EditGetFindStrg(Globals.hwndEdit, s_pEfrData, true); + if (StrIsNotEmpty(wchFind)) { + int const size = WideCharToMultiByte(Encoding_SciCP, 0, wchFind, -1, NULL, 0, NULL, NULL); + lpszSelection = AllocMem(size * sizeof(CHAR), HEAP_ZERO_MEMORY); + WideCharToMultiByte(Encoding_SciCP, 0, wchFind, -1, lpszSelection, size, NULL, NULL); + } + } + if (lpszSelection) { + ComboBox_SetTextMB2W(hwnd, IDC_FINDTEXT, lpszSelection); + FreeMem(lpszSelection); + lpszSelection = NULL; + bFndPatternChanged = true; + } + s_InitialTopLine = -1; // reset + + } // Globals.bFindReplCopySelOrClip + + _SetSearchFlags(hwnd, s_pEfrData); + SetFindPattern(StrgGet(s_pEfrData->chFindPattern)); + + // ------------------------ + + if (!(bFndPatternChanged || s_pEfrData->bStateChanged)) { + break; // return + } + // ------------------------ + + EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); + + if (_EnableFRDlgCtrls(hwnd)) { + EditSetSelectionEx(s_InitialAnchorPos, s_InitialCaretPos, -1, -1); + } + + DocPos start = s_InitialSearchStart; + DocPos end = Sci_GetDocEndPosition(); + + LPCWSTR wchFind = _EditGetFindStrg(s_pEfrData->hwnd, s_pEfrData, false); + DocPos const iPos = _FindInTarget(wchFind, (int)(s_pEfrData->fuFlags), &start, &end, false, FRMOD_NORM); + + if (s_pEfrData->bInstantIncrementalSearch) { + if (iPos >= 0) { + if (s_bIsReplaceDlg) { + SciCall_ScrollRange(end, iPos); + } + else { + EditSetSelectionEx(end, iPos, -1, -1); + } + if (iPos == end) { + _ShowZeroLengthCallTip(iPos); + } + } + else { + if (s_bIsReplaceDlg) { + SciCall_ScrollRange(s_InitialAnchorPos, s_InitialCaretPos); + } + if (s_InitialTopLine >= 0) { + SciCall_SetFirstVisibleLine(s_InitialTopLine); + } + } + } + _DelayMarkAll(_MQ_STD); + } + break; + + case IDT_TIMER_CALLBACK_MRKALL: { + bool const bRestoreFocusedView = s_bRestoreFocusedView; + s_bRestoreFocusedView = false; + static wchar_t s_lastFind[FNDRPL_BUFFER] = { L'\0' }; + bool const bRefreshMarks = s_pEfrData->bMarkOccurences && + (s_pEfrData->bStateChanged || (StringCchCompareX(s_lastFind, StrgGet(s_pEfrData->chFindPattern)) != 0)); + if (bRefreshMarks) { + StringCchCopyW(s_lastFind, COUNTOF(s_lastFind), StrgGet(s_pEfrData->chFindPattern)); + } + s_anyMatch = _FindHasMatch(s_pEfrData->hwnd, s_pEfrData, 0, bRefreshMarks); + InvalidateRect(GetDlgItem(hwnd, IDC_FINDTEXT), NULL, TRUE); // coloring + if (bRefreshMarks) { + if (bRestoreFocusedView && s_anyMatch == MATCH && (Settings.FocusViewMarkerMode & FVMM_FOLD)) { + // Fold the rebuilt matches without re-running Focused View's bookmark action. + FocusedView.HideNonMatchedLines = true; + EditFoldMarkedLineRange(s_pEfrData->hwnd, true); + UpdateDocumentReadOnlyState(); + } else if (FocusedView.HideNonMatchedLines) { + EditToggleView(s_pEfrData->hwnd); + } + } else if (!s_pEfrData->bMarkOccurences && s_pEfrData->bStateChanged) { + if (FocusedView.HideNonMatchedLines) { + SendWMCommand(hwnd, IDC_TOGGLE_VISIBILITY); + } else { + EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); + InvalidateRect(GetDlgItem(hwnd, IDC_FINDTEXT), NULL, TRUE); + } + } + s_pEfrData->bStateChanged = false; + } + break; + + case IDC_ALL_OCCURRENCES: { + _SetSearchFlags(hwnd, s_pEfrData); + + if (IsButtonChecked(hwnd, IDC_ALL_OCCURRENCES)) { + DialogEnableControl(hwnd, IDC_TOGGLE_VISIBILITY, true); + _DelayMarkAll(_MQ_STD); + } else { // switched OFF + DialogEnableControl(hwnd, IDC_TOGGLE_VISIBILITY, false); + if (FocusedView.HideNonMatchedLines) { + EditToggleView(s_pEfrData->hwnd); + } + EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); + InvalidateRect(GetDlgItem(hwnd, IDC_FINDTEXT), NULL, TRUE); + } + } + break; + + case IDC_INST_INCR_SEARCH: + _SetSearchFlags(hwnd, s_pEfrData); + _DelayMarkAll(_MQ_STD); + break; + + case IDC_TOGGLE_VISIBILITY: + if (s_pEfrData) { + s_bRestoreFocusedView = false; + EditToggleView(s_pEfrData->hwnd); + if (!FocusedView.HideNonMatchedLines) { + s_pEfrData->bStateChanged = true; + s_InitialTopLine = -1; // reset + EditClearAllOccurrenceMarkers(s_pEfrData->hwnd); + _DelayMarkAll(_MQ_STD); + } + } + break; + + case IDC_FINDREGEXP: + if (IsButtonChecked(hwnd, IDC_FINDREGEXP)) { + DialogEnableControl(hwnd, IDC_DOT_MATCH_ALL, true); + // Can not use wild-card search together with RegExp + CheckDlgButton(hwnd, IDC_WILDCARDSEARCH, BST_UNCHECKED); + // transform BS handled by regex + CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, BST_CHECKED); + DialogEnableControl(hwnd, IDC_FINDTRANSFORMBS, false); + } else { // unchecked + DialogEnableControl(hwnd, IDC_DOT_MATCH_ALL, false); + DialogEnableControl(hwnd, IDC_FINDTRANSFORMBS, true); + CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, SetBtn(s_pEfrData->bTransformBS)); + } + _SetSearchFlags(hwnd, s_pEfrData); + _DelayMarkAll(_MQ_STD); + break; + + case IDC_DOT_MATCH_ALL: + _SetSearchFlags(hwnd, s_pEfrData); + _DelayMarkAll(_MQ_STD); + break; + + case IDC_WILDCARDSEARCH: { + if (IsButtonChecked(hwnd, IDC_WILDCARDSEARCH)) { + // Can not use wild-card search together with RegExp + CheckDlgButton(hwnd, IDC_FINDREGEXP, BST_UNCHECKED); + DialogEnableControl(hwnd, IDC_DOT_MATCH_ALL, false); + // transform BS handled by regex (wild-card search based on): + CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, BST_CHECKED); + DialogEnableControl(hwnd, IDC_FINDTRANSFORMBS, false); + } else { // unchecked + DialogEnableControl(hwnd, IDC_FINDTRANSFORMBS, true); + CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, SetBtn(s_pEfrData->bTransformBS)); + } + _SetSearchFlags(hwnd, s_pEfrData); + _DelayMarkAll(_MQ_STD); + } + break; + + case IDC_FINDTRANSFORMBS: { + _SetSearchFlags(hwnd, s_pEfrData); + _DelayMarkAll(_MQ_STD); + } + break; + + case IDC_FINDCASE: + _SetSearchFlags(hwnd, s_pEfrData); + _DelayMarkAll(_MQ_STD); + break; + + case IDC_FINDWORD: + _SetSearchFlags(hwnd, s_pEfrData); + _DelayMarkAll(_MQ_STD); + break; + + case IDC_FINDSTART: + _SetSearchFlags(hwnd, s_pEfrData); + _DelayMarkAll(_MQ_STD); + break; + + case IDC_TRANSPARENT: + Settings.FindReplaceTransparentMode = IsButtonChecked(hwnd, IDC_TRANSPARENT); + break; + + case IDC_REPLACE: + case IDC_REPLACEALL: + case IDC_REPLACEINSEL: + Globals.iReplacedOccurrences = 0; + case IDOK: + case IDC_FINDPREV: + case IDACC_SELTONEXT: + case IDACC_SELTOPREV: + case IDMSG_SWITCHTOFIND: + case IDMSG_SWITCHTOREPLACE: { + + if ((!s_bIsReplaceDlg && LOWORD(wParam) == IDMSG_SWITCHTOREPLACE) || + (s_bIsReplaceDlg && LOWORD(wParam) == IDMSG_SWITCHTOFIND)) { + GetDlgPos(hwnd, &s_xFindReplaceDlgSave, &s_yFindReplaceDlgSave); + s_bSwitchedFindReplace = true; + } + + if (!s_bSwitchedFindReplace && !_EnableFRDlgCtrls(hwnd)) { + return true; + } + + _SetSearchFlags(hwnd, s_pEfrData); + + if (s_bSwitchedFindReplace) { + // Reload MRUs + SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_RESETCONTENT, 0, 0); + SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_RESETCONTENT, 0, 0); + + for (int i = 0; i < MRU_Count(Globals.pMRUfind); i++) { + MRU_Enum(Globals.pMRUfind, i, s_wchBufOut, COUNTOF(s_wchBufOut)); + SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_ADDSTRING, 0, (LPARAM)s_wchBufOut); + } + for (int i = 0; i < MRU_Count(Globals.pMRUreplace); i++) { + MRU_Enum(Globals.pMRUreplace, i, s_wchBufOut, COUNTOF(s_wchBufOut)); + SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_ADDSTRING, 0, (LPARAM)s_wchBufOut); + } + ComboBox_SetTextHW(hwnd, IDC_FINDTEXT, s_pEfrData->chFindPattern); + ComboBox_SetTextHW(hwnd, IDC_REPLACETEXT, s_pEfrData->chReplaceTemplate); + } + else { + // Save MRUs + if (StrgIsNotEmpty(s_pEfrData->chFindPattern)) { + MRU_Add(Globals.pMRUfind, StrgGet(s_pEfrData->chFindPattern), 0, -1, -1, NULL); + SetFindPattern(StrgGet(s_pEfrData->chFindPattern)); + } + MRU_Add(Globals.pMRUreplace, StrgGet(s_pEfrData->chReplaceTemplate), 0, -1, -1, NULL); + // Immediately reflect used patterns in dropdown (without touching the edit field) + _AddPatternToComboMRU(hwnd, IDC_FINDTEXT, StrgGet(s_pEfrData->chFindPattern)); + if (s_bIsReplaceDlg) { + _AddPatternToComboMRU(hwnd, IDC_REPLACETEXT, StrgGet(s_pEfrData->chReplaceTemplate)); + } + } + + if (!s_bSwitchedFindReplace) { + SendMessage(hwnd, WM_NEXTDLGCTL, (WPARAM)(GetFocus()), 1); + } + + bool bFound = false; + + switch (LOWORD(wParam)) { + case IDOK: // find next + case IDACC_SELTONEXT: + if (s_bIsReplaceDlg) { + Globals.bReplaceInitialized = true; + } + bFound = EditFindNext(s_pEfrData->hwnd, s_pEfrData, (LOWORD(wParam) == IDACC_SELTONEXT), IsKeyDown(VK_F3), true); + SET_INITIAL_ANCHORS() + break; + + case IDC_FINDPREV: // find previous + case IDACC_SELTOPREV: + if (s_bIsReplaceDlg) { + Globals.bReplaceInitialized = true; + } + bFound = EditFindPrev(s_pEfrData->hwnd, s_pEfrData, (LOWORD(wParam) == IDACC_SELTOPREV), IsKeyDown(VK_F3), true); + SET_INITIAL_ANCHORS() + break; + + case IDC_REPLACE: { + Globals.bReplaceInitialized = true; + bFound = EditReplace(s_pEfrData->hwnd, s_pEfrData); + } + break; + + case IDC_REPLACEALL: + Globals.bReplaceInitialized = true; + bFound = EditReplaceAll(s_pEfrData->hwnd, s_pEfrData, true); + break; + + case IDC_REPLACEINSEL: + if (!SciCall_IsSelectionEmpty()) { + Globals.bReplaceInitialized = true; + bFound = EditReplaceAllInSelection(s_pEfrData->hwnd, s_pEfrData, true); + } + break; + } + + if (bFound && !s_bIsReplaceDlg && (s_pEfrData->bFindClose)) { + //~EndDialog(hwnd, LOWORD(wParam)); ~ (!) not running on own message loop + DestroyWindow(hwnd); + } + else if (bFound && s_bIsReplaceDlg && s_pEfrData->bReplaceClose) { + //~EndDialog(hwnd, LOWORD(wParam)); ~ (!) not running on own message loop + DestroyWindow(hwnd); + } + } + _DelayMarkAll(_MQ_STD); + break; + + + case IDCANCEL: + //~EndDialog(hwnd, IDCANCEL); ~ (!) not running on own message loop + DestroyWindow(hwnd); + break; + + case IDC_FINDESCCTRLCHR: + case IDC_REPLESCCTRLCHR: { + UINT const ctrl_id = (LOWORD(wParam) == IDC_FINDESCCTRLCHR) ? IDC_FINDTEXT : IDC_REPLACETEXT; + GetDlgItemTextW(hwnd, ctrl_id, s_wchBufIn, COUNTOF(s_wchBufIn)); + size_t const inLen = StringCchLen(s_wchBufIn, 0); + if (SlashCtrlW(s_wchBufOut, COUNTOF(s_wchBufOut), s_wchBufIn) == inLen) { + UnSlashCtrlW(s_wchBufOut); + } + SetDlgItemTextW(hwnd, ctrl_id, s_wchBufOut); + if ((ctrl_id == IDC_FINDTEXT) && (inLen != StringCchLen(s_wchBufOut, 0))) { + Globals.FindReplaceMatchFoundState = FND_NOP; + _SetSearchFlags(hwnd, s_pEfrData); + _DelayMarkAll(_MQ_ASAP); + } + } + break; + + case IDC_SWAPSTRG: { + GetDlgItemTextW(hwnd, IDC_FINDTEXT, s_wchBufOut, COUNTOF(s_wchBufOut)); + GetDlgItemTextW(hwnd, IDC_REPLACETEXT, s_wchBufIn, COUNTOF(s_wchBufIn)); + SetDlgItemTextW(hwnd, IDC_FINDTEXT, s_wchBufIn); + SetDlgItemTextW(hwnd, IDC_REPLACETEXT, s_wchBufOut); + if (StringCchCompareX(s_wchBufIn, s_wchBufOut) != 0) { + Globals.FindReplaceMatchFoundState = FND_NOP; + _SetSearchFlags(hwnd, s_pEfrData); + _DelayMarkAll(_MQ_ASAP); + } + } + break; + + case IDACC_FIND: + PostWMCommand(GetParent(hwnd), IDM_EDIT_FIND); + break; + + case IDACC_REPLACE: + PostWMCommand(GetParent(hwnd), IDM_EDIT_REPLACE); + break; + + case IDACC_SAVEPOS: + GetDlgPos(hwnd, &Settings.FindReplaceDlgPosX, &Settings.FindReplaceDlgPosY); + break; + + case IDACC_RESETPOS: + CenterDlgInParent(hwnd, false); + Settings.FindReplaceDlgPosX = Settings.FindReplaceDlgPosY = CW_USEDEFAULT; + break; + + case IDACC_CLEAR_FIND_HISTORY: + MRU_Empty(Globals.pMRUfind, false, Globals.bCanSaveIniFile); + if (s_pEfrData) { + StrgEmpty(s_pEfrData->chFindPattern, false); + } + SetFindPattern(NULL); + while ((int)SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_DELETESTRING, 0, 0) > 0) {}; + SetDlgItemText(hwnd, IDC_FINDTEXT, L""); + break; + + case IDACC_CLEAR_REPL_HISTORY: + MRU_Empty(Globals.pMRUreplace, false, Globals.bCanSaveIniFile); + if (s_pEfrData) { + StrgEmpty(s_pEfrData->chReplaceTemplate, false); + } + while ((int)SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_DELETESTRING, 0, 0) > 0) {}; + SetDlgItemText(hwnd, IDC_REPLACETEXT, L""); + break; + + case IDACC_SEARCHCLIPIFEMPTY: + Settings.SearchByClipboardIfEmpty = !Settings.SearchByClipboardIfEmpty; + CheckCmd(GetSystemMenu(hwnd, FALSE), IDS_MUI_SEARCHCLIPIFEMPTY, Settings.SearchByClipboardIfEmpty); + break; + + case IDACC_REPLCLIPTAG: + Settings.ReplaceByClipboardTag = !Settings.ReplaceByClipboardTag; + CheckCmd(GetSystemMenu(hwnd, FALSE), IDS_MUI_REPLCLIPTAG, Settings.ReplaceByClipboardTag); + break; + + case IDACC_FINDNEXT: + PostWMCommand(hwnd, IDOK); + break; + + case IDACC_FINDPREV: + PostWMCommand(hwnd, IDC_FINDPREV); + break; + + case IDACC_REPLACENEXT: + if (s_bIsReplaceDlg) { + PostWMCommand(hwnd, IDC_REPLACE); + } + break; + + case IDACC_SAVEFIND: + Globals.FindReplaceMatchFoundState = FND_NOP; + SendWMCommand(Globals.hwndMain, IDM_EDIT_SAVEFIND); + ComboBox_SetTextHW(hwnd, IDC_FINDTEXT, s_pEfrData->chFindPattern); + CheckDlgButton(hwnd, IDC_FINDREGEXP, BST_UNCHECKED); + CheckDlgButton(hwnd, IDC_DOT_MATCH_ALL, BST_UNCHECKED); + CheckDlgButton(hwnd, IDC_WILDCARDSEARCH, BST_UNCHECKED); + CheckDlgButton(hwnd, IDC_FINDTRANSFORMBS, BST_UNCHECKED); + PostMessage(hwnd, WM_NEXTDLGCTL, (WPARAM)(GetDlgItem(hwnd, IDC_FINDTEXT)), 1); + break; + + case IDACC_VIEWSCHEMECONFIG: + PostWMCommand(GetParent(hwnd), IDM_VIEW_SCHEMECONFIG); + break; + + default: + return FALSE; + } + + } // WM_COMMAND: + return TRUE; + + + case WM_SYSCOMMAND: + if (wParam == IDS_MUI_SAVEPOS) { + PostWMCommand(hwnd, IDACC_SAVEPOS); + return TRUE; + } else if (wParam == IDS_MUI_RESETPOS) { + PostWMCommand(hwnd, IDACC_RESETPOS); + return TRUE; + } else if (wParam == IDS_MUI_CLEAR_FIND_HISTORY) { + PostWMCommand(hwnd, IDACC_CLEAR_FIND_HISTORY); + return TRUE; + } else if (wParam == IDS_MUI_CLEAR_REPL_HISTORY) { + PostWMCommand(hwnd, IDACC_CLEAR_REPL_HISTORY); + return TRUE; + } else if (wParam == IDS_MUI_SEARCHCLIPIFEMPTY) { + PostWMCommand(hwnd, IDACC_SEARCHCLIPIFEMPTY); + return TRUE; + } else if (wParam == IDS_MUI_REPLCLIPTAG) { + PostWMCommand(hwnd, IDACC_REPLCLIPTAG); + return TRUE; + } + break; + + case WM_NOTIFY: { + LPNMHDR pnmhdr = (LPNMHDR)lParam; + switch (pnmhdr->code) { + case NM_CLICK: + case NM_RETURN: + switch (pnmhdr->idFrom) { + case IDC_TOGGLEFINDREPLACE: + if (s_bIsReplaceDlg) { + PostWMCommand(GetParent(hwnd), IDM_EDIT_FIND); + } else { + PostWMCommand(GetParent(hwnd), IDM_EDIT_REPLACE); + } + break; + case IDC_FINDESCCTRLCHR: + SendWMCommand(hwnd, IDC_FINDESCCTRLCHR); + break; + case IDC_REPLESCCTRLCHR: + SendWMCommand(hwnd, IDC_REPLESCCTRLCHR); + break; + case IDC_BACKSLASHHELP: + // Display help messages in the find/replace windows + DisplayHelpDlgLng(hwnd, IDS_MUI_BACKSLASHHELP); + break; + case IDC_REGEXPHELP: + DisplayHelpDlgLng(hwnd, IDS_MUI_REGEXPHELP); + break; + case IDC_WILDCARDHELP: + DisplayHelpDlgLng(hwnd, IDS_MUI_WILDCARDHELP); + break; + default: + break; + } + break; + + default: + return false; + } + } + break; + + default: + break; + + } // switch(umsg) + + return FALSE; // message handled +} + + +//============================================================================= +// +// EditFindReplaceDlg() +// +static void EditFindReplaceDlg(bool bReplace, const FindReplaceDlgRestore* pRestore) +{ + s_FindReplaceData.hwnd = Globals.hwndEdit; + FindReplaceDlgInit const init = { &s_FindReplaceData, pRestore }; + HWND hDlg = CreateThemedDialogParam(Globals.hLngResContainer, + (bReplace) ? MAKEINTRESOURCEW(IDD_MUI_REPLACE) : MAKEINTRESOURCEW(IDD_MUI_FIND), + GetParent(s_FindReplaceData.hwnd), + EditFindReplaceDlgProc, + (LPARAM)&init); + + if (IS_VALID_HANDLE(hDlg)) { + ShowWindow(hDlg, SW_SHOW); + if (pRestore) { + _EnableFRDlgCtrls(hDlg); + } + UpdateStatusbar(true); + } +} + + +//============================================================================= +// +// FindReplaceShowDialog() +// +void FindReplaceShowDialog(bool bReplace) +{ + FindReplacePrepare(); + HWND const hwndDlg = Globals.hwndDlgFindReplace; + if (!IsWindow(hwndDlg)) { + // Don't overwrite cmd-line search pattern with editor selection. + Globals.bFindReplCopySelOrClip = !g_flagMatchText; + EditFindReplaceDlg(bReplace, NULL); + } else { + Globals.bFindReplCopySelOrClip = (GetForegroundWindow() != hwndDlg); + if ((GetDlgItem(hwndDlg, IDC_REPLACE) != NULL) != bReplace) { + SendWMCommand(hwndDlg, bReplace ? IDMSG_SWITCHTOREPLACE : IDMSG_SWITCHTOFIND); + DestroyWindow(Globals.hwndDlgFindReplace); + EditFindReplaceDlg(bReplace, NULL); + } else { + SetForegroundWindow(hwndDlg); + PostMessage(Globals.hwndDlgFindReplace, WM_NEXTDLGCTL, (WPARAM)GetDlgItem(Globals.hwndDlgFindReplace, IDC_FINDTEXT), 1); + } + } +} + +bool FindReplaceCaptureDialog(FindReplaceDlgRestore* pRestore) +{ + HWND const hwndDlg = Globals.hwndDlgFindReplace; + if (!IsWindow(hwndDlg)) { + return false; + } + pRestore->bReplace = GetDlgItem(hwndDlg, IDC_REPLACE) != NULL; + GetWindowRect(hwndDlg, &pRestore->windowRect); + pRestore->bFocusedView = FocusedView.HideNonMatchedLines; + return true; +} + +void FindReplaceRestoreDialog(const FindReplaceDlgRestore* pRestore) +{ + if (!IsWindow(Globals.hwndDlgFindReplace)) { + Globals.bFindReplCopySelOrClip = false; + EditFindReplaceDlg(pRestore->bReplace, pRestore); + } +} + + +//============================================================================= +// +// EditFindNext() +// +bool EditFindNext(HWND hwnd, const LPEDITFINDREPLACE lpefr, bool bExtendSelection, bool bFocusWnd, bool bFillEmpty) +{ + bool bSuppressNotFound = false; + bool bFoundWrapAround = false; + + if (bFocusWnd) { + SetFocus(hwnd); + } + + LPCWSTR wchFind = _EditGetFindStrg(hwnd, lpefr, bFillEmpty); + + if (StrIsEmpty(wchFind)) { + return false; + } + int const sFlags = (int)(lpefr->fuFlags); + bool const bIsRegExpr = (sFlags & SCFIND_REGEXP); + + DocPos const iDocEndPos = Sci_GetDocEndPosition(); + + EditSetCaretToSelectionEnd(); // fluent switch between Prev/Next + DocPos const curPos = SciCall_GetCurrentPos(); + DocPos start = (curPos < iDocEndPos) ? curPos : 0; + + DocPos end = iDocEndPos; + + Sci_CallTipCancelEx(); + + DocPos iPos = _FindInTarget(wchFind, sFlags, &start, &end, true, FRMOD_NORM); + + if (bIsRegExpr && Sci_ConsumeRegexWarnStatus()) { + InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.MsgInvalidRegex, IDS_MUI_REGEX_INVALID); + bSuppressNotFound = true; + } else if ((iPos < 0LL) && (start >= 0LL) && !bExtendSelection) { + UpdateStatusbar(false); + if (!lpefr->bNoFindWrap && !bSuppressNotFound) { + Globals.iSelectionMarkNumber = 0; + DocPos const _start = start; + //DocPos const _end = end; + end = min_p(start, iDocEndPos); + start = 0LL; + iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_WRAPED); + + if ((iPos < 0LL) || (end == _start)) { + if (bIsRegExpr && Sci_ConsumeRegexWarnStatus()) { + InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.MsgInvalidRegex, IDS_MUI_REGEX_INVALID); + bSuppressNotFound = true; + } + } else { + LONG const result = InfoBoxLng(MB_OKCANCEL, Constants.SuppressKey.MsgFindWrap1, IDS_MUI_FIND_WRAPFW); + if (!IsYesOkay(result)) { + iPos = NOT_FOUND; + bSuppressNotFound = true; + } + bFoundWrapAround = (INFOBOX_MODE(result) != 0); + } + } + } + + if (iPos < 0LL) { + if (!bSuppressNotFound) { + InfoBoxLng(MB_OK, Constants.SuppressKey.MsgNotFound, IDS_MUI_NOTFOUND); + } + return false; + } + + if (bExtendSelection) { + DocPos const iSelPos = SciCall_GetCurrentPos(); + DocPos const iSelAnchor = SciCall_GetAnchor(); + EditSetSelectionEx(min_p(iSelAnchor, iSelPos), end, -1, -1); + } else { + EditSetSelectionEx(iPos, end, -1, -1); + } + + if (!Globals.iSelectionMarkNumber && lpefr->bMarkOccurences) { + _FindHasMatch(hwnd, lpefr, 0, true); + } + else { + ++Globals.iSelectionMarkNumber; + } + + if (iPos == end) { + _ShowZeroLengthCallTip(iPos); + } + if ((iPos+1) == end) { + char const p = SciCall_GetCharAt(iPos); + char const e = SciCall_GetCharAt(end); + if (p == 0x0d && e == 0x0a) { + _ShowZeroLengthCallTip(iPos); + } + } + if (bFoundWrapAround) { + ShowWrapAroundCallTip(true); + } + + return true; +} + + +//============================================================================= +// +// EditFindPrev() +// +bool EditFindPrev(HWND hwnd, LPEDITFINDREPLACE lpefr, bool bExtendSelection, bool bFocusWnd, bool bFillEmpty) +{ + bool bSuppressNotFound = false; + bool bFoundWrapAround = false; + + if (bFocusWnd) { + SetFocus(hwnd); + } + + LPCWSTR wchFind = _EditGetFindStrg(hwnd, lpefr, bFillEmpty); + + if (StrIsEmpty(wchFind)) { + return false; + } + int const sFlags = (int)(lpefr->fuFlags); + bool const bIsRegExpr = (sFlags & SCFIND_REGEXP); + + DocPos const iDocEndPos = Sci_GetDocEndPosition(); + + EditSetCaretToSelectionStart(); // fluent switch between Next/Prev + DocPos const curPos = SciCall_GetCurrentPos(); + DocPos start = (curPos > 0) ? (SciCall_IsSelectionEmpty() ? curPos : SciCall_PositionBefore(curPos)) : SciCall_PositionBefore(iDocEndPos); + DocPos end = 0LL; + + Sci_CallTipCancelEx(); + + DocPos iPos = _FindInTarget(wchFind, sFlags, &start, &end, true, FRMOD_NORM); + + if (bIsRegExpr && Sci_ConsumeRegexWarnStatus()) { + InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.MsgInvalidRegex, IDS_MUI_REGEX_INVALID); + bSuppressNotFound = true; + } else if ((iPos < 0LL) && (start <= iDocEndPos) && !bExtendSelection) { + UpdateStatusbar(false); + if (!lpefr->bNoFindWrap && !bSuppressNotFound) { + Globals.iSelectionMarkNumber = Globals.iMarkOccurrencesCount + 1; + DocPos const _start = start; + //DocPos const _end = end; + end = max_p(start, 0LL); + start = iDocEndPos; + iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_WRAPED); + + if ((iPos < 0LL) || (start == _start)) { + if (bIsRegExpr && Sci_ConsumeRegexWarnStatus()) { + InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.MsgInvalidRegex, IDS_MUI_REGEX_INVALID); + bSuppressNotFound = true; + } + } else { + LONG const result = InfoBoxLng(MB_OKCANCEL, Constants.SuppressKey.MsgFindWrap2, IDS_MUI_FIND_WRAPRE); + if (!IsYesOkay(result)) { + iPos = NOT_FOUND; + bSuppressNotFound = true; + } + bFoundWrapAround = (INFOBOX_MODE(result) != 0); + } + } + } + + if (iPos < 0LL) { + if (!bSuppressNotFound) { + InfoBoxLng(MB_OK, Constants.SuppressKey.MsgNotFound, IDS_MUI_NOTFOUND); + } + return false; + } + + if (bExtendSelection) { + DocPos const iSelPos = SciCall_GetCurrentPos(); + DocPos const iSelAnchor = SciCall_GetAnchor(); + EditSetSelectionEx(max_p(iSelPos, iSelAnchor), iPos, -1, -1); + } else { + EditSetSelectionEx(end, iPos, -1, -1); + } + + if (!Globals.iSelectionMarkNumber && lpefr->bMarkOccurences) { + _FindHasMatch(hwnd, lpefr, 0, true); + } + else { + --Globals.iSelectionMarkNumber; + } + + if (iPos == end) { + _ShowZeroLengthCallTip(iPos); + } + if ((iPos + 1) == end) { + char const p = SciCall_GetCharAt(iPos); + char const e = SciCall_GetCharAt(end); + if (p == 0x0d && e == 0x0a) { + _ShowZeroLengthCallTip(iPos); + } + } + if (bFoundWrapAround) { + ShowWrapAroundCallTip(false); + } + + return true; +} + + +static int GetMarkAllOccSearchFlags(void) +{ + return (Settings.MarkOccurrencesMatchCase ? SCFIND_MATCHCASE : 0) | + ((Settings.MarkOccurrencesCurrentWord || Settings.MarkOccurrencesMatchWholeWords) ? SCFIND_WHOLEWORD : 0); +} + +//============================================================================= +// +// EditMarkAllOccurrences() +// +void EditMarkAllOccurrences(HWND hwnd, bool bForceClear) +{ + if (bForceClear) { + EditClearAllOccurrenceMarkers(hwnd); + } + + if (!IsMarkOccurrencesEnabled()) { + return; + } + + int const searchFlags = GetMarkAllOccSearchFlags(); + + if (Settings.MarkOccurrencesMatchVisible) { + + // get visible lines for update + DocLn const iStartLine = SciCall_DocLineFromVisible(SciCall_GetFirstVisibleLine()); + DocLn const iEndLine = min_ln((iStartLine + SciCall_LinesOnScreen()), Sci_GetLastDocLineNumber()); + DocPos const iPosStart = SciCall_PositionFromLine(iStartLine); + DocPos const iPosEnd = SciCall_GetLineEndPosition(iEndLine); + + // !!! don't clear all marks, else this method is re-called + // !!! on UpdateUI notification on drawing indicator mark + EditMarkAll(NULL, searchFlags, iPosStart, iPosEnd, false); + } else { + EditMarkAll(NULL, searchFlags, 0, Sci_GetDocEndPosition(), false); + } +} + + +//============================================================================= +// +// EditSelectionMultiSelectAll() +// +void EditSelectionMultiSelectAll(void) +{ + if (SciCall_GetSelText(NULL) > 0) { + SciCall_TargetWholeDocument(); + SciCall_SetSearchFlags(GetMarkAllOccSearchFlags()); + SciCall_MultipleSelectAddEach(); + SciCall_SetMainSelection(0); + if (SciCall_GetSelectionNAnchor(0) > SciCall_GetSelectionNCaret(0)) { + SciCall_SwapMainAnchorCaret(); + } + Sci_ScrollSelectionToView(); + } +} + + +//============================================================================= +// +// EditSelectionMultiSelectAllEx() +// +void EditSelectionMultiSelectAllEx(HWND hwnd, CLPCEDITFINDREPLACE edFndRpl) +{ + EDITFINDREPLACE efr = INIT_EFR_DATA; + DuplicateEFR(&efr, edFndRpl); + + if (IsWindow(Globals.hwndDlgFindReplace)) { + _SetSearchFlags(Globals.hwndDlgFindReplace, &efr); + } else { + efr.fuFlags = GetMarkAllOccSearchFlags(); + } + + LPCWSTR wchFind = _EditGetFindStrg(hwnd, &efr, false); + + if (StrIsNotEmpty(wchFind)) { + UndoTransActionBegin(); + EditMarkAll(wchFind, efr.fuFlags, 0, Sci_GetDocEndPosition(), true); + EndUndoTransAction(); + } + ReleaseEFR(&efr); +} + + +//============================================================================= +// +// EditReplace() +// +bool EditReplace(HWND hwnd, LPEDITFINDREPLACE lpefr) +{ + int iReplaceMsg = SciCall_GetChangeHistory() ? SCI_REPLACETARGETMINIMAL : SCI_REPLACETARGET; + DocPos const selBeg = SciCall_GetSelectionStart(); + DocPos const selEnd = SciCall_GetSelectionEnd(); + + // redo find to get group ranges filled + DocPos start = (SciCall_IsSelectionEmpty() ? SciCall_GetCurrentPos() : selBeg); + DocPos end = Sci_GetDocEndPosition(); + DocPos _start = start; + Globals.iReplacedOccurrences = 0; + + LPCWSTR wchFind = _EditGetFindStrg(hwnd, lpefr, false); + + if (StrIsEmpty(wchFind)) { + return false; + } + + char* const pszReplace = _GetReplaceString(hwnd, lpefr, &iReplaceMsg); + if (!pszReplace) { + return false; // recoding of clipboard canceled + } + + int const sFlags = (int)(lpefr->fuFlags); + DocPos const iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_NORM); + + // w/o selection, replacement string is put into current position + // but this maybe not intended here + if (SciCall_IsSelectionEmpty()) { + if ((iPos < 0LL) || (_start != start) || (_start != end)) { + // empty-replace was not intended + FreeMem(pszReplace); + if (iPos < 0LL) { + return EditFindNext(hwnd, lpefr, false, false, false); + } + EditSetSelectionEx(start, end, -1, -1); + return true; + } + } + // if selection is is not equal current find, set selection + else if ((selBeg != start) || (selEnd != end)) { + FreeMem(pszReplace); + SciCall_SetCurrentPos(selBeg); + return EditFindNext(hwnd, lpefr, false, false, false); + } + + UndoTransActionBegin(); + + SciCall_TargetFromSelection(); + DocPos const posTargetStart = SciCall_GetTargetStart(); + Sci_ReplaceTargetEx(iReplaceMsg, -1, pszReplace); + // move caret behind replacement + if (SCI_REPLACETARGETMINIMAL == iReplaceMsg) { + SciCall_SetCurrentPos(posTargetStart + strlen(pszReplace)); + } + else { + SciCall_SetCurrentPos(SciCall_GetTargetEnd()); + } + + Globals.iReplacedOccurrences = 1; + + EndUndoTransAction(); + + FreeMem(pszReplace); + + return EditFindNext(hwnd, lpefr, false, false, false); +} + + + +//============================================================================= +// +// EditReplaceAllInRange() +// +// +static DocPosU EditReplaceAllInRange(HWND hwnd, LPEDITFINDREPLACE lpefr, DocPos iStartPos, DocPos iEndPos, DocPos *enlargement) +{ + if (iStartPos > iEndPos) { + swapos(&iStartPos, &iEndPos); + } + DocPos const iOrigEndPos = iEndPos; // remember + + LPCWSTR wchFind = _EditGetFindStrg(hwnd, lpefr, false); + + if (StrIsEmpty(wchFind)) { + return 0; + } + + int const sFlags = (int)(lpefr->fuFlags); + bool const bIsRegExpr = (sFlags & SCFIND_REGEXP); + bool const bRegexStartOfLine = bIsRegExpr && (wchFind[0] == L'^'); + + // SCI_REPLACETARGET or SCI_REPLACETARGETRE + int iReplaceMsg = SCI_REPLACETARGET; + char* const pszReplace = _GetReplaceString(hwnd, lpefr, &iReplaceMsg); + if (!pszReplace) { + return 0; // recoding of clipboard canceled + } + + DocPos const _saveTargetBeg_ = SciCall_GetTargetStart(); + DocPos const _saveTargetEnd_ = SciCall_GetTargetEnd(); + + DocPos start = iStartPos; + DocPos end = iEndPos; + DocPos iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_NORM); + + if (bIsRegExpr && Sci_ConsumeRegexWarnStatus()) { + InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.MsgInvalidRegex, IDS_MUI_REGEX_INVALID); + return 0; + } + + DocPosU iCount = 0; + LimitNotifyEvents(); + UndoTransActionBegin(); + + while ((iPos >= 0LL) && (start <= iEndPos)) { + DocLn const lnCnt = bRegexStartOfLine ? SciCall_GetLineCount() : 0; + SciCall_SetTargetRange(iPos, end); + DocPos const replLen = Sci_ReplaceTargetEx(iReplaceMsg, -1, pszReplace); + ++iCount; + // start next search behind replacement + if (SCI_REPLACETARGETMINIMAL == iReplaceMsg) { + DocPos const replLength = strlen(pszReplace); + iStartPos = iPos + replLength; + iEndPos += replLength - (end - iPos); + } + else { + iStartPos = SciCall_GetTargetEnd(); + if (bRegexStartOfLine && (SciCall_GetLineCount() == lnCnt) && (Sci_GetLineStartPosition(iStartPos) == iStartPos)) { + iStartPos = SciCall_PositionAfter(iStartPos); + } + iEndPos += replLen - (end - iPos); + } + start = iStartPos; + end = iEndPos; + iPos = (start <= end) ? _FindInTarget(wchFind, sFlags, &start, &end, true, FRMOD_NORM) : NOT_FOUND; + } + + EndUndoTransAction(); + + FreeMem(pszReplace); + + *enlargement = (iEndPos - iOrigEndPos); + SciCall_SetTargetRange(_saveTargetBeg_, _saveTargetEnd_ + *enlargement); //restore + + RestoreNotifyEvents(); + + return iCount; +} + + +//============================================================================= +// +// EditReplaceAll() +// +bool EditReplaceAll(HWND hwnd, LPEDITFINDREPLACE lpefr, bool bShowInfo) +{ + DocPos const start = 0; + DocPos const end = Sci_GetDocEndPosition(); + DocPos enlargement = 0; + + BeginWaitCursorUID(true, IDS_MUI_SB_REPLACE_ALL); + Globals.iReplacedOccurrences = EditReplaceAllInRange(hwnd, lpefr, start, end, &enlargement); + EndWaitCursor(); + + WCHAR wchOcc[64] = { L'\0' }; + StringCchPrintf(wchOcc, COUNTOF(wchOcc), DOCPOSFMTW, Globals.iReplacedOccurrences); + FormatNumberStr(wchOcc, COUNTOF(wchOcc), 0); + + if (bShowInfo) { + if (Globals.iReplacedOccurrences) { + InfoBoxLng(MB_OK, Constants.SuppressKey.MsgReplaceCount, IDS_MUI_REPLCOUNT, wchOcc); + } else { + InfoBoxLng(MB_OK, Constants.SuppressKey.MsgNotFound, IDS_MUI_NOTFOUND); + } + } + + return (bool)Globals.iReplacedOccurrences; +} + + +//============================================================================= +// +// EditReplaceAllInSelection() +// +bool EditReplaceAllInSelection(HWND hwnd, LPEDITFINDREPLACE lpefr, bool bShowInfo) +{ + if (Sci_IsMultiOrRectangleSelection()) { + InfoBoxLng(MB_ICONWARNING, NULL, IDS_MUI_SELRECTORMULTI); + return false; + } + + const DocPos start = SciCall_GetSelectionStart(); + const DocPos end = SciCall_GetSelectionEnd(); + const DocPos currPos = SciCall_GetCurrentPos(); + const DocPos anchorPos = SciCall_GetAnchor(); + DocPos enlargement = 0; + + BeginWaitCursorUID(true, IDS_MUI_SB_REPLACE_ALL); + Globals.iReplacedOccurrences = EditReplaceAllInRange(hwnd, lpefr, start, end, &enlargement); + EndWaitCursor(); + + if (Globals.iReplacedOccurrences) { + if (currPos < anchorPos) { + SciCall_SetSel(anchorPos + enlargement, currPos); + } else { + SciCall_SetSel(anchorPos, currPos + enlargement); + } + if (bShowInfo) { + WCHAR wchOcc[64] = { L'\0' }; + StringCchPrintf(wchOcc, COUNTOF(wchOcc), DOCPOSFMTW, Globals.iReplacedOccurrences); + FormatNumberStr(wchOcc, COUNTOF(wchOcc), 0); + InfoBoxLng(MB_OK, Constants.SuppressKey.MsgReplaceCount, IDS_MUI_REPLCOUNT, wchOcc); + } + } + else if (bShowInfo) { + InfoBoxLng(MB_OK, Constants.SuppressKey.MsgNotFound, IDS_MUI_NOTFOUND); + } + + return (bool)Globals.iReplacedOccurrences; +} + + + +//============================================================================= +// +// EditClearAllOccurrenceMarkers() +// +void EditClearAllOccurrenceMarkers(HWND hwnd) +{ + UNREFERENCED_PARAMETER(hwnd); + + LimitNotifyEvents(); + + SciCall_SetIndicatorCurrent(INDIC_NP3_MARK_OCCURANCE); + SciCall_IndicatorClearRange(0, Sci_GetDocEndPosition()); + + SciCall_MarkerDeleteAll(MARKER_NP3_OCCURRENCE); + + Globals.iSelectionMarkNumber = Globals.iMarkOccurrencesCount = 0; + + RestoreNotifyEvents(); +} + + +//============================================================================= +// +// EditMarkAll() +// Mark all occurrences of the matching text in range (by Aleksandar Lekov) +// +static void EditMarkAll(LPCWSTR wchFind, int sFlags, DocPos rangeStart, DocPos rangeEnd, bool bMultiSel) +{ + char chText[FNDRPL_BUFFER] = { L'\0' }; + WCHAR wchText[FNDRPL_BUFFER] = { L'\0' }; + + DocPos iFindLength = 0; + + LimitNotifyEvents(); + + if (StrIsEmpty(wchFind)) { + + WideCharToMultiByte(Encoding_SciCP, 0, wchFind, -1, chText, COUNTOF(chText), NULL, NULL); + + if (SciCall_IsSelectionEmpty()) { + // nothing selected, get word under caret if flagged + if (Settings.MarkOccurrencesCurrentWord && (sFlags & SCFIND_WHOLEWORD)) { + DocPos const iCurPos = SciCall_GetCurrentPos(); + DocPos iWordStart = SciCall_WordStartPosition(iCurPos, true); + DocPos iWordEnd = SciCall_WordEndPosition(iCurPos, true); + if (iWordStart == iWordEnd) { + goto observe; + } + iFindLength = (iWordEnd - iWordStart); + + StringCchCopyNA(chText, COUNTOF(chText), SciCall_GetRangePointer(iWordStart, iFindLength), iFindLength); + + } else { + goto observe; // no pattern, no selection and no word mark chosen + } + } else { // we have a selection + + if (Sci_IsMultiSelection()) { + goto observe; + } + + // get current selection + DocPos const iSelStart = SciCall_GetSelectionStart(); + DocPos const iSelEnd = SciCall_GetSelectionEnd(); + //DocPos const iSelCount = (iSelEnd - iSelStart); + + // if multiple lines are selected exit + if (SciCall_LineFromPosition(iSelStart) != SciCall_LineFromPosition(iSelEnd)) { + goto observe; + } + + DocPosU const iSelLen = SciCall_GetSelText(NULL); + if (iSelLen >= COUNTOF(chText)) { + goto observe; + } + + iFindLength = SciCall_GetSelText(chText); + chText[iFindLength] = '\0'; + + // exit if selection is not a word and Match whole words only is enabled + if ((sFlags & SCFIND_WHOLEWORD) && EditContainsWordDelimiter(chText, iSelLen + 1)) { + goto observe; + } + } + + MultiByteToWideChar(Encoding_SciCP, 0, chText, (int)iFindLength, wchText, (int)COUNTOF(wchText)); + + } else { + StringCchCopy(wchText, COUNTOF(wchText), wchFind); + } + + if (StrIsNotEmpty(wchText)) { + + if (bMultiSel) { + SciCall_ClearSelections(); + } + DocPos const iSelStart = SciCall_GetSelectionStart(); + DocPos const iSelEnd = SciCall_GetSelectionEnd(); + + DocPos const iTextEnd = Sci_GetDocEndPosition(); + rangeStart = max_p(0, rangeStart); + rangeEnd = min_p(rangeEnd, iTextEnd); + + DocPos start = rangeStart; + DocPos end = rangeEnd; + DocPos iPos = _FindInTarget(wchText, sFlags, &start, &end, false, FRMOD_NORM); + + if (!bMultiSel) { + SciCall_SetIndicatorCurrent(INDIC_NP3_MARK_OCCURANCE); // once: doc-change notifications are disabled (LimitNotifyEvents) + } + + DocPosU count = 0; + DocPosU found = 0; + while ((iPos >= 0LL) && (start <= rangeEnd)) { + + if (bMultiSel) { + if (count) { + SciCall_AddSelection(end, iPos); + } else { + SciCall_SetSelection(end, iPos); + } + } else { + // mark this match if not done before + SciCall_IndicatorFillRange(iPos, (end - start)); + SciCall_MarkerAdd(SciCall_LineFromPosition(iPos), MARKER_NP3_OCCURRENCE); + } + ++count; + if (!found && ((iSelStart <= end) && (start <= iSelEnd))) { + // intersect = (max_p(iSelStart, start) < min_p(iSelEnd, end)) + found = count; + } + start = end; + end = rangeEnd; + iPos = _FindInTarget(wchText, sFlags, &start, &end, true, FRMOD_NORM); + }; + Globals.iSelectionMarkNumber = found; + Globals.iMarkOccurrencesCount = count; + assert(!bMultiSel || (SciCall_GetSelections() == count)); + } + +observe: + + RestoreNotifyEvents(); +} + + +// Decode \0oo without treating a lone \0 as an escape instead of a backreference. +static void _UnSlashLowOctalA(LPSTR s) +{ + LPSTR o = s; + while (*s) { + if ((s[0] == '\\') && (s[1] == '\\')) { + *o++ = *s++; + *o = *s; + } else if ((s[0] == '\\') && (s[1] == '0') && IsOctalDigitA(s[2]) && IsOctalDigitA(s[3])) { + *o = (CHAR)(8 * (s[2] - '0') + (s[3] - '0')); + s += 3; + } else { + *o = *s; + } + ++o; + if (*s) { + ++s; + } + } + *o = '\0'; +} + +static int _CheckRegExReplTargetA(LPCSTR pszInput) +{ + while (*pszInput) { + if (*pszInput == '$') { + ++pszInput; + if (((*pszInput >= '0') && (*pszInput <= '9')) || (*pszInput == '+') || (*pszInput == '{')) { + return SCI_REPLACETARGETRE; + } + } else if (*pszInput == '\\') { + ++pszInput; + if ((*pszInput >= '0') && (*pszInput <= '9')) { + return SCI_REPLACETARGETRE; + } + } else { + ++pszInput; + } + } + return SciCall_GetChangeHistory() ? SCI_REPLACETARGETMINIMAL : SCI_REPLACETARGET; +} + +static void _TransformReplaceBackslashes(LPSTR pszInput, bool bRegEx, int* iReplaceMsg) +{ + if (bRegEx) { + _UnSlashLowOctalA(pszInput); + *iReplaceMsg = _CheckRegExReplTargetA(pszInput); + } else { + *iReplaceMsg = SciCall_GetChangeHistory() ? SCI_REPLACETARGETMINIMAL : SCI_REPLACETARGET; + } + if (*iReplaceMsg != SCI_REPLACETARGETRE) { + UnSlashA(pszInput, CP_UTF8); + } +} diff --git a/src/FindReplace.h b/src/FindReplace.h new file mode 100644 index 0000000000..0cb1a6abb6 --- /dev/null +++ b/src/FindReplace.h @@ -0,0 +1,53 @@ +// encoding: UTF-8 +/****************************************************************************** +* * +* Notepad3 * +* * +* FindReplace.h * +* Find/Replace and occurrence matching * +* * +* (c) Rizonesoft 2008-2026 * +* https://rizonesoft.com * +* * +*******************************************************************************/ +#pragma once +#ifndef _NP3_FINDREPLACE_H_ +#define _NP3_FINDREPLACE_H_ + +#include "TypeDefs.h" + +typedef struct { + RECT windowRect; + bool bFocusedView; + bool bReplace; +} FindReplaceDlgRestore; + +void FindReplaceInit(void); +void FindReplaceRelease(void); +bool IsFindPatternEmpty(void); +LPCWSTR GetFindPattern(void); +void SetFindPattern(LPCWSTR wchFindPattern); +size_t LengthOfFindPattern(void); +void ReleaseEFR(LPEDITFINDREPLACE efr); + +LPEDITFINDREPLACE FindReplacePrepare(void); +LPEDITFINDREPLACE FindReplaceUseSelection(void); +void FindReplaceShowDialog(bool bReplace); +bool FindReplaceCaptureDialog(FindReplaceDlgRestore* pRestore); +void FindReplaceRestoreDialog(const FindReplaceDlgRestore* pRestore); + +bool EditFindNext(HWND hwnd, const LPEDITFINDREPLACE lpefr, bool bExtendSelection, bool bFocusWnd, bool bFillEmpty); +bool EditFindPrev(HWND hwnd, const LPEDITFINDREPLACE lpefr, bool bExtendSelection, bool bFocusWnd, bool bFillEmpty); +bool EditReplace(HWND hwnd, LPEDITFINDREPLACE lpefr); +bool EditReplaceAll(HWND hwnd, LPEDITFINDREPLACE lpefr, bool bShowInfo); +bool EditReplaceAllInSelection(HWND hwnd, LPEDITFINDREPLACE lpefr, bool bShowInfo); + +// Background matching does not update the Find/Replace status. +DocPos EditFindInTarget(LPCWSTR wchFind, int sFlags, DocPos* begin, DocPos* end, bool bForceNext); + +void EditMarkAllOccurrences(HWND hwnd, bool bForceClear); +void EditClearAllOccurrenceMarkers(HWND hwnd); +void EditSelectionMultiSelectAll(void); +void EditSelectionMultiSelectAllEx(HWND hwnd, CLPCEDITFINDREPLACE edFndRpl); + +#endif //_NP3_FINDREPLACE_H_ diff --git a/src/Helpers.c b/src/Helpers.c index bdcd168e05..4b37ab4abd 100644 --- a/src/Helpers.c +++ b/src/Helpers.c @@ -833,6 +833,24 @@ void GetSystemStatusFontA(LPSTR fontFaceName_out, bool bForceRefresh) } +int GetSubMenuPosByChildCmd(HMENU hParent, UINT childCmdId) +{ + int const count = GetMenuItemCount(hParent); + for (int i = 0; i < count; ++i) { + HMENU const hSub = GetSubMenu(hParent, i); + if (hSub) { + int const subCount = GetMenuItemCount(hSub); + for (int j = 0; j < subCount; ++j) { + if (GetMenuItemID(hSub, j) == childCmdId) { + return i; + } + } + } + } + return -1; +} + + //============================================================================= // // Update every occurrence, including aliases in nested submenus. @@ -1834,63 +1852,6 @@ UINT CharSetFromCodePage(const UINT uCodePage) } #endif -/** - * Convert C style \0oo into their indicated characters. - * This is used to get control characters into the regular expresion engine - * w/o interfering with group referencing ('\0'). - */ -ptrdiff_t UnSlashLowOctalA(LPSTR s) -{ - LPSTR sStart = s; - LPSTR o = s; - while (*s) { - if ((s[0] == '\\') && (s[1] == '\\')) { // esc seq - *o = *s; - ++o; - ++s; - *o = *s; - } else if ((s[0] == '\\') && (s[1] == '0') && IsOctalDigitA(s[2]) && IsOctalDigitA(s[3])) { - *o = (CHAR)(8 * (s[2] - '0') + (s[3] - '0')); - s += 3; - } else { - *o = *s; - } - ++o; - if (*s) { - ++s; - } - } - *o = '\0'; - return (ptrdiff_t)(o - sStart); -} - - -ptrdiff_t UnSlashLowOctalW(LPWSTR s) -{ - LPWSTR sStart = s; - LPWSTR o = s; - while (*s) { - if ((s[0] == L'\\') && (s[1] == L'\\')) { // esc seq - *o = *s; - ++o; - ++s; - *o = *s; - } else if ((s[0] == L'\\') && (s[1] == L'0') && IsOctalDigitW(s[2]) && IsOctalDigitW(s[3])) { - *o = (WCHAR)(8 * (s[2] - L'0') + (s[3] - L'0')); - s += 3; - } else { - *o = *s; - } - ++o; - if (*s) { - ++s; - } - } - *o = L'\0'; - return (ptrdiff_t)(o - sStart); -} - - /** ****************************************************************************** * * UnSlash functions @@ -2216,85 +2177,6 @@ size_t UnSlashCharW(LPWSTR pchInOut, WCHAR wch) } -/** - * check, if we have regex sub-group referencing - */ -static int _CheckRegExReplTargetA(LPSTR pszInput) -{ - while (*pszInput) { - if (*pszInput == '$') { - ++pszInput; - if (((*pszInput >= '0') && (*pszInput <= '9')) || (*pszInput == '+') || (*pszInput == '{')) { - return SCI_REPLACETARGETRE; - } - } else if (*pszInput == '\\') { - ++pszInput; - if ((*pszInput >= '0') && (*pszInput <= '9')) { - return SCI_REPLACETARGETRE; - } - } else { - ++pszInput; - } - } - return SciCall_GetChangeHistory() ? SCI_REPLACETARGETMINIMAL : SCI_REPLACETARGET; -} - -static int _CheckRegExReplTargetW(LPWSTR pszInput) -{ - while (*pszInput) { - if (*pszInput == L'$') { - ++pszInput; - if (((*pszInput >= L'0') && (*pszInput <= L'9')) || (*pszInput == L'+') || (*pszInput == L'{')) { - return SCI_REPLACETARGETRE; - } - } else if (*pszInput == L'\\') { - ++pszInput; - if ((*pszInput >= L'0') && (*pszInput <= L'9')) { - return SCI_REPLACETARGETRE; - } - } else { - ++pszInput; - } - } - return SciCall_GetChangeHistory() ? SCI_REPLACETARGETMINIMAL : SCI_REPLACETARGET; -} - - -void TransformBackslashesA(LPSTR pszInput, bool bRegEx, UINT cpEdit, int* iReplaceMsg) -{ - if (iReplaceMsg) { - if (bRegEx) { - UnSlashLowOctalA(pszInput); - *iReplaceMsg = _CheckRegExReplTargetA(pszInput); - } else { - *iReplaceMsg = SciCall_GetChangeHistory() ? SCI_REPLACETARGETMINIMAL : SCI_REPLACETARGET; - } - } - // regex handles backslashes itself - bool const bStdReplace = (iReplaceMsg && (SCI_REPLACETARGETRE != *iReplaceMsg)); - if (!bRegEx || bStdReplace) { - UnSlashA(pszInput, cpEdit); - } -} - -void TransformBackslashesW(LPWSTR pszInput, bool bRegEx, UINT cpEdit, int* iReplaceMsg) -{ - if (iReplaceMsg) { - if (bRegEx) { - UnSlashLowOctalW(pszInput); - *iReplaceMsg = _CheckRegExReplTargetW(pszInput); - } else { - *iReplaceMsg = SciCall_GetChangeHistory() ? SCI_REPLACETARGETMINIMAL : SCI_REPLACETARGET; - } - } - // regex handles backslashes itself - bool const bStdReplace = (iReplaceMsg && (SCI_REPLACETARGETRE != *iReplaceMsg)); - if (!bRegEx || bStdReplace) { - UnSlashW(pszInput, cpEdit); - } -} - - #if 0 void TransformMetaChars(char* pszInput, size_t cch, bool bRegEx, int iEOLMode) { diff --git a/src/Helpers.h b/src/Helpers.h index 1ca0d976d1..bb20f6c245 100644 --- a/src/Helpers.h +++ b/src/Helpers.h @@ -464,6 +464,8 @@ void GetSystemMessageFontA(LPSTR fontFaceName_out, bool bForceRefresh); void GetSystemStatusFontA(LPSTR fontFaceName_out, bool bForceRefresh); bool IsCmdEnabled(HWND hwnd, UINT uId); +// Zero-based position of the first submenu directly containing childCmdId, or -1. +int GetSubMenuPosByChildCmd(HMENU hParent, UINT childCmdId); BOOL EnableMenuCommand(HMENU hmenu, UINT uId, bool enabled); DWORD CheckMenuCommand(HMENU hmenu, UINT uId, bool checked); @@ -564,8 +566,6 @@ size_t UnSlashCharW(LPWSTR pchInOut, WCHAR wch); size_t SlashCtrlW(LPWSTR pchOutput, size_t cchOutLen, LPCWSTR pchInput); size_t UnSlashCtrlW(LPWSTR pchInOut); -void TransformBackslashesA(LPSTR pszInput, bool bRegEx, UINT cpEdit, int *iReplaceMsg); -void TransformBackslashesW(LPWSTR pszInput, bool bRegEx, UINT cpEdit, int *iReplaceMsg); //void TransformMetaChars(char *pszInput, size_t cch, bool bRegEx, int iEOLMode); diff --git a/src/Notepad3.c b/src/Notepad3.c index a73e4ecbaf..b6680542ac 100644 --- a/src/Notepad3.c +++ b/src/Notepad3.c @@ -41,12 +41,12 @@ #include "uthash/utlist.h" #include "tinyexprcpp/tinyexpr_cif.h" #include "Encoding.h" +#include "FindReplace.h" #include "VersionEx.h" #include "MuiLanguage.h" #include "Notepad3.h" #include "Config/Config.h" #include "DarkMode/DarkMode.h" -#include "Notepad3Util.h" #include "StyleLexers/EditLexer.h" #if (defined(_DEBUG) || defined(DEBUG)) && !defined(NDEBUG) @@ -208,8 +208,6 @@ static int s_cxEditFrame = 0; static int s_cyEditFrame = 0; static bool s_bUndoRedoScroll = false; -// Auto-scroll state moved to Notepad3Util.c - // for tiny expression calculation static double s_dExpression = 0.0; static te_int_t s_iExprError = -1; @@ -240,7 +238,6 @@ const char* const _assert_msg = "Broken UndoRedo-Transaction!"; // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // (!) ENSURE IDT_FILE_NEW -> IDT_VIEW_NEW_WINDOW corresponds to order of Toolbar.bmp -// NUMTOOLBITMAPS defined in Notepad3Util.h // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ static TBBUTTON s_tbbMainWnd[] = { @@ -339,7 +336,6 @@ void SetSaveDone() //============================================================================== // current find pattern -static HSTRINGW s_hstrCurrentFindPattern = NULL; // ---------------------------------------------------------------------------- @@ -1005,7 +1001,7 @@ static void _InitGlobals() s_hpthRelaunchElevatedFile = Path_Allocate(NULL); ThemesItems_Init(); - s_hstrCurrentFindPattern = StrgCreate(NULL); + FindReplaceInit(); s_pthArgFilePath = Path_Allocate(NULL); s_pthCheckFilePath = Path_Allocate(NULL); @@ -1175,7 +1171,7 @@ static void _CleanUpResources(const HWND hwnd, bool bIsInitialized) Path_Release(s_pthArgFilePath); Path_Release(s_pthCheckFilePath); - StrgDestroy(s_hstrCurrentFindPattern); + FindReplaceRelease(); ThemesItems_Release(); Path_Release(s_hpthRelaunchElevatedFile); @@ -1912,140 +1908,6 @@ static SIZE _StatusCalcTextSize(HWND hwnd, LPCWSTR lpsz) } -//============================================================================= -// -// Set/Get FindPattern() -// - -bool IsFindPatternEmpty() -{ - return StrgIsEmpty(s_hstrCurrentFindPattern); -} - -//============================================================================= -// -// GetFindPatternMB() -// -LPCWSTR GetFindPattern() -{ - return StrgGet(s_hstrCurrentFindPattern); -} - -//============================================================================= -// -// GetFindPatternMB() -// -void GetFindPatternMB(LPSTR chPattern, int cch) -{ - StrgGetAsUTF8(s_hstrCurrentFindPattern, chPattern, cch); -} - -//============================================================================= -// -// SetFindPattern() -// -void SetFindPattern(LPCWSTR wchFindPattern) -{ - StrgReset(s_hstrCurrentFindPattern, StrIsNotEmpty(wchFindPattern) ? wchFindPattern : L""); -} - -//============================================================================= -// -// SetFindPatternMB() -// -void SetFindPatternMB(LPCSTR chFindPattern) -{ - StrgResetFromUTF8(s_hstrCurrentFindPattern, !StrIsEmptyA(chFindPattern) ? chFindPattern : ""); -} - -//============================================================================= -// -// LengthOfFindPattern() -// -size_t LengthOfFindPattern() -{ - return StrgGetLength(s_hstrCurrentFindPattern); -} - -//============================================================================= -// -// LengthOfFindPatternMB() -// -size_t LengthOfFindPatternMB() -{ - return (size_t)StrgGetAsUTF8(s_hstrCurrentFindPattern, NULL, 0); -} - -// ---------------------------------------------------------------------------- - -static EDITFINDREPLACE s_FindReplaceData = INIT_EFR_DATA; - -//============================================================================= -// -// SetFindReplaceData() -// -static void SetFindReplaceData() -{ - // init find pattern with current - if (!IsFindPatternEmpty()) { - StrgReset(Settings.EFR_Data.chFindPattern, GetFindPattern()); - } - // copy settings to working data - DuplicateEFR(&s_FindReplaceData, &(Settings.EFR_Data)); - - if (g_flagMatchText) { // cmd line - if (g_flagMatchText & 4) { - s_FindReplaceData.fuFlags = (SCFIND_REGEXP | SCFIND_POSIX); - } else { - // /m without R flag: force text mode (clear regex flags) - fixes #5060 - s_FindReplaceData.fuFlags &= ~(SCFIND_REGEXP | SCFIND_POSIX); - } - if (g_flagMatchText & 8) { - s_FindReplaceData.fuFlags |= SCFIND_MATCHCASE; - } - if (g_flagMatchText & 16) { - s_FindReplaceData.fuFlags |= SCFIND_DOT_MATCH_ALL; - } - if (g_flagMatchText & 32) { - s_FindReplaceData.bTransformBS = true; - } - s_FindReplaceData.bRegExprSearch = (s_FindReplaceData.fuFlags & SCFIND_REGEXP); - s_FindReplaceData.bWildcardSearch = false; - s_FindReplaceData.bReplaceClose = false; - } -} - - -//============================================================================= -// -// SetCurrentSelAsFindReplaceData() -// -static bool SetCurrentSelAsFindReplaceData(LPEDITFINDREPLACE lpefr) -{ - if (SciCall_IsSelectionEmpty()) { - EditSelectWordAtPos(SciCall_GetCurrentPos(), true); - } - - size_t const cchSelection = SciCall_GetSelText(NULL); - - if (0 < cchSelection) { - char* const szSelection = AllocMem((cchSelection + 1), HEAP_ZERO_MEMORY); - if (szSelection) { - SciCall_GetSelText(szSelection); - - SetFindPatternMB(szSelection); - SetFindReplaceData(); // s_FindReplaceData - if (lpefr) { - StrgReset(lpefr->chFindPattern, GetFindPattern()); - } - - FreeMem(szSelection); - return true; - } - } - return false; -} - //============================================================================= // // InitApplication() @@ -2438,18 +2300,18 @@ HWND InitInstance(const HINSTANCE hInstance, int nCmdShow) if (g_flagMatchText && !IsFindPatternEmpty()) { if (!Sci_IsDocEmpty()) { - SetFindReplaceData(); // s_FindReplaceData + LPEDITFINDREPLACE const lpefr = FindReplacePrepare(); if (g_flagMatchText & 2) { if (!s_flagJumpTo) { Sci_SetCaretScrollDocEnd(); } - EditFindPrev(Globals.hwndEdit, &s_FindReplaceData, false, false, false); + EditFindPrev(Globals.hwndEdit, lpefr, false, false, false); } else { if (!s_flagJumpTo) { SciCall_DocumentStart(); } - EditFindNext(Globals.hwndEdit, &s_FindReplaceData, false, false, false); + EditFindNext(Globals.hwndEdit, lpefr, false, false, false); } } } @@ -2750,15 +2612,118 @@ LRESULT CALLBACK MainWndProc(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) } -// _SetWrapStartIndent, _SetWrapIndentMode, _SetWrapVisualFlags moved to Notepad3Util.c +//============================================================================= +// +// Auto-Scroll (middle-click continuous scroll, Firefox-style) +// + +#define ID_AUTOSCROLLTIMER (0xA004) +#define AUTOSCROLL_TIMER_MS 30 +#define AUTOSCROLL_DEADZONE 15 +#define AUTOSCROLL_DIVISOR 60.0 +#define AUTOSCROLL_CLICK_THRESHOLD_MS 200 + +static bool s_bAutoScrollMode = false; +static bool s_bAutoScrollHeld = false; +static ULONGLONG s_dwAutoScrollStartTick = 0; +static POINT s_ptAutoScrollOrigin = { 0, 0 }; +static POINT s_ptAutoScrollMouse = { 0, 0 }; +static double s_dAutoScrollAccumY = 0.0; + +static bool _IsAutoScrollMode(void) +{ + return s_bAutoScrollMode; +} + +static bool _IsAutoScrollHeld(void) +{ + return s_bAutoScrollHeld; +} + +static ULONGLONG _GetAutoScrollStartTick(void) +{ + return s_dwAutoScrollStartTick; +} + +static void _SetAutoScrollHeld(bool held) +{ + s_bAutoScrollHeld = held; +} + +static void _AutoScrollUpdateMouse(POINT pt) +{ + s_ptAutoScrollMouse = pt; +} //============================================================================= // -// Auto-Scroll (middle-click continuous scroll, Firefox-style) +// _AutoScrollStop() +// +static void _AutoScrollStop(HWND hwndEdit) +{ + if (s_bAutoScrollMode) { + KillTimer(hwndEdit, ID_AUTOSCROLLTIMER); + ReleaseCapture(); + SciCall_SetCursor(SC_CURSORNORMAL); + s_bAutoScrollMode = false; + s_bAutoScrollHeld = false; + s_dAutoScrollAccumY = 0.0; + } +} + + +//============================================================================= +// +// _AutoScrollTimerProc() +// +static void CALLBACK _AutoScrollTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) +{ + UNREFERENCED_PARAMETER(uMsg); + UNREFERENCED_PARAMETER(idEvent); + UNREFERENCED_PARAMETER(dwTime); + + if (!s_bAutoScrollMode) { + KillTimer(hwnd, ID_AUTOSCROLLTIMER); + return; + } + + int const deltaY = s_ptAutoScrollMouse.y - s_ptAutoScrollOrigin.y; + + if (abs(deltaY) <= AUTOSCROLL_DEADZONE) { + s_dAutoScrollAccumY = 0.0; + return; + } + + // Speed: proportional to distance beyond dead zone + double const speed = (double)(deltaY - (deltaY > 0 ? AUTOSCROLL_DEADZONE : -AUTOSCROLL_DEADZONE)) / AUTOSCROLL_DIVISOR; + s_dAutoScrollAccumY += speed; + + DocLn const linesToScroll = (DocLn)s_dAutoScrollAccumY; + if (linesToScroll != 0) { + SciCall_LineScroll(0, linesToScroll); + s_dAutoScrollAccumY -= (double)linesToScroll; + } +} + + +//============================================================================= // +// _AutoScrollStart() +// +static void _AutoScrollStart(HWND hwndEdit, POINT pt) +{ + s_bAutoScrollMode = true; + s_bAutoScrollHeld = false; + s_dwAutoScrollStartTick = GetTickCount64(); + s_ptAutoScrollOrigin = pt; + s_ptAutoScrollMouse = pt; + s_dAutoScrollAccumY = 0.0; + SetCapture(hwndEdit); + SetCursor(LoadCursor(NULL, IDC_SIZEALL)); + SetTimer(hwndEdit, ID_AUTOSCROLLTIMER, AUTOSCROLL_TIMER_MS, _AutoScrollTimerProc); +} -// _AutoScrollStop, _AutoScrollTimerProc, _AutoScrollStart moved to Notepad3Util.c static LRESULT CALLBACK _EditSubclassProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, @@ -2769,30 +2734,30 @@ static LRESULT CALLBACK _EditSubclassProc( switch (uMsg) { case WM_MBUTTONDOWN: { - if (NP3Util_IsAutoScrollMode()) { - NP3Util_AutoScrollStop(hwnd); + if (_IsAutoScrollMode()) { + _AutoScrollStop(hwnd); } else { POINT const pt = POINTFromLParam(lParam); DocPos const pos = SciCall_CharPositionFromPointClose(pt.x, pt.y); if ((pos >= 0) && SciCall_IndicatorValueAt(INDIC_NP3_HYPERLINK, pos)) { HandleHotSpotURLClicked(pos, OPEN_WITH_BROWSER); } else { - NP3Util_SetAutoScrollHeld(true); - NP3Util_AutoScrollStart(hwnd, pt); + _SetAutoScrollHeld(true); + _AutoScrollStart(hwnd, pt); } } return 0; } case WM_MBUTTONUP: { - if (NP3Util_IsAutoScrollMode() && NP3Util_IsAutoScrollHeld()) { - ULONGLONG const elapsed = GetTickCount64() - NP3Util_GetAutoScrollStartTick(); + if (_IsAutoScrollMode() && _IsAutoScrollHeld()) { + ULONGLONG const elapsed = GetTickCount64() - _GetAutoScrollStartTick(); if (elapsed > AUTOSCROLL_CLICK_THRESHOLD_MS) { // Hold-to-scroll: stop on release - NP3Util_AutoScrollStop(hwnd); + _AutoScrollStop(hwnd); } else { // Quick click: keep scrolling (toggle mode) - NP3Util_SetAutoScrollHeld(false); + _SetAutoScrollHeld(false); } return 0; } @@ -2800,8 +2765,8 @@ static LRESULT CALLBACK _EditSubclassProc( } case WM_MOUSEMOVE: - if (NP3Util_IsAutoScrollMode()) { - NP3Util_AutoScrollUpdateMouse(POINTFromLParam(lParam)); + if (_IsAutoScrollMode()) { + _AutoScrollUpdateMouse(POINTFromLParam(lParam)); SetCursor(LoadCursor(NULL, IDC_SIZEALL)); // maintain four-way arrow return 0; } @@ -2809,29 +2774,29 @@ static LRESULT CALLBACK _EditSubclassProc( case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: - if (NP3Util_IsAutoScrollMode()) { - NP3Util_AutoScrollStop(hwnd); + if (_IsAutoScrollMode()) { + _AutoScrollStop(hwnd); return 0; } break; case WM_MOUSEWHEEL: - if (NP3Util_IsAutoScrollMode()) { - NP3Util_AutoScrollStop(hwnd); + if (_IsAutoScrollMode()) { + _AutoScrollStop(hwnd); return 0; } break; case WM_SETCURSOR: - if (NP3Util_IsAutoScrollMode()) { + if (_IsAutoScrollMode()) { SetCursor(LoadCursor(NULL, IDC_SIZEALL)); return TRUE; } break; case WM_CAPTURECHANGED: - if (NP3Util_IsAutoScrollMode() && ((HWND)lParam != hwnd)) { - NP3Util_AutoScrollStop(hwnd); + if (_IsAutoScrollMode() && ((HWND)lParam != hwnd)) { + _AutoScrollStop(hwnd); } break; @@ -2844,6 +2809,98 @@ static LRESULT CALLBACK _EditSubclassProc( } +//============================================================================= +// +// _SetWrapStartIndent() +// +static void _SetWrapStartIndent(void) +{ + int i = 0; + switch (Settings.WordWrapIndent) { + case 1: + i = 1; + break; + case 2: + i = 2; + break; + case 3: + i = (Globals.fvCurFile.iIndentWidth) ? 1 * Globals.fvCurFile.iIndentWidth : 1 * Globals.fvCurFile.iTabWidth; + break; + case 4: + i = (Globals.fvCurFile.iIndentWidth) ? 2 * Globals.fvCurFile.iIndentWidth : 2 * Globals.fvCurFile.iTabWidth; + break; + default: + break; + } + SciCall_SetWrapStartIndent(i); +} + + +//============================================================================= +// +// _SetWrapIndentMode() +// +static void _SetWrapIndentMode(void) +{ + BeginWaitCursorUID(Flags.bHugeFileLoadState, IDS_MUI_SB_WRAP_LINES); + + Sci_SetWrapModeEx(GET_WRAP_MODE()); + + if (Settings.WordWrapIndent == 5) { + SciCall_SetWrapIndentMode(SC_WRAPINDENT_SAME); + } else if (Settings.WordWrapIndent == 6) { + SciCall_SetWrapIndentMode(SC_WRAPINDENT_INDENT); + } else if (Settings.WordWrapIndent == 7) { + SciCall_SetWrapIndentMode(SC_WRAPINDENT_DEEPINDENT); + } else { + _SetWrapStartIndent(); + SciCall_SetWrapIndentMode(SC_WRAPINDENT_FIXED); + } + + EndWaitCursor(); +} + + +//============================================================================= +// +// _SetWrapVisualFlags() +// +static void _SetWrapVisualFlags(HWND hwndEditCtrl) +{ + UNREFERENCED_PARAMETER(hwndEditCtrl); + + if (Settings.ShowWordWrapSymbols) { + int wrapVisualFlags = 0; + int wrapVisualFlagsLocation = 0; + if (Settings.WordWrapSymbols == 0) { + Settings.WordWrapSymbols = 22; + } + switch (Settings.WordWrapSymbols % 10) { + case 1: + wrapVisualFlags |= SC_WRAPVISUALFLAG_END; + wrapVisualFlagsLocation |= SC_WRAPVISUALFLAGLOC_END_BY_TEXT; + break; + case 2: + wrapVisualFlags |= SC_WRAPVISUALFLAG_END; + break; + } + switch (((Settings.WordWrapSymbols % 100) - (Settings.WordWrapSymbols % 10)) / 10) { + case 1: + wrapVisualFlags |= SC_WRAPVISUALFLAG_START; + wrapVisualFlagsLocation |= SC_WRAPVISUALFLAGLOC_START_BY_TEXT; + break; + case 2: + wrapVisualFlags |= SC_WRAPVISUALFLAG_START; + break; + } + SciCall_SetWrapVisualFlags(wrapVisualFlags); + SciCall_SetWrapVisualFlagsLocation(wrapVisualFlagsLocation); + } else { + SciCall_SetWrapVisualFlags(0); + } +} + + //============================================================================= // // InitializeSciEditCtrl() @@ -2996,8 +3053,8 @@ static void _InitializeSciEditCtrl(HWND hwndEditCtrl) Style_SetIndentGuides(hwndEditCtrl, Settings.ShowIndentGuides); // Word Wrap - NP3Util_SetWrapIndentMode(); - NP3Util_SetWrapVisualFlags(hwndEditCtrl); + _SetWrapIndentMode(); + _SetWrapVisualFlags(hwndEditCtrl); // Long Lines if (Settings.MarkLongLines) { @@ -3323,7 +3380,82 @@ bool SelectExternalToolBar(HWND hwnd) } -// LoadBitmapFile, XXX_CreateScaledImageListFromBitmap, CreateScaledImageListFromBitmap moved to Notepad3Util.c +#define NUMTOOLBITMAPS (31) + +//============================================================================= +// +// _LoadToolbarBitmapFile() +// +static HBITMAP _LoadToolbarBitmapFile(const HPATHL hpath) +{ + HBITMAP hbmp = NULL; + + if (Path_IsExistingFile(hpath)) { + + hbmp = (HBITMAP)LoadImage(NULL, Path_Get(hpath), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE); + + bool bDimOK = false; + int height = 16; + if (hbmp) { + BITMAP bmp = { 0 }; + GetObject(hbmp, sizeof(BITMAP), &bmp); + height = bmp.bmHeight; + bDimOK = (bmp.bmWidth >= (height * NUMTOOLBITMAPS)); + } + if (!bDimOK) { + InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.NotSuitableToolbarDim, IDS_MUI_ERR_BITMAP, Path_Get(hpath), + (height * NUMTOOLBITMAPS), height, NUMTOOLBITMAPS); + } + } + else { + WCHAR displayName[80]; + Path_GetDisplayName(displayName, 80, hpath, L"", false); + InfoBoxLng(MB_ICONWARNING, NULL, IDS_MUI_ERR_LOADFILE, displayName); + } + + return hbmp; +} + + +//============================================================================= +// +// _CreateScaledToolbarImageList() +// +static HIMAGELIST _CreateScaledToolbarImageList(HWND hWnd, HBITMAP hBmp) +{ + BITMAP bmp = { 0 }; + GetObject(hBmp, sizeof(BITMAP), &bmp); + + int const numOfToolBitmaps = (int)(bmp.bmWidth / bmp.bmHeight); + + int const mod = bmp.bmWidth % numOfToolBitmaps; + int const cx = (bmp.bmWidth - mod) / numOfToolBitmaps; + int const cy = bmp.bmHeight; + + HIMAGELIST himl = ImageList_Create(cx, cy, ILC_COLOR32 | ILC_MASK, numOfToolBitmaps, numOfToolBitmaps); + ImageList_AddMasked(himl, hBmp, CLR_DEFAULT); + + UINT const dpi = Scintilla_GetWindowDPI(hWnd); + if (!Settings.DpiScaleToolBar || (dpi == USER_DEFAULT_SCREEN_DPI)) { + return himl; // default DPI, we are done + } + + // Scale button icons/images + int const scx = ScaleIntToDPI(hWnd, cx); + int const scy = ScaleIntToDPI(hWnd, cy); + + HIMAGELIST hsciml = ImageList_Create(scx, scy, ILC_COLOR32 | ILC_MASK | ILC_HIGHQUALITYSCALE, numOfToolBitmaps, numOfToolBitmaps); + + for (int i = 0; i < numOfToolBitmaps; ++i) { + HICON const hicon = ImageList_GetIcon(himl, i, ILD_TRANSPARENT | ILD_PRESERVEALPHA | ILD_SCALE); + ImageList_AddIcon(hsciml, hicon); + DestroyIcon(hicon); + } + + ImageList_Destroy(himl); + + return hsciml; +} //==== Toolbar Style ========================================================== @@ -3402,7 +3534,7 @@ void CreateBars(HWND hwnd, HINSTANCE hInstance) if ((Settings.ToolBarTheme == 2) && Path_IsNotEmpty(g_tchToolbarBitmap)) { HPATHL hfile_pth = Path_Copy(g_tchToolbarBitmap); Path_AbsoluteFromApp(hfile_pth, true); - hbmp = NP3Util_LoadBitmapFile(hfile_pth); + hbmp = _LoadToolbarBitmapFile(hfile_pth); if (!hbmp) { Path_Reset(g_tchToolbarBitmap, L""); IniSectionDelete(L"Toolbar Images", L"BitmapDefault", false); @@ -3420,7 +3552,7 @@ void CreateBars(HWND hwnd, HINSTANCE hInstance) hbmpCopy = CopyImage(hbmp, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION); - HIMAGELIST himl = NP3Util_CreateScaledImageListFromBitmap(hwnd, hbmp); + HIMAGELIST himl = _CreateScaledToolbarImageList(hwnd, hbmp); DeleteObject(hbmp); hbmp = NULL; @@ -3434,7 +3566,7 @@ void CreateBars(HWND hwnd, HINSTANCE hInstance) if ((Settings.ToolBarTheme == 2) && Path_IsNotEmpty(g_tchToolbarBitmapHot)) { HPATHL hfile_pth = Path_Copy(g_tchToolbarBitmapHot); Path_AbsoluteFromApp(hfile_pth, true); - hbmp = Path_IsExistingFile(hfile_pth) ? NP3Util_LoadBitmapFile(hfile_pth) : NULL; + hbmp = Path_IsExistingFile(hfile_pth) ? _LoadToolbarBitmapFile(hfile_pth) : NULL; if (!hbmp) { Path_Reset(g_tchToolbarBitmapHot, L""); IniSectionDelete(L"Toolbar Images", L"BitmapHot", false); @@ -3447,7 +3579,7 @@ void CreateBars(HWND hwnd, HINSTANCE hInstance) hbmp = LoadImage(hInstance, toolBarIntRes, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION); } if (hbmp) { - himl = NP3Util_CreateScaledImageListFromBitmap(hwnd, hbmp); + himl = _CreateScaledToolbarImageList(hwnd, hbmp); DeleteObject(hbmp); hbmp = NULL; SendMessage(Globals.hwndToolbar, TB_SETHOTIMAGELIST, 0, (LPARAM)himl); @@ -3463,7 +3595,7 @@ void CreateBars(HWND hwnd, HINSTANCE hInstance) if ((Settings.ToolBarTheme == 2) && Path_IsNotEmpty(g_tchToolbarBitmapDisabled)) { HPATHL hfile_pth = Path_Copy(g_tchToolbarBitmapDisabled); Path_AbsoluteFromApp(hfile_pth, true); - hbmp = Path_IsExistingFile(hfile_pth) ? NP3Util_LoadBitmapFile(hfile_pth) : NULL; + hbmp = Path_IsExistingFile(hfile_pth) ? _LoadToolbarBitmapFile(hfile_pth) : NULL; if (!hbmp) { Path_Reset(g_tchToolbarBitmapDisabled, L""); IniSectionDelete(L"Toolbar Images", L"BitmapDisabled", false); @@ -3475,7 +3607,7 @@ void CreateBars(HWND hwnd, HINSTANCE hInstance) hbmp = LoadImage(hInstance, toolBarIntRes, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION); } if (hbmp) { - himl = NP3Util_CreateScaledImageListFromBitmap(hwnd, hbmp); + himl = _CreateScaledToolbarImageList(hwnd, hbmp); DeleteObject(hbmp); hbmp = NULL; SendMessage(Globals.hwndToolbar, TB_SETDISABLEDIMAGELIST, 0, (LPARAM)himl); @@ -3490,7 +3622,7 @@ void CreateBars(HWND hwnd, HINSTANCE hInstance) bProcessed = BitmapGrayScale(hbmpCopy); } if (bProcessed) { - himl = NP3Util_CreateScaledImageListFromBitmap(hwnd, hbmpCopy); + himl = _CreateScaledToolbarImageList(hwnd, hbmpCopy); SendMessage(Globals.hwndToolbar, TB_SETDISABLEDIMAGELIST, 0, (LPARAM)himl); } } @@ -4531,18 +4663,18 @@ LRESULT MsgCopyData(HWND hwnd, WPARAM wParam, LPARAM lParam) g_flagMatchText = params->flagMatchText; SetFindPattern(StrEndW(¶ms->wchData, 0) + 1); - SetFindReplaceData(); // s_FindReplaceData + LPEDITFINDREPLACE const lpefr = FindReplacePrepare(); if (g_flagMatchText & 2) { if (!s_flagJumpTo) { Sci_SetCaretScrollDocEnd(); } - EditFindPrev(Globals.hwndEdit, &s_FindReplaceData, false, false, false); + EditFindPrev(Globals.hwndEdit, lpefr, false, false, false); } else { if (!s_flagJumpTo) { SciCall_DocumentStart(); } - EditFindNext(Globals.hwndEdit, &s_FindReplaceData, false, false, false); + EditFindNext(Globals.hwndEdit, lpefr, false, false, false); } } @@ -4709,29 +4841,6 @@ LRESULT MsgContextMenu(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) return (imenu != MNU_NONE) ? !0 : 0; } -// --------------------------------------------------------------------------- -// Find the 0-based position of a POPUP submenu within hParent that contains -// childCmdId as a direct child MENUITEM. Returns -1 if not found. -// Replaces fragile hardcoded position numbers for POPUP items (which have -// no command ID in MENU resource format). -// --------------------------------------------------------------------------- -static int GetSubMenuPosByChildCmd(HMENU hParent, UINT childCmdId) -{ - int const count = GetMenuItemCount(hParent); - for (int i = 0; i < count; ++i) { - HMENU const hSub = GetSubMenu(hParent, i); - if (hSub) { - int const subCount = GetMenuItemCount(hSub); - for (int j = 0; j < subCount; ++j) { - if (GetMenuItemID(hSub, j) == childCmdId) { - return i; - } - } - } - } - return -1; -} - //============================================================================= // // MsgTrayMessage() - Handles WM_TRAYMESSAGE @@ -6217,8 +6326,7 @@ static bool _HandleEditBasicCommands(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM case IDM_EDIT_SELECTALLMATCHES: { if (!Sci_IsMultiOrRectangleSelection()) { if (IsWindow(Globals.hwndDlgFindReplace)) { - SetFindReplaceData(); // s_FindReplaceData - EditSelectionMultiSelectAllEx(Globals.hwndEdit, &s_FindReplaceData); + EditSelectionMultiSelectAllEx(Globals.hwndEdit, FindReplacePrepare()); } else { if (SciCall_IsSelectionEmpty()) { EditSelectWordAtPos(SciCall_GetCurrentPos(), false); @@ -6950,53 +7058,17 @@ static bool _HandleEditFind(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) break; - case IDM_EDIT_FIND: { - SetFindReplaceData(); // s_FindReplaceData - if (!IsWindow(Globals.hwndDlgFindReplace)) { - // Don't overwrite cmd-line search pattern with editor selection - Globals.bFindReplCopySelOrClip = !g_flagMatchText; - /*Globals.hwndDlgFindReplace =*/ EditFindReplaceDlg(Globals.hwndEdit, &s_FindReplaceData, false, NULL); - } else { - Globals.bFindReplCopySelOrClip = (GetForegroundWindow() != Globals.hwndDlgFindReplace); - if (GetDlgItem(Globals.hwndDlgFindReplace, IDC_REPLACE)) { - SendWMCommand(Globals.hwndDlgFindReplace, IDMSG_SWITCHTOFIND); - DestroyWindow(Globals.hwndDlgFindReplace); - /*Globals.hwndDlgFindReplace =*/ EditFindReplaceDlg(Globals.hwndEdit, &s_FindReplaceData, false, NULL); - } else { - SetForegroundWindow(Globals.hwndDlgFindReplace); - PostMessage(Globals.hwndDlgFindReplace, WM_NEXTDLGCTL, (WPARAM)(GetDlgItem(Globals.hwndDlgFindReplace, IDC_FINDTEXT)), 1); - } - } - } - break; - - - case IDM_EDIT_REPLACE: { - SetFindReplaceData(); // s_FindReplaceData - if (!IsWindow(Globals.hwndDlgFindReplace)) { - // Don't overwrite cmd-line search pattern with editor selection - Globals.bFindReplCopySelOrClip = !g_flagMatchText; - /*Globals.hwndDlgFindReplace =*/ EditFindReplaceDlg(Globals.hwndEdit, &s_FindReplaceData, true, NULL); - } else { - Globals.bFindReplCopySelOrClip = (GetForegroundWindow() != Globals.hwndDlgFindReplace); - if (!GetDlgItem(Globals.hwndDlgFindReplace, IDC_REPLACE)) { - SendWMCommand(Globals.hwndDlgFindReplace, IDMSG_SWITCHTOREPLACE); - DestroyWindow(Globals.hwndDlgFindReplace); - /*Globals.hwndDlgFindReplace =*/ EditFindReplaceDlg(Globals.hwndEdit, &s_FindReplaceData, true, NULL); - } else { - SetForegroundWindow(Globals.hwndDlgFindReplace); - PostMessage(Globals.hwndDlgFindReplace, WM_NEXTDLGCTL, (WPARAM)(GetDlgItem(Globals.hwndDlgFindReplace, IDC_FINDTEXT)), 1); - } - } - } - break; + case IDM_EDIT_FIND: + case IDM_EDIT_REPLACE: + FindReplaceShowDialog(iLoWParam == IDM_EDIT_REPLACE); + break; case IDM_EDIT_FINDNEXT: case IDM_EDIT_FINDPREV: case IDM_EDIT_REPLACENEXT: case IDM_EDIT_SELTONEXT: - case IDM_EDIT_SELTOPREV: + case IDM_EDIT_SELTOPREV: { if (Sci_IsDocEmpty()) { break; @@ -7028,9 +7100,9 @@ static bool _HandleEditFind(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) break; // done } - SetFindReplaceData(); // s_FindReplaceData + LPEDITFINDREPLACE lpefr = FindReplacePrepare(); - if (IsFindPatternEmpty() && StrgIsNotEmpty(s_FindReplaceData.chFindPattern)) { + if (IsFindPatternEmpty() && StrgIsNotEmpty(lpefr->chFindPattern)) { if (iLoWParam != IDM_EDIT_REPLACENEXT) { SendWMCommand(hwnd, IDM_EDIT_FIND); } else { @@ -7041,50 +7113,48 @@ static bool _HandleEditFind(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) switch (iLoWParam) { case IDM_EDIT_FINDNEXT: - EditFindNext(Globals.hwndEdit, &s_FindReplaceData, false, false, true); + EditFindNext(Globals.hwndEdit, lpefr, false, false, true); break; case IDM_EDIT_FINDPREV: - EditFindPrev(Globals.hwndEdit, &s_FindReplaceData, false, false, true); + EditFindPrev(Globals.hwndEdit, lpefr, false, false, true); break; case IDM_EDIT_REPLACENEXT: if (Globals.bReplaceInitialized) { - EditReplace(Globals.hwndEdit, &s_FindReplaceData); + EditReplace(Globals.hwndEdit, lpefr); } else { SendWMCommand(hwnd, IDM_EDIT_REPLACE); } break; case IDM_EDIT_SELTONEXT: - if (IsFindPatternEmpty()) { - if (!SetCurrentSelAsFindReplaceData(&s_FindReplaceData)) { - break; - } - } - EditFindNext(Globals.hwndEdit, &s_FindReplaceData, true, false, false); - break; - case IDM_EDIT_SELTOPREV: if (IsFindPatternEmpty()) { - if (!SetCurrentSelAsFindReplaceData(&s_FindReplaceData)) { - break; + lpefr = FindReplaceUseSelection(); + } + if (lpefr) { + if (iLoWParam == IDM_EDIT_SELTONEXT) { + EditFindNext(Globals.hwndEdit, lpefr, true, false, false); + } else { + EditFindPrev(Globals.hwndEdit, lpefr, true, false, false); } } - EditFindPrev(Globals.hwndEdit, &s_FindReplaceData, true, false, false); break; } } - break; + } + break; case CMD_FINDNEXTSEL: case CMD_FINDPREVSEL: case IDM_EDIT_SAVEFIND: { - if (SetCurrentSelAsFindReplaceData(&s_FindReplaceData)) { + LPEDITFINDREPLACE const lpefr = FindReplaceUseSelection(); + if (lpefr) { MRU_Add(Globals.pMRUfind, GetFindPattern(), 0, -1, -1, NULL); - s_FindReplaceData.fuFlags &= (~(SCFIND_REGEXP | SCFIND_POSIX)); - s_FindReplaceData.bTransformBS = false; + lpefr->fuFlags &= (~(SCFIND_REGEXP | SCFIND_POSIX)); + lpefr->bTransformBS = false; switch (iLoWParam) { @@ -7092,11 +7162,11 @@ static bool _HandleEditFind(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) break; case CMD_FINDNEXTSEL: - EditFindNext(Globals.hwndEdit, &s_FindReplaceData, false, false, false); + EditFindNext(Globals.hwndEdit, lpefr, false, false, false); break; case CMD_FINDPREVSEL: - EditFindPrev(Globals.hwndEdit, &s_FindReplaceData, false, false, false); + EditFindPrev(Globals.hwndEdit, lpefr, false, false, false); break; } } @@ -7174,7 +7244,7 @@ static bool _HandleViewAndSettingsCommands(HWND hwnd, UINT umsg, WPARAM wParam, case IDM_VIEW_WORDWRAP: Globals.fvCurFile.bWordWrap = Settings.WordWrap = !Settings.WordWrap; - NP3Util_SetWrapIndentMode(); + _SetWrapIndentMode(); SciCall_ScrollVertical(Sci_GetCurrentLineNumber(), 0); UpdateToolbar(); break; @@ -7182,8 +7252,8 @@ static bool _HandleViewAndSettingsCommands(HWND hwnd, UINT umsg, WPARAM wParam, case IDM_SET_WORDWRAPSETTINGS: if (WordWrapSettingsDlg(hwnd,IDD_MUI_WORDWRAP, &Settings.WordWrapIndent)) { - NP3Util_SetWrapIndentMode(); - NP3Util_SetWrapVisualFlags(Globals.hwndEdit); + _SetWrapIndentMode(); + _SetWrapVisualFlags(Globals.hwndEdit); UpdateToolbar(); } break; @@ -7191,7 +7261,7 @@ static bool _HandleViewAndSettingsCommands(HWND hwnd, UINT umsg, WPARAM wParam, case IDM_VIEW_WORDWRAPSYMBOLS: Settings.ShowWordWrapSymbols = !Settings.ShowWordWrapSymbols; - NP3Util_SetWrapVisualFlags(Globals.hwndEdit); + _SetWrapVisualFlags(Globals.hwndEdit); UpdateToolbar(); break; @@ -7267,7 +7337,7 @@ static bool _HandleViewAndSettingsCommands(HWND hwnd, UINT umsg, WPARAM wParam, SciCall_SetTabWidth(Globals.fvCurFile.iTabWidth); SciCall_SetIndent(Globals.fvCurFile.iIndentWidth); if (SciCall_GetWrapIndentMode() == SC_WRAPINDENT_FIXED) { - NP3Util_SetWrapStartIndent(); + _SetWrapStartIndent(); } } break; @@ -8701,23 +8771,16 @@ LRESULT MsgCommand(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) #if defined(HAVE_DYN_LOAD_LIBS_MUI_LNGS) bool const bIsLngMenuCmd = ((iLoWParam >= IDS_MUI_LANG_EN_US) && (iLoWParam < (IDS_MUI_LANG_EN_US + MuiLanguages_CountOf()))); if (bIsLngMenuCmd) { - bool const bHadFindReplace = IsWindow(Globals.hwndDlgFindReplace); - bool bReplace = false; FindReplaceDlgRestore restore = { 0 }; - if (bHadFindReplace) { - bReplace = GetDlgItem(Globals.hwndDlgFindReplace, IDC_REPLACE) != NULL; - GetWindowRect(Globals.hwndDlgFindReplace, &restore.windowRect); - restore.bFocusedView = FocusedView.HideNonMatchedLines; - } + bool const bHadFindReplace = FindReplaceCaptureDialog(&restore); if (!DynamicLanguageMenuCmd(iLoWParam)) { return FALSE; } Style_InsertThemesMenu(Globals.hMainMenu); DrawMenuBar(Globals.hwndMain); - if (bHadFindReplace && !IsWindow(Globals.hwndDlgFindReplace)) { - Globals.bFindReplCopySelOrClip = false; - EditFindReplaceDlg(Globals.hwndEdit, &s_FindReplaceData, bReplace, &restore); + if (bHadFindReplace) { + FindReplaceRestoreDialog(&restore); } UpdateToolbar(); UpdateStatusbar(true); @@ -11319,7 +11382,6 @@ static void _UpdateToolbarDelayed() EnableTool(Globals.hwndToolbar, IDT_EDIT_FIND, b2); //EnableTool(Globals.hwndToolbar, ,b2); - //EnableTool(Globals.hwndToolbar, IDT_EDIT_FINDPREV,b2 && !StrIsEmptyA(s_FindReplaceData.szFind)); EnableTool(Globals.hwndToolbar, IDT_EDIT_REPLACE, b2 && !ro); EnableTool(Globals.hwndToolbar, IDT_EDIT_CUT, !b1 && !ro); diff --git a/src/Notepad3.h b/src/Notepad3.h index 29c80e3cbd..4247080316 100644 --- a/src/Notepad3.h +++ b/src/Notepad3.h @@ -69,7 +69,6 @@ np3params, *LPnp3params; #define ID_PASTEBOARDTIMER (0xA001) // Paste Board #define ID_AUTOSAVETIMER (0xA002) // Auto Save Timer #define ID_LOGROTATETIMER (0xA003) // Log Rotation Retry -#define ID_AUTOSCROLLTIMER (0xA004) // Middle-Click Auto-Scroll #define ID_ATOMICSAVETIMER (0xA005) // Atomic Save Detection #define ID_DEFERMINIMIZETIMER (0xA006) // Deferred minimize on /B + /I startup #define ID_TINYEXPRCOPYTIMER (0xA007) // TinyExpr status-bar single-click copy debounce @@ -128,13 +127,7 @@ void HandleDWellStartEnd(const DocPos position, const UINT uid); bool HandleHotSpotURLClicked(const DocPos position, const HYPERLINK_OPS operation); void HandleColorDefClicked(HWND hwnd, const DocPos position); -bool IsFindPatternEmpty(); -LPCWSTR GetFindPattern(); -void GetFindPatternMB(LPSTR chPattern, int cch); -void SetFindPattern(LPCWSTR wchFindPattern); -void SetFindPatternMB(LPCSTR chFindPattern); -size_t LengthOfFindPattern(); -size_t LengthOfFindPatternMB(); +extern int g_flagMatchText; bool ConsistentIndentationCheck(EditFileIOStatus* status); diff --git a/src/Notepad3.vcxproj b/src/Notepad3.vcxproj index b6f368b567..00f3ba6a86 100644 --- a/src/Notepad3.vcxproj +++ b/src/Notepad3.vcxproj @@ -1057,6 +1057,7 @@ + @@ -1082,7 +1083,6 @@ - @@ -1185,12 +1185,12 @@ + - diff --git a/src/Notepad3.vcxproj.filters b/src/Notepad3.vcxproj.filters index 0bec93d2c2..7812cd0b6f 100644 --- a/src/Notepad3.vcxproj.filters +++ b/src/Notepad3.vcxproj.filters @@ -60,6 +60,9 @@ Source Files + + Source Files + Source Files @@ -75,9 +78,6 @@ Source Files - - Source Files - Source Files @@ -470,6 +470,9 @@ Header Files + + Header Files + Header Files @@ -491,9 +494,6 @@ Header Files - - Header Files - Resource Files diff --git a/src/Notepad3Util.c b/src/Notepad3Util.c deleted file mode 100644 index b317687e3d..0000000000 --- a/src/Notepad3Util.c +++ /dev/null @@ -1,349 +0,0 @@ -// encoding: UTF-8 -/****************************************************************************** -* * -* * -* Notepad3 * -* * -* Notepad3Util.c * -* Utility functions extracted from Notepad3.c * -* Based on code from Notepad2, (c) Florian Balmer 1996-2011 * -* * -* (c) Rizonesoft 2008-2026 * -* https://rizonesoft.com * -* * -* * -*******************************************************************************/ - -#include "Helpers.h" - -#include -#include -#include - -#include "PathLib.h" -#include "Dialogs.h" -#include "Encoding.h" -#include "MuiLanguage.h" -#include "Notepad3.h" -#include "Notepad3Util.h" - - -// ============================================================================ -// --- Bitmap / Image Loading --- -// ============================================================================ - -//============================================================================= -// -// NP3Util_LoadBitmapFile() -// -HBITMAP NP3Util_LoadBitmapFile(const HPATHL hpath) -{ - HBITMAP hbmp = NULL; - - if (Path_IsExistingFile(hpath)) { - - hbmp = (HBITMAP)LoadImage(NULL, Path_Get(hpath), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_LOADFROMFILE); - - bool bDimOK = false; - int height = 16; - if (hbmp) { - BITMAP bmp = { 0 }; - GetObject(hbmp, sizeof(BITMAP), &bmp); - height = bmp.bmHeight; - bDimOK = (bmp.bmWidth >= (height * NUMTOOLBITMAPS)); - } - if (!bDimOK) { - InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.NotSuitableToolbarDim, IDS_MUI_ERR_BITMAP, Path_Get(hpath), - (height * NUMTOOLBITMAPS), height, NUMTOOLBITMAPS); - } - } - else { - WCHAR displayName[80]; - Path_GetDisplayName(displayName, 80, hpath, L"", false); - InfoBoxLng(MB_ICONWARNING, NULL, IDS_MUI_ERR_LOADFILE, displayName); - } - - return hbmp; -} - - -//============================================================================= -// -// NP3Util_XXX_CreateScaledImageListFromBitmap() -// -HIMAGELIST NP3Util_XXX_CreateScaledImageListFromBitmap(HWND hWnd, HBITMAP hBmp) -{ - BITMAP bmp = { 0 }; - GetObject(hBmp, sizeof(BITMAP), &bmp); - - int const mod = bmp.bmWidth % NUMTOOLBITMAPS; - int const cx = (bmp.bmWidth - mod) / NUMTOOLBITMAPS; - int const cy = bmp.bmHeight; - - HIMAGELIST himl = ImageList_Create(cx, cy, ILC_COLOR32 | ILC_MASK, NUMTOOLBITMAPS, NUMTOOLBITMAPS); - ImageList_AddMasked(himl, hBmp, CLR_DEFAULT); - - UINT const dpi = Scintilla_GetWindowDPI(hWnd); - if (!Settings.DpiScaleToolBar || (dpi == USER_DEFAULT_SCREEN_DPI)) { - return himl; // default DPI, we are done - } - - // Scale button icons/images - int const scx = ScaleIntToDPI(hWnd, cx); - int const scy = ScaleIntToDPI(hWnd, cy); - - HIMAGELIST hsciml = ImageList_Create(scx, scy, ILC_COLOR32 | ILC_MASK | ILC_HIGHQUALITYSCALE, NUMTOOLBITMAPS, NUMTOOLBITMAPS); - - for (int i = 0; i < NUMTOOLBITMAPS; ++i) { - HICON const hicon = ImageList_GetIcon(himl, i, ILD_TRANSPARENT | ILD_PRESERVEALPHA | ILD_SCALE); - ImageList_AddIcon(hsciml, hicon); - DestroyIcon(hicon); - } - - ImageList_Destroy(himl); - - return hsciml; -} - - -//============================================================================= -// -// NP3Util_CreateScaledImageListFromBitmap() -// -HIMAGELIST NP3Util_CreateScaledImageListFromBitmap(HWND hWnd, HBITMAP hBmp) -{ - BITMAP bmp = { 0 }; - GetObject(hBmp, sizeof(BITMAP), &bmp); - - int const numOfToolBitmaps = (int)(bmp.bmWidth / bmp.bmHeight); - - int const mod = bmp.bmWidth % numOfToolBitmaps; - int const cx = (bmp.bmWidth - mod) / numOfToolBitmaps; - int const cy = bmp.bmHeight; - - HIMAGELIST himl = ImageList_Create(cx, cy, ILC_COLOR32 | ILC_MASK, numOfToolBitmaps, numOfToolBitmaps); - ImageList_AddMasked(himl, hBmp, CLR_DEFAULT); - - UINT const dpi = Scintilla_GetWindowDPI(hWnd); - if (!Settings.DpiScaleToolBar || (dpi == USER_DEFAULT_SCREEN_DPI)) { - return himl; // default DPI, we are done - } - - // Scale button icons/images - int const scx = ScaleIntToDPI(hWnd, cx); - int const scy = ScaleIntToDPI(hWnd, cy); - - HIMAGELIST hsciml = ImageList_Create(scx, scy, ILC_COLOR32 | ILC_MASK | ILC_HIGHQUALITYSCALE, numOfToolBitmaps, numOfToolBitmaps); - - for (int i = 0; i < numOfToolBitmaps; ++i) { - HICON const hicon = ImageList_GetIcon(himl, i, ILD_TRANSPARENT | ILD_PRESERVEALPHA | ILD_SCALE); - ImageList_AddIcon(hsciml, hicon); - DestroyIcon(hicon); - } - - ImageList_Destroy(himl); - - return hsciml; -} - - -// ============================================================================ -// --- Word-Wrap Configuration --- -// ============================================================================ - -//============================================================================= -// -// NP3Util_SetWrapStartIndent() -// -void NP3Util_SetWrapStartIndent(void) -{ - int i = 0; - switch (Settings.WordWrapIndent) { - case 1: - i = 1; - break; - case 2: - i = 2; - break; - case 3: - i = (Globals.fvCurFile.iIndentWidth) ? 1 * Globals.fvCurFile.iIndentWidth : 1 * Globals.fvCurFile.iTabWidth; - break; - case 4: - i = (Globals.fvCurFile.iIndentWidth) ? 2 * Globals.fvCurFile.iIndentWidth : 2 * Globals.fvCurFile.iTabWidth; - break; - default: - break; - } - SciCall_SetWrapStartIndent(i); -} - - -//============================================================================= -// -// NP3Util_SetWrapIndentMode() -// -void NP3Util_SetWrapIndentMode(void) -{ - BeginWaitCursorUID(Flags.bHugeFileLoadState, IDS_MUI_SB_WRAP_LINES); - - Sci_SetWrapModeEx(GET_WRAP_MODE()); - - if (Settings.WordWrapIndent == 5) { - SciCall_SetWrapIndentMode(SC_WRAPINDENT_SAME); - } else if (Settings.WordWrapIndent == 6) { - SciCall_SetWrapIndentMode(SC_WRAPINDENT_INDENT); - } else if (Settings.WordWrapIndent == 7) { - SciCall_SetWrapIndentMode(SC_WRAPINDENT_DEEPINDENT); - } else { - NP3Util_SetWrapStartIndent(); - SciCall_SetWrapIndentMode(SC_WRAPINDENT_FIXED); - } - - EndWaitCursor(); -} - - -//============================================================================= -// -// NP3Util_SetWrapVisualFlags() -// -void NP3Util_SetWrapVisualFlags(HWND hwndEditCtrl) -{ - UNREFERENCED_PARAMETER(hwndEditCtrl); - - if (Settings.ShowWordWrapSymbols) { - int wrapVisualFlags = 0; - int wrapVisualFlagsLocation = 0; - if (Settings.WordWrapSymbols == 0) { - Settings.WordWrapSymbols = 22; - } - switch (Settings.WordWrapSymbols % 10) { - case 1: - wrapVisualFlags |= SC_WRAPVISUALFLAG_END; - wrapVisualFlagsLocation |= SC_WRAPVISUALFLAGLOC_END_BY_TEXT; - break; - case 2: - wrapVisualFlags |= SC_WRAPVISUALFLAG_END; - break; - } - switch (((Settings.WordWrapSymbols % 100) - (Settings.WordWrapSymbols % 10)) / 10) { - case 1: - wrapVisualFlags |= SC_WRAPVISUALFLAG_START; - wrapVisualFlagsLocation |= SC_WRAPVISUALFLAGLOC_START_BY_TEXT; - break; - case 2: - wrapVisualFlags |= SC_WRAPVISUALFLAG_START; - break; - } - SciCall_SetWrapVisualFlags(wrapVisualFlags); - SciCall_SetWrapVisualFlagsLocation(wrapVisualFlagsLocation); - } else { - SciCall_SetWrapVisualFlags(0); - } -} - - -// ============================================================================ -// --- Auto-Scroll (middle-click continuous scroll, Firefox-style) --- -// ============================================================================ - -static bool s_bAutoScrollMode = false; -static bool s_bAutoScrollHeld = false; -static ULONGLONG s_dwAutoScrollStartTick = 0; -static POINT s_ptAutoScrollOrigin = { 0, 0 }; -static POINT s_ptAutoScrollMouse = { 0, 0 }; -static double s_dAutoScrollAccumY = 0.0; - -bool NP3Util_IsAutoScrollMode(void) -{ - return s_bAutoScrollMode; -} - -bool NP3Util_IsAutoScrollHeld(void) -{ - return s_bAutoScrollHeld; -} - -ULONGLONG NP3Util_GetAutoScrollStartTick(void) -{ - return s_dwAutoScrollStartTick; -} - -void NP3Util_SetAutoScrollHeld(bool held) -{ - s_bAutoScrollHeld = held; -} - -void NP3Util_AutoScrollUpdateMouse(POINT pt) -{ - s_ptAutoScrollMouse = pt; -} - - -//============================================================================= -// -// NP3Util_AutoScrollStop() -// -void NP3Util_AutoScrollStop(HWND hwndEdit) -{ - if (s_bAutoScrollMode) { - KillTimer(hwndEdit, ID_AUTOSCROLLTIMER); - ReleaseCapture(); - SciCall_SetCursor(SC_CURSORNORMAL); - s_bAutoScrollMode = false; - s_bAutoScrollHeld = false; - s_dAutoScrollAccumY = 0.0; - } -} - - -//============================================================================= -// -// NP3Util_AutoScrollTimerProc() -// -void CALLBACK NP3Util_AutoScrollTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime) -{ - UNREFERENCED_PARAMETER(uMsg); - UNREFERENCED_PARAMETER(idEvent); - UNREFERENCED_PARAMETER(dwTime); - - if (!s_bAutoScrollMode) { - KillTimer(hwnd, ID_AUTOSCROLLTIMER); - return; - } - - int const deltaY = s_ptAutoScrollMouse.y - s_ptAutoScrollOrigin.y; - - if (abs(deltaY) <= AUTOSCROLL_DEADZONE) { - s_dAutoScrollAccumY = 0.0; - return; - } - - // Speed: proportional to distance beyond dead zone - double const speed = (double)(deltaY - (deltaY > 0 ? AUTOSCROLL_DEADZONE : -AUTOSCROLL_DEADZONE)) / AUTOSCROLL_DIVISOR; - s_dAutoScrollAccumY += speed; - - DocLn const linesToScroll = (DocLn)s_dAutoScrollAccumY; - if (linesToScroll != 0) { - SciCall_LineScroll(0, linesToScroll); - s_dAutoScrollAccumY -= (double)linesToScroll; - } -} - - -//============================================================================= -// -// NP3Util_AutoScrollStart() -// -void NP3Util_AutoScrollStart(HWND hwndEdit, POINT pt) -{ - s_bAutoScrollMode = true; - s_bAutoScrollHeld = false; - s_dwAutoScrollStartTick = GetTickCount64(); - s_ptAutoScrollOrigin = pt; - s_ptAutoScrollMouse = pt; - s_dAutoScrollAccumY = 0.0; - SetCapture(hwndEdit); - SetCursor(LoadCursor(NULL, IDC_SIZEALL)); - SetTimer(hwndEdit, ID_AUTOSCROLLTIMER, AUTOSCROLL_TIMER_MS, NP3Util_AutoScrollTimerProc); -} diff --git a/src/Notepad3Util.h b/src/Notepad3Util.h deleted file mode 100644 index 4003fc6130..0000000000 --- a/src/Notepad3Util.h +++ /dev/null @@ -1,50 +0,0 @@ -// encoding: UTF-8 -/****************************************************************************** -* * -* * -* Notepad3 * -* * -* Notepad3Util.h * -* Utility functions extracted from Notepad3.c * -* Based on code from Notepad2, (c) Florian Balmer 1996-2011 * -* * -* (c) Rizonesoft 2008-2026 * -* https://rizonesoft.com * -* * -* * -*******************************************************************************/ -#pragma once -#ifndef _NP3_NOTEPAD3UTIL_H_ -#define _NP3_NOTEPAD3UTIL_H_ - -#include "TypeDefs.h" -#include "SciCall.h" - -// --- Bitmap / Image Loading --- -#define NUMTOOLBITMAPS (31) -HBITMAP NP3Util_LoadBitmapFile(const HPATHL hpath); -HIMAGELIST NP3Util_CreateScaledImageListFromBitmap(HWND hWnd, HBITMAP hBmp); -HIMAGELIST NP3Util_XXX_CreateScaledImageListFromBitmap(HWND hWnd, HBITMAP hBmp); - -// --- Word-Wrap Configuration --- -void NP3Util_SetWrapStartIndent(void); -void NP3Util_SetWrapIndentMode(void); -void NP3Util_SetWrapVisualFlags(HWND hwndEditCtrl); - -// --- Auto-Scroll (middle-click continuous scroll) --- -#define AUTOSCROLL_TIMER_MS 30 -#define AUTOSCROLL_DEADZONE 15 -#define AUTOSCROLL_DIVISOR 60.0 -#define AUTOSCROLL_CLICK_THRESHOLD_MS 200 - -bool NP3Util_IsAutoScrollMode(void); -void NP3Util_AutoScrollStop(HWND hwndEdit); -void NP3Util_AutoScrollStart(HWND hwndEdit, POINT pt); -void NP3Util_AutoScrollUpdateMouse(POINT pt); -bool NP3Util_IsAutoScrollHeld(void); -ULONGLONG NP3Util_GetAutoScrollStartTick(void); -void NP3Util_SetAutoScrollHeld(bool held); - -void CALLBACK NP3Util_AutoScrollTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime); - -#endif // _NP3_NOTEPAD3UTIL_H_ diff --git a/src/TypeDefs.h b/src/TypeDefs.h index 89575a4edb..11f558ffe1 100644 --- a/src/TypeDefs.h +++ b/src/TypeDefs.h @@ -229,7 +229,6 @@ typedef enum BUFFER_SIZES { typedef enum FR_STATES { FND_NOP = 0, NXT_NOT_FND, NXT_FND, NXT_WRP_FND, PRV_NOT_FND, PRV_FND, PRV_WRP_FND } FR_STATES; -typedef enum FR_UPD_MODES { FRMOD_IGNORE = 0, FRMOD_NORM, FRMOD_WRAPED } FR_UPD_MODES; typedef enum WIN_DISPL_MODE { WINDSPMOD_AUTO = 0, WINDSPMOD_DARK, WINDSPMOD_LIGHT } WIN_DISPL_MODE; typedef enum ZOOM_TOOLTIP_POSITION { @@ -322,8 +321,7 @@ typedef struct EDITFINDREPLACE { typedef const EDITFINDREPLACE* const CLPCEDITFINDREPLACE; #define INIT_EFR_DATA { 0, false, false, false, false, false, false, false, true, false, true, NULL, NULL, NULL } -// USE: void DuplicateEFR(LPEDITFINDREPLACE dst, CLPCEDITFINDREPLACE src); -// void ReleaseEFR(LPEDITFINDREPLACE efr); +// Release string handles with ReleaseEFR() from FindReplace.h. #define IDMSG_SWITCHTOFIND 300 #define IDMSG_SWITCHTOREPLACE 301 From e4e6700f35a21f035ab8141daac9cb8e74ef52d1 Mon Sep 17 00:00:00 2001 From: "METANEOCORTEX\\Kotti" Date: Wed, 18 Nov 2026 18:44:33 +0100 Subject: [PATCH 2/3] Fix Find/Replace matching and dialog state Reject failed pattern conversions and nonmatching selections before replacing, and release the replacement buffer on invalid regex input. Preserve replacement drafts across mode switches and rebuild Focused View from the same full pattern used to check for matches. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/FindReplace.c | 222 ++++++++++++++++++---------------------------- 1 file changed, 85 insertions(+), 137 deletions(-) diff --git a/src/FindReplace.c b/src/FindReplace.c index f349356373..f12b9070f2 100644 --- a/src/FindReplace.c +++ b/src/FindReplace.c @@ -338,7 +338,7 @@ static void _SetSearchFlags(HWND hwnd, LPEDITFINDREPLACE lpefr) { if (hwnd && lpefr) { - bool bIsFindDlg = (GetDlgItem(Globals.hwndDlgFindReplace, IDC_REPLACE) == NULL); + bool const bIsFindDlg = (GetDlgItem(hwnd, IDC_REPLACETEXT) == NULL); HSTRINGW hstr = StrgCreate(NULL); @@ -348,12 +348,13 @@ static void _SetSearchFlags(HWND hwnd, LPEDITFINDREPLACE lpefr) lpefr->bStateChanged = true; } - StrgReset(hstr, L""); - - ComboBox_GetTextHW(hwnd, IDC_REPLACETEXT, hstr); - if (StringCchCompareX(StrgGet(hstr), StrgGet(lpefr->chReplaceTemplate)) != 0) { - StrgReset(lpefr->chReplaceTemplate, StrgGet(hstr)); - lpefr->bStateChanged = true; + if (!bIsFindDlg) { + StrgReset(hstr, L""); + ComboBox_GetTextHW(hwnd, IDC_REPLACETEXT, hstr); + if (StringCchCompareX(StrgGet(hstr), StrgGet(lpefr->chReplaceTemplate)) != 0) { + StrgReset(lpefr->chReplaceTemplate, StrgGet(hstr)); + lpefr->bStateChanged = true; + } } StrgDestroy(hstr); @@ -606,50 +607,34 @@ static DocPos _FindInTarget(LPCWSTR wchFind, int sFlags, // earlier _FindInTarget call could leak into the next caller's Sci_ConsumeRegexWarnStatus. SciCall_SetStatus(SC_STATUS_OK); - SciCall_SetSearchFlags(sFlags); - SciCall_SetTargetRange(start, stop); - iPos = SciCall_SearchInTarget(len, chFind); - - // Bail out before the retry loop if the regex engine flagged an invalid - // pattern — every subsequent SearchInTarget would just re-set the warning. - // Status stays raised for the caller to consume via Sci_ConsumeRegexWarnStatus. - if ((sFlags & SCFIND_REGEXP) && SciCall_GetStatus() == SC_STATUS_WARN_REGEX) { - SciCall_SetTargetRange(saveTargetBeg, saveTargetEnd); - return NOT_FOUND; - } - -#if 1 - // handle next in case of zero-length-matches or invalid position (regex) ! - bool const bZeroLenMatch = ((iPos == start) && (start == SciCall_GetTargetEnd())); - bool bValidPos = !(bForceNext && bZeroLenMatch) && Sci_IsPosValid(iPos); - while (!bValidPos) { - DocPos const newStart = (bFindNext ? SciCall_PositionAfter(iPos) : SciCall_PositionBefore(iPos)); - bool const bProceed = (bFindNext ? (newStart < stop) : (newStart > stop)) && (newStart != iPos); - if (bProceed) { - SciCall_SetTargetRange(newStart, stop); - iPos = SciCall_SearchInTarget(len, chFind); // not found if beyond stop - } - else { - iPos = NOT_FOUND; // already at document begin, end or stuck => not found + // Scintilla treats a nonpositive pattern length as a match at the target start. + if (len > 0) { + SciCall_SetSearchFlags(sFlags); + SciCall_SetTargetRange(start, stop); + iPos = SciCall_SearchInTarget(len, chFind); + + // Leave the regex warning raised for the caller to consume. + if ((sFlags & SCFIND_REGEXP) && SciCall_GetStatus() == SC_STATUS_WARN_REGEX) { + SciCall_SetTargetRange(saveTargetBeg, saveTargetEnd); + return NOT_FOUND; } - bValidPos = Sci_IsPosValid(iPos); // NOT_FOUND is a valid pos - } -#else - // handle next in case of zero-length-matches (regex) ! - if (iPos == start) { - DocPos const nstop = SciCall_GetTargetEnd(); - if ((start == nstop) && bForceNext) { - DocPos const new_start = (bFindNext ? SciCall_PositionAfter(start) : SciCall_PositionBefore(start)); - bool const bProceed = (bFindNext ? (new_start < stop) : (new_start > stop)); - if ((new_start != start) && bProceed) { - SciCall_SetTargetRange(new_start, stop); - iPos = SciCall_SearchInTarget(len - 1, chFind); - } else { - iPos = (DocPos)-1LL; // already at document begin or end => not found + + // Advance past a zero-length regex match or an invalid position. + bool const bZeroLenMatch = ((iPos == start) && (start == SciCall_GetTargetEnd())); + bool bValidPos = !(bForceNext && bZeroLenMatch) && Sci_IsPosValid(iPos); + while (!bValidPos) { + DocPos const newStart = (bFindNext ? SciCall_PositionAfter(iPos) : SciCall_PositionBefore(iPos)); + bool const bProceed = (bFindNext ? (newStart < stop) : (newStart > stop)) && (newStart != iPos); + if (bProceed) { + SciCall_SetTargetRange(newStart, stop); + iPos = SciCall_SearchInTarget(len, chFind); + } + else { + iPos = NOT_FOUND; } + bValidPos = Sci_IsPosValid(iPos); // NOT_FOUND is a valid pos } } -#endif if (iPos >= 0) { if (fMode != FRMOD_IGNORE) { @@ -685,31 +670,26 @@ typedef enum { MATCH = 0, NO_MATCH = 1, INVALID = 2 } RegExResult_t; static RegExResult_t _FindHasMatch(HWND hwnd, const LPEDITFINDREPLACE lpefr, DocPos iStartPos, bool bMarkAll) { - if (StrgIsEmpty(lpefr->chFindPattern)) { - return NO_MATCH; - } - int const sFlags = (int)(lpefr->fuFlags); - DocPos const iStart = iStartPos; DocPos const iTextEnd = Sci_GetDocEndPosition(); - - DocPos start = iStart; + DocPos start = iStartPos; DocPos end = iTextEnd; + int const sFlags = (int)(lpefr->fuFlags); LPCWSTR wchFind = _EditGetFindStrg(hwnd, lpefr, false); DocPos const iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_IGNORE); - bool const bRegexInvalid = (sFlags & SCFIND_REGEXP) && Sci_ConsumeRegexWarnStatus(); + bool const bRegexInvalid = StrIsNotEmpty(wchFind) && (sFlags & SCFIND_REGEXP) && Sci_ConsumeRegexWarnStatus(); if (bMarkAll) { EditClearAllOccurrenceMarkers(hwnd); if (iPos >= 0) { - EditMarkAll(wchFind, (int)(lpefr->fuFlags), 0, iTextEnd, false); + EditMarkAll(wchFind, sFlags, 0, iTextEnd, false); if (FocusedView.HideNonMatchedLines) { + // Lines hidden by the previous match set may now be headers. + SciCall_FoldAll(EXPAND); EditFoldMarkedLineRange(lpefr->hwnd, true); } - } else { - if (FocusedView.HideNonMatchedLines) { - EditFoldMarkedLineRange(lpefr->hwnd, false); - } + } else if (FocusedView.HideNonMatchedLines) { + EditToggleView(lpefr->hwnd); } } return ((iPos >= 0) ? MATCH : (bRegexInvalid ? INVALID : NO_MATCH)); @@ -860,6 +840,7 @@ static INT_PTR CALLBACK EditFindReplaceDlgProc(HWND hwnd, UINT umsg, WPARAM wPar static LPEDITFINDREPLACE s_pEfrData = NULL; static bool s_bIsReplaceDlg = false; + static bool s_bHasReplacementDraft = false; static bool s_bRestoreFocusedView = false; static UINT_PTR pTimerIdentifier = 0; @@ -1011,15 +992,25 @@ static INT_PTR CALLBACK EditFindReplaceDlgProc(HWND hwnd, UINT umsg, WPARAM wPar CheckDlgButton(hwnd, IDC_TRANSPARENT, SetBtn(Settings.FindReplaceTransparentMode)); - // Now set combobox text — CBN_EDITCHANGE will fire and call - // _SetSearchFlags(), which can now read the correct checkbox states. - if (pInit->pRestore) { - // Restore both fields before edit notifications can sync the partially initialized dialog. + if (s_bIsReplaceDlg) { + // Populate replacement text before the find combo can sync both fields. s_pEfrData = NULL; - ComboBox_SetTextHW(hwnd, IDC_FINDTEXT, pInit->pEfrData->chFindPattern); - if (s_bIsReplaceDlg) { + if (pInit->pRestore || s_bHasReplacementDraft || StrgIsNotEmpty(pInit->pEfrData->chReplaceTemplate)) { ComboBox_SetTextHW(hwnd, IDC_REPLACETEXT, pInit->pEfrData->chReplaceTemplate); } + else if (MRU_Count(Globals.pMRUreplace)) { + MRU_Enum(Globals.pMRUreplace, 0, s_wchBufOut, COUNTOF(s_wchBufOut)); + ComboBox_SetTextW(hwnd, IDC_REPLACETEXT, s_wchBufOut); + } + else { + ComboBox_SetTextW(hwnd, IDC_REPLACETEXT, NULL); + } + s_pEfrData = pInit->pEfrData; + } + + if (pInit->pRestore) { + s_pEfrData = NULL; + ComboBox_SetTextHW(hwnd, IDC_FINDTEXT, pInit->pEfrData->chFindPattern); s_pEfrData = pInit->pEfrData; } else if (!GetWindowTextLengthW(GetDlgItem(hwnd, IDC_FINDTEXT))) { if (StrgIsNotEmpty(s_pEfrData->chFindPattern)) { @@ -1034,21 +1025,6 @@ static INT_PTR CALLBACK EditFindReplaceDlgProc(HWND hwnd, UINT umsg, WPARAM wPar } } - if (s_bIsReplaceDlg && !pInit->pRestore) { - if (!GetWindowTextLengthW(GetDlgItem(hwnd, IDC_REPLACETEXT))) { - if (StrgIsNotEmpty(s_pEfrData->chReplaceTemplate)) { - ComboBox_SetTextHW(hwnd, IDC_REPLACETEXT, s_pEfrData->chReplaceTemplate); - } - else if (MRU_Count(Globals.pMRUreplace)) { - MRU_Enum(Globals.pMRUreplace, 0, s_wchBufOut, COUNTOF(s_wchBufOut)); - ComboBox_SetTextW(hwnd, IDC_REPLACETEXT, s_wchBufOut); - } - else { - ComboBox_SetTextW(hwnd, IDC_REPLACETEXT, NULL); - } - } - } - if (s_bSwitchedFindReplace) { // restore from prev Dlg SetDlgPos(hwnd, s_xFindReplaceDlgSave, s_yFindReplaceDlgSave); @@ -1125,15 +1101,16 @@ static INT_PTR CALLBACK EditFindReplaceDlgProc(HWND hwnd, UINT umsg, WPARAM wPar DuplicateEFR(&(Settings.EFR_Data), s_pEfrData); if (!s_bSwitchedFindReplace) { + s_bHasReplacementDraft = false; if (s_anyMatch == MATCH) { // Save MRUs if (StrgIsNotEmpty(s_pEfrData->chFindPattern)) { MRU_Add(Globals.pMRUfind, StrgGet(s_pEfrData->chFindPattern), 0, -1, -1, NULL); SetFindPattern(StrgGet(s_pEfrData->chFindPattern)); } - //~if (StrgIsNotEmpty(s_pEfrData->chReplaceTemplate)) { + if (s_bIsReplaceDlg) { MRU_Add(Globals.pMRUreplace, StrgGet(s_pEfrData->chReplaceTemplate), 0, -1, -1, NULL); - //~} + } } Globals.iReplacedOccurrences = 0; @@ -1456,8 +1433,6 @@ static INT_PTR CALLBACK EditFindReplaceDlgProc(HWND hwnd, UINT umsg, WPARAM wPar FocusedView.HideNonMatchedLines = true; EditFoldMarkedLineRange(s_pEfrData->hwnd, true); UpdateDocumentReadOnlyState(); - } else if (FocusedView.HideNonMatchedLines) { - EditToggleView(s_pEfrData->hwnd); } } else if (!s_pEfrData->bMarkOccurences && s_pEfrData->bStateChanged) { if (FocusedView.HideNonMatchedLines) { @@ -1577,55 +1552,24 @@ static INT_PTR CALLBACK EditFindReplaceDlgProc(HWND hwnd, UINT umsg, WPARAM wPar case IDOK: case IDC_FINDPREV: case IDACC_SELTONEXT: - case IDACC_SELTOPREV: - case IDMSG_SWITCHTOFIND: - case IDMSG_SWITCHTOREPLACE: { - - if ((!s_bIsReplaceDlg && LOWORD(wParam) == IDMSG_SWITCHTOREPLACE) || - (s_bIsReplaceDlg && LOWORD(wParam) == IDMSG_SWITCHTOFIND)) { - GetDlgPos(hwnd, &s_xFindReplaceDlgSave, &s_yFindReplaceDlgSave); - s_bSwitchedFindReplace = true; - } - - if (!s_bSwitchedFindReplace && !_EnableFRDlgCtrls(hwnd)) { + case IDACC_SELTOPREV: { + if (!_EnableFRDlgCtrls(hwnd)) { return true; } _SetSearchFlags(hwnd, s_pEfrData); - if (s_bSwitchedFindReplace) { - // Reload MRUs - SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_RESETCONTENT, 0, 0); - SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_RESETCONTENT, 0, 0); - - for (int i = 0; i < MRU_Count(Globals.pMRUfind); i++) { - MRU_Enum(Globals.pMRUfind, i, s_wchBufOut, COUNTOF(s_wchBufOut)); - SendDlgItemMessage(hwnd, IDC_FINDTEXT, CB_ADDSTRING, 0, (LPARAM)s_wchBufOut); - } - for (int i = 0; i < MRU_Count(Globals.pMRUreplace); i++) { - MRU_Enum(Globals.pMRUreplace, i, s_wchBufOut, COUNTOF(s_wchBufOut)); - SendDlgItemMessage(hwnd, IDC_REPLACETEXT, CB_ADDSTRING, 0, (LPARAM)s_wchBufOut); - } - ComboBox_SetTextHW(hwnd, IDC_FINDTEXT, s_pEfrData->chFindPattern); - ComboBox_SetTextHW(hwnd, IDC_REPLACETEXT, s_pEfrData->chReplaceTemplate); + // Save MRUs + if (StrgIsNotEmpty(s_pEfrData->chFindPattern)) { + MRU_Add(Globals.pMRUfind, StrgGet(s_pEfrData->chFindPattern), 0, -1, -1, NULL); + SetFindPattern(StrgGet(s_pEfrData->chFindPattern)); } - else { - // Save MRUs - if (StrgIsNotEmpty(s_pEfrData->chFindPattern)) { - MRU_Add(Globals.pMRUfind, StrgGet(s_pEfrData->chFindPattern), 0, -1, -1, NULL); - SetFindPattern(StrgGet(s_pEfrData->chFindPattern)); - } + if (s_bIsReplaceDlg) { MRU_Add(Globals.pMRUreplace, StrgGet(s_pEfrData->chReplaceTemplate), 0, -1, -1, NULL); - // Immediately reflect used patterns in dropdown (without touching the edit field) - _AddPatternToComboMRU(hwnd, IDC_FINDTEXT, StrgGet(s_pEfrData->chFindPattern)); - if (s_bIsReplaceDlg) { - _AddPatternToComboMRU(hwnd, IDC_REPLACETEXT, StrgGet(s_pEfrData->chReplaceTemplate)); - } - } - - if (!s_bSwitchedFindReplace) { - SendMessage(hwnd, WM_NEXTDLGCTL, (WPARAM)(GetFocus()), 1); + _AddPatternToComboMRU(hwnd, IDC_REPLACETEXT, StrgGet(s_pEfrData->chReplaceTemplate)); } + _AddPatternToComboMRU(hwnd, IDC_FINDTEXT, StrgGet(s_pEfrData->chFindPattern)); + SendMessage(hwnd, WM_NEXTDLGCTL, (WPARAM)(GetFocus()), 1); bool bFound = false; @@ -1679,6 +1623,14 @@ static INT_PTR CALLBACK EditFindReplaceDlgProc(HWND hwnd, UINT umsg, WPARAM wPar _DelayMarkAll(_MQ_STD); break; + case IDMSG_SWITCHTOFIND: + case IDMSG_SWITCHTOREPLACE: + if (s_bIsReplaceDlg == (LOWORD(wParam) == IDMSG_SWITCHTOFIND)) { + GetDlgPos(hwnd, &s_xFindReplaceDlgSave, &s_yFindReplaceDlgSave); + s_bSwitchedFindReplace = true; + s_bHasReplacementDraft |= s_bIsReplaceDlg; + } + break; case IDCANCEL: //~EndDialog(hwnd, IDCANCEL); ~ (!) not running on own message loop @@ -2269,8 +2221,8 @@ bool EditReplace(HWND hwnd, LPEDITFINDREPLACE lpefr) return true; } } - // if selection is is not equal current find, set selection - else if ((selBeg != start) || (selEnd != end)) { + // Only replace a selection when the search matched it. + else if ((iPos < 0LL) || (selBeg != start) || (selEnd != end)) { FreeMem(pszReplace); SciCall_SetCurrentPos(selBeg); return EditFindNext(hwnd, lpefr, false, false, false); @@ -2337,6 +2289,7 @@ static DocPosU EditReplaceAllInRange(HWND hwnd, LPEDITFINDREPLACE lpefr, DocPos DocPos iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_NORM); if (bIsRegExpr && Sci_ConsumeRegexWarnStatus()) { + FreeMem(pszReplace); InfoBoxLng(MB_ICONWARNING, Constants.SuppressKey.MsgInvalidRegex, IDS_MUI_REGEX_INVALID); return 0; } @@ -2490,9 +2443,6 @@ static void EditMarkAll(LPCWSTR wchFind, int sFlags, DocPos rangeStart, DocPos r LimitNotifyEvents(); if (StrIsEmpty(wchFind)) { - - WideCharToMultiByte(Encoding_SciCP, 0, wchFind, -1, chText, COUNTOF(chText), NULL, NULL); - if (SciCall_IsSelectionEmpty()) { // nothing selected, get word under caret if flagged if (Settings.MarkOccurrencesCurrentWord && (sFlags & SCFIND_WHOLEWORD)) { @@ -2540,12 +2490,10 @@ static void EditMarkAll(LPCWSTR wchFind, int sFlags, DocPos rangeStart, DocPos r } MultiByteToWideChar(Encoding_SciCP, 0, chText, (int)iFindLength, wchText, (int)COUNTOF(wchText)); - - } else { - StringCchCopy(wchText, COUNTOF(wchText), wchFind); + wchFind = wchText; } - if (StrIsNotEmpty(wchText)) { + if (StrIsNotEmpty(wchFind)) { if (bMultiSel) { SciCall_ClearSelections(); @@ -2559,7 +2507,7 @@ static void EditMarkAll(LPCWSTR wchFind, int sFlags, DocPos rangeStart, DocPos r DocPos start = rangeStart; DocPos end = rangeEnd; - DocPos iPos = _FindInTarget(wchText, sFlags, &start, &end, false, FRMOD_NORM); + DocPos iPos = _FindInTarget(wchFind, sFlags, &start, &end, false, FRMOD_NORM); if (!bMultiSel) { SciCall_SetIndicatorCurrent(INDIC_NP3_MARK_OCCURANCE); // once: doc-change notifications are disabled (LimitNotifyEvents) @@ -2587,7 +2535,7 @@ static void EditMarkAll(LPCWSTR wchFind, int sFlags, DocPos rangeStart, DocPos r } start = end; end = rangeEnd; - iPos = _FindInTarget(wchText, sFlags, &start, &end, true, FRMOD_NORM); + iPos = _FindInTarget(wchFind, sFlags, &start, &end, true, FRMOD_NORM); }; Globals.iSelectionMarkNumber = found; Globals.iMarkOccurrencesCount = count; From 610c95ee07f21e4b266985cda5da08b72b984e85 Mon Sep 17 00:00:00 2001 From: "METANEOCORTEX\\Kotti" Date: Wed, 18 Nov 2026 18:57:42 +0100 Subject: [PATCH 3/3] Refresh Find/Replace match counts after Undo and Redo Invalidate dialog matches on coalesced text changes rather than save-point transitions, and request a status refresh after the delayed recount. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/FindReplace.c | 1 + src/Notepad3.c | 7 +++---- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/FindReplace.c b/src/FindReplace.c index f12b9070f2..5f248c4dc6 100644 --- a/src/FindReplace.c +++ b/src/FindReplace.c @@ -1434,6 +1434,7 @@ static INT_PTR CALLBACK EditFindReplaceDlgProc(HWND hwnd, UINT umsg, WPARAM wPar EditFoldMarkedLineRange(s_pEfrData->hwnd, true); UpdateDocumentReadOnlyState(); } + UpdateStatusbar(false); } else if (!s_pEfrData->bMarkOccurences && s_pEfrData->bStateChanged) { if (FocusedView.HideNonMatchedLines) { SendWMCommand(hwnd, IDC_TOGGLE_VISIBILITY); diff --git a/src/Notepad3.c b/src/Notepad3.c index b6680542ac..7b1b819dc1 100644 --- a/src/Notepad3.c +++ b/src/Notepad3.c @@ -315,9 +315,6 @@ static inline void SetSaveNeeded(const bool bSetFlagForced) if (bSetFlagForced) { s_NeedSavingForced = true; } - if (IsWindow(Globals.hwndDlgFindReplace)) { - PostWMCommand(Globals.hwndDlgFindReplace, IDC_DOC_MODIFIED); - } UpdateToolbar(); } @@ -10233,7 +10230,9 @@ static LRESULT _MsgNotifyFromEdit(HWND hwnd, const SCNotification* const scn) // Scintilla 5.6.6+: coalesced per-UI-update text/line-count refresh, // replacing the former per-edit work in the rapid SCN_MODIFIED handler. if (iUpd & SC_UPDATE_TEXT) { - if (!bMarkOccUpdated && IsMarkOccurrencesEnabled()) { + if (IsWindow(Globals.hwndDlgFindReplace)) { + PostWMCommand(Globals.hwndDlgFindReplace, IDC_DOC_MODIFIED); + } else if (!bMarkOccUpdated && IsMarkOccurrencesEnabled()) { MarkAllOccurrences(-1, true); } // Scintilla 5.6.6 delivers scn->position = earliest changed