LoginSignup
2
0

More than 5 years have passed since last update.

String s = の行でペーストするとダブルクォーテーションをエスケープするプラグイン

Last updated at Posted at 2013-03-14

おぉ、NetBeans7.3は「{"id":1,"name":"hoge"}」をペーストするときに、「String s="」の続きにペーストすると勝手に「{\"id\":1,\"name\":\"hoge\"}」になってくれる!文字列リテラルの外だとそのままペーストされる!便利!

@kis さんがこう言っていたのでSublimeTextのプラグインを作ってみました。

StringEscapePaste.py
import sublime, sublime_plugin
import re

class StringEscapePasteCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        line_str = self.view.substr(self.view.line(self.view.sel()[0]))
        match = re.match('^\s*String\s+.+\s*=', line_str, re.I)
        if match:
            clipboard = sublime.get_clipboard()
            self.view.insert(edit, self.view.sel()[0].begin(), clipboard.replace('\"', '\\\"'))
        else:
            self.view.run_command('paste')

正規表現を見て、ん?と思った方。素晴らしい洞察力です。
その想像通り変数初期化時にしか使えません。

これではあまりにも酷いので

キャレットがダブルクォーテーションに挟まれていたらエスケープするように改良しました。

StringEscapePaste.py
class StringEscapePasteCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        line_str = self.view.substr(self.view.line(self.view.sel()[0]))
        match = re.search('\".*\"', line_str)
        if match:
            sel_rowcol = self.view.rowcol(self.view.sel()[0].begin())
            if match.start() < sel_rowcol[1] and sel_rowcol[1] < match.end():
                clipboard = sublime.get_clipboard()
                self.view.insert(edit, self.view.sel()[0].begin(), clipboard.replace('\"', '\\\"'))
            else:
                self.view.run_command('paste')
        else:
            self.view.run_command('paste')
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0