├── wp2md ├── __init__.py ├── __main__.py ├── version.py ├── authoring.py ├── wp2md.py └── html2text.py ├── .gitignore ├── .editorconfig ├── setup.py ├── README.md └── LICENSE /wp2md/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /wp2md/__main__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from .wp2md import main 3 | 4 | sys.exit(main()) 5 | -------------------------------------------------------------------------------- /wp2md/version.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | __version_info__ = (0, 8, 1) 4 | __version__ = '.'.join(map(str, __version_info__)) 5 | 6 | 7 | def get_version(): 8 | return __version__ 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[co] 2 | *.log 3 | 4 | ; Python packaging 5 | bin 6 | build 7 | dist 8 | sdist 9 | MANIFEST 10 | *.egg-info 11 | 12 | ; Wordpress exported data 13 | *.xml 14 | 15 | ; Generated files 16 | out/* 17 | -------------------------------------------------------------------------------- /wp2md/authoring.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | 3 | __author__ = 'Alex Musayev' 4 | __email__ = 'alex.musayev@gmail.com' 5 | __copyright__ = "Copyright 2012, %s " % __author__ 6 | __license__ = 'GNU GPL 3' 7 | __status__ = 'Development' 8 | __url__ = 'http://github.com/dreikanter/wp2md' 9 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | ; top-most EditorConfig file 2 | root = true 3 | 4 | ; Unix-style newlines 5 | [*] 6 | end_of_line = CRLF 7 | 8 | ; 4 space indentation 9 | [*.py] 10 | indent_style = space 11 | indent_size = 4 12 | 13 | ; Tab indentation (no size specified) 14 | [*.js] 15 | indent_style = tab 16 | 17 | ; Indentation override for all JS under lib directory 18 | [lib/**.js] 19 | indent_style = space 20 | indent_size = 2 21 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # coding: utf-8 3 | 4 | from setuptools import setup, find_packages 5 | import sys 6 | import wp2md.authoring 7 | from wp2md.version import get_version 8 | 9 | setup( 10 | name='wp2md', 11 | description='A script to convert Wordpress XML dumps to plain text/markdown files.', 12 | version=get_version(), 13 | license=wp2md.authoring.__license__, 14 | author=wp2md.authoring.__author__, 15 | author_email=wp2md.authoring.__email__, 16 | url=wp2md.authoring.__url__, 17 | long_description=open('README.md',"rb").read().decode('utf8'), 18 | platforms=['any'], 19 | packages=find_packages(), 20 | install_requires=[ 21 | 'markdown', 22 | 'html2text' 23 | ], 24 | entry_points={'console_scripts': ['wp2md = wp2md.wp2md:main']}, 25 | include_package_data=True, 26 | zip_safe=False, 27 | classifiers=[ 28 | 'Development Status :: 5 - Production/Stable', 29 | 'Intended Audience :: Developers', 30 | 'License :: OSI Approved :: GNU General Public License (GPL)', 31 | 'Programming Language :: Python', 32 | 'Programming Language :: Python :: 2.7', 33 | 'Programming Language :: Python :: 3.3', 34 | ], 35 | dependency_links=[ 36 | 'https://github.com/aaronsw/html2text/tarball/master#egg=html2text' 37 | ], 38 | ) 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WordPress to Markdown Exporter 2 | 3 | > **Update:** I don't have much time to maintain this project, but I would really appreciate community help. If you looking for an open source project to contribute, it's a great opportunity. Pull request a very appreciated by me and migrating WordPress users. 4 | 5 | A python script to convert WordPress XML dump to a set of plain text/[markdown](http://daringfireball.net/projects/markdown) files. Intended to be used for migration from WordPress to [public-static](http://github.com/dreikanter/public-static) website generator, but could also be helpful as general purpose WordPress content processor. 6 | 7 | 8 | ## Installation 9 | 10 | The script could be installed by command: 11 | 12 | pip install git+https://github.com/dreikanter/wp2md 13 | 14 | It will install wp2md and the following dependencies: 15 | 16 | * [html2text](https://github.com/aaronsw/html2text/) 17 | * [python-markdown](http://pypi.python.org/pypi/Markdown/) 18 | 19 | 20 | ## Usage 21 | 22 | [Export](http://en.support.wordpress.com/export/) WordPress data to XML file (Tools → Export → All content): 23 | 24 | ![WordPress content export](http://img-fotki.yandex.ru/get/6403/988666.0/0_a05db_af845b23_L.jpg) 25 | 26 | And then run the following command: 27 | 28 | wp2md -d /export/path/ wordpress-dump.xml 29 | 30 | Where `/export/path/` is the directory where post and page files will be generated, and `wordpress-dump.xml` is the XML file exported by WordPress. 31 | 32 | Use `--help` parameter to see the complete list of command line options: 33 | 34 | usage: wp2md [options] source 35 | 36 | Export WordPress XML dump to markdown files 37 | 38 | positional arguments: 39 | source source XML dump exported from WordPress 40 | 41 | optional arguments: 42 | -h, --help show this help message and exit 43 | -v verbose logging 44 | -l FILE log to file 45 | -d PATH destination path for generated files 46 | -u FMT date/time parsing format 47 | -o FMT and parsing format 48 | -f FMT date/time fields format for exported data 49 | -p FMT date prefix format for generated files 50 | -m preprocess content with Markdown (helpful for MD input) 51 | -n LEN post name (slug) length limit for file naming 52 | -r generate reference links instead of inline 53 | -ps PATH post files path (see docs for variable names) 54 | -pg PATH page files path 55 | -dr PATH draft files path 56 | -url keep absolute URLs in hrefs and image srcs 57 | -b URL base URL to subtract from hrefs (default is the root) 58 | 59 | 60 | ## The output 61 | 62 | The script generates a separate file for each post, page and draft, and groups it by configurable directory structure. By default posts are grouped by year-named directories and pages are just stored to the output folder. 63 | 64 | ![Exported files](http://img-fotki.yandex.ru/get/6500/988666.0/0_a05da_66f67f9f_L.jpg) 65 | 66 | But you could specify different directory structure and file naming pattern using `-ps`, `-pg` and `-dr` parameters for posts, pages and drafts respectively. For example `-ps {year}/{month}/{day}/{title}.md` will produce date-based subfolders for blog posts. 67 | 68 | Each exported file has a straightforward structure intended for further processing with [public-static](http://github.com/dreikanter/public-static) website generator. It has an INI-like formatted header followed by markdown-formatted post (or page) contents: 69 | 70 | title: Я.Субботник в Санкт-Петербурге, 3 декабря 71 | link: http://paradigm.ru/yandex-subbotni 72 | creator: admin 73 | description: 74 | post_id: 635 75 | post_date: 2011-11-23 22:10:35 76 | post_date_gmt: 2011-11-23 19:10:35 77 | comment_status: open 78 | post_name: yandex-subbotnik 79 | status: publish 80 | post_type: post 81 | 82 | # Я.Субботник в Санкт-Петербурге, 3 декабря 83 | 84 | Я.Субботник в Санкт-Петербурге пройдет 3 декабря в [офисе Яндекса](http://company.yandex.ru/contacts/spb/). 85 | ... 86 | 87 | If the post contains comments, they will be included below. 88 | 89 | 90 | ## See also 91 | 92 | * How to [export WordPress data](http://codex.wordpress.org/Tools_Export_Screen) 93 | * How to [export Wordpress.com data](http://en.support.wordpress.com/export/) 94 | * [Wordpress to Hugo exporter](https://github.com/SchumacherFM/wordpress-to-hugo-exporter) 95 | 96 | 97 | ## Copyright and licensing 98 | 99 | Copyright © 2013 by [Alex Musayev](http://alex.musayev.com). 100 | License: GNU (see [LICENSE](https://raw.github.com/dreikanter/wp2md/master/LICENSE)). 101 | 102 | Project home: [https://github.com/dreikanter/wp2md](https://github.com/dreikanter/wp2md). 103 | -------------------------------------------------------------------------------- /wp2md/wp2md.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """A script to convert Wordpress XML dumps to plain text/markdown files.""" 3 | 4 | import argparse 5 | import codecs 6 | import datetime 7 | import logging 8 | import markdown 9 | import os.path 10 | import re 11 | import sys 12 | import time 13 | import traceback 14 | from xml.etree.ElementTree import XMLParser 15 | from . import html2text 16 | 17 | PY2 = sys.version_info[0] == 2 18 | 19 | str_t = unicode if PY2 else str 20 | 21 | # XML elements to save (starred ones are additional fields 22 | # generated during export data processing) 23 | WHAT2SAVE = { 24 | 'channel': [ 25 | 'title', 26 | 'description', 27 | 'author_display_name', 28 | 'author_login', 29 | 'author_email', 30 | 'base_site_url', 31 | 'base_blog_url', 32 | 'export_date', # Generated: data export timestamp 33 | 'content', # Generated: items list 34 | # 'link', 35 | # 'language', 36 | ], 37 | 'item': [ 38 | 'title', 39 | 'link', 40 | 'creator', 41 | 'description', 42 | 'post_id', 43 | 'post_date', 44 | 'post_date_gmt', 45 | 'comment_status', 46 | 'post_name', 47 | 'status', 48 | 'post_type', 49 | 'excerpt', 50 | 'content', # Generated: item content 51 | 'comments', # Generated: comments lis 52 | # 'guid', 53 | # 'is_sticky', 54 | # 'menu_order', 55 | # 'ping_status', 56 | # 'post_parent', 57 | # 'post_password', 58 | ], 59 | 'comment': [ 60 | 'comment_id', 61 | 'comment_author', 62 | 'comment_author_email', 63 | 'comment_author_url', 64 | 'comment_author_IP', 65 | 'comment_date', 66 | 'comment_date_gmt', 67 | 'comment_content', 68 | 'comment_approved', 69 | 'comment_type', 70 | # 'comment_parent', 71 | # 'comment_user_id', 72 | ], 73 | } 74 | 75 | # Wordpress RSS items to public-static page header fields mapping 76 | # (undefined names will remain unchanged) 77 | FIELD_MAP = { 78 | 'creator': 'author', 79 | 'post_date': 'created', 80 | 'post_date_gmt': 'created_gmt', 81 | } 82 | 83 | DEFAULT_MAX_NAME_LEN = 50 84 | UNTITLED = 'untitled' 85 | MD_URL_RE = None 86 | 87 | log = logging.getLogger(__name__) 88 | conf = {} 89 | stats = { 90 | 'page': 0, 91 | 'post': 0, 92 | 'comment': 0, 93 | } 94 | 95 | 96 | # Configuration and logging 97 | 98 | def init(): 99 | global conf 100 | args = parse_args() 101 | init_logging(args.l, args.v) 102 | conf = { 103 | 'source_file': args.source, 104 | 'dump_path': args.d, 105 | 'page_path': args.pg, 106 | 'post_path': args.ps, 107 | 'draft_path': args.dr, 108 | 'verbose': args.v, 109 | 'parse_date_fmt': args.u, 110 | 'post_date_fmt': args.o, 111 | 'date_fmt': args.f, 112 | 'page_date_fmt': args.ef, 113 | 'file_date_fmt': args.p, 114 | 'log_file': args.l, 115 | 'md_input': args.m, 116 | 'max_name_len': args.n, 117 | 'ref_links': args.r, 118 | 'fix_urls': args.url, 119 | 'base_url': args.b, 120 | } 121 | 122 | try: 123 | value = int(conf['max_name_len']) 124 | if value < 0 or value > 100: 125 | raise ValueError() 126 | conf['max_name_len'] = value 127 | except: 128 | log.warn('Bad post name length limitation value. Using default.') 129 | conf['max_name_len'] = DEFAULT_MAX_NAME_LEN 130 | 131 | 132 | def init_logging(log_file, verbose): 133 | try: 134 | global log 135 | log.setLevel(logging.DEBUG) 136 | log_level = logging.DEBUG if verbose else logging.INFO 137 | 138 | channel = logging.StreamHandler() 139 | channel.setLevel(log_level) 140 | fmt = '%(message)s' 141 | channel.setFormatter(logging.Formatter(fmt)) 142 | log.addHandler(channel) 143 | 144 | if log_file: 145 | channel = logging.FileHandler(log_file) 146 | channel.setLevel(logging.DEBUG) 147 | fmt = '%(asctime)s %(levelname)s: %(message)s' 148 | channel.setFormatter(logging.Formatter(fmt, '%H:%M:%S')) 149 | log.addHandler(channel) 150 | 151 | except Exception as e: 152 | log.debug(traceback.format_exc()) 153 | raise Exception(getxm('Logging initialization failed', e)) 154 | 155 | 156 | def parse_args(): 157 | desc = __doc__.split('\n\n')[0] 158 | parser = argparse.ArgumentParser(description=desc) 159 | parser.add_argument( 160 | '-v', 161 | action='store_true', 162 | default=False, 163 | help='verbose logging') 164 | parser.add_argument( 165 | '-l', 166 | action='store', 167 | metavar='FILE', 168 | default=None, 169 | help='log to file') 170 | parser.add_argument( 171 | '-d', 172 | action='store', 173 | metavar='PATH', 174 | default='{year}{month}{day}_{source}', 175 | help='destination path for generated files') 176 | parser.add_argument( 177 | '-u', 178 | action='store', 179 | metavar='FMT', 180 | default="%a, %d %b %Y %H:%M:%S +0000", 181 | help=' date/time parsing format') 182 | parser.add_argument( 183 | '-o', 184 | action='store', 185 | metavar='FMT', 186 | default="%Y %H:%M:%S", 187 | help=' and parsing format') 188 | parser.add_argument( 189 | '-f', 190 | action='store', 191 | metavar='FMT', 192 | default="%Y-%m-%d %H:%M:%S", 193 | help='date/time fields parsing format for input data') 194 | parser.add_argument( 195 | '-ef', 196 | action='store', 197 | metavar='FMT', 198 | default="%Y/%m/%d %H:%M:%S", 199 | help='date/time fields format for generated pages') 200 | parser.add_argument( 201 | '-p', 202 | action='store', 203 | metavar='FMT', 204 | default="%Y%m%d", 205 | help='date prefix format for generated files') 206 | parser.add_argument( 207 | '-m', 208 | action='store_true', 209 | default=False, 210 | help='preprocess content with Markdown (helpful for MD input)') 211 | parser.add_argument( 212 | '-n', 213 | action='store', 214 | metavar='LEN', 215 | default=DEFAULT_MAX_NAME_LEN, 216 | help='post name (slug) length limit for file naming') 217 | parser.add_argument( 218 | '-r', 219 | action='store_true', 220 | default=False, 221 | help='generate reference links instead of inline') 222 | parser.add_argument( 223 | '-ps', 224 | action='store', 225 | metavar='PATH', 226 | default=os.path.join("posts", "{year}{month}{day}-{name}.md"), 227 | help='post files path (see docs for variable names)') 228 | parser.add_argument( 229 | '-pg', 230 | action='store', 231 | metavar='PATH', 232 | default=os.path.join("pages", "{name}.md"), 233 | help='page files path') 234 | parser.add_argument( 235 | '-dr', 236 | action='store', 237 | metavar='PATH', 238 | default="drafts/{name}.md", 239 | help='draft files path') 240 | parser.add_argument( 241 | '-url', 242 | action='store_false', 243 | default=True, 244 | help="keep absolute URLs in hrefs and image srcs") 245 | parser.add_argument( 246 | '-b', 247 | action='store', 248 | metavar='URL', 249 | default=None, 250 | help='base URL to subtract from hrefs (default is the root)') 251 | parser.add_argument( 252 | 'source', 253 | action='store', 254 | help='source XML dump exported from Wordpress') 255 | return parser.parse_args(sys.argv[1:]) 256 | 257 | 258 | # Helpers 259 | 260 | def getxm(message, exception): 261 | """Returns annotated exception messge.""" 262 | return ("%s: %s" % (message, str(exception))) if exception else message 263 | 264 | 265 | def tag_name(name): 266 | """Removes expanded namespace from tag name.""" 267 | result = name[name.find('}') + 1:] 268 | if result == 'encoded': 269 | if name.find('/content/') > -1: 270 | result = 'content' 271 | elif name.find('/excerpt/') > -1: 272 | result = 'excerpt' 273 | return result 274 | 275 | 276 | def parse_date(date_str, format, default=None): 277 | """Parses date string according to specified format.""" 278 | try: 279 | result = time.strptime(date_str, format) 280 | except: 281 | msg = "Error parsing date string '%s'. Using default value." % date_str 282 | log.debug(msg) 283 | result = default 284 | 285 | return result 286 | 287 | 288 | def get_path_fmt(item_type, data): 289 | """Returns preconfigured export path format for specified 290 | RSS item type and metadata.""" 291 | 292 | if data.get('status', None).lower() == 'draft': 293 | return conf['draft_path'] 294 | is_post = item_type == 'post' 295 | return conf['post_path'] if is_post else conf['page_path'] 296 | 297 | 298 | def get_path(item_type, file_name=None, data=None): 299 | """Generates full path for the generated file using configuration 300 | and explicitly specified name or RSS item data. At least one argument 301 | should be specified. @file_name has higher priority during output 302 | path generation. 303 | 304 | Arguments: 305 | item_type -- 'post' or 'page' 306 | file_name -- explicitly defined correct file name. 307 | data -- preprocessed RSS item data dictionary.""" 308 | 309 | if not file_name and type(data) is not dict: 310 | raise Exception('File name or RSS item data dict should be defined') 311 | 312 | root = conf['dump_path'] 313 | root = root.format(date=time.strftime(conf['file_date_fmt']), 314 | year=time.strftime("%Y"), 315 | month=time.strftime("%m"), 316 | day=time.strftime("%d"), 317 | source=os.path.basename(conf['source_file'])) 318 | 319 | if file_name: 320 | relpath = file_name 321 | else: 322 | name = data.get('post_name', '').strip() 323 | name = name or data.get('post_id', UNTITLED) 324 | relpath = get_path_fmt(item_type, data) 325 | field = FIELD_MAP.get('post_date', 'post_date') 326 | post_date = data[field] 327 | relpath = relpath.format(year=time.strftime("%Y", post_date), 328 | month=time.strftime("%m", post_date), 329 | day=time.strftime("%d", post_date), 330 | name=name, 331 | title=name) 332 | 333 | return uniquify(os.path.join(os.path.abspath(root), relpath)) 334 | 335 | 336 | def uniquify(file_name): 337 | """Inserts numeric suffix at the end of file name to make 338 | it's name unique in the directory.""" 339 | 340 | suffix = 0 341 | result = file_name 342 | while True: 343 | if os.path.exists(result): 344 | suffix += 1 345 | result = insert_suffix(file_name, suffix) 346 | else: 347 | return result 348 | 349 | 350 | def insert_suffix(file_name, suffix): 351 | """Inserts suffix to the end of file name (before extension). 352 | If suffix is zero (or False in boolean representation), nothing 353 | will be inserted. 354 | 355 | Usage: 356 | >>> insert_suffix('c:/temp/hello.txt', 2) 357 | c:/temp/hello-2.txt 358 | >>> insert_suffix('readme.txt', 0) 359 | readme.txt 360 | 361 | Intended to be used for numeric suffixes for file 362 | name uniquification (what a word!).""" 363 | 364 | if not suffix: 365 | return file_name 366 | base, ext = os.path.splitext(file_name) 367 | return "%s-%s%s" % (base, suffix, ext) 368 | 369 | 370 | # Markdown processing and generation 371 | 372 | def html2md(html): 373 | h2t = html2text.HTML2Text() 374 | h2t.unicode_snob = True 375 | h2t.inline_links = not conf['ref_links'] 376 | h2t.body_width = 0 377 | return h2t.handle(html).strip() 378 | 379 | 380 | def generate_toc(meta, items): 381 | """Generates MD-formatted index page.""" 382 | if not meta.get('description', ''): 383 | content = '\n\n' 384 | else: 385 | content = meta.get('description', '') + '\n\n' 386 | for item in items: 387 | content += str_t("* {post_date}: [{title}]({link})\n").format(**item) 388 | return content 389 | 390 | 391 | def generate_comments(comments): 392 | """Generates MD-formatted comments list from parsed data.""" 393 | 394 | result = str_t('') 395 | for comment in comments: 396 | try: 397 | approved = comment['comment_approved'] == '1' 398 | pingback = comment.get('comment_type', '').lower() == 'pingback' 399 | if approved and not pingback: 400 | cmfmt = str_t("**[{author}](#{id} \"{timestamp}\"):** {content}\n\n") 401 | content = html2md(comment['comment_content']) 402 | result += cmfmt.format(id=comment['comment_id'], 403 | timestamp=comment['comment_date'], 404 | author=comment['comment_author'], 405 | content=content) 406 | except: 407 | # Ignore malformed data 408 | pass 409 | 410 | return result and str_t("## Comments\n\n" + result) 411 | 412 | 413 | def fix_urls(text): 414 | """Removes base_url prefix from MD links and image sources.""" 415 | global MD_URL_RE 416 | if MD_URL_RE is None: 417 | base_url = re.escape(conf['base_url']) 418 | MD_URL_RE = re.compile(r'\]\(%s(.*)\)' % base_url) 419 | return MD_URL_RE.sub(r'](\1)', text) 420 | 421 | 422 | # Statistics 423 | 424 | def stopwatch_set(): 425 | """Starts stopwatch timer.""" 426 | globals()['_stopwatch_start_time'] = datetime.datetime.now() 427 | 428 | 429 | def stopwatch_get(): 430 | """Returns string representation for elapsed time since last 431 | stopwatch_set() call.""" 432 | delta = datetime.datetime.now() - globals().get('_stopwatch_start_time', 0) 433 | delta = str(delta).strip('0:') 434 | return ('0' + delta) if delta[0] == '.' else delta 435 | 436 | 437 | def statplusplus(field, value=1): 438 | global stats 439 | if field in stats: 440 | stats[field] += value 441 | else: 442 | raise ValueError("Illegal name for stats field: " + str(field)) 443 | 444 | 445 | # Parser data handlers 446 | 447 | def dump_channel(meta, items): 448 | """Dumps RSS channel metadata and items index.""" 449 | file_name = get_path('page', 'index.md') 450 | log.info("Dumping index to '%s'" % file_name) 451 | fields = WHAT2SAVE['channel'] 452 | meta = {field: meta.get(field, None) for field in fields} 453 | 454 | # Append export_date 455 | pub_date = meta.get('pubDate', None) 456 | format = conf['parse_date_fmt'] 457 | meta['export_date'] = parse_date(pub_date, format, time.gmtime()) 458 | 459 | # Append table of contents 460 | meta['content'] = generate_toc(meta, items) 461 | 462 | dump(file_name, meta, fields) 463 | 464 | 465 | def dump_item(data): 466 | """Dumps RSS channel item.""" 467 | if not 'post_type' in data: 468 | log.error('Malformed RSS item: item type is not specified.') 469 | return 470 | 471 | item_type = data['post_type'] 472 | if item_type not in ['post', 'page', 'draft']: 473 | return 474 | 475 | fields = WHAT2SAVE['item'] 476 | pdata = {} 477 | for field in fields: 478 | pdata[FIELD_MAP.get(field, field)] = data.get(field, '') 479 | 480 | # Post date 481 | format = conf['date_fmt'] 482 | field = FIELD_MAP.get('post_date', 'post_date') 483 | value = pdata.get(field, None) 484 | pdata[field] = value and parse_date(value, format, None) 485 | 486 | # Post date GMT 487 | field = FIELD_MAP.get('post_date_gmt', 'post_date_gmt') 488 | value = pdata.get(field, None) 489 | pdata[field] = value and parse_date(value, format, None) 490 | 491 | dump_path = get_path(item_type, data=pdata) 492 | log.info("Dumping %s to '%s'" % (item_type, dump_path)) 493 | 494 | fields = [FIELD_MAP.get(field, field) for field in fields] 495 | dump(dump_path, pdata, fields) 496 | 497 | statplusplus(item_type) 498 | if 'comments' in data: 499 | statplusplus('comment', len(data['comments'])) 500 | 501 | 502 | def dump(file_name, data, order): 503 | """Dumps a dictionary to YAML-like text file.""" 504 | try: 505 | dir_path = os.path.dirname(os.path.abspath(file_name)) 506 | if dir_path and not os.path.exists(dir_path): 507 | os.makedirs(dir_path) 508 | 509 | with codecs.open(file_name, 'w', 'utf-8') as f: 510 | extras = {} 511 | for field in filter(lambda x: x in data, [item for item in order]): 512 | if field in ['content', 'comments', 'excerpt']: 513 | # Fields for non-standard processing 514 | extras[field] = data[field] 515 | else: 516 | if type(data[field]) == time.struct_time: 517 | value = time.strftime(conf['page_date_fmt'], data[field]) 518 | else: 519 | value = data[field] or '' 520 | f.write(str_t("%s: %s\n") % (str_t(field), str_t(value))) 521 | 522 | if extras: 523 | excerpt = extras.get('excerpt', '') 524 | excerpt = excerpt and '' % excerpt 525 | 526 | content = extras.get('content', '') 527 | if conf['md_input']: 528 | # Using new MD instance works 3x faster than 529 | # reusing existing one for some reason 530 | md = markdown.Markdown(extensions=[]) 531 | content = md.convert(content) 532 | 533 | if conf['fix_urls']: 534 | content = fix_urls(html2md(content)) 535 | 536 | if 'title' in data: 537 | content = str_t("# %s\n\n%s") % (data['title'], content) 538 | 539 | comments = generate_comments(extras.get('comments', [])) 540 | extras = filter(None, [excerpt, content, comments]) 541 | f.write('\n' + '\n\n'.join(extras)) 542 | 543 | except Exception as e: 544 | log.error("Error saving data to '%s'" % (file_name)) 545 | log.debug(e) 546 | 547 | 548 | def store_base_url(channel): 549 | """Stores base URL in configuration if it's not defined explicitly.""" 550 | if conf['fix_urls'] and not conf['base_url']: 551 | conf['base_url'] = channel.get('base_site_url', '') 552 | 553 | 554 | # The Parser 555 | 556 | class CustomParser: 557 | def __init__(self): 558 | self.section_stack = [] 559 | self.channel = {} 560 | self.items = [] 561 | self.item = None 562 | self.cmnt = None 563 | self.subj = None 564 | 565 | def start(self, tag, attrib): 566 | tag = tag_name(tag) 567 | if tag == 'channel': 568 | self.start_section('channel') 569 | 570 | elif tag == 'item': 571 | self.item = {'comments': []} 572 | self.start_section('item') 573 | 574 | elif self.item and tag == 'comment': 575 | self.cmnt = {} 576 | self.start_section('comment') 577 | 578 | elif self.cur_section(): 579 | self.subj = tag 580 | 581 | else: 582 | self.subj = None 583 | 584 | def end(self, tag): 585 | tag = tag_name(tag) 586 | if tag == 'comment' and self.cur_section() == 'comment': 587 | self.end_section() 588 | self.item['comments'].append(self.cmnt) 589 | self.cmnt = None 590 | 591 | elif tag == 'item' and self.cur_section() == 'item': 592 | self.end_section() 593 | dump_item(self.item) 594 | self.store_item_info() 595 | self.item = None 596 | 597 | elif tag == 'channel': 598 | self.end_section() 599 | dump_channel(self.channel, self.items) 600 | 601 | elif self.cur_section(): 602 | self.subj = None 603 | 604 | def data(self, data): 605 | if self.subj: 606 | if self.cur_section() == 'comment': 607 | self.cmnt[self.subj] = data 608 | 609 | elif self.cur_section() == 'item': 610 | self.item[self.subj] = data 611 | 612 | elif self.cur_section() == 'channel': 613 | self.channel[self.subj] = data 614 | if self.subj == 'base_site_url': 615 | store_base_url(self.channel) 616 | self.subj = None 617 | 618 | def start_section(self, what): 619 | self.section_stack.append(what) 620 | 621 | def end_section(self): 622 | if len(self.section_stack): 623 | self.section_stack.pop() 624 | 625 | def cur_section(self): 626 | try: 627 | return self.section_stack[-1] 628 | except: 629 | return None 630 | 631 | def store_item_info(self): 632 | post_type = self.item.get('post_type', '').lower() 633 | if not post_type in ['post', 'page']: 634 | return 635 | 636 | fields = [ 637 | 'title', 638 | 'link', 639 | 'post_id', 640 | 'post_date', 641 | 'post_type', 642 | ] 643 | 644 | self.items.append({}) 645 | for field in fields: 646 | self.items[-1][field] = self.item.get(field, None) 647 | 648 | 649 | def main(): 650 | init() 651 | log.info("Parsing '%s'..." % os.path.basename(conf['source_file'])) 652 | 653 | stopwatch_set() 654 | target = CustomParser() 655 | parser = XMLParser(target=target) 656 | if PY2: 657 | text = open(conf['source_file']).read() 658 | else: 659 | text = codecs.open(conf['source_file'], encoding='utf-8').read() 660 | parser.feed(text) 661 | 662 | log.info('') 663 | totals = 'Total: posts: {post}; pages: {page}; comments: {comment}' 664 | log.info(totals.format(**stats)) 665 | log.info('Elapsed time: %s s' % stopwatch_get()) 666 | 667 | 668 | if __name__ == '__main__': 669 | main() 670 | -------------------------------------------------------------------------------- /wp2md/html2text.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """html2text: Turn HTML into equivalent Markdown-structured text.""" 3 | __version__ = "3.200.3" 4 | __author__ = "Aaron Swartz (me@aaronsw.com)" 5 | __copyright__ = "(C) 2004-2008 Aaron Swartz. GNU GPL 3." 6 | __contributors__ = ["Martin 'Joey' Schulze", "Ricardo Reyes", "Kevin Jay North"] 7 | 8 | # TODO: 9 | # Support decoded entities with unifiable. 10 | 11 | try: 12 | True 13 | except NameError: 14 | setattr(__builtins__, 'True', 1) 15 | setattr(__builtins__, 'False', 0) 16 | 17 | def has_key(x, y): 18 | if hasattr(x, 'has_key'): return x.has_key(y) 19 | else: return y in x 20 | 21 | try: 22 | import htmlentitydefs 23 | import urlparse 24 | import HTMLParser 25 | except ImportError: #Python3 26 | import html.entities as htmlentitydefs 27 | import urllib.parse as urlparse 28 | import html.parser as HTMLParser 29 | try: #Python3 30 | import urllib.request as urllib 31 | except: 32 | import urllib 33 | import optparse, re, sys, codecs, types 34 | 35 | try: from textwrap import wrap 36 | except: pass 37 | 38 | import sys 39 | 40 | PY2 = sys.version_info[0] == 2 41 | 42 | strtype = unicode if PY2 else str 43 | 44 | # Use Unicode characters instead of their ascii psuedo-replacements 45 | UNICODE_SNOB = 0 46 | 47 | # Escape all special characters. Output is less readable, but avoids corner case formatting issues. 48 | ESCAPE_SNOB = 0 49 | 50 | # Put the links after each paragraph instead of at the end. 51 | LINKS_EACH_PARAGRAPH = 0 52 | 53 | # Wrap long lines at position. 0 for no wrapping. (Requires Python 2.3.) 54 | BODY_WIDTH = 78 55 | 56 | # Don't show internal links (href="#local-anchor") -- corresponding link targets 57 | # won't be visible in the plain text file anyway. 58 | SKIP_INTERNAL_LINKS = True 59 | 60 | # Use inline, rather than reference, formatting for images and links 61 | INLINE_LINKS = True 62 | 63 | # Number of pixels Google indents nested lists 64 | GOOGLE_LIST_INDENT = 36 65 | 66 | IGNORE_ANCHORS = False 67 | IGNORE_IMAGES = False 68 | IGNORE_EMPHASIS = False 69 | 70 | ### Entity Nonsense ### 71 | 72 | def name2cp(k): 73 | if k == 'apos': return ord("'") 74 | if hasattr(htmlentitydefs, "name2codepoint"): # requires Python 2.3 75 | return htmlentitydefs.name2codepoint[k] 76 | else: 77 | k = htmlentitydefs.entitydefs[k] 78 | if k.startswith("&#") and k.endswith(";"): return int(k[2:-1]) # not in latin-1 79 | return ord(codecs.latin_1_decode(k)[0]) 80 | 81 | unifiable = {'rsquo':"'", 'lsquo':"'", 'rdquo':'"', 'ldquo':'"', 82 | 'copy':'(C)', 'mdash':'--', 'nbsp':' ', 'rarr':'->', 'larr':'<-', 'middot':'*', 83 | 'ndash':'-', 'oelig':'oe', 'aelig':'ae', 84 | 'agrave':'a', 'aacute':'a', 'acirc':'a', 'atilde':'a', 'auml':'a', 'aring':'a', 85 | 'egrave':'e', 'eacute':'e', 'ecirc':'e', 'euml':'e', 86 | 'igrave':'i', 'iacute':'i', 'icirc':'i', 'iuml':'i', 87 | 'ograve':'o', 'oacute':'o', 'ocirc':'o', 'otilde':'o', 'ouml':'o', 88 | 'ugrave':'u', 'uacute':'u', 'ucirc':'u', 'uuml':'u', 89 | 'lrm':'', 'rlm':''} 90 | 91 | unifiable_n = {} 92 | 93 | for k in unifiable.keys(): 94 | unifiable_n[name2cp(k)] = unifiable[k] 95 | 96 | ### End Entity Nonsense ### 97 | 98 | def onlywhite(line): 99 | """Return true if the line does only consist of whitespace characters.""" 100 | for c in line: 101 | if c is not ' ' and c is not ' ': 102 | return c is ' ' 103 | return line 104 | 105 | def hn(tag): 106 | if tag[0] == 'h' and len(tag) == 2: 107 | try: 108 | n = int(tag[1]) 109 | if n in range(1, 10): return n 110 | except ValueError: return 0 111 | 112 | def dumb_property_dict(style): 113 | """returns a hash of css attributes""" 114 | return dict([(x.strip(), y.strip()) for x, y in [z.split(':', 1) for z in style.split(';') if ':' in z]]); 115 | 116 | def dumb_css_parser(data): 117 | """returns a hash of css selectors, each of which contains a hash of css attributes""" 118 | # remove @import sentences 119 | data += ';' 120 | importIndex = data.find('@import') 121 | while importIndex != -1: 122 | data = data[0:importIndex] + data[data.find(';', importIndex) + 1:] 123 | importIndex = data.find('@import') 124 | 125 | # parse the css. reverted from dictionary compehension in order to support older pythons 126 | elements = [x.split('{') for x in data.split('}') if '{' in x.strip()] 127 | try: 128 | elements = dict([(a.strip(), dumb_property_dict(b)) for a, b in elements]) 129 | except ValueError: 130 | elements = {} # not that important 131 | 132 | return elements 133 | 134 | def element_style(attrs, style_def, parent_style): 135 | """returns a hash of the 'final' style attributes of the element""" 136 | style = parent_style.copy() 137 | if 'class' in attrs: 138 | for css_class in attrs['class'].split(): 139 | css_style = style_def['.' + css_class] 140 | style.update(css_style) 141 | if 'style' in attrs: 142 | immediate_style = dumb_property_dict(attrs['style']) 143 | style.update(immediate_style) 144 | return style 145 | 146 | def google_list_style(style): 147 | """finds out whether this is an ordered or unordered list""" 148 | if 'list-style-type' in style: 149 | list_style = style['list-style-type'] 150 | if list_style in ['disc', 'circle', 'square', 'none']: 151 | return 'ul' 152 | return 'ol' 153 | 154 | def google_has_height(style): 155 | """check if the style of the element has the 'height' attribute explicitly defined""" 156 | if 'height' in style: 157 | return True 158 | return False 159 | 160 | def google_text_emphasis(style): 161 | """return a list of all emphasis modifiers of the element""" 162 | emphasis = [] 163 | if 'text-decoration' in style: 164 | emphasis.append(style['text-decoration']) 165 | if 'font-style' in style: 166 | emphasis.append(style['font-style']) 167 | if 'font-weight' in style: 168 | emphasis.append(style['font-weight']) 169 | return emphasis 170 | 171 | def google_fixed_width_font(style): 172 | """check if the css of the current element defines a fixed width font""" 173 | font_family = '' 174 | if 'font-family' in style: 175 | font_family = style['font-family'] 176 | if 'Courier New' == font_family or 'Consolas' == font_family: 177 | return True 178 | return False 179 | 180 | def list_numbering_start(attrs): 181 | """extract numbering from list element attributes""" 182 | if 'start' in attrs: 183 | return int(attrs['start']) - 1 184 | else: 185 | return 0 186 | 187 | class HTML2Text(HTMLParser.HTMLParser): 188 | def __init__(self, out=None, baseurl=''): 189 | HTMLParser.HTMLParser.__init__(self) 190 | 191 | # Config options 192 | self.unicode_snob = UNICODE_SNOB 193 | self.escape_snob = ESCAPE_SNOB 194 | self.links_each_paragraph = LINKS_EACH_PARAGRAPH 195 | self.body_width = BODY_WIDTH 196 | self.skip_internal_links = SKIP_INTERNAL_LINKS 197 | self.inline_links = INLINE_LINKS 198 | self.google_list_indent = GOOGLE_LIST_INDENT 199 | self.ignore_links = IGNORE_ANCHORS 200 | self.ignore_images = IGNORE_IMAGES 201 | self.ignore_emphasis = IGNORE_EMPHASIS 202 | self.google_doc = False 203 | self.ul_item_mark = '*' 204 | self.emphasis_mark = '_' 205 | self.strong_mark = '**' 206 | 207 | if out is None: 208 | self.out = self.outtextf 209 | else: 210 | self.out = out 211 | 212 | self.outtextlist = [] # empty list to store output characters before they are "joined" 213 | 214 | try: 215 | self.outtext = unicode() 216 | except NameError: # Python3 217 | self.outtext = str() 218 | 219 | self.quiet = 0 220 | self.p_p = 0 # number of newline character to print before next output 221 | self.outcount = 0 222 | self.start = 1 223 | self.space = 0 224 | self.a = [] 225 | self.astack = [] 226 | self.maybe_automatic_link = None 227 | self.absolute_url_matcher = re.compile(r'^[a-zA-Z+]+://') 228 | self.acount = 0 229 | self.list = [] 230 | self.blockquote = 0 231 | self.pre = 0 232 | self.startpre = 0 233 | self.code = False 234 | self.br_toggle = '' 235 | self.lastWasNL = 0 236 | self.lastWasList = False 237 | self.style = 0 238 | self.style_def = {} 239 | self.tag_stack = [] 240 | self.emphasis = 0 241 | self.drop_white_space = 0 242 | self.inheader = False 243 | self.abbr_title = None # current abbreviation definition 244 | self.abbr_data = None # last inner HTML (for abbr being defined) 245 | self.abbr_list = {} # stack of abbreviations to write later 246 | self.baseurl = baseurl 247 | 248 | try: del unifiable_n[name2cp('nbsp')] 249 | except KeyError: pass 250 | unifiable['nbsp'] = ' _place_holder;' 251 | 252 | 253 | def feed(self, data): 254 | data = data.replace("", "") 255 | HTMLParser.HTMLParser.feed(self, data) 256 | 257 | def handle(self, data): 258 | self.feed(data) 259 | self.feed("") 260 | return self.optwrap(self.close()) 261 | 262 | def outtextf(self, s): 263 | self.outtextlist.append(s) 264 | if s: self.lastWasNL = s[-1] == '\n' 265 | 266 | def close(self): 267 | HTMLParser.HTMLParser.close(self) 268 | 269 | self.pbr() 270 | self.o('', 0, 'end') 271 | 272 | self.outtext = self.outtext.join(self.outtextlist) 273 | if self.unicode_snob: 274 | try: 275 | nbsp = unichr(name2cp('nbsp')) 276 | except: 277 | nbsp = chr(name2cp('nbsp')) 278 | else: 279 | nbsp = strtype(' ') 280 | self.outtext = self.outtext.replace(strtype(' _place_holder;'), nbsp) 281 | 282 | return self.outtext 283 | 284 | def handle_charref(self, c): 285 | self.o(self.charref(c), 1) 286 | 287 | def handle_entityref(self, c): 288 | self.o(self.entityref(c), 1) 289 | 290 | def handle_starttag(self, tag, attrs): 291 | self.handle_tag(tag, attrs, 1) 292 | 293 | def handle_endtag(self, tag): 294 | self.handle_tag(tag, None, 0) 295 | 296 | def previousIndex(self, attrs): 297 | """ returns the index of certain set of attributes (of a link) in the 298 | self.a list 299 | 300 | If the set of attributes is not found, returns None 301 | """ 302 | if not has_key(attrs, 'href'): return None 303 | 304 | i = -1 305 | for a in self.a: 306 | i += 1 307 | match = 0 308 | 309 | if has_key(a, 'href') and a['href'] == attrs['href']: 310 | if has_key(a, 'title') or has_key(attrs, 'title'): 311 | if (has_key(a, 'title') and has_key(attrs, 'title') and 312 | a['title'] == attrs['title']): 313 | match = True 314 | else: 315 | match = True 316 | 317 | if match: return i 318 | 319 | def drop_last(self, nLetters): 320 | if not self.quiet: 321 | self.outtext = self.outtext[:-nLetters] 322 | 323 | def handle_emphasis(self, start, tag_style, parent_style): 324 | """handles various text emphases""" 325 | tag_emphasis = google_text_emphasis(tag_style) 326 | parent_emphasis = google_text_emphasis(parent_style) 327 | 328 | # handle Google's text emphasis 329 | strikethrough = 'line-through' in tag_emphasis and self.hide_strikethrough 330 | bold = 'bold' in tag_emphasis and not 'bold' in parent_emphasis 331 | italic = 'italic' in tag_emphasis and not 'italic' in parent_emphasis 332 | fixed = google_fixed_width_font(tag_style) and not \ 333 | google_fixed_width_font(parent_style) and not self.pre 334 | 335 | if start: 336 | # crossed-out text must be handled before other attributes 337 | # in order not to output qualifiers unnecessarily 338 | if bold or italic or fixed: 339 | self.emphasis += 1 340 | if strikethrough: 341 | self.quiet += 1 342 | if italic: 343 | self.o(self.emphasis_mark) 344 | self.drop_white_space += 1 345 | if bold: 346 | self.o(self.strong_mark) 347 | self.drop_white_space += 1 348 | if fixed: 349 | self.o('`') 350 | self.drop_white_space += 1 351 | self.code = True 352 | else: 353 | if bold or italic or fixed: 354 | # there must not be whitespace before closing emphasis mark 355 | self.emphasis -= 1 356 | self.space = 0 357 | self.outtext = self.outtext.rstrip() 358 | if fixed: 359 | if self.drop_white_space: 360 | # empty emphasis, drop it 361 | self.drop_last(1) 362 | self.drop_white_space -= 1 363 | else: 364 | self.o('`') 365 | self.code = False 366 | if bold: 367 | if self.drop_white_space: 368 | # empty emphasis, drop it 369 | self.drop_last(2) 370 | self.drop_white_space -= 1 371 | else: 372 | self.o(self.strong_mark) 373 | if italic: 374 | if self.drop_white_space: 375 | # empty emphasis, drop it 376 | self.drop_last(1) 377 | self.drop_white_space -= 1 378 | else: 379 | self.o(self.emphasis_mark) 380 | # space is only allowed after *all* emphasis marks 381 | if (bold or italic) and not self.emphasis: 382 | self.o(" ") 383 | if strikethrough: 384 | self.quiet -= 1 385 | 386 | def handle_tag(self, tag, attrs, start): 387 | #attrs = fixattrs(attrs) 388 | if attrs is None: 389 | attrs = {} 390 | else: 391 | attrs = dict(attrs) 392 | 393 | if self.google_doc: 394 | # the attrs parameter is empty for a closing tag. in addition, we 395 | # need the attributes of the parent nodes in order to get a 396 | # complete style description for the current element. we assume 397 | # that google docs export well formed html. 398 | parent_style = {} 399 | if start: 400 | if self.tag_stack: 401 | parent_style = self.tag_stack[-1][2] 402 | tag_style = element_style(attrs, self.style_def, parent_style) 403 | self.tag_stack.append((tag, attrs, tag_style)) 404 | else: 405 | dummy, attrs, tag_style = self.tag_stack.pop() 406 | if self.tag_stack: 407 | parent_style = self.tag_stack[-1][2] 408 | 409 | if hn(tag): 410 | self.p() 411 | if start: 412 | self.inheader = True 413 | self.o(hn(tag)*"#" + ' ') 414 | else: 415 | self.inheader = False 416 | return # prevent redundant emphasis marks on headers 417 | 418 | if tag in ['p', 'div']: 419 | if self.google_doc: 420 | if start and google_has_height(tag_style): 421 | self.p() 422 | else: 423 | self.soft_br() 424 | else: 425 | self.p() 426 | 427 | if tag == "br" and start: self.o(" \n") 428 | 429 | if tag == "hr" and start: 430 | self.p() 431 | self.o("* * *") 432 | self.p() 433 | 434 | if tag in ["head", "style", 'script']: 435 | if start: self.quiet += 1 436 | else: self.quiet -= 1 437 | 438 | if tag == "style": 439 | if start: self.style += 1 440 | else: self.style -= 1 441 | 442 | if tag in ["body"]: 443 | self.quiet = 0 # sites like 9rules.com never close 444 | 445 | if tag == "blockquote": 446 | if start: 447 | self.p(); self.o('> ', 0, 1); self.start = 1 448 | self.blockquote += 1 449 | else: 450 | self.blockquote -= 1 451 | self.p() 452 | 453 | if tag in ['em', 'i', 'u'] and not self.ignore_emphasis: self.o(self.emphasis_mark) 454 | if tag in ['strong', 'b'] and not self.ignore_emphasis: self.o(self.strong_mark) 455 | if tag in ['del', 'strike', 's']: 456 | if start: 457 | self.o("<"+tag+">") 458 | else: 459 | self.o("") 460 | 461 | if self.google_doc: 462 | if not self.inheader: 463 | # handle some font attributes, but leave headers clean 464 | self.handle_emphasis(start, tag_style, parent_style) 465 | 466 | if tag in ["code", "tt"] and not self.pre: self.o('`') #TODO: `` `this` `` 467 | if tag == "abbr": 468 | if start: 469 | self.abbr_title = None 470 | self.abbr_data = '' 471 | if has_key(attrs, 'title'): 472 | self.abbr_title = attrs['title'] 473 | else: 474 | if self.abbr_title != None: 475 | self.abbr_list[self.abbr_data] = self.abbr_title 476 | self.abbr_title = None 477 | self.abbr_data = '' 478 | 479 | if tag == "a" and not self.ignore_links: 480 | if start: 481 | if has_key(attrs, 'href') and not (self.skip_internal_links and attrs['href'].startswith('#')): 482 | self.astack.append(attrs) 483 | self.maybe_automatic_link = attrs['href'] 484 | else: 485 | self.astack.append(None) 486 | else: 487 | if self.astack: 488 | a = self.astack.pop() 489 | if self.maybe_automatic_link: 490 | self.maybe_automatic_link = None 491 | elif a: 492 | if self.inline_links: 493 | self.o("](" + escape_md(a['href']) + ")") 494 | else: 495 | i = self.previousIndex(a) 496 | if i is not None: 497 | a = self.a[i] 498 | else: 499 | self.acount += 1 500 | a['count'] = self.acount 501 | a['outcount'] = self.outcount 502 | self.a.append(a) 503 | self.o("][" + str(a['count']) + "]") 504 | 505 | if tag == "img" and start and not self.ignore_images: 506 | if has_key(attrs, 'src'): 507 | attrs['href'] = attrs['src'] 508 | alt = attrs.get('alt', '') 509 | self.o("![" + escape_md(alt) + "]") 510 | 511 | if self.inline_links: 512 | self.o("(" + escape_md(attrs['href']) + ")") 513 | else: 514 | i = self.previousIndex(attrs) 515 | if i is not None: 516 | attrs = self.a[i] 517 | else: 518 | self.acount += 1 519 | attrs['count'] = self.acount 520 | attrs['outcount'] = self.outcount 521 | self.a.append(attrs) 522 | self.o("[" + str(attrs['count']) + "]") 523 | 524 | if tag == 'dl' and start: self.p() 525 | if tag == 'dt' and not start: self.pbr() 526 | if tag == 'dd' and start: self.o(' ') 527 | if tag == 'dd' and not start: self.pbr() 528 | 529 | if tag in ["ol", "ul"]: 530 | # Google Docs create sub lists as top level lists 531 | if (not self.list) and (not self.lastWasList): 532 | self.p() 533 | if start: 534 | if self.google_doc: 535 | list_style = google_list_style(tag_style) 536 | else: 537 | list_style = tag 538 | numbering_start = list_numbering_start(attrs) 539 | self.list.append({'name':list_style, 'num':numbering_start}) 540 | else: 541 | if self.list: self.list.pop() 542 | self.lastWasList = True 543 | else: 544 | self.lastWasList = False 545 | 546 | if tag == 'li': 547 | self.pbr() 548 | if start: 549 | if self.list: li = self.list[-1] 550 | else: li = {'name':'ul', 'num':0} 551 | if self.google_doc: 552 | nest_count = self.google_nest_count(tag_style) 553 | else: 554 | nest_count = len(self.list) 555 | self.o(" " * nest_count) #TODO: line up
  1. s > 9 correctly. 556 | if li['name'] == "ul": self.o(self.ul_item_mark + " ") 557 | elif li['name'] == "ol": 558 | li['num'] += 1 559 | self.o(str(li['num'])+". ") 560 | self.start = 1 561 | 562 | if tag in ["table", "tr"] and start: self.p() 563 | if tag == 'td': self.pbr() 564 | 565 | if tag == "pre": 566 | if start: 567 | self.startpre = 1 568 | self.pre = 1 569 | else: 570 | self.pre = 0 571 | self.p() 572 | 573 | def pbr(self): 574 | if self.p_p == 0: 575 | self.p_p = 1 576 | 577 | def p(self): 578 | self.p_p = 2 579 | 580 | def soft_br(self): 581 | self.pbr() 582 | self.br_toggle = ' ' 583 | 584 | def o(self, data, puredata=0, force=0): 585 | if self.abbr_data is not None: 586 | self.abbr_data += data 587 | 588 | if not self.quiet: 589 | if self.google_doc: 590 | # prevent white space immediately after 'begin emphasis' marks ('**' and '_') 591 | lstripped_data = data.lstrip() 592 | if self.drop_white_space and not (self.pre or self.code): 593 | data = lstripped_data 594 | if lstripped_data != '': 595 | self.drop_white_space = 0 596 | 597 | if puredata and not self.pre: 598 | data = re.sub('\s+', ' ', data) 599 | if data and data[0] == ' ': 600 | self.space = 1 601 | data = data[1:] 602 | if not data and not force: return 603 | 604 | if self.startpre: 605 | #self.out(" :") #TODO: not output when already one there 606 | if not data.startswith("\n"): #
    stuff...
    607 |                     data = "\n" + data
    608 | 
    609 |             bq = (">" * self.blockquote)
    610 |             if not (force and data and data[0] == ">") and self.blockquote: bq += " "
    611 | 
    612 |             if self.pre:
    613 |                 if not self.list:
    614 |                     bq += "    "
    615 |                 #else: list content is already partially indented
    616 |                 for i in xrange(len(self.list)):
    617 |                     bq += "    "
    618 |                 data = data.replace("\n", "\n"+bq)
    619 | 
    620 |             if self.startpre:
    621 |                 self.startpre = 0
    622 |                 if self.list:
    623 |                     data = data.lstrip("\n") # use existing initial indentation
    624 | 
    625 |             if self.start:
    626 |                 self.space = 0
    627 |                 self.p_p = 0
    628 |                 self.start = 0
    629 | 
    630 |             if force == 'end':
    631 |                 # It's the end.
    632 |                 self.p_p = 0
    633 |                 self.out("\n")
    634 |                 self.space = 0
    635 | 
    636 |             if self.p_p:
    637 |                 self.out((self.br_toggle+'\n'+bq)*self.p_p)
    638 |                 self.space = 0
    639 |                 self.br_toggle = ''
    640 | 
    641 |             if self.space:
    642 |                 if not self.lastWasNL: self.out(' ')
    643 |                 self.space = 0
    644 | 
    645 |             if self.a and ((self.p_p == 2 and self.links_each_paragraph) or force == "end"):
    646 |                 if force == "end": self.out("\n")
    647 | 
    648 |                 newa = []
    649 |                 for link in self.a:
    650 |                     if self.outcount > link['outcount']:
    651 |                         self.out("   ["+ str(link['count']) +"]: " + urlparse.urljoin(self.baseurl, link['href']))
    652 |                         if has_key(link, 'title'): self.out(" ("+link['title']+")")
    653 |                         self.out("\n")
    654 |                     else:
    655 |                         newa.append(link)
    656 | 
    657 |                 if self.a != newa: self.out("\n") # Don't need an extra line when nothing was done.
    658 | 
    659 |                 self.a = newa
    660 | 
    661 |             if self.abbr_list and force == "end":
    662 |                 for abbr, definition in self.abbr_list.items():
    663 |                     self.out("  *[" + abbr + "]: " + definition + "\n")
    664 | 
    665 |             self.p_p = 0
    666 |             self.out(data)
    667 |             self.outcount += 1
    668 | 
    669 |     def handle_data(self, data):
    670 |         if r'\/script>' in data: self.quiet -= 1
    671 | 
    672 |         if self.style:
    673 |             self.style_def.update(dumb_css_parser(data))
    674 | 
    675 |         if not self.maybe_automatic_link is None:
    676 |             href = self.maybe_automatic_link
    677 |             if href == data and self.absolute_url_matcher.match(href):
    678 |                 self.o("<" + data + ">")
    679 |                 return
    680 |             else:
    681 |                 self.o("[")
    682 |                 self.maybe_automatic_link = None
    683 | 
    684 |         if not self.code and not self.pre:
    685 |             data = escape_md_section(data, snob=self.escape_snob)
    686 |         self.o(data, 1)
    687 | 
    688 |     def unknown_decl(self, data): pass
    689 | 
    690 |     def charref(self, name):
    691 |         if name[0] in ['x','X']:
    692 |             c = int(name[1:], 16)
    693 |         else:
    694 |             c = int(name)
    695 | 
    696 |         if not self.unicode_snob and c in unifiable_n.keys():
    697 |             return unifiable_n[c]
    698 |         else:
    699 |             try:
    700 |                 return unichr(c)
    701 |             except NameError: #Python3
    702 |                 return chr(c)
    703 | 
    704 |     def entityref(self, c):
    705 |         if not self.unicode_snob and c in unifiable.keys():
    706 |             return unifiable[c]
    707 |         else:
    708 |             try: name2cp(c)
    709 |             except KeyError: return "&" + c + ';'
    710 |             else:
    711 |                 try:
    712 |                     return unichr(name2cp(c))
    713 |                 except NameError: #Python3
    714 |                     return chr(name2cp(c))
    715 | 
    716 |     def replaceEntities(self, s):
    717 |         s = s.group(1)
    718 |         if s[0] == "#":
    719 |             return self.charref(s[1:])
    720 |         else: return self.entityref(s)
    721 | 
    722 |     r_unescape = re.compile(r"&(#?[xX]?(?:[0-9a-fA-F]+|\w{1,8}));")
    723 |     def unescape(self, s):
    724 |         return self.r_unescape.sub(self.replaceEntities, s)
    725 | 
    726 |     def google_nest_count(self, style):
    727 |         """calculate the nesting count of google doc lists"""
    728 |         nest_count = 0
    729 |         if 'margin-left' in style:
    730 |             nest_count = int(style['margin-left'][:-2]) / self.google_list_indent
    731 |         return nest_count
    732 | 
    733 | 
    734 |     def optwrap(self, text):
    735 |         """Wrap all paragraphs in the provided text."""
    736 |         if not self.body_width:
    737 |             return text
    738 | 
    739 |         assert wrap, "Requires Python 2.3."
    740 |         result = ''
    741 |         newlines = 0
    742 |         for para in text.split("\n"):
    743 |             if len(para) > 0:
    744 |                 if not skipwrap(para):
    745 |                     result += "\n".join(wrap(para, self.body_width))
    746 |                     if para.endswith('  '):
    747 |                         result += "  \n"
    748 |                         newlines = 1
    749 |                     else:
    750 |                         result += "\n\n"
    751 |                         newlines = 2
    752 |                 else:
    753 |                     if not onlywhite(para):
    754 |                         result += para + "\n"
    755 |                         newlines = 1
    756 |             else:
    757 |                 if newlines < 2:
    758 |                     result += "\n"
    759 |                     newlines += 1
    760 |         return result
    761 | 
    762 | ordered_list_matcher = re.compile(r'\d+\.\s')
    763 | unordered_list_matcher = re.compile(r'[-\*\+]\s')
    764 | md_chars_matcher = re.compile(r"([\\\[\]\(\)])")
    765 | md_chars_matcher_all = re.compile(r"([`\*_{}\[\]\(\)#!])")
    766 | md_dot_matcher = re.compile(r"""
    767 |     ^             # start of line
    768 |     (\s*\d+)      # optional whitespace and a number
    769 |     (\.)          # dot
    770 |     (?=\s)        # lookahead assert whitespace
    771 |     """, re.MULTILINE | re.VERBOSE)
    772 | md_plus_matcher = re.compile(r"""
    773 |     ^
    774 |     (\s*)
    775 |     (\+)
    776 |     (?=\s)
    777 |     """, flags=re.MULTILINE | re.VERBOSE)
    778 | md_dash_matcher = re.compile(r"""
    779 |     ^
    780 |     (\s*)
    781 |     (-)
    782 |     (?=\s|\-)     # followed by whitespace (bullet list, or spaced out hr)
    783 |                   # or another dash (header or hr)
    784 |     """, flags=re.MULTILINE | re.VERBOSE)
    785 | slash_chars = r'\`*_{}[]()#+-.!'
    786 | md_backslash_matcher = re.compile(r'''
    787 |     (\\)          # match one slash
    788 |     (?=[%s])      # followed by a char that requires escaping
    789 |     ''' % re.escape(slash_chars),
    790 |     flags=re.VERBOSE)
    791 | 
    792 | def skipwrap(para):
    793 |     # If the text begins with four spaces or one tab, it's a code block; don't wrap
    794 |     if para[0:4] == '    ' or para[0] == '\t':
    795 |         return True
    796 |     # If the text begins with only two "--", possibly preceded by whitespace, that's
    797 |     # an emdash; so wrap.
    798 |     stripped = para.lstrip()
    799 |     if stripped[0:2] == "--" and len(stripped) > 2 and stripped[2] != "-":
    800 |         return False
    801 |     # I'm not sure what this is for; I thought it was to detect lists, but there's
    802 |     # a 
    -inside- case in one of the tests that also depends upon it. 803 | if stripped[0:1] == '-' or stripped[0:1] == '*': 804 | return True 805 | # If the text begins with a single -, *, or +, followed by a space, or an integer, 806 | # followed by a ., followed by a space (in either case optionally preceeded by 807 | # whitespace), it's a list; don't wrap. 808 | if ordered_list_matcher.match(stripped) or unordered_list_matcher.match(stripped): 809 | return True 810 | return False 811 | 812 | def wrapwrite(text): 813 | text = text.encode('utf-8') 814 | try: #Python3 815 | sys.stdout.buffer.write(text) 816 | except AttributeError: 817 | sys.stdout.write(text) 818 | 819 | def html2text(html, baseurl=''): 820 | h = HTML2Text(baseurl=baseurl) 821 | return h.handle(html) 822 | 823 | def unescape(s, unicode_snob=False): 824 | h = HTML2Text() 825 | h.unicode_snob = unicode_snob 826 | return h.unescape(s) 827 | 828 | def escape_md(text): 829 | """Escapes markdown-sensitive characters within other markdown constructs.""" 830 | return md_chars_matcher.sub(r"\\\1", text) 831 | 832 | def escape_md_section(text, snob=False): 833 | """Escapes markdown-sensitive characters across whole document sections.""" 834 | text = md_backslash_matcher.sub(r"\\\1", text) 835 | if snob: 836 | text = md_chars_matcher_all.sub(r"\\\1", text) 837 | text = md_dot_matcher.sub(r"\1\\\2", text) 838 | text = md_plus_matcher.sub(r"\1\\\2", text) 839 | text = md_dash_matcher.sub(r"\1\\\2", text) 840 | return text 841 | 842 | 843 | def main(): 844 | baseurl = '' 845 | 846 | p = optparse.OptionParser('%prog [(filename|url) [encoding]]', 847 | version='%prog ' + __version__) 848 | p.add_option("--ignore-emphasis", dest="ignore_emphasis", action="store_true", 849 | default=IGNORE_EMPHASIS, help="don't include any formatting for emphasis") 850 | p.add_option("--ignore-links", dest="ignore_links", action="store_true", 851 | default=IGNORE_ANCHORS, help="don't include any formatting for links") 852 | p.add_option("--ignore-images", dest="ignore_images", action="store_true", 853 | default=IGNORE_IMAGES, help="don't include any formatting for images") 854 | p.add_option("-g", "--google-doc", action="store_true", dest="google_doc", 855 | default=False, help="convert an html-exported Google Document") 856 | p.add_option("-d", "--dash-unordered-list", action="store_true", dest="ul_style_dash", 857 | default=False, help="use a dash rather than a star for unordered list items") 858 | p.add_option("-e", "--asterisk-emphasis", action="store_true", dest="em_style_asterisk", 859 | default=False, help="use an asterisk rather than an underscore for emphasized text") 860 | p.add_option("-b", "--body-width", dest="body_width", action="store", type="int", 861 | default=BODY_WIDTH, help="number of characters per output line, 0 for no wrap") 862 | p.add_option("-i", "--google-list-indent", dest="list_indent", action="store", type="int", 863 | default=GOOGLE_LIST_INDENT, help="number of pixels Google indents nested lists") 864 | p.add_option("-s", "--hide-strikethrough", action="store_true", dest="hide_strikethrough", 865 | default=False, help="hide strike-through text. only relevant when -g is specified as well") 866 | p.add_option("--escape-all", action="store_true", dest="escape_snob", 867 | default=False, help="Escape all special characters. Output is less readable, but avoids corner case formatting issues.") 868 | (options, args) = p.parse_args() 869 | 870 | # process input 871 | encoding = "utf-8" 872 | if len(args) > 0: 873 | file_ = args[0] 874 | if len(args) == 2: 875 | encoding = args[1] 876 | if len(args) > 2: 877 | p.error('Too many arguments') 878 | 879 | if file_.startswith('http://') or file_.startswith('https://'): 880 | baseurl = file_ 881 | j = urllib.urlopen(baseurl) 882 | data = j.read() 883 | if encoding is None: 884 | try: 885 | from feedparser import _getCharacterEncoding as enc 886 | except ImportError: 887 | enc = lambda x, y: ('utf-8', 1) 888 | encoding = enc(j.headers, data)[0] 889 | if encoding == 'us-ascii': 890 | encoding = 'utf-8' 891 | else: 892 | data = open(file_, 'rb').read() 893 | if encoding is None: 894 | try: 895 | from chardet import detect 896 | except ImportError: 897 | detect = lambda x: {'encoding': 'utf-8'} 898 | encoding = detect(data)['encoding'] 899 | else: 900 | data = sys.stdin.read() 901 | 902 | if PY2: 903 | data = data.decode(encoding) 904 | 905 | h = HTML2Text(baseurl=baseurl) 906 | # handle options 907 | if options.ul_style_dash: h.ul_item_mark = '-' 908 | if options.em_style_asterisk: 909 | h.emphasis_mark = '*' 910 | h.strong_mark = '__' 911 | 912 | h.body_width = options.body_width 913 | h.list_indent = options.list_indent 914 | h.ignore_emphasis = options.ignore_emphasis 915 | h.ignore_links = options.ignore_links 916 | h.ignore_images = options.ignore_images 917 | h.google_doc = options.google_doc 918 | h.hide_strikethrough = options.hide_strikethrough 919 | h.escape_snob = options.escape_snob 920 | 921 | wrapwrite(h.handle(data)) 922 | 923 | 924 | if __name__ == "__main__": 925 | main() 926 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------