mahin
mahin

Reputation: 367

Sublime Text 3: How to select multiple words and paste them into a single line separated by commas?

When you select multiple words in Sublime (by holding down Ctrl) and paste them into a single place, by default each word is separated from the next by \n. I'd like to change that to a comma and, optionally, have quotes put around each word. I'm wondering if there's an easy way to do that. Any help is appreciated.

Upvotes: 2

Views: 1587

Answers (1)

Angus Yeh
Angus Yeh

Reputation: 447

Here is what I would do with some build-in shortcuts:

  1. somehow select the lines you just paste (eg. expand_selection_to_paragraph, which is mapable)
  2. ctrl+shift+l to make them into multi-cursor
  3. ctrl+j to join lines
  4. move cursor to end of each selection by moving right, insert comma, which will be between each selection.

If you want to write a plugin to simplify it (and customise to your exact need). Here is a very crude one I use to make a selection into a python list object. Feel free to modify and map to a key.

import sublime, sublime_plugin

class PythonListifyCommand(sublime_plugin.TextCommand):
    """Change a selected text into a Python list structure.

    Basically this is done by replacing space, comma, tab with comma.  
    Then Python list brackets are attached to both start and end to make 
    a Python list.

    If ther are multiple selections, then multiple lists will be created.
    If any selection is of zero length, then that particular line will 
    be listified.  There will always be a comma at the end of each line, 
    this is to make sure multiple line list can connect up.  Python does 
    not mind extra comma at the end of a list inside bracket.
    """
    def listify(self,line):
        import re
        no_leading = re.sub('^[ ,\t]+','',line)
        no_leading = re.sub('\n[ ,\t]+','\n',no_leading)
        in_line = re.sub('[ ,\t]+',',',no_leading)
        end_line_comma = re.sub('\n',',\n',in_line)
        return end_line_comma

    def run(self, edit):
        sel = self.view.sel()
        view = self.view

        for s in sel:
            if s.a == s.b:
                r = view.line(s)
            else:
                r = s
            rep = '[' + self.listify(view.substr(r)) + ']'
            if rep[-1] is ']' and rep[-2] is '\n':
                rep = rep[:-2] + ']\n'
            view.replace(edit, r, rep)

Upvotes: 2

Related Questions