Any way to create a shortcut to add prefix and suffix to a word?



  • Say there is a word testword and i want to select it and convert it into ABCtestwordXyZ… is there a way i can define a macro or some other shortcut to do so?
    I have a use case where i need to do this quite often in a certain type of document so a shortcut would come quite handy.

    Thanks!



  • @phenomenal11,

    There is a section in the usermanual with a detailed description of macros for search/replace functions: https://npp-user-manual.org/docs/searching/#searching-actions-when-recorded-as-macros

    However, all you likely need is to use Macro > Start Recording, then Ctrl+H to open the replace dialog, then fill out and run the Replace or Replace All, then Macro > Stop Recording and Macro > Save Current Recorded Macro

    Note that this assumes that your testword is always the same testword (or at least can always match the same regular expression)… if it’s not, you’ll just need to learn how to run the replace macro and fill out the regex quickly.

    For an example, assuming that \b(testword)\b will match your desired search term, and ABC${1}XyZ will be the correct replacement, if you record that macro and save it, then %AppData%\Notepad++\shortcuts.xml will contain something similar to

        <Macro name="ex19459b" Ctrl="no" Alt="no" Shift="no" Key="0">
            <Action type="3" message="1700" wParam="0" lParam="0" sParam="" />
            <Action type="3" message="1601" wParam="0" lParam="0" sParam="\b(testword)\b" />
            <Action type="3" message="1625" wParam="0" lParam="2" sParam="" />
            <Action type="3" message="1602" wParam="0" lParam="0" sParam="ABC${1}XyZ" />
            <Action type="3" message="1702" wParam="0" lParam="768" sParam="" />
            <Action type="3" message="1701" wParam="0" lParam="1608" sParam="" />
        </Macro>
    

    and when you run that macro from the Macro menu, it will replace a single instance of the testword. If you recorded with Replace All instead of Replace, then the last action would have had lparam="1609" instead.

    Using Macro > Modify Shortcut / Delete Macro will allow you to add a keyboard shortcut to that particular macro by selecting the ex19459b (*) row in the dialog, then clicking on Modify and assigning the desired keyboard shortcut. (edit: or when you originally saved and named the macro, you could have assigned the keyboard shortcut then.)

    *: I chose that name ex19459b because ex means example, 19459 is the topic number in the URL of your question here, and b because I made a mistake while recording the first version of the macro)



  • @PeterJones Hi Peter,

    Thanks for taking the time to help me.
    Unfortunately, this method won’t work for me because i do have multiple words that i need to input.
    But i might have a way to bypass this requirement so i ask you another question: Say i want to add a prefix and a suffix to only the bookmarked lines how would i achieve that using find/replace. I saw a couple of solutions on google but they apply the change to all of the lines.
    Thanks



  • @phenomenal11

    You will probably have to resort to scripting, which can do that stuff and more.
    Let us know if you want to go in that direction.
    And your preference for Python, Perl, or even Lua for a scripting language choice.



  • @Alan-Kilborn Hi Alan,

    Sorry for the late reply. Will i be able to execute these said scripts using a keyboard shortcut? If yes, then please do guide me :)
    And i’d say a python script because i have not heard of the other 2 languages…



  • @PeterJones
    :-D
    Do you know when you are getting old?
    If someone reply’s with something like:
    I haven’t heard of those languages and one of those is perl.
    :-D



  • @phenomenal11 said in Any way to create a shortcut to add prefix and suffix to a word?:

    Will i be able to execute these said scripts using a keyboard shortcut?

    Yes.
    Scripts are runnable via selecting them in a menu (always), keyboard-shortcut (optionally, you must pick the keycombo), or toolbar button (optionally).

    And i’d say a python script …

    A good choice. :-)



  • So a bit of research shows there is a script method for prefixing/suffixing entire lines, if that is of interest. See HERE.



  • Here’s a first-cut of a Pythonscript to prefix/suffix a word; there may be some tweaking we need to do to it, depending on my “confusion” about the spec :-) :

    # -*- coding: utf-8 -*-
    
    from Npp import editor
    
    class T19459(object):
        def __init__(self):
            sep = '-'
            word_at_caret_or_selection = ''
            sel_start = editor.getSelectionStart()
            sel_end = editor.getSelectionEnd()
            if editor.getSelections() == 1 and sel_start != sel_end:
                word_at_caret_or_selection = editor.getTextRange(sel_start, sel_end)
            else:
                start_of_word_pos = editor.wordStartPosition(editor.getCurrentPos(), True)
                end_of_word_pos = editor.wordEndPosition(start_of_word_pos, True)
                if start_of_word_pos != end_of_word_pos:
                    word_at_caret_or_selection = editor.getTextRange(start_of_word_pos, end_of_word_pos)
            while True:
                user_input = notepad.prompt(
                    'Enter PREFIX{s}word{s}SUFFIX :\r\n(PREFIX or SUFFIX maybe be empty, but must still use {s})'.format(s=sep),
                    '', sep + word_at_caret_or_selection + sep if len(word_at_caret_or_selection) > 0 else '')
                if user_input == None: return  # Cancel
                parms_list = user_input.strip().split(sep)
                if len(parms_list) == 3:
                    (prefix, word, suffix) = parms_list
                    if len(word) == 0: continue
                    if len(prefix) + len(suffix) == 0: continue
                    break
            editor.beginUndoAction()
            editor.replace(word, prefix + word + suffix)
            editor.endUndoAction()
    
    if __name__ == '__main__': T19459()
    


  • So how does one use a (Python) script?

    • Obtain the Pythonscript plugin (via _Plugins Admin)
    • Create a new script via Plugins > Pythonscript > New Script
    • Give it a (file)name (I chose PrefixOrSuffixAWord.py for this one)
    • Paste the above script text into the file tab; save it
    • To run it, menu to Plugins > Pythonscript > Scripts and then pick the script from the list shown

    Instructions for how to do a keyboard shortcut for a script can come after we determine if it works well for the need.



  • Actually, thinking about it some more, this scripted approach isn’t substantially different from a non-scripted Replace operation! LOL

    I guess I await clarification from the OP!



  • @Alan-Kilborn
    Hi Alan, I followed your instructions and the script works!!
    I get a pop box asking what prefix and suffix i need to enter and it changes the word perfectly. Also tested on an entire line and it works for that as well.

    But if that word(or line) is repeated multiple times in the file it just replaces all of them. There is no option to replace only that instance of the word(or line)…

    Also is there a way i can pre-define what prefix and suffix need to be entered so that regardless of the selected word it adds same prefix and suffix?



  • @phenomenal11

    Yes, okay, I knew I had some “disconnects” there about what was needed. :-)

    I’ll rework it a bit. Check back later.



  • @phenomenal11 said in Any way to create a shortcut to add prefix and suffix to a word?:

    because i do have multiple words that i need to input.

    One thing you haven’t made clear: whether this means (1) “I have exactly N words, testword and anotherword and … and wordN, which need prefixes and suffixes added”, or whether this means (2) “one time I run the script, it will be with testword, the next time, it will be with randomword, and I will not know before-the-fact what testword and randomword will or won’t be”.

    In case (1), it would be easy to tweak the regex to look for a variety of words: \b(testword|anotherword|wordN)\b.

    In case (2), as @Alan-Kilborn said, “isn’t substantially differerent from a non-scripted Replace operation”.

    Your further clarification while I was writing this, “There is no option to replace only that instance of the word(or line)…” shows that you really seem to want a specialized search/replace dialog with pre-defined values rather than having to type them in. The easiest thing to do is to have a file somewhere that pre-defines your replace expression, and so you paste in the replacement, then modify the search to your heart’s content. But if you would prefer a custom dialog, @Alan-Kilborn is kindly providing that for you.

    I highly recommend you study the code he’s already provided, and start thinking about how you might modify it to suit your needs. When Alan comes back with a reply with customized code, you can compare his results to what you came up with. Even if you don’t know Python all that well, at least try to come up with pseudo-Python to do it: that is, think algorithmically, and try to define the steps that you as a human would have to take to accomplish the job. This will help you in the future, if you later decide you need to tweak the stored prefix and suffix in the code, or if you need to change your rule for when your word matches or doesn’t.



  • Okay, here’s another (and probably last) try.
    Basically, if there’s no active selection and the caret isn’t touching a word when the script is run, it means you want to modify the current prefix/suffix setup.
    Otherwise, the current prefix/suffix is applied to the current selection/word.

    # -*- coding: utf-8 -*-
    
    from Npp import editor
    
    class T19459a(object):
    
        def __init__(self):
    
            self._prefix = ''
            self._suffix = ''
    
        def update_prefix_suffix_info(self):
    
            separator = '-'
            while True:
                user_input = notepad.prompt(
                    'Enter PREFIX{s}SUFFIX :\r\n(PREFIX or SUFFIX (not both) maybe be empty, but must still use {s})'.format(s=separator),
                    '', '')
                if user_input == None: return  # Cancel
                parms_list = user_input.strip().split(separator)
                if len(parms_list) == 2:
                    (prefix, suffix) = parms_list
                    if len(prefix) + len(suffix) == 0: continue
                    break
            self._prefix = prefix
            self._suffix = suffix
    
        def run(self):
    
            already_ran_input_prompt_this_cycle = False
            if len(self._prefix + self._suffix) == 0:
                self.update_prefix_suffix_info()
                already_ran_input_prompt_this_cycle = True
    
            word_at_caret_or_selection = ''
            (sel_start, sel_end) = (editor.getSelectionStart(), editor.getSelectionEnd())
            if editor.getSelections() == 1 and sel_start != sel_end:
                word_at_caret_or_selection = editor.getTextRange(sel_start, sel_end)
            else:
                start_of_word_pos = editor.wordStartPosition(editor.getCurrentPos(), True)
                end_of_word_pos = editor.wordEndPosition(start_of_word_pos, True)
                if start_of_word_pos != end_of_word_pos:
                    word_at_caret_or_selection = editor.getTextRange(start_of_word_pos, end_of_word_pos)
                    editor.setSelection(end_of_word_pos, start_of_word_pos)
    
            if len(word_at_caret_or_selection) == 0:
                if not already_ran_input_prompt_this_cycle: self.update_prefix_suffix_info()
            elif len(self._prefix + self._suffix) > 0:
                editor.beginUndoAction()
                editor.replaceSel(self._prefix + word_at_caret_or_selection + self._suffix)
                editor.endUndoAction()
    
    if __name__ == '__main__':
    
        try:
            t19459a
        except NameError:
            t19459a = T19459a()
    
        t19459a.run()
    

Log in to reply