Skip to content

Commit

Permalink
Merge pull request #53 from daddel80/feature/init-at-start
Browse files Browse the repository at this point in the history
Feature/init at start
  • Loading branch information
daddel80 authored Sep 6, 2024
2 parents 81ca57c + 8cef508 commit a9a0149
Show file tree
Hide file tree
Showing 4 changed files with 91 additions and 15 deletions.
9 changes: 8 additions & 1 deletion languages.ini
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ status_no_find_string="No 'Find' String entered. Please provide a value to add t
status_no_rows_selected_to_shift="No rows selected to shift."
status_add_values_or_uncheck="Add values into the list or uncheck 'Use in List'."
status_no_occurrence_found="No occurrence found."
status_found_text_not_replaced="Found text was not replaced."
status_replace_one_next_found="Replace: 1 occurrence replaced. Next found."
status_replace_one_none_left="Replace: 1 occurrence replaced. None left."
status_add_values_or_find_directly="Add values into the list. Or uncheck 'Use in List' to find directly."
Expand Down Expand Up @@ -168,6 +169,7 @@ ctxmenu_select_all="Select &All Ctrl+A"
ctxmenu_enable="E&nable Alt+A"
ctxmenu_disable="D&isable Alt+D"


[german]
; Panel labels (visible text on the control elements)
panel_find_what="Suche nach: "
Expand Down Expand Up @@ -261,6 +263,7 @@ status_no_find_string="Keinen Suchtext eingegeben. Bitte geben Sie eine Zeichenf
status_no_rows_selected_to_shift="Keine Zeilen zum Verschieben ausgewählt."
status_add_values_or_uncheck="Texte in die Liste einfügen oder 'Liste ein' abwählen."
status_no_occurrence_found="Kein Vorkommen gefunden."
status_found_text_not_replaced="Gefundener Text wurde nicht ersetzt."
status_replace_one_next_found="Ersetzen: 1 Vorkommen ersetzt. Nächstes gefunden."
status_replace_one_none_left="Ersetzen: 1 Vorkommen ersetzt. Keine weiteren übrig."
status_add_values_or_find_directly="Texte in die Liste einfügen oder 'Liste ein' abwählen, um direkt zu finden."
Expand Down Expand Up @@ -432,6 +435,7 @@ status_no_find_string="Nessuna 'Stringa di ricerca' inserita. Inserire a valore
status_no_rows_selected_to_shift="Nessuna riga selezionata da spostare."
status_add_values_or_uncheck="Aggiungi valori alla lista oppure deseleziona 'Usa nell'elenco''."
status_no_occurrence_found="Nessuna corrispondenza trovata."
status_found_text_not_replaced="Testo trovato non sostituito."
status_replace_one_next_found="Sostituisci: 1 corrispondenza sostituita. Successiva trovata."
status_replace_one_none_left="Sostituisci: 1 corrispondenza sostituita. Nessuna successiva."
status_add_values_or_find_directly="Aggiungi valori alla lista. Oppure deseleziona 'Usa nella lista' per cercare direttamente."
Expand Down Expand Up @@ -603,6 +607,7 @@ status_no_find_string="Nincs beírva 'Keresett Szöveg'. Kérem adjon meg egy é
status_no_rows_selected_to_shift="Nincsenek kiválasztott sorok a mozgatáshoz."
status_add_values_or_uncheck="Adjon értékeket a listához vagy pipálja ki a 'Listában használ' opciót."
status_no_occurrence_found="Nem található előfordulás."
status_found_text_not_replaced="A megtalált szöveg nem lett cserélve."
status_replace_one_next_found="Csere: 1 előfordulás cserélve. Következő megtalálva."
status_replace_one_none_left="Csere: 1 előfordulás cserélve. Egyik sem maradt."
status_add_values_or_find_directly="Adjon értékeket a listához. Vagy pipálja ki a 'Listában használ' opciót a közvetlen kereséshez."
Expand Down Expand Up @@ -679,6 +684,7 @@ ctxmenu_select_all="&Összes kiválasztása Ctrl+A"
ctxmenu_enable="&Engedélyez Alt+A"
ctxmenu_disable="&Letilt Alt+D"
[russian]
; Panel labels (visible text on the control elements)
panel_find_what="Найти:"
Expand Down Expand Up @@ -773,6 +779,7 @@ status_no_find_string="Поле 'Найти' пусто. Внесите знач
status_no_rows_selected_to_shift="Нет выделенных строк для перемещения строк."
status_add_values_or_uncheck="Добавьте значения в список или снимите флажок 'Список'."
status_no_occurrence_found="Не найдено."
status_found_text_not_replaced="Найденный текст не заменён."
status_replace_one_next_found="Заменено 1 раз. Найдено следующее."
status_replace_one_none_left="Заменено 1 раз. Больше не найдено."
status_add_values_or_find_directly="Добавьте значения в список или снимите флажок 'Список' для прямой замены."
Expand Down Expand Up @@ -944,7 +951,7 @@ status_add_values_instructions="Agregue valores a la lista. O desmarque 'Usar li
status_no_find_string="No se ingresó cadena de 'Buscar'. Proporcione un valor para agregar a la lista."
status_no_rows_selected_to_shift="No se seleccionaron filas para mover."
status_add_values_or_uncheck="Agregue valores a la lista o desmarque 'Usar lista'."
status_no_occurrence_found="No se encontró ninguna ocurrencia."
status_found_text_not_replaced="El texto encontrado no fue sustituido."
status_replace_one_next_found="Reemplazar: 1 ocurrencia reemplazada. Siguiente encontrado."
status_replace_one_none_left="Reemplazar: 1 ocurrencia reemplazada. No quedan más."
status_add_values_or_find_directly="Agregue valores a la lista. O desmarque 'Usar lista' para buscar directamente."
Expand Down
91 changes: 79 additions & 12 deletions src/MultiReplacePanel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -607,8 +607,10 @@ void MultiReplace::createListViewColumns(HWND listView) {
}

void MultiReplace::insertReplaceListItem(const ReplaceItemData& itemData) {
// Return early if findText is empty
if (itemData.findText.empty()) {
int useVariables = IsDlgButtonChecked(_hSelf, IDC_USE_VARIABLES_CHECKBOX) == BST_CHECKED ? 1 : 0;

// Return early if findText is empty and "Use Variables" is not enabled
if (itemData.findText.empty() && useVariables == 0) {
showStatusMessage(getLangStr(L"status_no_find_string"), RGB(255, 0, 0));
return;
}
Expand Down Expand Up @@ -2511,6 +2513,12 @@ void MultiReplace::handleReplaceAllButton() {
showStatusMessage(getLangStr(L"status_add_values_instructions"), RGB(255, 0, 0));
return;
}

// Check the status if stopped by DEBUG
if (!preProcessListForReplace()) {
return;
}

::SendMessage(_hScintilla, SCI_BEGINUNDOACTION, 0, 0);
for (size_t i = 0; i < replaceListData.size(); ++i)
{
Expand Down Expand Up @@ -2564,6 +2572,9 @@ void MultiReplace::handleReplaceButton() {
return;
}

// Clear all stored Lua Global Variables
globalLuaVariablesMap.clear();

bool useListEnabled = (IsDlgButtonChecked(_hSelf, IDC_USE_LIST_CHECKBOX) == BST_CHECKED);
bool wrapAroundEnabled = (IsDlgButtonChecked(_hSelf, IDC_WRAP_AROUND_CHECKBOX) == BST_CHECKED);

Expand All @@ -2581,6 +2592,11 @@ void MultiReplace::handleReplaceButton() {
return;
}

// Check the status if stopped by DEBUG
if (!preProcessListForReplace()) {
return;
}

SelectionInfo selection = getSelectionInfo();

int replacements = 0; // Counter for replacements
Expand Down Expand Up @@ -2611,6 +2627,9 @@ void MultiReplace::handleReplaceButton() {
if (searchResult.pos < 0) {
showStatusMessage(getLangStr(L"status_no_occurrence_found"), RGB(255, 0, 0));
}
else {
showStatusMessage(getLangStr(L"status_found_text_not_replaced"), RGB(255, 0, 0));
}
}
}
else {
Expand Down Expand Up @@ -2652,9 +2671,11 @@ void MultiReplace::handleReplaceButton() {
if (searchResult.pos < 0) {
showStatusMessage(getLangStr(L"status_no_occurrence_found"), RGB(255, 0, 0));
}
else {
showStatusMessage(getLangStr(L"status_found_text_not_replaced"), RGB(255, 0, 0));
}
}
}

}

bool MultiReplace::replaceOne(const ReplaceItemData& itemData, const SelectionInfo& selection, SearchResult& searchResult, Sci_Position& newPos)
Expand Down Expand Up @@ -2845,6 +2866,24 @@ Sci_Position MultiReplace::performRegexReplace(const std::string& replaceTextUtf
return newTargetEnd;
}

bool MultiReplace::preProcessListForReplace() {
if (!replaceListData.empty()) {
for (size_t i = 0; i < replaceListData.size(); ++i) {
if (replaceListData[i].isEnabled && replaceListData[i].useVariables) {
if (replaceListData[i].findText.empty()) {
std::string localReplaceTextUtf8 = wstringToString(replaceListData[i].replaceText);
bool skipReplace = false;
LuaVariables vars;
if (!resolveLuaSyntax(localReplaceTextUtf8, vars, skipReplace, replaceListData[i].regex)) {
return false;
}
}
}
}
}
return true;
}

SelectionInfo MultiReplace::getSelectionInfo() {
// Get selected text
Sci_Position selectionStart = ::SendMessage(_hScintilla, SCI_GETSELECTIONSTART, 0, 0);
Expand Down Expand Up @@ -2963,7 +3002,7 @@ bool MultiReplace::resolveLuaSyntax(std::string& inputString, const LuaVariables
luaL_dostring(L, "LPOS = math.tointeger(LPOS)");
luaL_dostring(L, "APOS = math.tointeger(APOS)");
luaL_dostring(L, "COL = math.tointeger(COL)");

setLuaVariable(L, "MATCH", vars.MATCH);
// Get CAPs from Scintilla using SCI_GETTAG
std::vector<std::string> capNames; // Vector to store the names of the set CAP variables for DEBUG Window
Expand Down Expand Up @@ -3056,8 +3095,7 @@ bool MultiReplace::resolveLuaSyntax(std::string& inputString, const LuaVariables
" end\n"
" resultTable = res\n"
" return res -- Return the table containing result and skip\n"
"end\n");

"end\n");

// Declare the set function
luaL_dostring(L,
Expand Down Expand Up @@ -3117,12 +3155,13 @@ bool MultiReplace::resolveLuaSyntax(std::string& inputString, const LuaVariables
" end\n"
" end\n"
" return output\n"
"end");
"end\n");

// Declare the init function
luaL_dostring(L,
"function init(args)\n"
" for name, value in pairs(args) do\n"
" -- Set the global variable only if it does not already exist\n"
" if _G[name] == nil then\n"
" if type(name) ~= 'string' then\n"
" error('Variable name must be a string')\n"
Expand All @@ -3140,8 +3179,27 @@ bool MultiReplace::resolveLuaSyntax(std::string& inputString, const LuaVariables
" _G[name] = value\n"
" end\n"
" end\n"

" -- Forward or initialize resultTable\n"
" local res = {result = '', skip = true} -- Defaults for resultTable\n"

" -- Ensure resultTable is not overwritten if combined with cond or set\n"
" if resultTable == nil then\n"
" resultTable = res -- Initialize resultTable if it does not exist\n"
" else\n"
" -- Ensure required fields are present without overwriting existing values\n"
" if resultTable.result == nil then\n"
" resultTable.result = res.result\n"
" end\n"
" if resultTable.skip == nil then\n"
" resultTable.skip = res.skip\n"
" end\n"
" end\n"

" return resultTable -- Return the existing or new resultTable\n"
"end\n");


// Show syntax error
if (luaL_dostring(L, inputString.c_str()) != LUA_OK) {
const char* cstr = lua_tostring(L, -1);
Expand All @@ -3153,7 +3211,7 @@ bool MultiReplace::resolveLuaSyntax(std::string& inputString, const LuaVariables
lua_close(L);
return false;
}

// Retrieve the result from the table
lua_getglobal(L, "resultTable");
if (lua_istable(L, -1)) {
Expand Down Expand Up @@ -3713,6 +3771,11 @@ void MultiReplace::handleFindPrevButton() {

SearchResult MultiReplace::performSingleSearch(const std::string& findTextUtf8, int searchFlags, bool selectMatch, SelectionRange range) {

// Check if the search string is empty
if (findTextUtf8.empty()) {
return SearchResult(); // Returns the default-initialized SearchResult
}

send(SCI_SETTARGETSTART, range.start, 0);
send(SCI_SETTARGETEND, range.end, 0);
send(SCI_SETSEARCHFLAGS, searchFlags, 0);
Expand Down Expand Up @@ -3977,23 +4040,23 @@ SearchResult MultiReplace::performListSearchForward(const std::vector<ReplaceIte
closestMatch.length = 0;
closestMatch.foundText = "";

closestMatchIndex = std::numeric_limits<size_t>::max(); // Initialisiert mit einem Wert, der "keinen Index" darstellt.
closestMatchIndex = std::numeric_limits<size_t>::max(); // Initialize with a value representing "no index".

for (size_t i = 0; i < list.size(); i++) {
if (list[i].isEnabled) {
int searchFlags = (list[i].wholeWord * SCFIND_WHOLEWORD) | (list[i].matchCase * SCFIND_MATCHCASE) | (list[i].regex * SCFIND_REGEXP);
std::string findTextUtf8 = convertAndExtend(list[i].findText, list[i].extended);
SearchResult result = performSearchForward(findTextUtf8, searchFlags, false, cursorPos);

// Wenn ein Treffer gefunden wurde, der näher am Cursor liegt als der aktuelle nächste Treffer, aktualisiere den nächstgelegenen Treffer
// If a match is found that is closer to the cursor than the current closest match, update the closest match
if (result.pos >= 0 && (closestMatch.pos < 0 || result.pos < closestMatch.pos)) {
closestMatch = result;
closestMatchIndex = i; // Aktualisiere den Index des nächstgelegenen Treffers
closestMatchIndex = i; // Update the index of the closest match
}
}
}

if (closestMatch.pos >= 0) { // Überprüfe, ob ein Treffer gefunden wurde
if (closestMatch.pos >= 0) { // Check if a match was found
displayResultCentered(closestMatch.pos, closestMatch.pos + closestMatch.length, true);
}

Expand Down Expand Up @@ -5789,6 +5852,10 @@ sptr_t MultiReplace::send(unsigned int iMessage, uptr_t wParam, sptr_t lParam, b
*/

bool MultiReplace::normalizeAndValidateNumber(std::string& str) {
if (str.empty()) {
return false; // An empty string is not a valid number
}

if (str == "." || str == ",") {
return false;
}
Expand Down
5 changes: 3 additions & 2 deletions src/MultiReplacePanel.h
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,8 @@ struct LuaVariables {
int LPOS = 0;
int LCNT = 0;
int APOS = 0;
int COL = 1;
std::string MATCH;
int COL = 0;
std::string MATCH = "";
};

enum class LuaVariableType {
Expand Down Expand Up @@ -459,6 +459,7 @@ class MultiReplace : public StaticDialog
bool replaceOne(const ReplaceItemData& itemData, const SelectionInfo& selection, SearchResult& searchResult, Sci_Position& newPos);
Sci_Position performReplace(const std::string& replaceTextUtf8, Sci_Position pos, Sci_Position length);
Sci_Position performRegexReplace(const std::string& replaceTextUtf8, Sci_Position pos, Sci_Position length);
bool MultiReplace::preProcessListForReplace();
SelectionInfo getSelectionInfo();
void captureLuaGlobals(lua_State* L);
void loadLuaGlobals(lua_State* L);
Expand Down
1 change: 1 addition & 0 deletions src/language_mapping.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ std::unordered_map<std::wstring, std::wstring> languageMap = {
{ L"status_no_rows_selected_to_shift", L"No rows selected to shift." },
{ L"status_add_values_or_uncheck", L"Add values into the list or uncheck 'Use in List'." },
{ L"status_no_occurrence_found", L"No occurrence found." },
{ L"status_found_text_not_replaced", L"Found text was not replaced." },
{ L"status_replace_one_next_found", L"Replace: 1 occurrence replaced. Next found." },
{ L"status_replace_one_none_left", L"Replace: 1 occurrence replaced. None left." },
{ L"status_add_values_or_find_directly", L"Add values into the list. Or uncheck 'Use in List' to find directly." },
Expand Down

0 comments on commit a9a0149

Please sign in to comment.