1 # jcode.rb - ruby code to handle japanese (EUC/SJIS) string
3 if $VERBOSE && $KCODE == "NONE"
4 warn "Warning: $KCODE is NONE."
7 $vsave, $VERBOSE = $VERBOSE, false
9 warn "feel free for some warnings:\n" if $VERBOSE
12 str.gsub(/(\\[\[\]\-\\])|\\(.)|([\[\]\\])/) do
18 PATTERN_SJIS = '[\x81-\x9f\xe0-\xef][\x40-\x7e\x80-\xfc]'
19 PATTERN_EUC = '[\xa1-\xfe][\xa1-\xfe]'
20 PATTERN_UTF8 = '[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]'
22 RE_SJIS = Regexp.new(PATTERN_SJIS, 0, 'n')
23 RE_EUC = Regexp.new(PATTERN_EUC, 0, 'n')
24 RE_UTF8 = Regexp.new(PATTERN_UTF8, 0, 'n')
27 SUCC['s'] = Hash.new(1)
29 SUCC['s'][i.chr] = 0x40 - i
31 SUCC['s']["\x7e"] = 0x80 - 0x7e
32 SUCC['s']["\xfd"] = 0x100 - 0xfd
33 SUCC['s']["\xfe"] = 0x100 - 0xfe
34 SUCC['s']["\xff"] = 0x100 - 0xff
35 SUCC['e'] = Hash.new(1)
37 SUCC['e'][i.chr] = 0xa1 - i
40 SUCC['u'] = Hash.new(1)
42 SUCC['u'][i.chr] = 0x80 - i
44 SUCC['u']["\xbf"] = 0x100 - 0xbf
72 alias original_succ! succ!
73 private :original_succ!
75 alias original_succ succ
76 private :original_succ
80 if $KCODE != 'NONE' && self =~ reg
81 succ_table = SUCC[$KCODE[0,1].downcase]
83 self[-1] += succ_table[self[-1]]
84 self[-2] += 1 if self[-1] == 0
101 str.scan(/(?:\\(.)|([^\\]))-(?:\\(.)|([^\\]))|(?:\\(.)|(.))/m) do
107 elsif from.length != to.length
109 elsif from.length == 1
110 from[0].upto(to[0]) { |c| a.push c.chr }
112 from.upto(to) { |c| a.push c }
118 def expand_ch_hash from, to
120 afrom = _expand_ch(from)
122 afrom.each_with_index do |x,i| h[x] = ato[i] || ato[-1] end
128 DeletePatternCache = {}
129 SqueezePatternCache = {}
134 return nil if from == ""
135 return self.delete!(from) if to == ""
137 pattern = TrPatternCache[from] ||= /[#{_regex_quote(from)}]/
139 last = /.$/.match(to)[0]
140 self.gsub!(pattern, last)
142 h = HashCache[from + "1-0" + to] ||= expand_ch_hash(from, to)
143 self.gsub!(pattern) do |c| h[c] end
148 (str = self.dup).tr!(from, to) or str
152 return nil if del == ""
153 self.gsub!(DeletePatternCache[del] ||= /[#{_regex_quote(del)}]+/, '')
157 (str = self.dup).delete!(del) or str
160 def squeeze!(del=nil)
161 return nil if del == ""
164 SqueezePatternCache[del] ||= /([#{_regex_quote(del)}])\1+/
168 self.gsub!(pattern, '\1')
172 (str = self.dup).squeeze!(del) or str
176 return self.delete!(from) if to.length == 0
178 pattern = SqueezePatternCache[from] ||= /([#{_regex_quote(from)}])\1*/
180 last = /.$/.match(to)[0]
181 self.gsub!(pattern, last)
183 h = HashCache[from + "1-0" + to] ||= expand_ch_hash(from, to)
184 self.gsub!(pattern) do h[$1] end
189 (str = self.dup).tr_s!(from,to) or str
193 self.gsub!(/(?:.|\r?\n)\z/, '')
197 (str = self.dup).chop! or str
201 self.gsub(/[^\Wa-zA-Z_\d]/, ' ').length
206 self.delete("^#{str}").jlength