@@ -2902,9 +2902,6 @@ def _complete_statement(self, line: str) -> Statement:
29022902 if not statement .command :
29032903 raise EmptyStatement
29042904
2905- # Add the complete command to prompt-toolkit's history.
2906- cast (Cmd2History , self .main_session .history ).add_command (statement .raw )
2907-
29082905 return statement
29092906
29102907 def _input_line_to_statement (self , line : str ) -> Statement :
@@ -3176,12 +3173,11 @@ def onecmd(self, statement: Statement | str, *, add_to_history: bool = True) ->
31763173 func = self .cmd_func (statement .command )
31773174 if func :
31783175 # Check to see if this command should be stored in history
3179- if (
3180- statement .command not in self .exclude_from_history
3181- and statement .command not in self .disabled_commands
3182- and add_to_history
3183- ):
3184- self .history .append (statement )
3176+ if statement .command not in self .disabled_commands and add_to_history :
3177+ if statement .command not in self .exclude_from_history :
3178+ self .history .append (statement )
3179+
3180+ self ._add_to_pt_history (statement .raw )
31853181
31863182 try :
31873183 self .current_command = statement
@@ -3202,6 +3198,7 @@ def default(self, statement: Statement) -> bool | None:
32023198 if self .default_to_shell :
32033199 if 'shell' not in self .exclude_from_history :
32043200 self .history .append (statement )
3201+ self ._add_to_pt_history (statement .raw )
32053202 return self .do_shell (statement .command_and_args )
32063203
32073204 err_msg = self .default_error .format (statement .command )
@@ -3236,6 +3233,16 @@ def _is_tty_session(session: PromptSession[str]) -> bool:
32363233 # tests to inject PipeInput for programmatic interaction.
32373234 return not isinstance (session .input , DummyInput )
32383235
3236+ def _add_to_pt_history (self , line : str ) -> None :
3237+ """Add a command to the prompt-toolkit UI history if it's a Cmd2History instance."""
3238+ if hasattr (self , 'main_session' ) and isinstance (self .main_session .history , Cmd2History ):
3239+ self .main_session .history .add_command (line )
3240+
3241+ def _clear_pt_history (self ) -> None :
3242+ """Clear the prompt-toolkit UI history if it's a Cmd2History instance."""
3243+ if hasattr (self , 'main_session' ) and isinstance (self .main_session .history , Cmd2History ):
3244+ self .main_session .history .clear ()
3245+
32393246 def _read_raw_input (
32403247 self ,
32413248 prompt : Callable [[], ANSI | str ] | ANSI | str ,
@@ -5005,7 +5012,7 @@ def do_history(self, args: argparse.Namespace) -> bool | None:
50055012
50065013 # Clear command and prompt-toolkit history
50075014 self .history .clear ()
5008- cast ( Cmd2History , self .main_session . history ). clear ()
5015+ self ._clear_pt_history ()
50095016
50105017 if self .persistent_history_file :
50115018 try :
0 commit comments