@@ -87,6 +87,7 @@ class Irb
8787 # Creates a new irb session
8888 def initialize ( workspace = nil , input_method = nil , from_binding : false )
8989 @from_binding = from_binding
90+ @prompt_part_cache = nil
9091 @context = Context . new ( self , workspace , input_method )
9192 @context . workspace . load_helper_methods_to_main
9293 @signal_status = :IN_IRB
@@ -239,6 +240,7 @@ def read_input(prompt)
239240 end
240241
241242 def readmultiline
243+ @prompt_part_cache = { }
242244 prompt = generate_prompt ( [ ] , false , 0 )
243245
244246 # multiline
@@ -263,6 +265,8 @@ def readmultiline
263265 continue = @scanner . should_continue? ( tokens )
264266 prompt = generate_prompt ( opens , continue , line_offset )
265267 end
268+ ensure
269+ @prompt_part_cache = nil
266270 end
267271
268272 def each_top_level_statement
@@ -598,25 +602,28 @@ def generate_prompt(opens, continue, line_offset)
598602 end
599603
600604 def truncate_prompt_main ( str ) # :nodoc:
601- str = str . tr ( CONTROL_CHARACTERS_PATTERN , ' ' )
602- if str . size <= PROMPT_MAIN_TRUNCATE_LENGTH
603- str
604- else
605- str [ 0 , PROMPT_MAIN_TRUNCATE_LENGTH - PROMPT_MAIN_TRUNCATE_OMISSION . size ] + PROMPT_MAIN_TRUNCATE_OMISSION
605+ if str . size > PROMPT_MAIN_TRUNCATE_LENGTH
606+ str = str [ 0 , PROMPT_MAIN_TRUNCATE_LENGTH - PROMPT_MAIN_TRUNCATE_OMISSION . size ] + PROMPT_MAIN_TRUNCATE_OMISSION
606607 end
608+ str . tr ( CONTROL_CHARACTERS_PATTERN , ' ' )
607609 end
608610
609611 def format_prompt ( format , ltype , indent , line_no ) # :nodoc:
612+ part_cache = @prompt_part_cache || { }
610613 format . gsub ( /%([0-9]+)?([a-zA-Z%])/ ) do
611614 case $2
612615 when "N"
613616 @context . irb_name
614617 when "m"
615- main_str = "#{ @context . safe_method_call_on_main ( :to_s ) } " rescue "!#{ $!. class } "
616- truncate_prompt_main ( main_str )
618+ part_cache [ :m ] ||= (
619+ main_str = "#{ @context . safe_method_call_on_main ( :to_s ) } " rescue "!#{ $!. class } "
620+ truncate_prompt_main ( main_str )
621+ )
617622 when "M"
618- main_str = "#{ @context . safe_method_call_on_main ( :inspect ) } " rescue "!#{ $!. class } "
619- truncate_prompt_main ( main_str )
623+ part_cache [ :M ] ||= (
624+ main_str = "#{ @context . safe_method_call_on_main ( :inspect ) } " rescue "!#{ $!. class } "
625+ truncate_prompt_main ( main_str )
626+ )
620627 when "l"
621628 ltype
622629 when "i"
0 commit comments