Python script to replace on selection
I’m using Python Sscript plugin v188.8.131.52 and I created a script to replace charaters and words.
The full script is below
with open(‘D:/config/Notepadpp/replace_char_list.txt’) as f:
for l in f:
s = l.split()
if s == " ":
editor.replace(s, " ")
And here is the contents of the input file
What I’d like to do is to replace only on selection. I’ve read about editor.replaceSel but I don’t know how to use and I haven’t found any examples on the web.
PS: the if statement is there because I couldn’t make the script replace nbsp with a space.
Open the console and type
>>> help(editor.replaceSel) Help on method replaceSel: replaceSel(...) method of Npp.Editor instance replaceSel( (Editor)arg1, (object)text) -> None : Replace the selected text with the argument text.
The first argument, editor, can always be ignored because you call it from
an editor instance, so you need just to provide the text which should be used to replace the content.
But I need to do a search and replace within the selection. If the first argument is the editor, and second is the text to replace, where do I add the item to search?
as the help states it replaces the selected text but from your responds
I understand that you want to, let’s say’ select 4 lines and within this 4 lines
you want to do a search and replace, correct?
If this is the case you need to use the getSelection functions,
most probably getSelectionStart() and getSelectionEnd() and use your
replace with the returned start and end position.
To elaborate a bit on @Claudia-Frank 's explanation, here’s some code that shows how to do a replace on only the text in one or more selections:
find = 'a' replace = 'A' num_selections = editor.getSelections() for sel_nbr in range(num_selections): start_pos = editor.getSelectionNStart(sel_nbr) end_pos = editor.getSelectionNEnd(sel_nbr) editor.replace(find, replace, 0, start_pos, end_pos)