Ubuntuのときに使っていたテキストエディタのGeditにWindows版があったから、Atomの重さにキレて消したたついでに入れてみた。
インストールはインストーラー拾ってきて実行して終了。
ボトムペインが出てこないのはなんでだろう…Pythonコンソール使いたい…
ついでなんでプラグイン書いてみた。
Atomのpretty-jsonみたいなものが欲しかったので、Geditのプラグインの学習がてら書いてみた。
だいたいのことはGedit プラグインの作り方(v3.12 以降)をコピーしつつ修正
jsonformat.plugin
    [Plugin]
    Loader=python3
    Module=jsonformat
    IAge=3
    Name=Json format
    Name[ja]=Json フォーマット
    Description=Json format
    Description[ja]=Jsonを見やすく
    Authors=mattyan <mattyan@gmail.com>
    Copyright=Copyright © 2016 mattyan <mattyan@gmail.com>
    Website=https://mattyan.net/
プラグインの設定ファイル
jsonformat/__init__.py
[python]
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gedit", "3.0")
from .appactivatable import AppActivatable
from .windowactivatable import WindowActivatable
[/python]
AppActivateとWindowActivateを読み込み
jsonformat/appactivate.py
[python]
from gi.repository import GObject, Gedit, Gtk, Gio
class AppActivatable(GObject.Object, Gedit.AppActivatable):
	app = GObject.property(type = Gedit.App)
	def __init__(self):
		GObject.Object.__init__(self)
	def do_activate(self):
		item = Gio.MenuItem.new(‘JsonFormat’, ‘win.JsonFormatAction’)
		self.menu_extend = self.extend_menu(‘tools-section’)
		self.menu_extend.append_menu_item(item)
	def do_deactivate(self):
		pass
[/python]
アプリケーションの初期設定。do_activate()ではメーニューの設定をしている。
jsonformat/windowactivate.py
[python]
from gi.repository import GObject, Gedit, Gtk, Gio
import json
class WindowActivatable(GObject.Object, Gedit.WindowActivatable):
	__gtype_name__ = ‘WindowActivatable’
	window = GObject.property(type = Gedit.Window)
	def __init__(self):
		GObject.Object.__init__(self)
	def do_activate(self):
		action = Gio.SimpleAction.new(‘JsonFormatAction’, None)
		action.connect(‘activate’, self.on_click_format)
		self.window.add_action(action)
		pass
	def do_deactivate(self):
		self.window.remove_action(‘JsonFormatAction’)
		pass
	def do_update_state(self):
		pass
	def on_click_format(self, action, data = None):
		doc = self.window.get_active_document()
		try:
			data = json.loads(doc.get_start_iter().get_text(doc.get_end_iter()))
			doc.set_text(json.dumps(data, indent = 4))
		except Exception as e:
			pass
[/python]
イベントの設定と実行。do_activate()でイベントの設定をしてon_click_format()で実際の処理。
面倒なんで実行中の例外は全部握りつぶしてる。
あとたぶんGtkの仕様なんだろうけど、アクティブタグのテキスト取得がちょっと面倒。
設定は
[python]
doc = self.window.get_active_document()
doc.set_text(‘text’)
[/python]
でいいのに読み込みは
[python]
doc = self.window.get_active_document()
data = doc.get_start_iter().get_text(doc.get_end_iter())
[/python]
とドキュメントの開始イテレーターを取得してからそれのget_textを呼ぶみたい。よくわからん…
あとWindows版Geditは標準出力や標準エラーに出力しないからプラグイン実装中にバグっても何もわからん…VirtualBoxにUbuntu入れてそっちでデバッグしたけど面倒…