Python: Give goto_url_hook only one argument, like follow_url_hook.
[elinks.git] / contrib / python / hooks.py
bloba4726e4901d8ca92fee4733b518dbcad5d3f9a94
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):
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.
59 """
60 if url in dumbprefixes:
61 return dumbprefixes[url]
63 def follow_url_hook(url):
64 """Rewrite a URL for a link that's about to be followed.
66 This function should return a URL for ELinks to follow, or None if
67 ELinks should follow the original URL.
69 Arguments:
71 url -- The URL of the link.
73 """
74 google_redirect = 'http://www.google.com/url?sa=D&q='
75 if url.startswith(google_redirect):
76 return url.replace(google_redirect, '')
78 def pre_format_html_hook(url, html):
79 """Rewrite the body of a document before it's formatted.
81 This function should return a string for ELinks to format, or None
82 if ELinks should format the original document body. It can be used
83 to repair bad HTML, alter the layout or colors of a document, etc.
85 Arguments:
87 url -- The URL of the document.
88 html -- The body of the document.
90 """
91 if "cygwin.com" in url:
92 return html.replace('<body bgcolor="#000000" color="#000000"',
93 '<body bgcolor="#ffffff" color="#000000"')
94 elif url.startswith("https://www.mbank.com.pl/ib_navibar_3.asp"):
95 return html.replace('<td valign="top"><img',
96 '<tr><td valign="top"><img')
98 def proxy_for_hook(url):
99 """Determine what proxy server to use for a given URL.
101 This function should return a string of the form "hostname:portnumber"
102 identifying a proxy server to use, or an empty string if the request
103 shouldn't use any proxy server, or None if ELinks should use its
104 default proxy server.
106 Arguments:
108 url -- The URL that is about to be followed.
111 pass
113 def quit_hook():
114 """Clean up before ELinks exits.
116 This function should handle any clean-up tasks that need to be
117 performed before ELinks exits. Its return value is ignored.
120 pass
123 # The rest of this file demonstrates some of the functionality available
124 # within hooks.py through the embedded Python interpreter's elinks module.
125 # Full documentation for the elinks module (as well as the hooks module)
126 # can be found in doc/python.txt in the ELinks source distribution.
129 # This class shows how to use elinks.input_box() and elinks.open(). It
130 # creates a dialog box to prompt the user for a URL, and provides a callback
131 # function that opens the URL in a new tab.
133 class goto_url_in_new_tab:
134 """Prompter that opens a given URL in a new tab."""
135 def __init__(self):
136 """Prompt for a URL."""
137 elinks.input_box("Enter URL", self._callback, title="Go to URL")
138 def _callback(self, url):
139 """Open the given URL in a new tab."""
140 if 'goto_url_hook' in globals():
141 # Mimic the standard "Go to URL" dialog by calling goto_url_hook().
142 url = goto_url_hook(url) or url
143 if url:
144 elinks.open(url, new_tab=True)
145 # The elinks.bind_key() function can be used to create a keystroke binding
146 # that will instantiate the class.
148 elinks.bind_key("Ctrl-g", goto_url_in_new_tab)
151 # This class can be used to enter arbitrary Python expressions for the embedded
152 # interpreter to evaluate. (Note that it can only evalute Python expressions,
153 # not execute arbitrary Python code.) The callback function will use
154 # elinks.info_box() to display the results.
156 class simple_console:
157 """Simple console for passing expressions to the Python interpreter."""
158 def __init__(self):
159 """Prompt for a Python expression."""
160 elinks.input_box("Enter Python expression", self._callback, "Console")
161 def _callback(self, input):
162 """Evalute input and display the result (unless it's None)."""
163 if input is None:
164 # The user canceled.
165 return
166 result = eval(input)
167 if result is not None:
168 elinks.info_box(result, "Result")
169 elinks.bind_key("F5", simple_console)
172 # If you edit ~/.elinks/hooks.py while the browser is running, you can use
173 # this function to make your changes take effect immediately (without having
174 # to restart ELinks).
176 def reload_hooks():
177 """Reload the ELinks Python hooks."""
178 import hooks
179 reload(hooks)
180 elinks.bind_key("F6", reload_hooks)
183 # This example demonstrates how to create a menu by providing a sequence of
184 # (string, function) tuples specifying each menu item.
186 def menu():
187 """Let the user choose from a menu of Python functions."""
188 items = (
189 ("~Go to URL in new tab", goto_url_in_new_tab),
190 ("Simple Python ~console", simple_console),
191 ("~Reload Python hooks", reload_hooks),
192 ("Read my favorite RSS/ATOM ~feeds", feedreader),
194 elinks.menu(items)
195 elinks.bind_key("F4", menu)
198 # Finally, a more elaborate demonstration: If you install the add-on Python
199 # module from http://feedparser.org/ this class can use it to parse a list
200 # of your favorite RSS/ATOM feeds, figure out which entries you haven't seen
201 # yet, open each of those entries in a new tab, and report statistics on what
202 # it fetched. The class is instantiated by pressing the "!" key.
204 # This class demonstrates the elinks.load() function, which can be used to
205 # load a document into the ELinks cache without displaying it to the user;
206 # the document's contents are passed to a Python callback function.
208 my_favorite_feeds = (
209 "http://rss.gmane.org/messages/excerpts/gmane.comp.web.elinks.user",
210 # ... add any other RSS or ATOM feeds that interest you ...
211 # "http://elinks.cz/news.rss",
212 # "http://www.python.org/channews.rdf",
215 class feedreader:
217 """RSS/ATOM feed reader."""
219 def __init__(self, feeds=my_favorite_feeds):
220 """Constructor."""
221 if elinks.home is None:
222 raise elinks.error("Cannot identify unread entries without "
223 "a ~/.elinks configuration directory.")
224 self._results = {}
225 self._feeds = feeds
226 for feed in feeds:
227 elinks.load(feed, self._callback)
229 def _callback(self, header, body):
230 """Read a feed, identify unseen entries, and open them in new tabs."""
231 import anydbm
232 import feedparser # you need to get this module from feedparser.org
233 import os
235 if not body:
236 return
237 seen = anydbm.open(os.path.join(elinks.home, "rss.seen"), "c")
238 feed = feedparser.parse(body)
239 new = 0
240 errors = 0
241 for entry in feed.entries:
242 try:
243 if not seen.has_key(entry.link):
244 elinks.open(entry.link, new_tab=True)
245 seen[entry.link] = ""
246 new += 1
247 except:
248 errors += 1
249 seen.close()
250 self._tally(feed.channel.title, new, errors)
252 def _tally(self, title, new, errors):
253 """Record and report feed statistics."""
254 self._results[title] = (new, errors)
255 if len(self._results) == len(self._feeds):
256 feeds = self._results.keys()
257 feeds.sort()
258 width = max([len(title) for title in feeds])
259 fmt = "%*s new entries: %2d errors: %2d\n"
260 summary = ""
261 for title in feeds:
262 new, errors = self._results[title]
263 summary += fmt % (-width, title, new, errors)
264 elinks.info_box(summary, "Feed Statistics")
266 elinks.bind_key("!", feedreader)