Python script to replace on selection
-
Hello,
I’m using Python Sscript plugin v1.0.8.0 and I created a script to replace charaters and words.
The full script is belowwith open(‘D:/config/Notepadpp/replace_char_list.txt’) as f:
for l in f:
s = l.split()
if s[0] == " ":
editor.replace(s[0], " ")
else:
editor.replace(s[0], s[1])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.
Thank you
-
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.Cheers
Claudia -
@Claudia-Frank
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.Cheers
Claudia -
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)
Hello! It looks like you're interested in this conversation, but you don't have an account yet.
Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.
With your input, this post could be even better 💗
Register Login