up, add new config files and delete old tar conf file
[arrow.git] / conf_slk120 / bin / .bin / shell / html2text.py
blob06d61e19beaaa4d8b44012a45c472395dd33ae92
1 """html2text: Turn HTML into equivalent Markdown-structured text."""
2 __version__ = "2.23"
3 __author__ = "Aaron Swartz (me@aaronsw.com)"
4 __copyright__ = "(C) 2004 Aaron Swartz. GNU GPL 2."
5 __contributors__ = ["Martin 'Joey' Schulze", "Ricardo Reyes"]
7 # TODO:
8 # Support decoded entities with unifiable.
9 # Relative URL resolution
11 if not hasattr(__builtins__, 'True'): True, False = 1, 0
12 import re, sys, urllib, htmlentitydefs, codecs, StringIO, types
13 import sgmllib
14 sgmllib.charref = re.compile('&#([xX]?[0-9a-fA-F]+)[^0-9a-fA-F]')
16 try: from textwrap import wrap
17 except: pass
19 # Use Unicode characters instead of their ascii psuedo-replacements
20 UNICODE_SNOB = 0
22 # Put the links after each paragraph instead of at the end.
23 LINKS_EACH_PARAGRAPH = 0
25 # Wrap long lines at position. 0 for no wrapping. (Requires Python 2.3.)
26 BODY_WIDTH = 0
28 ### Entity Nonsense ###
30 def name2cp(k):
31 if k == 'apos': return ord("'")
32 if hasattr(htmlentitydefs, "name2codepoint"): # requires Python 2.3
33 return htmlentitydefs.name2codepoint[k]
34 else:
35 k = htmlentitydefs.entitydefs[k]
36 if k.startswith("&#") and k.endswith(";"): return int(k[2:-1]) # not in latin-1
37 return ord(codecs.latin_1_decode(k)[0])
39 unifiable = {'rsquo':"'", 'lsquo':"'", 'rdquo':'"', 'ldquo':'"',
40 'copy':'(C)', 'mdash':'--', 'nbsp':' ', 'rarr':'->', 'larr':'<-', 'middot':'*',
41 'ndash':'-', 'oelig':'oe', 'aelig':'ae',
42 'agrave':'a', 'aacute':'a', 'acirc':'a', 'atilde':'a', 'auml':'a', 'aring':'a',
43 'egrave':'e', 'eacute':'e', 'ecirc':'e', 'euml':'e',
44 'igrave':'i', 'iacute':'i', 'icirc':'i', 'iuml':'i',
45 'ograve':'o', 'oacute':'o', 'ocirc':'o', 'otilde':'o', 'ouml':'o',
46 'ugrave':'u', 'uacute':'u', 'ucirc':'u', 'uuml':'u'}
48 unifiable_n = {}
50 for k in unifiable.keys():
51 unifiable_n[name2cp(k)] = unifiable[k]
53 def charref(name):
54 if name[0] in ['x','X']:
55 c = int(name[1:], 16)
56 else:
57 c = int(name)
59 if not UNICODE_SNOB and c in unifiable_n.keys():
60 return unifiable_n[c]
61 else:
62 return unichr(c)
64 def entityref(c):
65 if not UNICODE_SNOB and c in unifiable.keys():
66 return unifiable[c]
67 else:
68 try: name2cp(c)
69 except KeyError: return "&" + c
70 else: return unichr(name2cp(c))
72 def replaceEntities(s):
73 s = s.group(1)
74 if s[0] == "#":
75 return charref(s[1:])
76 else: return entityref(s)
78 r_unescape = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
79 def unescape(s):
80 return r_unescape.sub(replaceEntities, s)
82 def fixattrs(attrs):
83 # Fix bug in sgmllib.py
84 if not attrs: return attrs
85 newattrs = []
86 for attr in attrs:
87 newattrs.append((attr[0], unescape(attr[1])))
88 return newattrs
90 ### End Entity Nonsense ###
92 def onlywhite(line):
93 """Return true if the line does only consist of whitespace characters."""
94 for c in line:
95 if c is not ' ' and c is not ' ':
96 return c is ' '
97 return line
99 def optwrap(text):
100 """Wrap all paragraphs in the provided text."""
101 if not BODY_WIDTH:
102 return text
104 assert wrap # Requires Python 2.3.
105 result = ''
106 newlines = 0
107 for para in text.split("\n"):
108 if len(para) > 0:
109 if para[0] is not ' ' and para[0] is not '-' and para[0] is not '*':
110 for line in wrap(para, BODY_WIDTH):
111 result += line + "\n"
112 result += "\n"
113 newlines = 2
114 else:
115 if not onlywhite(para):
116 result += para + "\n"
117 newlines = 1
118 else:
119 if newlines < 2:
120 result += "\n"
121 newlines += 1
122 return result
124 def hn(tag):
125 if tag[0] == 'h' and len(tag) == 2:
126 try:
127 n = int(tag[1])
128 if n in range(1, 10): return n
129 except ValueError: return 0
131 class _html2text(sgmllib.SGMLParser):
132 def __init__(self, out=sys.stdout.write):
133 sgmllib.SGMLParser.__init__(self)
135 if out is None: self.out = self.outtextf
136 else: self.out = out
137 self.outtext = u''
138 self.quiet = 0
139 self.p_p = 0
140 self.outcount = 0
141 self.start = 1
142 self.space = 0
143 self.a = []
144 self.astack = []
145 self.acount = 0
146 self.list = []
147 self.blockquote = 0
148 self.pre = 0
149 self.startpre = 0
150 self.lastWasNL = 0
152 def outtextf(self, s):
153 if type(s) is type(''): s = codecs.utf_8_decode(s)[0]
154 self.outtext += s
156 def close(self):
157 sgmllib.SGMLParser.close(self)
159 self.pbr()
160 self.o('', 0, 'end')
162 return self.outtext
164 def handle_charref(self, c):
165 self.o(charref(c))
167 def handle_entityref(self, c):
168 self.o(entityref(c))
170 def unknown_starttag(self, tag, attrs):
171 self.handle_tag(tag, attrs, 1)
173 def unknown_endtag(self, tag):
174 self.handle_tag(tag, None, 0)
176 def previousIndex(self, attrs):
177 """ returns the index of certain set of attributes (of a link) in the
178 self.a list
180 If the set of attributes is not found, returns None
182 if not attrs.has_key('href'): return None
184 i = -1
185 for a in self.a:
186 i += 1
187 match = 0
189 if a.has_key('href') and a['href'] == attrs['href']:
190 if a.has_key('title') or attrs.has_key('title'):
191 if (a.has_key('title') and attrs.has_key('title') and
192 a['title'] == attrs['title']):
193 match = True
194 else:
195 match = True
197 if match: return i
199 def handle_tag(self, tag, attrs, start):
200 attrs = fixattrs(attrs)
202 if hn(tag):
203 self.p()
204 if start: self.o(hn(tag)*"#" + ' ')
206 if tag in ['p', 'div']: self.p()
208 if tag == "br" and start: self.o(" \n")
210 if tag == "hr" and start:
211 self.p()
212 self.o("* * *")
213 self.p()
215 if tag in ["head", "style", 'script']:
216 if start: self.quiet += 1
217 else: self.quiet -= 1
219 if tag == "blockquote":
220 if start:
221 self.p(); self.o('> ', 0, 1); self.start = 1
222 self.blockquote += 1
223 else:
224 self.blockquote -= 1
225 self.p()
227 if tag in ['em', 'i', 'u']: self.o("_")
228 if tag in ['strong', 'b']: self.o("**")
229 if tag == "code" and not self.pre: self.o('`') #TODO: `` `this` ``
231 if tag == "a":
232 if start:
233 attrsD = {}
234 for (x, y) in attrs: attrsD[x] = y
235 attrs = attrsD
236 if attrs.has_key('href'):
237 self.astack.append(attrs)
238 self.o("[")
239 else:
240 self.astack.append(None)
241 else:
242 if self.astack:
243 a = self.astack.pop()
244 if a:
245 i = self.previousIndex(a)
246 if i is not None:
247 a = self.a[i]
248 else:
249 self.acount += 1
250 a['count'] = self.acount
251 a['outcount'] = self.outcount
252 self.a.append(a)
253 self.o("][" + `a['count']` + "]")
255 if tag == "img" and start:
256 attrsD = {}
257 for (x, y) in attrs: attrsD[x] = y
258 attrs = attrsD
259 if attrs.has_key('src'):
260 attrs['href'] = attrs['src']
261 alt = attrs.get('alt', '')
262 i = self.previousIndex(attrs)
263 if i is not None:
264 attrs = self.a[i]
265 else:
266 self.acount += 1
267 attrs['count'] = self.acount
268 attrs['outcount'] = self.outcount
269 self.a.append(attrs)
270 self.o("![")
271 self.o(alt)
272 self.o("]["+`attrs['count']`+"]")
274 if tag in ["ol", "ul"]:
275 if start:
276 self.list.append({'name':tag, 'num':0})
277 else:
278 if self.list: self.list.pop()
280 self.p()
282 if tag == 'li':
283 if start:
284 self.pbr()
285 if self.list: li = self.list[-1]
286 else: li = {'name':'ul', 'num':0}
287 self.o(" "*len(self.list)) #TODO: line up <ol><li>s > 9 correctly.
288 if li['name'] == "ul": self.o("* ")
289 elif li['name'] == "ol":
290 li['num'] += 1
291 self.o(`li['num']`+". ")
292 self.start = 1
293 else:
294 self.pbr()
296 if tag in ['tr']: self.pbr()
298 if tag == "pre":
299 if start:
300 self.startpre = 1
301 self.pre = 1
302 else:
303 self.pre = 0
304 self.p()
306 def pbr(self):
307 if self.p_p == 0: self.p_p = 1
309 def p(self): self.p_p = 2
311 def o(self, data, puredata=0, force=0):
312 if not self.quiet:
313 if puredata and not self.pre:
314 data = re.sub('\s+', ' ', data)
315 if data and data[0] == ' ':
316 self.space = 1
317 data = data[1:]
318 if not data and not force: return
320 if self.startpre:
321 #self.out(" :") #TODO: not output when already one there
322 self.startpre = 0
324 bq = (">" * self.blockquote)
325 if not (force and data and data[0] == ">") and self.blockquote: bq += " "
327 if self.pre:
328 bq += " "
329 data = data.replace("\n", "\n"+bq)
331 if self.start:
332 self.space = 0
333 self.p_p = 0
334 self.start = 0
336 if force == 'end':
337 # It's the end.
338 self.p_p = 0
339 self.out("\n")
340 self.space = 0
343 if self.p_p:
344 self.out(('\n'+bq)*self.p_p)
345 self.space = 0
347 if self.space:
348 if not self.lastWasNL: self.out(' ')
349 self.space = 0
351 if self.a and ((self.p_p == 2 and LINKS_EACH_PARAGRAPH) or force == "end"):
352 if force == "end": self.out("\n")
354 newa = []
355 for link in self.a:
356 if self.outcount > link['outcount']:
357 self.out(" ["+`link['count']`+"]: " + link['href']) #TODO: base href
358 if link.has_key('title'): self.out(" ("+link['title']+")")
359 self.out("\n")
360 else:
361 newa.append(link)
363 if self.a != newa: self.out("\n") # Don't need an extra line when nothing was done.
365 self.a = newa
367 self.p_p = 0
368 self.out(data)
369 self.lastWasNL = data and data[-1] == '\n'
370 self.outcount += 1
372 def handle_data(self, data):
373 self.o(data, 1)
375 def unknown_decl(self, data): pass
377 def html2text_file(html, out=sys.stdout.write):
378 h = _html2text(out)
379 h.feed(html)
380 h.feed("")
381 return h.close()
383 def html2text(html):
384 return optwrap(html2text_file(html, None))
386 if __name__ == "__main__":
387 if sys.argv[1:]:
388 arg = sys.argv[1]
389 if arg.startswith('http://'):
390 data = urllib.urlopen(arg).read()
391 else:
392 data = open(arg, 'r').read()
393 else:
394 data = sys.stdin.read()
395 html2text_file(data)