# -*- coding utf-8 -*- require 'nkf' module Ykutils module NKFUTIL CODE_TO_NAME = Hash.new("ASCII") CODE_TO_NAME[NKF::JIS] = "JIS" CODE_TO_NAME[NKF::EUC] = "EUC" CODE_TO_NAME[NKF::SJIS] = "SJIS" CODE_TO_NAME[NKF::BINARY] = "BINARY" CODE_TO_NAME[NKF::UTF8] = "UTF8" if NKF.const_defined?(:UTF8) def NKFUTIL.guess_encoding(str) CODE_TO_NAME[NKF.guess(str)] end class Assoc @@hs = {} @@config = nil def Assoc.set( key, value ) if value @@hs[key] = Assoc.convert( value ) else @@hs[key] = value end end def Assoc.get( key ) @@hs[key] end def Assoc.to_nkf_encoding_format( encoding ) case encoding when "UTF8" "w" else encoding[0,1] end end def Assoc.config( src_encoding, dest_encoding , misc_option = nil ) @@config = "-#{(dest_encoding.to_s)[0,1].downcase}#{(src_encoding.to_s)[0,1].upcase}" if misc_option != nil @@config += " #{misc_option}" end end def Assoc.auto_config_to_inner( str , misc_option = nil ) if str src_encoding = Assoc.to_nkf_encoding_format( NKFUTIL.guess_encoding( str ) ) else src_encoding = "A" end inner_encoding = Assoc.to_nkf_encoding_format( Assoc.get_inner_encoding ) if inner_encoding != "A" @@config = "-#{inner_encoding.downcase}#{src_encoding.upcase}" if misc_option != nil @@config += " #{misc_option}" end end src_encoding end def Assoc.auto_config_from_inner( dest_enc , misc_option = nil ) dest_encoding = Assoc.to_nkf_encoding_format( dest_enc ) inner_encoding = Assoc.to_nkf_encoding_format( Assoc.get_inner_encoding ) if inner_encoding != "A" @@config = "-#{dest_encoding.downcase}#{inner_encoding.upcase}" if misc_option != nil @@config += " #{misc_option}" end end end def Assoc.convert( str ) nstr = nil if str != nil if @@config != nil begin nstr = NKF.nkf( @@config , str ) rescue => ex puts ex puts "=========" pp caller(0) end else nstr = str end end nstr end def Assoc.get_inner_encoding @@inner_encoding = ($KCODE != "NONE") ? $KCODE : "ASCII" end end def NKFUTIL.set( key, value ) Assoc.set( key , value ) end def NKFUTIL.get( key ) Assoc.get( key ) end def NKFUTIL.convert( str ) if str != nil Assoc.convert( str ) else "" end end def NKFUTIL.assoc_equal( target , key ) target == key || target == Assoc.get( key ) end def NKFUTIL.config( src_encoding, dest_encoding , misc_option = nil ) Assoc.config( src_encoding, dest_encoding , misc_option ) end def NKFUTIL.auto_config_to_inner( str, misc_option = nil ) Assoc.auto_config_to_inner( str , misc_option ) end def NKFUTIL.auto_config_from_inner( dest_encoding , misc_option = nil ) Assoc.auto_config_to_inner( dest_encoding , misc_option ) end def puts_sj( line ) puts NKF.nkf( "-Ws -m0" , line ) end def puts_u( line ) puts NKF.nkf( "-Sw -m0" , line ) end def nkf_utf8_file( infname , outfname ) File.open( outfname ){|outf| File.open( infname ){|file| while line = file.gets line.chomp! oline = NKF.nkf( "-w -m0" , line ) outf.printf("%s\n" , oline ) end } } end end end