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.
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 string containing a URL for ELinks to
53 follow, or an empty string if no URL should be followed, or None if
54 ELinks should follow the original URL.
58 url -- The URL provided by the user.
61 if url
in dumbprefixes
:
62 return dumbprefixes
[url
]
64 def follow_url_hook(url
):
65 """Rewrite a URL for a link that's about to be followed.
67 This function should return a string containing a URL for ELinks to
68 follow, or an empty string if no URL should be followed, or None if
69 ELinks should follow the original URL.
73 url -- The URL of the link.
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.
89 url -- The URL of the document.
90 html -- The body of the document.
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.
110 url -- The URL that is about to be followed.
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.
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."""
138 """Prompt for a URL."""
139 elinks
.input_box("Enter URL", self
._callback
, title
="Go to URL")
140 def _callback(self
, url
):
141 """Open the given URL in a new tab."""
142 if 'goto_url_hook' in globals():
143 # Mimic the standard "Go to URL" dialog by calling goto_url_hook().
144 url
= goto_url_hook(url
) or url
146 elinks
.open(url
, new_tab
=True)
147 # The elinks.bind_key() function can be used to create a keystroke binding
148 # that will instantiate the class.
150 elinks
.bind_key("Ctrl-g", goto_url_in_new_tab
)
153 # This class can be used to enter arbitrary Python expressions for the embedded
154 # interpreter to evaluate. (Note that it can only evalute Python expressions,
155 # not execute arbitrary Python code.) The callback function will use
156 # elinks.info_box() to display the results.
158 class simple_console
:
159 """Simple console for passing expressions to the Python interpreter."""
161 """Prompt for a Python expression."""
162 elinks
.input_box("Enter Python expression", self
._callback
, "Console")
163 def _callback(self
, input):
164 """Evalute input and display the result (unless it's None)."""
169 if result
is not None:
170 elinks
.info_box(result
, "Result")
171 elinks
.bind_key("F5", simple_console
)
174 # If you edit ~/.elinks/hooks.py while the browser is running, you can use
175 # this function to make your changes take effect immediately (without having
176 # to restart ELinks).
179 """Reload the ELinks Python hooks."""
182 elinks
.bind_key("F6", reload_hooks
)
185 # This example demonstrates how to create a menu by providing a sequence of
186 # (string, function) tuples specifying each menu item.
189 """Let the user choose from a menu of Python functions."""
191 ("~Go to URL in new tab", goto_url_in_new_tab
),
192 ("Simple Python ~console", simple_console
),
193 ("~Reload Python hooks", reload_hooks
),
194 ("Read my favorite RSS/ATOM ~feeds", feedreader
),
197 elinks
.bind_key("F4", menu
)
200 # Finally, a more elaborate demonstration: If you install the add-on Python
201 # module from http://feedparser.org/ this class can use it to parse a list
202 # of your favorite RSS/ATOM feeds, figure out which entries you haven't seen
203 # yet, open each of those entries in a new tab, and report statistics on what
204 # it fetched. The class is instantiated by pressing the "!" key.
206 # This class demonstrates the elinks.load() function, which can be used to
207 # load a document into the ELinks cache without displaying it to the user;
208 # the document's contents are passed to a Python callback function.
210 my_favorite_feeds
= (
211 "http://rss.gmane.org/messages/excerpts/gmane.comp.web.elinks.user",
212 # ... add any other RSS or ATOM feeds that interest you ...
213 # "http://elinks.cz/news.rss",
214 # "http://www.python.org/channews.rdf",
219 """RSS/ATOM feed reader."""
221 def __init__(self
, feeds
=my_favorite_feeds
):
223 if elinks
.home
is None:
224 raise elinks
.error("Cannot identify unread entries without "
225 "a ~/.elinks configuration directory.")
229 elinks
.load(feed
, self
._callback
)
231 def _callback(self
, header
, body
):
232 """Read a feed, identify unseen entries, and open them in new tabs."""
234 import feedparser
# you need to get this module from feedparser.org
239 seen
= anydbm
.open(os
.path
.join(elinks
.home
, "rss.seen"), "c")
240 feed
= feedparser
.parse(body
)
243 for entry
in feed
.entries
:
245 if not seen
.has_key(entry
.link
):
246 elinks
.open(entry
.link
, new_tab
=True)
247 seen
[entry
.link
] = ""
252 self
._tally
(feed
.channel
.title
, new
, errors
)
254 def _tally(self
, title
, new
, errors
):
255 """Record and report feed statistics."""
256 self
._results
[title
] = (new
, errors
)
257 if len(self
._results
) == len(self
._feeds
):
258 feeds
= self
._results
.keys()
260 width
= max([len(title
) for title
in feeds
])
261 fmt
= "%*s new entries: %2d errors: %2d\n"
264 new
, errors
= self
._results
[title
]
265 summary
+= fmt
% (-width
, title
, new
, errors
)
266 elinks
.info_box(summary
, "Feed Statistics")
268 elinks
.bind_key("!", feedreader
)