Bug 880: Prevent SIGSEGV in init_python when -no-home is used.
[elinks.git] / contrib / python / hooks.py
blob0d4151acf40781de453314aac7e87bc5f143f8b6
1 """Example Python hooks for ELinks.
3 If ELinks is compiled with an embedded Python interpreter, it will try
4 to import a Python module called hooks when the browser starts up. To
5 use Python code from within ELinks, create a file called hooks.py in
6 the ~/.elinks directory, or in the system-wide configuration directory
7 (defined when ELinks was compiled), or in the standard Python search path.
8 An example hooks.py file can be found in the contrib/python directory of
9 the ELinks source distribution.
11 The hooks module may implement any of several functions that will be
12 called automatically by ELinks in appropriate circumstances; it may also
13 bind ELinks keystrokes to callable Python objects so that arbitrary Python
14 code can be invoked at the whim of the user.
16 Functions that will be automatically called by ELinks (if they're defined):
18 follow_url_hook() -- Rewrite a URL for a link that's about to be followed.
19 goto_url_hook() -- Rewrite a URL received from a "Go to URL" dialog box.
20 pre_format_html_hook() -- Rewrite a document's body before it's formatted.
21 proxy_for_hook() -- Determine what proxy server to use for a given URL.
22 quit_hook() -- Clean up before ELinks exits.
24 """
26 import elinks
28 dumbprefixes = {
29 "7th" : "http://7thguard.net/",
30 "b" : "http://babelfish.altavista.com/babelfish/tr/",
31 "bz" : "http://bugzilla.elinks.cz/",
32 "bug" : "http://bugzilla.elinks.cz/",
33 "d" : "http://www.dict.org/",
34 "g" : "http://www.google.com/",
35 "gg" : "http://www.google.com/",
36 "go" : "http://www.google.com/",
37 "fm" : "http://www.freshmeat.net/",
38 "sf" : "http://www.sourceforge.net/",
39 "dbug" : "http://bugs.debian.org/",
40 "dpkg" : "http://packages.debian.org/",
41 "pycur" : "http://www.python.org/doc/current/",
42 "pydev" : "http://www.python.org/dev/doc/devel/",
43 "pyhelp" : "http://starship.python.net/crew/theller/pyhelp.cgi",
44 "pyvault" : "http://www.vex.net/parnassus/",
45 "e2" : "http://www.everything2.org/",
46 "sd" : "http://www.slashdot.org/"
49 def goto_url_hook(url, current_url):
50 """Rewrite a URL that was entered in a "Go to URL" dialog box.
52 This function should return a URL for ELinks to follow, or None if
53 ELinks should follow the original URL.
55 Arguments:
57 url -- The URL provided by the user.
58 current_url -- The URL of the document being viewed, or None if no
59 document is being viewed.
61 """
62 if url in dumbprefixes:
63 return dumbprefixes[url]
65 def follow_url_hook(url):
66 """Rewrite a URL for a link that's about to be followed.
68 This function should return a URL for ELinks to follow, or None if
69 ELinks should follow the original URL.
71 Arguments:
73 url -- The URL of the link.
75 """
76 google_redirect = 'http://www.google.com/url?sa=D&q='
77 if url.startswith(google_redirect):
78 return url.replace(google_redirect, '')
80 def pre_format_html_hook(url, html):
81 """Rewrite the body of a document before it's formatted.
83 This function should return a string for ELinks to format, or None
84 if ELinks should format the original document body. It can be used
85 to repair bad HTML, alter the layout or colors of a document, etc.
87 Arguments:
89 url -- The URL of the document.
90 html -- The body of the document.
92 """
93 if "cygwin.com" in url:
94 return html.replace('<body bgcolor="#000000" color="#000000"',
95 '<body bgcolor="#ffffff" color="#000000"')
96 elif url.startswith("https://www.mbank.com.pl/ib_navibar_3.asp"):
97 return html.replace('<td valign="top"><img',
98 '<tr><td valign="top"><img')
100 def proxy_for_hook(url):
101 """Determine what proxy server to use for a given URL.
103 This function should return a string of the form "hostname:portnumber"
104 identifying a proxy server to use, or an empty string if the request
105 shouldn't use any proxy server, or None if ELinks should use its
106 default proxy server.
108 Arguments:
110 url -- The URL that is about to be followed.
113 pass
115 def quit_hook():
116 """Clean up before ELinks exits.
118 This function should handle any clean-up tasks that need to be
119 performed before ELinks exits. Its return value is ignored.
122 pass
125 # The rest of this file demonstrates some of the functionality available
126 # within hooks.py through the embedded Python interpreter's elinks module.
127 # Full documentation for the elinks module (as well as the hooks module)
128 # can be found in doc/python.txt in the ELinks source distribution.
131 # This class shows how to use elinks.input_box() and elinks.open(). It
132 # creates a dialog box to prompt the user for a URL, and provides a callback
133 # function that opens the URL in a new tab.
135 class goto_url_in_new_tab:
136 """Prompter that opens a given URL in a new tab."""
137 def __init__(self):
138 """Prompt for a URL."""
139 self.current_location = elinks.current_url()
140 elinks.input_box("Enter URL", self._callback, title="Go to URL")
141 def _callback(self, url):
142 """Open the given URL in a new tab."""
143 if 'goto_url_hook' in globals():
144 # Mimic the standard "Go to URL" dialog by calling goto_url_hook().
145 url = goto_url_hook(url, self.current_location) or url
146 if url:
147 elinks.open(url, new_tab=True)
148 # The elinks.bind_key() function can be used to create a keystroke binding
149 # that will instantiate the class.
151 elinks.bind_key("Ctrl-g", goto_url_in_new_tab)
154 # This class can be used to enter arbitrary Python expressions for the embedded
155 # interpreter to evaluate. (Note that it can only evalute Python expressions,
156 # not execute arbitrary Python code.) The callback function will use
157 # elinks.info_box() to display the results.
159 class simple_console:
160 """Simple console for passing expressions to the Python interpreter."""
161 def __init__(self):
162 """Prompt for a Python expression."""
163 elinks.input_box("Enter Python expression", self._callback, "Console")
164 def _callback(self, input):
165 """Evalute input and display the result (unless it's None)."""
166 if input is None:
167 # The user canceled.
168 return
169 result = eval(input)
170 if result is not None:
171 elinks.info_box(result, "Result")
172 elinks.bind_key("F5", simple_console)
175 # If you edit ~/.elinks/hooks.py while the browser is running, you can use
176 # this function to make your changes take effect immediately (without having
177 # to restart ELinks).
179 def reload_hooks():
180 """Reload the ELinks Python hooks."""
181 import hooks
182 reload(hooks)
183 elinks.bind_key("F6", reload_hooks)
186 # This example demonstrates how to create a menu by providing a sequence of
187 # (string, function) tuples specifying each menu item.
189 def menu():
190 """Let the user choose from a menu of Python functions."""
191 items = (
192 ("~Go to URL in new tab", goto_url_in_new_tab),
193 ("Simple Python ~console", simple_console),
194 ("~Reload Python hooks", reload_hooks),
195 ("Read my favorite RSS/ATOM ~feeds", feedreader),
197 elinks.menu(items)
198 elinks.bind_key("F4", menu)
201 # Finally, a more elaborate demonstration: If you install the add-on Python
202 # module from http://feedparser.org/ this class can use it to parse a list
203 # of your favorite RSS/ATOM feeds, figure out which entries you haven't seen
204 # yet, open each of those entries in a new tab, and report statistics on what
205 # it fetched. The class is instantiated by pressing the "!" key.
207 # This class demonstrates the elinks.load() function, which can be used to
208 # load a document into the ELinks cache without displaying it to the user;
209 # the document's contents are passed to a Python callback function.
211 my_favorite_feeds = (
212 "http://rss.gmane.org/messages/excerpts/gmane.comp.web.elinks.user",
213 # ... add any other RSS or ATOM feeds that interest you ...
214 # "http://elinks.cz/news.rss",
215 # "http://www.python.org/channews.rdf",
218 class feedreader:
220 """RSS/ATOM feed reader."""
222 def __init__(self, feeds=my_favorite_feeds):
223 """Constructor."""
224 if elinks.home is None:
225 raise elinks.error("Cannot identify unread entries without "
226 "a ~/.elinks configuration directory.")
227 self._results = {}
228 self._feeds = feeds
229 for feed in feeds:
230 elinks.load(feed, self._callback)
232 def _callback(self, header, body):
233 """Read a feed, identify unseen entries, and open them in new tabs."""
234 import anydbm
235 import feedparser # you need to get this module from feedparser.org
236 import os
238 if not body:
239 return
240 seen = anydbm.open(os.path.join(elinks.home, "rss.seen"), "c")
241 feed = feedparser.parse(body)
242 new = 0
243 errors = 0
244 for entry in feed.entries:
245 try:
246 if not seen.has_key(entry.link):
247 elinks.open(entry.link, new_tab=True)
248 seen[entry.link] = ""
249 new += 1
250 except:
251 errors += 1
252 seen.close()
253 self._tally(feed.channel.title, new, errors)
255 def _tally(self, title, new, errors):
256 """Record and report feed statistics."""
257 self._results[title] = (new, errors)
258 if len(self._results) == len(self._feeds):
259 feeds = self._results.keys()
260 feeds.sort()
261 width = max([len(title) for title in feeds])
262 fmt = "%*s new entries: %2d errors: %2d\n"
263 summary = ""
264 for title in feeds:
265 new, errors = self._results[title]
266 summary += fmt % (-width, title, new, errors)
267 elinks.info_box(summary, "Feed Statistics")
269 elinks.bind_key("!", feedreader)