Community
    • Login

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

    Scheduled Pinned Locked Moved Help wanted · · · – – – · · ·
    15 Posts 4 Posters 2.8k Views
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • phenomenal11P
      phenomenal11 @Alan Kilborn
      last edited by

      @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…

      Alan KilbornA 1 Reply Last reply Reply Quote 0
      • EkopalypseE
        Ekopalypse
        last edited by

        @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

        1 Reply Last reply Reply Quote 2
        • Alan KilbornA
          Alan Kilborn @phenomenal11
          last edited by Alan Kilborn

          @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. :-)

          1 Reply Last reply Reply Quote 1
          • Alan KilbornA
            Alan Kilborn
            last edited by

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

            1 Reply Last reply Reply Quote 1
            • Alan KilbornA
              Alan Kilborn
              last edited by

              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()
              
              1 Reply Last reply Reply Quote 2
              • Alan KilbornA
                Alan Kilborn
                last edited by

                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.

                phenomenal11P 1 Reply Last reply Reply Quote 1
                • Alan KilbornA
                  Alan Kilborn
                  last edited by

                  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!

                  1 Reply Last reply Reply Quote 0
                  • phenomenal11P
                    phenomenal11 @Alan Kilborn
                    last edited by

                    @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?

                    Alan KilbornA 1 Reply Last reply Reply Quote 0
                    • Alan KilbornA
                      Alan Kilborn @phenomenal11
                      last edited by

                      @phenomenal11

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

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

                      1 Reply Last reply Reply Quote 1
                      • PeterJonesP
                        PeterJones @phenomenal11
                        last edited by

                        @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.

                        1 Reply Last reply Reply Quote 1
                        • Alan KilbornA
                          Alan Kilborn
                          last edited by

                          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()
                          
                          1 Reply Last reply Reply Quote 1
                          • First post
                            Last post
                          The Community of users of the Notepad++ text editor.
                          Powered by NodeBB | Contributors