@@ -167,7 +167,22 @@ def history_file
167167 def read_history_file
168168 if history && File . exist? ( path = history_file )
169169 f = ( [ '' , 'DAI-' , 'CHU-' , 'SHO-' ] . map { |e | e +'KICHI' } +[ 'KYO' ] ) . sample
170- [ "#{ FH } #{ f } " . dup ] + File . readlines ( path )
170+ begin
171+ # Force UTF-8 encoding to handle history files with Unicode characters
172+ lines = File . readlines ( path , encoding : 'UTF-8' )
173+ [ "#{ FH } #{ f } " . dup ] + lines
174+ rescue ArgumentError , Encoding ::UndefinedConversionError
175+ # If UTF-8 reading fails, try with binary mode and force UTF-8
176+ begin
177+ lines = File . readlines ( path , mode : 'rb' ) . map do |line |
178+ line . force_encoding ( 'UTF-8' ) . scrub ( '?' )
179+ end
180+ [ "#{ FH } #{ f } " . dup ] + lines
181+ rescue
182+ # If all encoding attempts fail, return empty history to avoid crash
183+ [ "#{ FH } #{ f } " . dup ]
184+ end
185+ end
171186 else
172187 [ ]
173188 end
@@ -191,10 +206,20 @@ def deactivate
191206
192207 if !added_records . empty? && !path . empty?
193208 orig_records = read_history_file
194- open ( history_file , 'w' ) { |f |
209+ open ( history_file , 'w' , encoding : 'UTF-8' ) { |f |
195210 ( orig_records + added_records ) . last ( max ) . each { |line |
196- if !line . start_with? ( FH ) && !line . strip . empty?
197- f . puts line . strip
211+ begin
212+ # Ensure proper encoding before calling strip
213+ if line . encoding != Encoding ::UTF_8
214+ line = line . encode ( 'UTF-8' , invalid : :replace , undef : :replace )
215+ end
216+ stripped_line = line . strip
217+ if !line . start_with? ( FH ) && !stripped_line . empty?
218+ f . puts stripped_line
219+ end
220+ rescue Encoding ::CompatibilityError , ArgumentError
221+ # Skip lines that cannot be properly encoded to avoid crashes
222+ next
198223 end
199224 }
200225 }
@@ -204,8 +229,17 @@ def deactivate
204229
205230 def load_history
206231 read_history_file . each { |line |
207- line . strip!
208- history << line unless line . empty?
232+ begin
233+ # Ensure proper encoding before calling strip!
234+ if line . encoding != Encoding ::UTF_8
235+ line = line . encode ( 'UTF-8' , invalid : :replace , undef : :replace )
236+ end
237+ line . strip!
238+ history << line unless line . empty?
239+ rescue Encoding ::CompatibilityError , ArgumentError
240+ # Skip lines that cannot be properly encoded to avoid crashes
241+ next
242+ end
209243 } if history . empty?
210244 history . count
211245 end
0 commit comments