Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Sublime Text2 | 文字列をスネークケースに変換するプラグインを作成

概要

文字列をスネークケースに変換するプラグインを作成

内容

仕様
・変換結果をすべて大文字にするかどうか設定で選べるようにする。
※全大文字はRubyの定数での利用想定
・すべて大文字にするかどうか設定を省略した場合は小文字をデフォルトにする
・区切り文字は大文字,半角スペースになっているものをスネークケースへの変換対象とする

変換前 変換後 upper
hogeHigeHage hoge_hige_hage false
hoge_hoge hoge_hoge false
hoge hoge hoge_hoge false
hogeHigeHage HOGE_HIGE_HAGE true
hoge_hoge HOGE_HOGE true
hoge hoge HOGE_HOGE true
空文字 空文字 --
None None --

複数選択していた場合はすべてが処理対象

サンプルコード

# -*- coding: utf-8 -*-
import sublime, sublime_plugin
from string_utils import *
 
class ToSnakeCommand(sublime_plugin.TextCommand):
  def run(self, edit, **kwargs):
    is_upper = False
    if kwargs["upper"] is not None:
      is_upper = bool(kwargs["upper"])

    for region in self.view.sel():
      if not region.empty():
        ret = StringUtils.to_snake(self.view.substr(region), is_upper)
        self.view.replace(edit, region, ret)

※string_utilsの部分は下記参照
Python | 文字列をスネークケースに変換
http://d.hatena.ne.jp/tbpg/20130624/1372079671

キーバインド設定

※何かのキー+sにしたかったもののいいキーが相手なくて暫定で下記に設定

{ "keys": ["ctrl+shift+o"], "command": "to_snake", "args": {"upper": false }},
{ "keys": ["ctrl+alt+shift+o"], "command": "to_snake", "args": {"upper": true }}

実行例

upper false

変換前

選択中

変換後