How to wrap selected text in a custom wrapper with keybindings


#1

In my code I have a lot of code like so:

<h4>Custom Entity</h4>

I need to change all instances of plaintext so it’s now to be passed through the Vuex i18n translator like this

<h4>{{ $t(Custom Entity) }}</h4>

This is so it can be internationalized later on.

I really can’t be bothered going to every single one and typing it all out. What i’d like to be able to do is define the wrapping somewhere (e.g {{ $t(x) }}), highlight the plaintext and then hit a keybinding (e.g crtl-shift-A) which will wrap it in that. Would save me a lot of time and potential mistakes. Any thoughts on packages that could do that?


#2

You don’t need a package. You can do it in your init.coffee easily enough using Atom’s API methods, like scan().

# Wrap matched text with other text.
atom.commands.add 'atom-text-editor', 'user:wrap-match', -> # Defines a command to work within the TextEditor.
  return unless editor = atom.workspace.getActiveTextEditor() # Get the active editor object and also return immediately if something goes wrong and there's no active text editor.
  
  # <h4>Example</h4>
  
  prefix = "{{ $t("
  suffix = ") }}"

  editor.scan /(<h4>)(.*)(<\/h4>)/, (result) ->
    console.log result.match     # Remove this after you use it and observe the match object.
    result.replace result.match[1] + prefix + result.match[2] + suffix + result.match[3]

#3

Thank you very much, I will look into that.