3535from IPython .utils .process import arg_split , system # type:ignore[attr-defined]
3636from jupyter_client .session import Session , extract_header
3737from jupyter_core .paths import jupyter_runtime_dir
38- from traitlets import Any , CBool , CBytes , Instance , Type , default , observe
38+ from traitlets import Any , Bool , CBool , CBytes , Instance , Type , default , observe
3939
4040from ipykernel import connect_qtconsole , get_connection_file , get_connection_info
4141from ipykernel .displayhook import ZMQShellDisplayHook
4242from ipykernel .jsonutil import encode_images , json_clean
4343
44+ try :
45+ from IPython .core .history import HistoryOutput
46+ except ImportError :
47+ HistoryOutput = None # type: ignore[assignment,misc]
48+
4449# -----------------------------------------------------------------------------
4550# Functions and classes
4651# -----------------------------------------------------------------------------
@@ -54,6 +59,11 @@ class ZMQDisplayPublisher(DisplayPublisher):
5459 _parent_header : contextvars .ContextVar [dict [str , Any ]]
5560 topic = CBytes (b"display_data" )
5661
62+ store_display_history = Bool (
63+ False ,
64+ help = "If set to True, store display outputs in the history manager. Default is False." ,
65+ ).tag (config = True )
66+
5767 # thread_local:
5868 # An attribute used to ensure the correct output message
5969 # is processed. See ipykernel Issue 113 for a discussion.
@@ -115,6 +125,21 @@ def publish( # type:ignore[override]
115125 update : bool, optional, keyword-only
116126 If True, send an update_display_data message instead of display_data.
117127 """
128+ if (
129+ self .store_display_history
130+ and self .shell is not None
131+ and hasattr (self .shell , "history_manager" )
132+ and HistoryOutput is not None
133+ ):
134+ # Reference: github.com/ipython/ipython/pull/14998
135+ exec_count = self .shell .execution_count
136+ if getattr (self .shell .display_pub , "_in_post_execute" , False ):
137+ exec_count -= 1
138+ outputs = getattr (self .shell .history_manager , "outputs" , None )
139+ if outputs is not None :
140+ outputs .setdefault (exec_count , []).append (
141+ HistoryOutput (output_type = "display_data" , bundle = data )
142+ )
118143 self ._flush_streams ()
119144 if metadata is None :
120145 metadata = {}
0 commit comments