2 # Ruby/CHISE module by eto 2002-1114
3 # $Id: char.rb,v 1.1 2003-11-10 08:11:46 eto Exp $
4 # Copyright (C) 2002-2003 Kouichirou Eto, All rights reserved.
5 # This is free software with ABSOLUTELY NO WARRANTY.
6 # You can redistribute it and/or modify it under the terms of the GNU GPL2.
10 $LOAD_PATH << '../../src' if $0 == __FILE__
13 $KCODE = 'u' #今のところこれ以外では動かない。String.splitが影響大。inspectも影響。
14 $debug = false #これはテスト用
15 $debug = true #これはテスト用
16 $stdout.binmode if $debug
17 $stdout.sync = true if $debug
19 class String #======================================================================
20 def to_a() self.split(//) end #$KCODEが設定されているので、UTF-8的な一文字づつがchにはいる
21 def each_char() to_a.each {|ch| yield ch } end
22 def each_character() to_a.each {|ch| yield ch.char } end
23 def char_length() to_a.length end
24 def char_at(n) to_a()[n] end
25 def first_char() to_a[0] end
26 def char() Character.get(to_a[0]) end
28 #def char_id() char.char_id() end #なんとなく廃止
29 #def get_char_attribute(a) char.get_char_attribute(a) end #なんとなく廃止
30 #def ucs() char.ucs() end
37 def map_char(block = Proc.new)
38 return unless block_given?
39 return self.to_a.map {|ch| (block.call(ch)).to_s }.join("")
41 def map_char!(block = Proc.new)
42 return unless block_given?
43 self.replace(self.map_char {|ch| block.call(ch)})
45 def map_character(block = Proc.new)
46 return unless block_given?
47 return self.to_a.map {|ch| (block.call(ch.char)).to_s }.join("")
49 def map_character!(block = Proc.new)
50 return unless block_given?
51 self.replace(self.map_char {|ch| block.call(ch.char)})
54 def method_missing(mid, *args)
55 if char_length == 1 #省略形が有効なのは、一文字の時だけ
56 char.method_missing(mid, *args)
58 raise NameError, "undefined method `#{mid.id2name}'", caller(1)
62 def map_utf8() map_char {|ch| ch.char.map_utf8 } end
63 alias map_ucs map_utf8
64 def map_ucs_er() map_char {|ch| ch.char.map_ucs_er } end
65 def to_er() map_char {|ch| ch.char.to_er } end
67 #put関係、[]関係は用意しないことにした。
68 def de_er!() #EntityReferenceを取り除く
69 return self unless self =~ Regexp.new(EntityReference::REGEXP_PART) #それらしいのが無ければ何もしない
71 self.sub!(Regexp.new(Regexp.escape(er)), Character.new(er).mcs_utf8) #変換自体はCharacterにまかせる
72 return self.de_er! if self =~ Regexp.new(EntityReference::REGEXP_PART) #まだあったら再帰
75 def de_er() return self.dup.de_er!; end
77 def inspect_all() map_char {|ch| ch.char.inspect_all } end
78 def inspect_x() map_char {|ch| ch.char.inspect_x } end
80 def to_euc() map_char {|ch| ch.char.to_euc } end
81 def map_euc() map_char {|ch| ch.char.map_euc } end
82 def to_sjis() map_char {|ch| ch.char.to_sjis } end
83 def map_sjis() map_char {|ch| ch.char.map_sjis } end
85 def glyph_decompose() map_char {|ch| ch.char.glyph_decompose } end
86 def decompose() map_char {|ch| ch.char.decompose } end
87 def decompose!() self.replace(self.decompose); self; end
88 def decompose_all_nu(level=nil)
89 level = 0 if level.nil?
91 p ['too many recursive', self]
95 return de.decompose_all(level+1) if de != self #なにか変化があったから再帰
98 def decompose_all() map_char {|ch| ch.char.decompose_all } end
99 def decompose_all!() self.replace(self.decompose_all); self; end
101 def find() #"日雲"→"曇"とかいう感じの操作
103 length = char_length()
106 ar << char.ids_contained #その文字を含んでいる漢字のリスト
118 if length == v #全部に顔を出していたら
126 db = CodesysDB.instance
127 composed = db.get('ids', self)
128 return "" if composed.nil? #なかったよと。
129 return "" if composed.char_length == 0 #なにごと?
130 return composed if composed.char_length == 1
131 composed.each_char {|ch|
133 return ch if char.has_attribute? #とりあえず最初にみつかったものを返すというヌルい仕様
135 return "" #attributeを持つものが一つも無かったら、""にする
138 #selfである文字列をIDSだと仮定し、それを完全にcomposeしきらないで、
139 #その部分集合だけをとりだして、compose可能であればできるだけcomposeする。
140 tree = IDS_Tree.new(self)
141 return self if tree.depth <= 1 #sub_nodesが無い場合はここでさよなら
142 tree.sub_nodes.each {|node|
144 next if c.nil? || c == ""
145 # print "#{self} #{node} #{c}\n"
147 n = self.gsub(node, c)
150 return self #おきかえられるものがまったくなかったら、自分をかえす。
154 module CHISE #======================================================================
156 (RUBY_PLATFORM =~ /cygwin/ || RUBY_PLATFORM =~ /mswin32/ || RUBY_PLATFORM =~ /mingw32/)
158 module_function :windows?
160 DB_DIR = 'd:/work/chise/char-db' #この後に/sysmtem-char-id/ucsという感じに続く
161 IDS_DB_DIR = 'd:/work/chise/ids/' #この後にIDS-JIS-X0208-1990.txtという感じに続く
163 DB_DIR = '/usr/local/lib/xemacs-21.4.12/i686-pc-linux/char-db' #この後に/sysmtem-char-id/ucsという感じに続く
164 IDS_DB_DIR = '/home/eto/work/chise/ids/' #この後にIDS-JIS-X0208-1990.txtという感じに続く
167 class EntityReference #======================================================================
168 #状況によってどのERに変換するかが異なる可能性があるので、普通のclassとして実装したほうがいい?
170 # %w( chinese-big5-cdp CDP- 4 X),
171 # %w( ideograph-daikanwa M- 5 d),
172 # %w( ideograph-cbeta CB 5 d),
173 # %w( ideograph-gt GT- 5 d),
174 # %w( ideograph-gt-k GT-K 5 d),
175 # %w( japanese-jisx0208-1990 J90- 4 X),
176 # %w( japanese-jisx0208 J83- 4 X),
177 # %w( japanese-jisx0213-1 JX1- 4 X),
178 # %w( japanese-jisx0213-2 JX2- 4 X),
179 # %w( japanese-jisx0212 JSP- 4 X),
180 # %w( japanese-jisx0208-1978 J78- 4 X),
181 # %w( chinese-cns11643-1 C1- 4 X),
182 # %w( chinese-cns11643-2 C2- 4 X),
183 # %w( chinese-cns11643-3 C3- 4 X),
184 # %w( chinese-cns11643-4 C4- 4 X),
185 # %w( chinese-cns11643-5 C5- 4 X),
186 # %w( chinese-cns11643-6 C6- 4 X),
187 # %w( chinese-cns11643-7 C7- 4 X),
188 # %w( korean-ksc5601 K0- 4 X),
190 # CODESYS_ORDER = %w(japanese chinese korean ideograph)
192 %w( =jis-x0208-1990 J90- 4 X),
193 %w( =jis-x0208-1983 J83- 4 X),
194 %w( =jis-x0208-1978 J78- 4 X),
195 %w( =jis-x0208 J90- 4 X), #継承のアドホックな実装
196 %w( =jis-x0208 J83- 4 X), #継承のアドホックな実装
197 %w( =jis-x0208 J78- 4 X), #継承のアドホックな実装
198 %w( =jis-x0213-1-2000 JX1- 4 X),
199 %w( =jis-x0213-2-2000 JX2- 4 X),
200 %w( =jis-x0212 JSP- 4 X),
201 %w( =big5-cdp CDP- 4 X),
202 %w( =cns11643-1 C1- 4 X),
203 %w( =cns11643-2 C2- 4 X),
204 %w( =cns11643-3 C3- 4 X),
205 %w( =cns11643-4 C4- 4 X),
206 %w( =cns11643-5 C5- 4 X),
207 %w( =cns11643-6 C6- 4 X),
208 %w( =cns11643-7 C7- 4 X),
209 %w( =ks-x1001 K0- 4 X),
210 %w( =daikanwa M- 5 d),
215 REGEXP_PART = "&([-+0-9A-Za-z#]+);"
216 REGEXP_ALL = "^#{REGEXP_PART}$"
218 def self.match?(er) (er =~ Regexp.new(REGEXP_PART)) != nil end
220 def self.parse(er) #char_idをFIXNUMで返す
221 return "" unless er =~ Regexp.new(REGEXP_ALL) #なんか、間違ってる?
222 er = $1 #ついでに中身の部分を取り出す
223 return $1.hex if er =~ /^MCS-([0-9A-Fa-f]+)/ #MCS
224 # if er =~ /^U[-+]?([0-9A-Fa-f]+)/ #Unicode直打ち
225 if er =~ /^U[-+]?([0-9A-Fa-f]+)/ || er =~ /^#x([0-9A-Fa-f]+)/ #Unicode直打ち
229 er.sub!(/^I-/, '') if er =~ /^I-/ #I-がついてるとどう違うのかはよくわからない
230 each_codesys {|codesys, er_prefix, keta, numtype| #p [codesys, er_prefix, keta, numtype]
231 numtyperegex = '\d' #if numtype == 'd'
232 numtyperegex = '[0-9A-Fa-f]' if numtype == 'X'
233 regexpstr = "^#{er_prefix}(#{numtyperegex}{#{keta},#{keta}})$"
234 if er =~ Regexp.new(regexpstr)
236 code = codestr.to_i #if numtype == 'd'
237 code = codestr.hex if numtype == 'X'
238 char_id_u8 = EntityReference.get_database(codesys, code)
239 char_id_num = Character.parse_char_id(char_id_u8)
240 next if char_id_num == nil
247 def self.each_codesys()
248 # CODESYS_ORDER.each {|lang|
249 # CODESYS_TABLE.each {|codesys, er_prefix, keta, numtype| #普通こういう書き方はしない。ループ一個にする。
250 # next unless codesys =~ lang
251 # yield(codesys, er_prefix, keta, numtype)
254 CODESYS_TABLE.each {|codesys, er_prefix, keta, numtype|
255 yield(codesys, er_prefix, keta, numtype)
258 def self.get_database(codesys, code)
259 c = CodesysDB.instance.get(codesys, code)
261 # if codesys =~ /-jisx0208/
262 # #return self.get_database("=jis-x0208", code) #再帰でどうだ?
263 # c = CodesysDB.instance.get("=jis-x0208", code)
270 class CharacterFactory #============================================文字オブジェクトの生成、cache
279 n = Character.parse_char_id(char_id)
281 @chars[n] = Character.new(n) if @chars[n] == nil
287 GC.start #ガーベージコレクション
289 def length() @chars.length; end
291 reset if @max < @chars.length #MAXを超えたらresetしてしまう。乱暴じゃがcacheなのでこれでいいのだ。
295 class Character #=============================================================== 文字オブジェクト
296 def initialize(char_id=nil)
297 @char_id = Character.parse_char_id(char_id)
298 @attributes = Hash.new
299 @check_all_database = false
302 def to_i() @char_id end
303 def mcs_utf8() Character.u4itou8(@char_id) end
304 def mcs_hex() sprintf("%x", @char_id) end
306 #----------------------------------------------------------------------
307 def self.get(char_id) CharacterFactory.instance.get(char_id) end #flyweightパターン
309 #----------------------------------------------------------------------
310 def normalize_attribute_name(b)
312 a.gsub!(/_/, '-') #underlineは-に置換
314 a.sub!(/^map-/, '=>')
316 a.sub!(/^from-/, '<-')
319 def get_char_attribute(b) # XEmacs UTF-2000互換API群
320 a = normalize_attribute_name(b)
324 atr = check_database(a)
329 return get_char_attribute("="+a) unless a =~ /^=/ #頭に=がついてない場合はそれが省略されていることを仮定して、再帰する
332 def put_char_attribute(b,v)
333 a = normalize_attribute_name(b)
335 CharDB.instance.put(a, mcs_utf8(), v)
337 def char_attribute_alist() check_all_database(); @attributes; end
338 def char_attribute_list() check_all_database(); @attributes.keys; end
339 alias [] get_char_attribute #その略称
340 alias []= put_char_attribute
341 alias alist char_attribute_alist
342 alias list char_attribute_list
344 def method_missing(mid, *args) #参考:ostruct.rb
346 return get_char_attribute(mname) if args.length == 0
347 put_char_attribute(mname.chop, args[0]) if mname =~ /=$/ #代入
350 def has_attribute?() #意味のあるattributeを持ってますか?
355 return (keys.length != 0)
358 #----------------------------------------------------------------------
360 return false if ch == nil
361 return false unless ch.is_a? Character
362 self.char_id == ch.char_id
365 #----------------------------------------------------------------------
366 def self.parse_char_id(char_id) #FIXNUMを返す
367 return nil if char_id == nil
368 if char_id.is_a?(Numeric) #p [char_id]
369 char_id = 0x80000000 + char_id if char_id < 0 #補数表現
371 elsif char_id.is_a?(String)
372 return char_id.to_i if char_id =~ /^\d+$/ && 1 < char_id.length #文字列による数字だったら数値化してreturn
373 return EntityReference.parse(char_id) if char_id =~ Regexp.new(EntityReference::REGEXP_ALL) #実体参照?
374 char_id.sub!(/^\?/, '') if char_id =~ /^\?/ #もし先頭に?がついていたら削除
375 #このへん本当はもっとちゃんとチェックするべし
377 u4 = Uconv.u8tou4(char_id) #UCS-4文字列に変換
383 return Character.u4tou4i(u4) #UCS-4数値にしてreturn
385 raise ArgumentError, "unknown object for char_id", caller(1)
389 return 0 if u4 == nil || u4 == ""
390 return (u4[3] << 24 | u4[2] << 16 | u4[1] << 8 | u4[0]) #UCS-4数値にしてreturn
392 def self.u4itou4(num)
393 return "" unless num.is_a?(Integer)
394 return sprintf("%c%c%c%c", num&0xff, (num >> 8)&0xff, (num >> 16)&0xff, (num >> 24)&0xff) #UCS-4数値を文字列にしてreturn
396 def self.u4itou8(char_id) #ucsの数値を受けとり、UTF-8の文字一文字を返す
398 u4 = Character.u4itou4(char_id)
399 u8 = Uconv.u4tou8(u4)
402 #raise ArgumentError, "invalid char_id (#{char_id})", caller(1)
408 #----------------------------------------------------------------------
409 def check_database(a)
412 v = db.get(a, u8) #u8で表される文字のaアトリビュートを調べる。
415 def check_all_database() #現在の@char_idから、文字データベースを参照する
416 return if @check_all_database
417 return if @char_id == nil
420 atrs = db.get_all(u8) #u8で表される文字のアトリビュートを全部持ってこい
422 @attributes[a] = v #とかいう感じで代入するのでええかな?
424 @check_all_database = true #重い処理なので一応checkする
427 #----------------------------------------------------------------------
429 #ar = %w{ucs ucs-big5 ucs-cdp ucs-cns ucs-jis ucs-ks =>ucs =>ucs* =>ucs-jis}
430 #ar = %w{ucs ucs-jis ucs-big5 ucs-cdp ucs-cns ucs-ks =>ucs =>ucs* =>ucs-jis}
431 ar = %w{ucs-jis ucs =>ucs-jis}
432 #並び順は恣意的で、ucs-jisを先に出している。本来はこれも指定できるようにするべき。
434 u = get_char_attribute(a)
440 #----------------------------------------------------------------------CCS関係
441 def to_utf8() Uconv.u4tou8(Character.u4itou4(ucs())) end #UTF8文字列を返す
446 if u.nil? || 0xffff < u
452 alias map_ucs map_utf8
455 if u.nil? || 0xffff < u
458 return Character.get(u).to_er()
463 return "" if u.nil? || 0xffff < u
464 Uconv.u16toeuc(Uconv.u4tou16(Character.u4itou4(ucs())))
473 return "" if u.nil? || 0xffff < u
474 Uconv.u16tosjis(Uconv.u4tou16(Character.u4itou4(ucs())))
482 #----------------------------------------------------------------------
483 def to_er(codesys=nil) #実体参照を返す、希望するcodesysが引数(未実装)
484 return "" if @char_id == nil
485 return sprintf("&#x%04x;", @char_id) if @char_id <= 0xffff
486 return sprintf("&#x%05x;", @char_id) if @char_id <= 0xfffff
487 EntityReference.each_codesys {|codesys, er_prefix, keta, numtype|
490 return sprintf("&#{er_prefix}%0#{keta}#{numtype};", code)
492 return sprintf("&MCS-%08X;", @char_id) #本当はこれは無しにしたい
496 EntityReference.each_codesys {|codesys, er_prefix, keta, numtype|
498 ar << er if er != nil
504 return "<>" if @char_id == nil
505 ar = [to_utf8(), to_er().sub(/^&/,'').chop]
508 alias inspect inspect_x
509 def inspect_all_codesys() #未完成
510 #to_erを全てのcodesysにおいて実行する。その結果をコンパクトにまとめる
514 alist.to_a.sort.each {|a, v| ar << "#{a}:#{v}" }
515 return ar.join(',')+">"
519 alist.to_a.sort.each {|a, v| ar << "#{a}:#{v}" }
520 return ar.join('\n')+'\n'
524 alist.to_a.sort.each {|a, v|
525 str += "#{a}: #{v}\n"
530 def inspect_ids(hex_flag=false)
533 ar << (hex_flag ? "x"+mcs_hex : to_utf8)
534 if to_s != ids #idsが部品そのものだったら部品追加はしない
539 ar << "x"+char.mcs_hex
550 return "("+ar.join("\t")+")"
553 #----------------------------------------------------------------------IDS関係
554 def glyph_decompose() do_decompose(false) end
555 def decompose() do_decompose(true) end
556 def do_decompose(check_meaning = true)
559 # return idss if idss
560 # return k if self.is_basic_kanji? #基本漢字はstop kanjiとするぞと。
562 return self['ids-represent'] if self['ids-represent'] #ids_representを持っている場合はその値とする。
563 return self['ids-element'] if self['ids-element'] #ids_elementを持っている場合はその値とする。
564 idss = self['ids-meaning']
565 return idss if idss != nil && 0 < idss.length && k != idss
567 idss = self['ids-aggregated']
568 return idss if idss != nil && 0 < idss.length && k != idss
570 return idss if idss != nil && 0 < idss.length && k != idss
572 # return k if idss.nil? || idss.length == 0 || k == idss
573 # if idss.char_length == 2
574 # p ['What???', k, idss, k.inspect_all]
575 # #return idssx[1] #二個目だけ返すとか?
576 # return k #IDSに展開する方法が無いと。
578 # return k if k == idss
579 # if idss.include?(k) #<C5-4C4D><C6-4A37>この二文字のBUG対策
580 # #return idss.sub(k, '')
581 # return k #IDSに展開する方法が無いと。
587 de = self.decompose #出発点
591 de = pde.decompose #もう一度分解をしてみる。
592 break if pde == de #ループを抜けだす
593 exit if 10 < level #p ['too many recursive', self]
598 def decompose_all_nu(level=nil)
599 level = 0 if level.nil?
601 p ['too many recursive', self]
605 return de.decompose_all(level+1) if de != self #なにか変化があったから再帰
606 return de #もうこれ以上変化は無さそうだぞと。
608 def is_ids?() 0x2ff0 <= @char_id && @char_id <= 0x2fff end
609 def ids_operator_argc()
610 return 0 unless is_ids?
611 return 3 if @char_id == 0x2ff2 || @char_id == 0x2ff3
618 #----------------------------------------------------------------------終了