1"""
2COMMAND-LINE SPECIFIC STUFF
3=============================================================================
4
5The rest of the code is specifically for handling the case where Python
6Markdown is called from the command line.
7"""
8
9import markdown
10import sys
11import logging
12from logging import DEBUG, INFO, WARN, ERROR, CRITICAL
13
14EXECUTABLE_NAME_FOR_USAGE = "python markdown.py"
15""" The name used in the usage statement displayed for python versions < 2.3.
16(With python 2.3 and higher the usage statement is generated by optparse
17and uses the actual name of the executable called.) """
18
19OPTPARSE_WARNING = """
20Python 2.3 or higher required for advanced command line options.
21For lower versions of Python use:
22
23      %s INPUT_FILE > OUTPUT_FILE
24
25""" % EXECUTABLE_NAME_FOR_USAGE
26
27def parse_options():
28    """
29    Define and parse `optparse` options for command-line usage.
30    """
31
32    try:
33        optparse = __import__("optparse")
34    except:
35        if len(sys.argv) == 2:
36            return {'input': sys.argv[1],
37                    'output': None,
38                    'safe': False,
39                    'extensions': [],
40                    'encoding': None }, CRITICAL
41        else:
42            print OPTPARSE_WARNING
43            return None, None
44
45    parser = optparse.OptionParser(usage="%prog INPUTFILE [options]")
46    parser.add_option("-f", "--file", dest="filename", default=sys.stdout,
47                      help="write output to OUTPUT_FILE",
48                      metavar="OUTPUT_FILE")
49    parser.add_option("-e", "--encoding", dest="encoding",
50                      help="encoding for input and output files",)
51    parser.add_option("-q", "--quiet", default = CRITICAL,
52                      action="store_const", const=CRITICAL+10, dest="verbose",
53                      help="suppress all messages")
54    parser.add_option("-v", "--verbose",
55                      action="store_const", const=INFO, dest="verbose",
56                      help="print info messages")
57    parser.add_option("-s", "--safe", dest="safe", default=False,
58                      metavar="SAFE_MODE",
59                      help="safe mode ('replace', 'remove' or 'escape'  user's HTML tag)")
60    parser.add_option("-o", "--output_format", dest="output_format",
61                      default='xhtml1', metavar="OUTPUT_FORMAT",
62                      help="Format of output. One of 'xhtml1' (default) or 'html4'.")
63    parser.add_option("--noisy",
64                      action="store_const", const=DEBUG, dest="verbose",
65                      help="print debug messages")
66    parser.add_option("-x", "--extension", action="append", dest="extensions",
67                      help = "load extension EXTENSION", metavar="EXTENSION")
68
69    (options, args) = parser.parse_args()
70
71    if not len(args) == 1:
72        parser.print_help()
73        return None, None
74    else:
75        input_file = args[0]
76
77    if not options.extensions:
78        options.extensions = []
79
80    return {'input': input_file,
81            'output': options.filename,
82            'safe_mode': options.safe,
83            'extensions': options.extensions,
84            'encoding': options.encoding,
85            'output_format': options.output_format}, options.verbose
86
87def run():
88    """Run Markdown from the command line."""
89
90    # Parse options and adjust logging level if necessary
91    options, logging_level = parse_options()
92    if not options: sys.exit(0)
93    if logging_level: logging.getLogger('MARKDOWN').setLevel(logging_level)
94
95    # Run
96    markdown.markdownFromFile(**options)
97