changeset 34:8535209b61ff

replace
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 14 Apr 2025 14:21:36 -0600
parents e19ac0784287
children c5b57654147b
files editor.luan
diffstat 1 files changed, 36 insertions(+), 5 deletions(-) [+]
line wrap: on
line diff
--- a/editor.luan	Mon Apr 14 12:48:05 2025 -0600
+++ b/editor.luan	Mon Apr 14 14:21:36 2025 -0600
@@ -11,6 +11,7 @@
 local find = String.find or error()
 local regex = String.regex or error()
 local regex_quote = String.regex_quote or error()
+local regex_quote_replacement = String.regex_quote_replacement or error()
 local Io = require "luan:Io.luan"
 local print = Io.print or error()
 local new_file = Io.schemes.file or error()
@@ -231,7 +232,7 @@
 
 local function make_find_panel(window)
 	local text_area = window.text_area
-	local find_field, regex_check_box, output
+	local find_field, replace_field, regex_check_box, output
 	local function find_match(event)
 		--logger.info("action "..event.action)
 		local s = find_field.text
@@ -284,12 +285,42 @@
 			error(action)
 		end
 	end
+	local function replace_match(_)
+		local find = find_field.text
+		if #find == 0 then
+			output.text = ""
+			return
+		end
+		local replace = replace_field.text
+		if not regex_check_box.is_selected then
+			find = regex_quote(find)
+			replace = regex_quote_replacement(replace)
+		end
+		local r
+		try
+			r = regex(find)
+		catch e
+			output.text = "Regex error: "..e.get_message()
+			return
+		end
+		local selection = text_area.selected_text
+		local new, n = r.gsub(selection,replace)
+		if n > 0 then
+			text_area.selected_text = new
+		end
+		output.text = n.." replacements"
+	end
 	find_field = new_text_field{
 		constraints = "growx"
 		show_whitespace = true
 		action = "next"
 		action_listener = find_match
 	}
+	replace_field = new_text_field{
+		constraints = "growx"
+		show_whitespace = true
+		action_listener = replace_match
+	}
 	regex_check_box = new_check_box{
 		text = "Use Regex"
 	}
@@ -322,13 +353,12 @@
 				constraints = "right"
 				text = "Replace:"
 			}
-			new_text_field{
-				constraints = "growx"
-				show_whitespace = true
-			}
+			replace_field
 			new_button{
 				constraints = "grow"
 				text = "Replace"
+				tool_tip_text = "Replace matches in selected text"
+				action_listener = replace_match
 			}
 			new_button{
 				constraints = "grow,wrap"
@@ -360,6 +390,7 @@
 		find_field.text = "(?i)\Q\E"
 		find_field.set_selection(7)
 		find_field.request_focus_in_window()
+		output.text = ""
 	end
 	return find_panel
 end