Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/IPython/core/hooks.py: 35%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

55 statements  

1"""Hooks for IPython. 

2 

3In Python, it is possible to overwrite any method of any object if you really 

4want to. But IPython exposes a few 'hooks', methods which are *designed* to 

5be overwritten by users for customization purposes. This module defines the 

6default versions of all such hooks, which get used by IPython if not 

7overridden by the user. 

8 

9Hooks are simple functions, but they should be declared with ``self`` as their 

10first argument, because when activated they are registered into IPython as 

11instance methods. The self argument will be the IPython running instance 

12itself, so hooks have full access to the entire IPython object. 

13 

14If you wish to define a new hook and activate it, you can make an :doc:`extension 

15</config/extensions/index>` or a :ref:`startup script <startup_files>`. For 

16example, you could use a startup file like this:: 

17 

18 import os 

19 

20 def calljed(self,filename, linenum): 

21 "My editor hook calls the jed editor directly." 

22 print("Calling my own editor, jed ...") 

23 if os.system('jed +%d %s' % (linenum,filename)) != 0: 

24 raise TryNext() 

25 

26 def load_ipython_extension(ip): 

27 ip.set_hook('editor', calljed) 

28 

29""" 

30 

31#***************************************************************************** 

32# Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> 

33# 

34# Distributed under the terms of the BSD License. The full license is in 

35# the file COPYING, distributed as part of this software. 

36#***************************************************************************** 

37 

38from __future__ import annotations 

39 

40from typing import Any 

41from collections.abc import Callable 

42 

43import os 

44import subprocess 

45import sys 

46 

47from .error import TryNext 

48 

49# List here all the default hooks. For now it's just the editor functions 

50# but over time we'll move here all the public API for user-accessible things. 

51 

52__all__ = [ 

53 "editor", 

54 "synchronize_with_editor", 

55 "show_in_pager", 

56 "clipboard_get", 

57] 

58 

59def editor(self, filename, linenum=None, wait=True): 

60 """Open the default editor at the given filename and linenumber. 

61 

62 This is IPython's default editor hook, you can use it as an example to 

63 write your own modified one. To set your own editor function as the 

64 new editor hook, call ip.set_hook('editor',yourfunc).""" 

65 

66 # IPython configures a default editor at startup by reading $EDITOR from 

67 # the environment, and falling back on vi (unix) or notepad (win32). 

68 editor = self.editor 

69 

70 # marker for at which line to open the file (for existing objects) 

71 if linenum is None or editor=='notepad': 

72 linemark = '' 

73 else: 

74 linemark = '+%d' % int(linenum) 

75 

76 # Enclose in quotes if necessary and legal 

77 if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': 

78 editor = '"%s"' % editor 

79 

80 # Call the actual editor 

81 proc = subprocess.Popen('{} {} {}'.format(editor, linemark, filename), 

82 shell=True) 

83 if wait and proc.wait() != 0: 

84 raise TryNext() 

85 

86 

87def synchronize_with_editor(self, filename, linenum, column): 

88 pass 

89 

90 

91class CommandChainDispatcher: 

92 """ Dispatch calls to a chain of commands until some func can handle it 

93 

94 Usage: instantiate, execute "add" to add commands (with optional 

95 priority), execute normally via f() calling mechanism. 

96 

97 """ 

98 def __init__(self, commands: list[tuple[int, Callable[..., Any]]] | None = None) -> None: 

99 if commands is None: 

100 self.chain: list[tuple[int, Callable[..., Any]]] = [] 

101 else: 

102 self.chain = commands 

103 

104 

105 def __call__(self, *args: Any, **kw: Any) -> Any: 

106 """ Command chain is called just like normal func. 

107 

108 This will call all funcs in chain with the same args as were given to 

109 this function, and return the result of first func that didn't raise 

110 TryNext""" 

111 last_exc = TryNext() 

112 for prio,cmd in self.chain: 

113 # print("prio",prio,"cmd",cmd) # dbg 

114 try: 

115 return cmd(*args, **kw) 

116 except TryNext as exc: 

117 last_exc = exc 

118 # if no function will accept it, raise TryNext up to the caller 

119 raise last_exc 

120 

121 def __str__(self) -> str: 

122 return str(self.chain) 

123 

124 def add(self, func: Callable[..., Any], priority: int = 0) -> None: 

125 """ Add a func to the cmd chain with given priority """ 

126 self.chain.append((priority, func)) 

127 self.chain.sort(key=lambda x: x[0]) 

128 

129 def __iter__(self): 

130 """ Return all objects in chain. 

131 

132 Handy if the objects are not callable. 

133 """ 

134 return iter(self.chain) 

135 

136 

137def show_in_pager(self, data, start, screen_lines): 

138 """ Run a string through pager """ 

139 # raising TryNext here will use the default paging functionality 

140 raise TryNext 

141 

142 

143 

144def clipboard_get(self): 

145 """ Get text from the clipboard. 

146 """ 

147 from ..lib.clipboard import ( 

148 osx_clipboard_get, 

149 tkinter_clipboard_get, 

150 win32_clipboard_get, 

151 wayland_clipboard_get, 

152 ) 

153 if sys.platform == 'win32': 

154 chain = [win32_clipboard_get, tkinter_clipboard_get] 

155 elif sys.platform == 'darwin': 

156 chain = [osx_clipboard_get, tkinter_clipboard_get] 

157 else: 

158 chain = [wayland_clipboard_get, tkinter_clipboard_get] 

159 dispatcher = CommandChainDispatcher() 

160 for func in chain: 

161 dispatcher.add(func) 

162 text = dispatcher() 

163 return text