MarkdownをHTMLに変換するエディタ(2)

[前回][1] で作成したプログラムに、ポップアップメニューから「コピー」「切り取り」「貼り付け」の機能を追加する。

ポップアップメニューの作成は、「[逆引き Ruby/Tk][2]」の「[ポップアップメニューを作る][3]」で実装方法を発見した。

「コピー」「切り取り」「貼り付け」の実装方法がわからず、ソースコードを見ることに。

tk/text.rbを見ると、「text\_cut」「text\_copy」「text\_paste」という、まさにそのままのメソッドを発見して、無事に完成。

ちなみに環境は、Windows + [One-Click Installer 1.8.2-15][4]

#!/usr/bin/env ruby
$KCODE = ‘SJIS’
require ‘tk’
require ‘bluecloth’

class MarkdownEditor
TITLE = ‘Markdown Editor’

def initialize
Tk.root.title(TITLE)
f = TkFrame.new.pack(:fill => :x)
@button = TkButton.new(f,
‘text’=>’Change Mode’,
‘command’ => proc{swich_mode()}
).pack(‘side’ => ‘left’)
@label = TkLabel.new(f).pack(:side => :left)

scr_x = TkScrollbar.new.pack(:fill=>:x, :side=>:bottom)
scr_y = TkScrollbar.new.pack(:fill=>:y, :side=>:right)
@editor = TkText.new {
xscrollbar(scr_x)
yscrollbar(scr_y)
}.pack(:fill => :both, :expand => true)

menu = TkMenu.new { tearoff ‘off’ }
menu.add(‘command’, :label => ‘Cut’, :command => proc{ @editor.text_cut })
menu.add(‘command’, :label => ‘Copy’, :command => proc{ @editor.text_copy })
menu.add(‘command’, :label => ‘Paste’, :command => proc{ @editor.text_paste })
@editor.bind(‘ButtonPress-3’, proc { |x, y| menu.popup(x, y) }, “%X %Y”)

to_text()
Tk.mainloop
end

def to_html
return if @state == :html
begin
Tk.root.cursor “watch”
Tk.root.update
@state = :html
@label.text(‘HTML Mode’)
@source = @editor.value
@editor.value = BlueCloth::new(@source).to_html
ensure
Tk.root.cursor “”
Tk.root.update
end
end

def to_text
return if @state == :text
@state = :text
@label.text(‘Text Mode’)
@editor.value = @source
end

# モードを切り替える
def swich_mode
case @state
when :text
to_html()
when :html
to_text()
end
end
end

if __FILE__ == $0
MarkdownEditor.new
end

[1]: http://www.gesource.jp/weblog/archives/2005/10/markdownhtml.html
[2]: http://pub.cozmixng.org/~the-rwiki/rw-cgi.rb?cmd=view;name=%B5%D5%B0%FA%A4%ADRuby%2FTk
[3]: http://pub.cozmixng.org/~the-rwiki/rw-cgi.rb?cmd=view;name=%B5%D5%B0%FA%A4%ADRuby%2FTk#a.a5.dd.a5.c3.a5.d7.a5.a2.a5.c3.a5.d7.a5.e1.a5.cb.a5.e5.a1.bc.a4.f2.ba.ee.a4.eb
[4]: http://rubyforge.org/frs/?group_id=167&release_id=2049

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください