2 # Ruby/CHISE module by eto 2002-1114
11 $KCODE = 'u' #今のところこれ以外では動かない。String.splitが影響大。inspectも影響。
12 $debug = false #これはテスト用
13 $debug = true #これはテスト用
14 $stdout.binmode if $debug
15 $stdout.sync = true if $debug
17 class String #======================================================================
18 def to_a() self.split(//) end #$KCODEが設定されているので、UTF-8的な一文字づつがchにはいる
19 def each_char() to_a.each {|ch| yield ch } end
20 def each_character() to_a.each {|ch| yield ch.char } end
21 def char_length() to_a.length end
22 def char_at(n) to_a()[n] end
23 def char() Character.get(to_a[0]) end
25 #def char_id() char.char_id() end #なんとなく廃止
26 #def get_char_attribute(a) char.get_char_attribute(a) end #なんとなく廃止
27 #def ucs() char.ucs() end
34 def map_char(block = Proc.new)
35 return unless block_given?
36 return self.to_a.map {|ch| (block.call(ch)).to_s }.join("")
38 def map_char!(block = Proc.new)
39 return unless block_given?
40 self.replace(self.map_char {|ch| block.call(ch)})
42 def map_character(block = Proc.new)
43 return unless block_given?
44 return self.to_a.map {|ch| (block.call(ch.char)).to_s }.join("")
46 def map_character!(block = Proc.new)
47 return unless block_given?
48 self.replace(self.map_char {|ch| block.call(ch.char)})
51 def method_missing(mid, *args)
52 if char_length == 1 #省略形が有効なのは、一文字の時だけ
53 char.method_missing(mid, *args)
55 raise NameError, "undefined method `#{mid.id2name}'", caller(1)
59 def map_utf8() map_char {|ch| ch.char.map_utf8 } end
60 alias map_ucs map_utf8
61 def map_ucs_er() map_char {|ch| ch.char.map_ucs_er } end
62 def to_er() map_char {|ch| ch.char.to_er } end
64 #put関係、[]関係は用意しないことにした。
65 def de_er!() #EntityReferenceを取り除く
66 return self unless self =~ Regexp.new(EntityReference::REGEXP_PART) #それらしいのが無ければ何もしない
68 self.sub!(Regexp.new(Regexp.escape(er)), Character.new(er).mcs_utf8) #変換自体はCharacterにまかせる
69 return self.de_er! if self =~ Regexp.new(EntityReference::REGEXP_PART) #まだあったら再帰
72 def de_er() return self.dup.de_er!; end
74 def inspect_all() map_char {|ch| ch.char.inspect_all } end
75 def inspect_x() map_char {|ch| ch.char.inspect_x } end
77 def to_euc() map_char {|ch| ch.char.to_euc } end
78 def map_euc() map_char {|ch| ch.char.map_euc } end
79 def to_sjis() map_char {|ch| ch.char.to_sjis } end
80 def map_sjis() map_char {|ch| ch.char.map_sjis } end
82 def decompose() map_char {|ch| ch.char.decompose } end
83 def decompose!() self.replace(self.decompose); self; end
84 def decompose_all_nu(level=nil)
85 level = 0 if level.nil?
87 p ['too many recursive', self]
91 return de.decompose_all(level+1) if de != self #なにか変化があったから再帰
94 def decompose_all() map_char {|ch| ch.char.decompose_all } end
95 def decompose_all!() self.replace(self.decompose_all); self; end
97 def find() #"日雲"→"曇"とかいう感じの操作
99 length = char_length()
102 ar << char.ids_contained #その文字を含んでいる漢字のリスト
114 if length == v #全部に顔を出していたら
122 db = CodesysDB.instance
123 composed = db.get('ids', self)
124 return "" if composed.nil? #なかったよと。
125 return "" if composed.char_length == 0 #なにごと?
126 return composed if composed.char_length == 1
127 composed.each_char {|ch|
129 return ch if char.has_attribute? #とりあえず最初にみつかったものを返すというヌルい仕様
131 return "" #attributeを持つものが一つも無かったら、""にする
134 #selfである文字列をIDSだと仮定し、それを完全にcomposeしきらないで、
135 #その部分集合だけをとりだして、compose可能であればできるだけcomposeする。
136 tree = IDS_Tree.new(self)
137 return self if tree.depth <= 1 #sub_nodesが無い場合はここでさよなら
138 tree.sub_nodes.each {|node|
140 next if c.nil? || c == ""
141 # print "#{self} #{node} #{c}\n"
143 n = self.gsub(node, c)
146 return self #おきかえられるものがまったくなかったら、自分をかえす。
150 module CHISE #======================================================================
152 (RUBY_PLATFORM =~ /cygwin/ || RUBY_PLATFORM =~ /mswin32/ || RUBY_PLATFORM =~ /mingw32/)
154 module_function :windows?
156 DB_DIR = 'd:/work/chise/char-db' #この後に/sysmtem-char-id/ucsという感じに続く
157 IDS_DB_DIR = 'd:/work/chise/ids/' #この後にIDS-JIS-X0208-1990.txtという感じに続く
159 DB_DIR = '/usr/local/lib/xemacs-21.4.10/i686-pc-linux/char-db' #この後に/sysmtem-char-id/ucsという感じに続く
160 IDS_DB_DIR = '/home/eto/work/chise/ids/' #この後にIDS-JIS-X0208-1990.txtという感じに続く
163 class EntityReference #======================================================================
164 #状況によってどのERに変換するかが異なる可能性があるので、普通のclassとして実装したほうがいい?
166 %w( chinese-big5-cdp CDP- 4 X),
167 %w( ideograph-daikanwa M- 5 d),
168 %w( ideograph-cbeta CB 5 d),
169 %w( ideograph-gt GT- 5 d),
170 %w( ideograph-gt-k GT-K 5 d),
171 %w( japanese-jisx0208-1990 J90- 4 X),
172 %w( japanese-jisx0208 J83- 4 X),
173 %w( japanese-jisx0213-1 JX1- 4 X),
174 %w( japanese-jisx0213-2 JX2- 4 X),
175 %w( japanese-jisx0212 JSP- 4 X),
176 %w( japanese-jisx0208-1978 J78- 4 X),
177 %w( chinese-cns11643-1 C1- 4 X),
178 %w( chinese-cns11643-2 C2- 4 X),
179 %w( chinese-cns11643-3 C3- 4 X),
180 %w( chinese-cns11643-4 C4- 4 X),
181 %w( chinese-cns11643-5 C5- 4 X),
182 %w( chinese-cns11643-6 C6- 4 X),
183 %w( chinese-cns11643-7 C7- 4 X),
184 %w( korean-ksc5601 K0- 4 X),
186 CODESYS_ORDER = %w(japanese chinese korean ideograph)
187 REGEXP_PART = "&([-+0-9A-Za-z#]+);"
188 REGEXP_ALL = "^#{REGEXP_PART}$"
190 def self.match?(er) (er =~ Regexp.new(REGEXP_PART)) != nil end
192 def self.parse(er) #char_idをFIXNUMで返す
193 return "" unless er =~ Regexp.new(REGEXP_ALL) #なんか、間違ってる?
194 er = $1 #ついでに中身の部分を取り出す
195 return $1.hex if er =~ /^MCS-([0-9A-Fa-f]+)/ #MCS
196 # if er =~ /^U[-+]?([0-9A-Fa-f]+)/ #Unicode直打ち
197 if er =~ /^U[-+]?([0-9A-Fa-f]+)/ || er =~ /^#x([0-9A-Fa-f]+)/ #Unicode直打ち
201 er.sub!(/^I-/, '') if er =~ /^I-/ #I-がついてるとどう違うのかはよくわからない
202 each_codesys {|codesys, er_prefix, keta, numtype| #p [codesys, er_prefix, keta, numtype]
203 numtyperegex = '\d' #if numtype == 'd'
204 numtyperegex = '[0-9A-Fa-f]' if numtype == 'X'
205 regexpstr = "^#{er_prefix}(#{numtyperegex}{#{keta},#{keta}})$" #p regexpstr
206 if er =~ Regexp.new(regexpstr)
208 code = codestr.to_i #if numtype == 'd'
209 code = codestr.hex if numtype == 'X'
210 char_id_u8 = EntityReference.get_database(codesys, code)
211 char_id_num = Character.parse_char_id(char_id_u8)
218 def self.each_codesys()
219 CODESYS_ORDER.each {|lang|
220 CODESYS_TABLE.each {|codesys, er_prefix, keta, numtype| #普通こういう書き方はしない。ループ一個にする。
221 next unless codesys =~ lang
222 yield(codesys, er_prefix, keta, numtype)
226 def self.get_database(codesys, code)
227 c = CodesysDB.instance.get(codesys, code)
229 if codesys =~ /-jisx0208/
230 #return self.get_database("=jis-x0208", code) #再帰でどうだ?
231 c = CodesysDB.instance.get("=jis-x0208", code)
238 class CharacterFactory #============================================文字オブジェクトの生成、cache
247 n = Character.parse_char_id(char_id)
249 @chars[n] = Character.new(n) if @chars[n] == nil
255 GC.start #ガーベージコレクション
257 def length() @chars.length; end
259 reset if @max < @chars.length #MAXを超えたらresetしてしまう。乱暴じゃがcacheなのでこれでいいのだ。
263 class Character #=============================================================== 文字オブジェクト
264 def initialize(char_id=nil)
265 @char_id = Character.parse_char_id(char_id)
266 @attributes = Hash.new
267 @check_all_database = false
270 def to_i() @char_id end
271 def mcs_utf8() Character.u4itou8(@char_id) end
272 def mcs_hex() sprintf("%x", @char_id) end
274 #----------------------------------------------------------------------
275 def self.get(char_id) CharacterFactory.instance.get(char_id) end #flyweightパターン
277 #----------------------------------------------------------------------
278 def normalize_attribute_name(b)
280 a.gsub!(/_/, '-') #underlineは-に置換
281 a.sub!(/^map-/, '=>')
283 a.sub!(/^from-/, '<-')
286 def get_char_attribute(b) # XEmacs UTF-2000互換API群
287 a = normalize_attribute_name(b)
290 return atr if atr != nil
291 atr = check_database(a)
292 @attributes[a] = atr if atr != nil
293 return get_char_attribute("=jis-x0208") if a =~ /jisx0208/ #ここだけ特殊形
294 return @attributes[a]
296 def put_char_attribute(b,v)
297 a = normalize_attribute_name(b)
299 CharDB.instance.put(a, mcs_utf8(), v)
301 def char_attribute_alist() check_all_database(); @attributes; end
302 def char_attribute_list() check_all_database(); @attributes.keys; end
303 alias [] get_char_attribute #その略称
304 alias []= put_char_attribute
305 alias alist char_attribute_alist
306 alias list char_attribute_list
308 def method_missing(mid, *args) #参考:ostruct.rb
310 return get_char_attribute(mname) if args.length == 0
311 put_char_attribute(mname.chop, args[0]) if mname =~ /=$/ #代入
314 def has_attribute?() #意味のあるattributeを持ってますか?
319 return (keys.length != 0)
322 #----------------------------------------------------------------------
324 return false if ch == nil
325 return false unless ch.is_a? Character
326 self.char_id == ch.char_id
329 #----------------------------------------------------------------------
330 def self.parse_char_id(char_id) #FIXNUMを返す
331 return nil if char_id == nil
332 if char_id.is_a?(Numeric) #p [char_id]
333 char_id = 0x80000000 + char_id if char_id < 0 #補数表現
335 elsif char_id.is_a?(String)
336 return char_id.to_i if char_id =~ /^\d+$/ && 1 < char_id.length #文字列による数字だったら数値化してreturn
337 return EntityReference.parse(char_id) if char_id =~ Regexp.new(EntityReference::REGEXP_ALL) #実体参照?
338 char_id.sub!(/^\?/, '') if char_id =~ /^\?/ #もし先頭に?がついていたら削除
339 #このへん本当はもっとちゃんとチェックするべし
341 u4 = Uconv.u8tou4(char_id) #UCS-4文字列に変換
347 return Character.u4tou4i(u4) #UCS-4数値にしてreturn
349 raise ArgumentError, "unknown object for char_id", caller(1)
353 return 0 if u4 == nil || u4 == ""
354 return (u4[3] << 24 | u4[2] << 16 | u4[1] << 8 | u4[0]) #UCS-4数値にしてreturn
356 def self.u4itou4(num)
357 return "" unless num.is_a?(Integer)
358 return sprintf("%c%c%c%c", num&0xff, (num >> 8)&0xff, (num >> 16)&0xff, (num >> 24)&0xff) #UCS-4数値を文字列にしてreturn
360 def self.u4itou8(char_id) #ucsの数値を受けとり、UTF-8の文字一文字を返す
362 u4 = Character.u4itou4(char_id)
363 u8 = Uconv.u4tou8(u4)
366 #raise ArgumentError, "invalid char_id (#{char_id})", caller(1)
372 #----------------------------------------------------------------------
373 def check_database(a)
376 v = db.get(a, u8) #u8で表される文字のaアトリビュートを調べる。
379 def check_all_database() #現在の@char_idから、文字データベースを参照する
380 return if @check_all_database
381 return if @char_id == nil
384 atrs = db.get_all(u8) #u8で表される文字のアトリビュートを全部持ってこい
386 @attributes[a] = v #とかいう感じで代入するのでええかな?
388 @check_all_database = true #重い処理なので一応checkする
391 #----------------------------------------------------------------------
393 #ar = %w{ucs ucs-big5 ucs-cdp ucs-cns ucs-jis ucs-ks =>ucs =>ucs* =>ucs-jis}
394 #ar = %w{ucs ucs-jis ucs-big5 ucs-cdp ucs-cns ucs-ks =>ucs =>ucs* =>ucs-jis}
395 ar = %w{ucs-jis ucs =>ucs-jis}
396 #並び順は恣意的で、ucs-jisを先に出している。本来はこれも指定できるようにするべき。
398 u = get_char_attribute(a)
404 #----------------------------------------------------------------------CCS関係
405 def to_utf8() Uconv.u4tou8(Character.u4itou4(ucs())) end #UTF8文字列を返す
410 if u.nil? || 0xffff < u
416 alias map_ucs map_utf8
419 if u.nil? || 0xffff < u
422 return Character.get(u).to_er()
427 return "" if u.nil? || 0xffff < u
428 Uconv.u16toeuc(Uconv.u4tou16(Character.u4itou4(ucs())))
437 return "" if u.nil? || 0xffff < u
438 Uconv.u16tosjis(Uconv.u4tou16(Character.u4itou4(ucs())))
446 #----------------------------------------------------------------------
447 def to_er(codesys=nil) #実体参照を返す、希望するcodesysが引数(未実装)
448 return "" if @char_id == nil
449 return sprintf("&#x%04x;", @char_id) if @char_id <= 0xffff
450 return sprintf("&#x%05x;", @char_id) if @char_id <= 0xfffff
451 EntityReference.each_codesys {|codesys, er_prefix, keta, numtype|
454 return sprintf("&#{er_prefix}%0#{keta}#{numtype};", code)
456 return sprintf("&MCS-%08X;", @char_id) #本当はこれは無しにしたい
460 EntityReference.each_codesys {|codesys, er_prefix, keta, numtype|
462 ar << er if er != nil
468 return "<>" if @char_id == nil
469 ar = [to_utf8(), to_er().sub(/^&/,'').chop]
472 alias inspect inspect_x
473 def inspect_all_codesys() #未完成
474 #to_erを全てのcodesysにおいて実行する。その結果をコンパクトにまとめる
478 alist.to_a.sort.each {|a, v| ar << "#{a}:#{v}" }
479 return ar.join(',')+">"
483 alist.to_a.sort.each {|a, v| ar << "#{a}:#{v}" }
484 return ar.join('\n')+'\n'
488 alist.to_a.sort.each {|a, v|
489 str += "#{a}: #{v}\n"
494 def inspect_ids(hex_flag=false)
497 ar << (hex_flag ? "x"+mcs_hex : to_utf8)
498 if to_s != ids #idsが部品そのものだったら部品追加はしない
503 ar << "x"+char.mcs_hex
514 return "("+ar.join("\t")+")"
517 #----------------------------------------------------------------------IDS関係
521 # return idss if idss
522 # return k if self.is_basic_kanji? #基本漢字はstop kanjiとするぞと。
523 return self['ids-represent'] if self['ids-represent'] #ids_representを持っている場合はその値とする。
524 return self['ids-element'] if self['ids-element'] #ids_elementを持っている場合はその値とする。
526 idss = self['ids-meaning']
527 return idss if idss != nil && 0 < idss.length && k != idss
528 idss = self['ids-aggregated']
529 return idss if idss != nil && 0 < idss.length && k != idss
531 return idss if idss != nil && 0 < idss.length && k != idss
533 # return k if idss.nil? || idss.length == 0 || k == idss
534 # if idss.char_length == 2
535 # p ['What???', k, idss, k.inspect_all]
536 # #return idssx[1] #二個目だけ返すとか?
537 # return k #IDSに展開する方法が無いと。
539 # return k if k == idss
540 # if idss.include?(k) #<C5-4C4D><C6-4A37>この二文字のBUG対策
541 # #return idss.sub(k, '')
542 # return k #IDSに展開する方法が無いと。
548 de = self.decompose #出発点
552 de = pde.decompose #もう一度分解をしてみる。
553 break if pde == de #ループを抜けだす
554 exit if 10 < level #p ['too many recursive', self]
559 def decompose_all_nu(level=nil)
560 level = 0 if level.nil?
562 p ['too many recursive', self]
566 return de.decompose_all(level+1) if de != self #なにか変化があったから再帰
567 return de #もうこれ以上変化は無さそうだぞと。
569 def is_ids?() 0x2ff0 <= @char_id && @char_id <= 0x2fff end
570 def ids_operator_argc()
571 return 0 unless is_ids?
572 return 3 if @char_id == 0x2ff2 || @char_id == 0x2ff3
579 #----------------------------------------------------------------------終了