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

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

60 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 sys 

45 

46from .error import TryNext 

47 

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

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

50 

51__all__ = [ 

52 "editor", 

53 "synchronize_with_editor", 

54 "show_in_pager", 

55 "clipboard_get", 

56] 

57 

58 

59def _quote_if_needed(path): 

60 """Wrap path in double quotes if it contains spaces and isn't already quoted.""" 

61 if " " in path and not (path.startswith('"') and path.endswith('"')): 

62 return '"%s"' % path 

63 return path 

64 

65 

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

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

68 

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

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

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

72 

73 Notes 

74 ----- 

75 `filename` is always passed in raw/unquoted form. Any quoting or 

76 escaping needed to safely build a shell command is the responsibility 

77 of the hook implementation, not the caller. 

78 """ 

79 

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

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

82 editor = self.editor 

83 

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

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

86 linemark = '' 

87 else: 

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

89 

90 # Enclose in quotes if necessary and legal 

91 if os.path.isfile(editor): 

92 editor = _quote_if_needed(editor) 

93 filename = _quote_if_needed(filename) 

94 

95 # Call the actual editor 

96 import subprocess 

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

98 shell=True) 

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

100 raise TryNext() 

101 

102 

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

104 pass 

105 

106 

107class CommandChainDispatcher: 

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

109 

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

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

112 

113 """ 

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

115 if commands is None: 

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

117 else: 

118 self.chain = commands 

119 

120 

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

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

123 

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

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

126 TryNext""" 

127 last_exc = TryNext() 

128 for prio,cmd in self.chain: 

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

130 try: 

131 return cmd(*args, **kw) 

132 except TryNext as exc: 

133 last_exc = exc 

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

135 raise last_exc 

136 

137 def __str__(self) -> str: 

138 return str(self.chain) 

139 

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

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

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

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

144 

145 def __iter__(self): 

146 """ Return all objects in chain. 

147 

148 Handy if the objects are not callable. 

149 """ 

150 return iter(self.chain) 

151 

152 

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

154 """ Run a string through pager """ 

155 # raising TryNext here will use the default paging functionality 

156 raise TryNext 

157 

158 

159 

160def clipboard_get(self): 

161 """ Get text from the clipboard. 

162 """ 

163 from ..lib.clipboard import ( 

164 osx_clipboard_get, 

165 tkinter_clipboard_get, 

166 win32_clipboard_get, 

167 wayland_clipboard_get, 

168 ) 

169 if sys.platform == 'win32': 

170 chain = [win32_clipboard_get, tkinter_clipboard_get] 

171 elif sys.platform == 'darwin': 

172 chain = [osx_clipboard_get, tkinter_clipboard_get] 

173 else: 

174 chain = [wayland_clipboard_get, tkinter_clipboard_get] 

175 dispatcher = CommandChainDispatcher() 

176 for func in chain: 

177 dispatcher.add(func) 

178 text = dispatcher() 

179 return text