text
stringlengths
0
1.05M
meta
dict
""" Helper package to make Python scripts with command-line options, parsing database structure. """ __all__ = ['TOP_COMMENT', 'TABLE_SEP', 'sql_to_asciidoc', 'main_sql2asciidoc'] from db import * import asciidoc import getopt, os, re import sys TOP_COMMENT = \ r"""// '''''''''''''''''''''''''''''''''''''''''''''''''' // THIS FILE IS GENERATED AUTOMATICALLY - DON'T EDIT! // '''''''''''''''''''''''''''''''''''''''''''''''''' // Tables parsed from SQL // using script, written on Python // and sql2asciidoc library // '''''''''''''''''''''''''''''''''''''''''''''''''' """ TABLES_CPT = "Tables" VIEWS_CPT = "Views" TABLE_SEP = "|============================================================" # Text inclusions TEXT_INCLS = [] def preformat_coldesc(txt): """ Preformats column description to represent lists """ # Converting unnumbered lists directly to DocBook: # # The list: # # - one # - two # - three # # Is converted to: # The list: # +++<itemizedlist> # <listitem><simpara> one </simpara></listitem> # <listitem><simpara> two </simpara></listitem> # <listitem><simpara> three </simpara></listitem> # </itemizedlist> # # 1. The list must be preceded with a text line, # followed by two blank lines. # 2. Each list item must start with "minus" (-) without indention. # Line breaks inside list items are not allowed. # 3. Two or more list items must exist. if not txt: txt="" g = re.compile("(\n\s*)((\n- [^\n]+){2,})") txt = g.sub(r"\1 +++<itemizedlist> \2 </itemizedlist>+++", txt) g = re.compile(r"(\+\+\+<itemizedlist>.*\n)- ([^\n]+)(.*</itemizedlist>\+\+\+)", re.DOTALL) while(g.search(txt)): txt = g.sub(r"\1 <listitem><simpara>+++ \2 +++</simpara></listitem> \3", txt) return txt def columndict_callback(c): """ Callback funciton, returning column formatting dictionary for Table::render_cols function """ def subQ(txt): return re.sub(r"'([^']*)'", r"`\1'", (txt or '')).replace(r'|', r'\|') return { 'name' : c.name, 'type' : c.type, 'nullable' : c.nullable, 'value' : subQ(c.value), 'default' : subQ(c.default), 'defaultf' : ("\n\n*Default: %s*" % subQ(c.default)) if c.default else '', 'notnull' : '' if c.nullable else ' not null', 'desc': c.desc, 'descf': preformat_coldesc(c.desc), } def grants_to_asciidoc(obj): """ Converts grants/revokes for specified object (table/view) to AsciiDoc format """ if not obj.permits: return u'' coldesctbl_attributes = '[cols="8m,%d*^3m",options="header",width="70%%"]' % len(PERMITS_LIST) coldesctbl_header = "|User or Role " + ' '.join(['|%s' % k for k in PERMITS_LIST]) # Some globals to locals table_sep = TABLE_SEP grt_rows = [] for k,v in obj.permits.iteritems(): s = '|**%s**' % k for p in PERMITS_LIST: s += '|%s' % {True:'GRANT',False:'REVOKE',None:''}[v[p]] grt_rows.append(s) grt_rows = '\n'.join(grt_rows) return """ .Privileges %(coldesctbl_attributes)s %(table_sep)s %(coldesctbl_header)s %(grt_rows)s %(table_sep)s """ % locals() def tables_to_asciidoc( sql, title_char = r'~'): """ Renders SQL with Tables creation DDL -- to ASCIIDOC. """ ret = "" coldesctbl_header = "|Column |Type |Description" coldesctbl_attributes = '[cols="8m,5m,15",options="header"]' # Parse tables tbs = parse_tables(sql) # Some globals to locals table_sep = TABLE_SEP # Render tables for t in tbs: tnm = t.name ttl = title_char * len(tnm) dsc = t.desc cols = t.render_cols("|%(name)s |%(type)s|%(descf)s%(defaultf)s\n", columndict_callback) grants = grants_to_asciidoc(t) ret += """ %(tnm)s %(ttl)s %(dsc)s .Columns of the table %(coldesctbl_attributes)s %(table_sep)s %(coldesctbl_header)s %(cols)s %(table_sep)s %(grants)s """ % locals() return ret def views_to_asciidoc( sql, title_char = r'~'): """ Renders SQL with Views creation DDL -- to ASCIIDOC. """ global TEXT_INCLS ret = "" coldesctbl_attributes = '[cols="8m,8m,12",options="header"]' coldesctbl_header = "|Alias |Value |Description" # Parse tables vws = parse_views(sql) # Some globals to locals table_sep = TABLE_SEP # Render views for t in vws: tnm = t.name ttl = title_char * len(tnm) dsc = t.desc cols = t.render_cols("|%(name)s |+++%(value)s+++|%(descf)s\n", columndict_callback) grants = grants_to_asciidoc(t) ret += """ %(tnm)s %(ttl)s %(dsc)s """ % locals() if t.sources: srcs = "" for src1 in t.sources: a, tmp, b = src1.rpartition(" ") srcs += "|%s |%s\n" % ( # Getting left part (Table/View) or entire if not partitioned, # replacing at-sign with inline-block ($$@$$) to avoid generating # mailto: link automatically. (a or b).replace(r"|", r"\|").replace(r"@", r"$$@$$"), # Getting right part or nothing if not partitioned (b if a else '').replace(r"|", r"\|"), ) ret += """ .Sources of the view [cols="8m,5m",options="header",width="70%%"] %(table_sep)s |Table/View |Alias %(srcs)s %(table_sep)s """ % locals() if cols: ret += """ .Columns of the view %(coldesctbl_attributes)s %(table_sep)s %(coldesctbl_header)s %(cols)s %(table_sep)s """ % locals() if t.is_union: TEXT_INCLS.append(t.text) ret += """ The view is created using UNION select. Script of the view is shown below: .View SQL [source,sql] ------------------------------------------------------------ INCLUSION_%d ------------------------------------------------------------ """ % (len(TEXT_INCLS) - 1) if grants: ret += "\n\n%s\n\n" % grants return ret def objects_to_comments(sql): """ Parses tables, views, columns and makes file of comments """ def colf(c): """ Callback funciton, returning column formatting dictionary for Table::render_cols function """ return { 'name' : c.name, 'desc' : (c.desc or "").replace("'", "''"), } # Parse tables & views objs = parse_tables(sql) + parse_views(sql) # Render objects ret = """ -- COMMENTS ON DATABASE OBJECTS -- -- Auto-generated from SQL CREATE script -- ------------------------------------------- """ for o in objs: onm = o.name OTP = o._obj_type.upper() dsc = (o.desc or "").replace("'", "''") cols = o.render_cols("comment on column %s.%%(name)s\n is '%%(desc)s';\n" % onm, colf) ret += """ ------ %(OTP)s: %(onm)s ------ comment on table %(onm)s is '%(dsc)s'; %(cols)s """ % locals() return ret def main(argv): """ %(command)s - Prints ASCIIDOC of table descriptions from SQL, passed as command-line in argv. Usage: %(command)s [options] sql_filename Options: -c, --title-char=TITLECHAR Characters for title underlines. If ONE character, only tables are rendered. if TWO OR MORE -- both tables and views are rendered; In this case first character is underline for "Tables" or "Views" captions, second - for table and viewnames themselves. Default: ~ -h, --help Display this help message. -o, --output=FILENAME Output file. By default - sql_filename with asciidoc extension. If "-" is specified as FILENAME, output is written to stdout. -m, --comments Generate SQL comments rather than asciidoc output -v, --verbose Write detailed information to stderr. Note: If sql_filename is not specified, SQL is expected from stdin. In this case output goes to stdout as well, unless -o parameter is specified. """ def log_error(s): sys.stderr.write(s) sys.stderr.write('\n') def log(s): pass global TEXT_INCLS TEXT_INCLS = [] command = os.path.split(argv[0])[1] params = {} cpt_char = None comments = False #Extract options try: opts, args = getopt.getopt( argv[1:], "c:a:t:r:A:V:R:o:vmh", ["title-char=", "table-attributes=", "table-header=", "row-pattern=", "view-table-attributes=", "view-header=", "view-row-pattern=", "output=", "verbose", "comments", "help"]) infile = args and args[0] or None outfile = infile and "%s.asciidoc" % os.path.splitext(os.path.split(infile)[1])[0] or '-' except getopt.GetoptError, err: log_error(main.__doc__ % locals()) log_error("Error: %s" % err) return -2 except IndexError, err: log_error(main.__doc__ % locals()) log_error("Error: File not specified.") return -2 for o, a in opts: if o in ("-c", "--title-char"): a = a.strip() if len(a) > 1: cpt_char = a[0] params['title_char'] = a[1] else: params['title_char'] = a elif o in ("-v", "--verbose"): log = log_error elif o in ("-o", "--output"): outfile = a elif o in ("-m", "--comments"): comments = True elif o in ("-h", "--help"): print main.__doc__ % locals() return 0 if outfile=='-': outfile = None if comments: log("Generating SQL COMMENTS from SQL") log("================================") else: log("Generating ASCIIDOC from SQL") log("============================") try: # Read SQL log("Reading file %s ..." % infile) f = infile and open(infile) or sys.stdin sql = f.read() f.close() if comments: ret = objects_to_comments(sql) else: ret = TOP_COMMENT if cpt_char: ret += "\n\n%s\n%s\n" % (TABLES_CPT, cpt_char*len(TABLES_CPT)) # Parse Tables from SQL log("Parsing Tables...") ret += tables_to_asciidoc(sql, **params) if cpt_char: # Parse Views from SQL vws = views_to_asciidoc(sql, **params) log("Parsing Views...") if vws.strip(): ret += "\n\n%s\n%s\n" % (VIEWS_CPT, cpt_char*len(VIEWS_CPT)) ret += vws # Making title references ret = asciidoc.make_title_references(ret) # Making text inclusions of the Views for i in range(len(TEXT_INCLS)): ret = ret.replace("INCLUSION_%d" % i, TEXT_INCLS[i]) # Write SQL log("Writing file %s ..." % outfile) f = outfile and open(outfile, "w") or sys.stdout f.write(ret) f.close() log("Done!") except Exception,err: log_error("Error: %s" % err) raise log("") return 0
{ "repo_name": "avsd/sql2asciidoc", "path": "sql2asciidoc/script_tools.py", "copies": "1", "size": "12217", "license": "bsd-3-clause", "hash": 7796730780844560000, "line_mean": 24.9690949227, "line_max": 98, "alpha_frac": 0.4792502251, "autogenerated": false, "ratio": 3.562846310877807, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45420965359778065, "avg_score": null, "num_lines": null }
""" Module for parsing database structure from Oracle SQL DDL script """ __all__ = ['Table','Column','parse_tables','parse_views','PERMITS_LIST'] import re RXX_TABLENAME = \ "(?P<tablename>([\\w\\$]+\\.|\"[\\w\\$]+\"\\.)?([\\w\\$]+|\"[\\w\\$]+\"))" RX_TABLE = re.compile( r"\bCREATE\s+TABLE\s+" + RXX_TABLENAME + r"\s*\(" r"(?P<columns>.*?)" r"\)" r"\s*(;|tablespace .*?;)" , re.DOTALL | re.IGNORECASE) RX_COLUMN = re.compile( r'(?P<colname>([\w\$]+|"[\w\$ ]+"))\s+' r'(?P<coltype>(\w+|"[^"]+")\s*[\(\)\d]*)\s*' r"(\bdefault\s+(?P<default>\S+))?\s*" r"(?P<primarykey>\bprimary\s+key)?\s*" r"(?P<notnull>\bnot\s+null)?\s*" r"(\benable)?\s*" r"(?:\Z|,)" , re.DOTALL | re.IGNORECASE) RX_VIEW = re.compile( r"\bCREATE\s+(?:OR\s+REPLACE\s+)?VIEW\s(?P<tablename>[\w\$]*\.?[\w\$]+)\b" r"\s*(\((?P<aliases>[\s\w\$,]*)\))?" r"\s*\bAS\s+SELECT\s+" r"(?P<columns>.*?)" r"\bFROM\s+(?P<sources>.*?)(?P<isunion>\bUNION\b(\s+ALL\b)?.*?)?" r"(?:(\bWHERE\b)|(\bORDER\s+BY\b)|(\bGROUP\s+BY\b)|;)" , re.DOTALL | re.IGNORECASE) RX_TAB_COMMENT = re.compile( r"\bCOMMENT\s+ON\s+TABLE\s+" + RXX_TABLENAME + r"\s+is\s+" r"'(?P<comment>.*?)'\s*;" , re.DOTALL|re.IGNORECASE) RX_COL_COMMENT = re.compile( r"\bCOMMENT\s+ON\s+COLUMN\s+" + RXX_TABLENAME + r"\.(?P<colname>[\w\$]+)" r"\s+is\s+" r"'(?P<comment>.*?)'\s*;" , re.DOTALL|re.IGNORECASE) PERMITS_LIST = ['SELECT', 'INSERT', 'UPDATE', 'DELETE'] RX_PRIVILEGE = re.compile( r"\b(?P<privilege>GRANT|REVOKE)\s+(?P<permit>" + "|".join(PERMITS_LIST) + ")\s+" r"ON\s+" + RXX_TABLENAME + r"\s+TO\s+(?P<schema>[\w&$]+)\s*;" , re.DOTALL|re.IGNORECASE) class Column(object): def __init__(self, nm, tp = "", nl = False, default=None, dsc = "", value = None): self.name = nm.replace("\"", "") self.type = tp self.nullable = nl self.desc = dsc self.default = default self.value = value class Privileges(object): """ Represents DB level privileges for certain schema """ def __init__(self): self.privileges = dict([(p,None) for p in PERMITS_LIST]) def grant(self, permit): if permit in PERMITS_LIST: self.privileges[permit] = True def revoke(self, permit): if permit in PERMITS_LIST: self.privileges[permit] = False def __getitem__(self,index): return self.privileges[index] class TableView(object): _obj_type = "" def __init__(self, nm, dsc = "", txt = ""): self.name = nm.replace("\"", "") self.desc = dsc self.text = txt # Columns self.cols = [] # Permissions self.permits = {} def grant(self, schema, permit): if not schema in self.permits: self.permits[schema] = Privileges() self.permits[schema].grant(permit) def revoke(self, schema, permit): if not schema in self.permits: self.permits[schema] = Privileges() self.permits[schema].revoke(permit) def __str__(self): return "%s %s" % (self._obj_type, self.name) def add_col(self, col): self.cols.append(col) return col def add_column(self, nm, tp, nl=False, default=None, dsc=""): return self.add_col(Column(nm, tp, nl, default, dsc)) def render_cols(self, pattern, column_format_func=None): """ Renders columns using string-formatting pattern. Parameters: pattern -- string, representing formatting pattern. May contain following named parameters: %(name)s %(type)s %(nullable)s %(notnull)s %(default)s %(value)s %(desc)s In case of using column_format_func parameter these names may be altered. column_format_func -- optional callback function, called for each column and returning dictionary to be applied to the "pattern" to format it. Must accept single argument - Column object. """ ret = "" # If only one column - '*', not render: if len(self.cols) == 1 and self.cols[0].name == '*': return '' for c in self.cols: dct = column_format_func(c) if column_format_func else { 'name' : c.name, 'type' : c.type, 'nullable' : c.nullable, 'notnull' : '' if c.nullable else ' not null', 'default' : c.default, 'value' : c.value, 'desc' : c.desc, } ret += pattern % dct return ret def parse_privileges(self,sql): """ Parses privileges and revokes for the object from passed SQL """ for g in RX_PRIVILEGE.finditer(sql): dt = g.groupdict() if dt['tablename'].replace("\"", "").lower() == self.name.lower(): if dt['privilege'].lower() == 'revoke': self.revoke(dt['schema'],dt['permit']) else: self.grant(dt['schema'],dt['permit']) class Table(TableView): _obj_type = "Table" class View(TableView): _obj_type = "View" def __init__(self, nm, dsc = "", txt = ""): super(View, self).__init__(nm, dsc, txt) self.sources = [] self.is_union = False def remove_sql_comments(sql): """ Removes inline and block comments of SQL (/*...*/, --...) """ fnd =re.compile(r"(\/\*.*?\*\/)", re.DOTALL) while fnd.search(sql): sql = fnd.sub("", sql) is_str = False is_cmt = False sql2 = "" i = 0 while i < len(sql): if is_cmt: if sql[i]=="\n": is_cmt = False sql2 += sql[i] else: if is_str: sql2 += sql[i] else: if sql[i:i+2] == '--': is_cmt = True else: sql2 += sql[i] if sql[i]=="'": is_str = not is_str i+=1 sql = sql2 return sql def parse_table_comments(sql): """ Parses comments for TABLES and returns as Dictionary """ tabcoms = {} for t in RX_TAB_COMMENT.finditer(sql): t = t.groupdict() tabcoms[t['tablename']] = t['comment'].replace("''", "'") return tabcoms def parse_column_comments(sql): """ Parses comments for COLUMNS and returns as Dictionary (by table) of Dictionaries (column comments) """ colcoms = {} for t in RX_COL_COMMENT.finditer(sql): t = t.groupdict() # Add new dictionary if not exists if not colcoms.has_key(t['tablename']): colcoms[t['tablename']] = {} colcoms[t['tablename']][t['colname']] = t['comment'].replace("''", "'") return colcoms def parse_tables(sql): """ Parses Oracle-formatted SQL file, extracts tables and returns them as List """ sql = remove_sql_comments(sql) # Parse comments tab_comments = parse_table_comments(sql) col_comments = parse_column_comments(sql) # Parse tables tables = [] for t in RX_TABLE.finditer(sql): dt = t.groupdict() # Create table object tabl = Table(dt['tablename'], tab_comments.get(dt['tablename'], ''), t.group()) tabl_colcomments = col_comments.get(tabl.name, {}) # Parse columns of the table for t2 in RX_COLUMN.finditer(dt['columns']): dc = t2.groupdict() # Add column tabl.add_column( dc['colname'], dc['coltype'], False if str(dc['notnull']).upper()=="NOT NULL" else True, dc['default'], tabl_colcomments.get(dc['colname'], "")) #print dc['colname'] # Parse privileges of the table tabl.parse_privileges(sql) # Add table to Dictionary tables.append(tabl) return tables def parse_views(sql): """ Parses views, represented with "Create As Select" script and returns them as a list. """ sql = remove_sql_comments(sql) # Parse comments tab_comments = parse_table_comments(sql) col_comments = parse_column_comments(sql) # Parse views views = [] for t in RX_VIEW.finditer(sql): dt = t.groupdict() # Create View object view = View(dt['tablename'], tab_comments.get(dt['tablename'], ''), t.group()) view_colcomments = col_comments.get(view.name, {}) view.is_union = bool(dt.get('isunion')) # --------------------- # Adding Columns # --------------------- col_vl = "" #Value col_al = "" #Alias bFillingAlias = False def add_col_to_view(view, col_al, col_vl, colcomments_dict): """ Adds a column to View """ col_al = (col_al.strip() or col_vl).split(".")[-1].strip() cc = Column( nm = col_al, value = col_vl.strip()) cc.desc = colcomments_dict.get(cc.name) cc = view.add_col(col=cc) #------------------------- parth = 0 is_str = False for c in dt['columns']: if not (parth>0 or is_str): if c == ",": add_col_to_view(view, col_al, col_vl, view_colcomments) col_vl = "" col_al = "" bFillingAlias = False continue # If some space found elif c in " \n" and bool(col_vl.strip()): bFillingAlias = True if c == "'": is_str = not is_str if not is_str: if c == '(': parth+=1 elif c == ')': parth-=1 if bFillingAlias: col_al +=c else: col_vl +=c # Add the final column add_col_to_view(view, col_al, col_vl, view_colcomments) # Optional column aliases before the AS keyword aliases = dt.get('aliases') if aliases: aliases = aliases.split(",") if len(aliases)==len(view.cols): for i in range(len(aliases)): view.cols[i].name = aliases[i].strip() view.cols[i].desc = view_colcomments.get(view.cols[i].name) # --------------------- # Adding View-Sources # --------------------- if dt['sources'].strip(): view.sources = dt['sources'].split(",") for i in range(0,len(view.sources)): view.sources[i] = view.sources[i].strip() # Parse privileges of the view view.parse_privileges(sql) # Add view to Dictionary views.append(view) return views
{ "repo_name": "avsd/sql2asciidoc", "path": "sql2asciidoc/db.py", "copies": "1", "size": "11897", "license": "bsd-3-clause", "hash": -5504215562167272000, "line_mean": 27.375308642, "line_max": 87, "alpha_frac": 0.4632260234, "autogenerated": false, "ratio": 3.768451061133988, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9682067902765678, "avg_score": 0.009921836353662087, "num_lines": 405 }
from setuptools import setup # from os.path import dirname, join # longdesc = open(join(dirname(__file__), './README.md')).read() setup( name='imgix-lokoplugins', version='0.0.1', url='https://github.com/imgix/imgix-lokoplugins', maintainer='Imgix', maintainer_email='david@imgix.com', packages=['imgix_lokoplugins',], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Environment :: No Input/Output (Daemon)', 'Environment :: Web Environment', 'Intended Audience :: System Administrators', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'Topic :: Software Development :: Version Control', 'Topic :: System :: Archiving :: Packaging', 'Topic :: System :: Systems Administration' ], description='imgix-lokoplugins', long_description='' )
{ "repo_name": "imgix/imgix-lokoplugins", "path": "setup.py", "copies": "1", "size": "2311", "license": "bsd-2-clause", "hash": 8691872161440626000, "line_mean": 42.6037735849, "line_max": 77, "alpha_frac": 0.7247944613, "autogenerated": false, "ratio": 4.08303886925795, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.530783333055795, "avg_score": null, "num_lines": null }
from bs4 import BeautifulSoup from time import sleep import urllib.request as ul import ctypes import winsound # Array of Milestone names, change for the desired milestone name, must be equal at the title of milestone at the Github milestone page milestonenames = ['Homestead', '1.3.4'] # Array of Percent Alarm(s) targetpercent = ('85%','90%','95%','100%') # You can setup more alarms in the same list separated by comma, like this ('10%','30%','60%,'80%') # Milestone full url, you need to put like the example : 'https://github.com/[ACCOUNT]/[REPOSITORY]/milestones' milestonesurl = 'https://github.com/ethereum/go-ethereum/milestones' alert = ctypes.windll.user32.MessageBoxW modal_flag = 0x00001000 nbeeps = 4 # Number of beeps Freq = 2700 # Set Frequency of Beep To 2700 Hertz Dur = 400 # Set Duration of Beep To 400 ms == 0,4 second htmldocument = ul.urlopen(milestonesurl).read() soup = BeautifulSoup(htmldocument, 'html.parser') mildivs = soup.find_all('div', class_='table-list-item') # Main for mname in milestonenames: for div in mildivs: wanteddiv = div.find('div', class_='table-list-cell') if wanteddiv.find('a', string=mname ): milpercent = wanteddiv.find_next_sibling().find('span',class_='progress-percent').contents if milpercent[0] in targetpercent : for x in range (0,nbeeps): winsound.Beep(Freq,Dur) sleep(0.01) boxmessage = 'The ' + mname + ' milestone is at ' + milpercent[0] boxtitle = 'Github Milestone Status' alert(None, boxmessage, boxtitle, 0x40 | modal_flag)
{ "repo_name": "kartojal/checkmilestones-py", "path": "checkmilestones.py", "copies": "1", "size": "2131", "license": "mit", "hash": 5105973246122995000, "line_mean": 41.62, "line_max": 142, "alpha_frac": 0.6809009855, "autogenerated": false, "ratio": 3.3559055118110237, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9472097363232505, "avg_score": 0.012941826815703722, "num_lines": 50 }
__author__ = 'David C. Dean' import requests import json class OAuth: def __init__(self, endpoint='https://login.salesforce.com', username='', password='', client_id='', client_secret=''): self.__endpoint = endpoint self.__username = username self.__password = password self.__client_id = client_id self.__client_secret = client_secret self.__auth_data = None def request_token(self): request_resp = requests.post(self._get_auth_url(), params=self._get_params()) if request_resp.status_code == 200: self.__auth_data = json.loads(request_resp.text) return True else: return False def _get_auth_url(self): return self.__endpoint + '/services/oauth2/token' def _get_params(self): params = { 'grant_type': 'password', 'username': self.__username, 'password': self.__password, 'client_id': self.__client_id, 'client_secret': self.__client_secret} return params def get_token(self): return self.__auth_data['access_token'] def get_instance(self): return self.__auth_data['instance_url']
{ "repo_name": "DavidCDean/salesforce-streaming", "path": "salesforce_streaming/authorization.py", "copies": "1", "size": "1223", "license": "mit", "hash": 1659756529466363400, "line_mean": 28.119047619, "line_max": 122, "alpha_frac": 0.5707277187, "autogenerated": false, "ratio": 4.049668874172186, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5120396592872186, "avg_score": null, "num_lines": null }
__author__ = 'David C. Dean' import requests import json class StreamingAPI: def __init__(self, instance=None, token=None): self.__endpoint = instance + '/cometd/28.0' self.__token = token self.__hs_data = None self.__session = requests.session() def handshake(self): hs_response = self.__session.post(self.__endpoint, data=self._handshake_payload(), headers=self._get_headers(), stream=True) if hs_response.status_code == 200: print(hs_response.text) self.__hs_data = json.loads(hs_response.text)[0] return True else: print('BAD HANDSHAKE\n') return False def connect(self): cn_response = self.__session.post(self.__endpoint, data=self._connect_payload(), headers=self._get_headers()) if cn_response.status_code == 200: print(cn_response.text) return True else: print('BAD CONNECT\n') return False def subscribe(self, topic=None): sub_response = self.__session.post(self.__endpoint, data=self._subscribe_payload(topic), headers=self._get_headers()) if sub_response.status_code == 200 and json.loads(sub_response.text)[0]['successful'] == True: print(sub_response.text) return True else: print('BAD SUBSCRIBE\n') return False def get_client_id(self): return self.__hs_data['clientId'] def _subscribe_payload(self, topic=None): return json.dumps([{'channel': '/meta/subscribe', 'clientId': self.get_client_id(), 'subscription': topic }]) def _handshake_payload(self): return json.dumps({'supportedConnectionTypes': ['long-polling'], 'version': '1.0', 'channel': '/meta/handshake', 'minimumVersion': '1.0'}) def _connect_payload(self): return json.dumps([{'channel': '/meta/connect', 'clientId': self.get_client_id(), 'connectionType': 'long-polling'}]) def _get_headers(self): return {'Content-Type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer ' + self.__token}
{ "repo_name": "DavidCDean/salesforce-streaming", "path": "salesforce_streaming/streaming_api.py", "copies": "1", "size": "2141", "license": "mit", "hash": 4050099670045952500, "line_mean": 37.2321428571, "line_max": 146, "alpha_frac": 0.6029892574, "autogenerated": false, "ratio": 3.836917562724014, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4939906820124014, "avg_score": null, "num_lines": null }
""" The :mod:`ensemble` module implements the ensemble selection technique of Caruana et al [1][2]. Currently supports f1, auc, rmse, accuracy and mean cross entropy scores for hillclimbing. Based on numpy, scipy, sklearn and sqlite. Work in progress. References ---------- .. [1] Caruana, et al, "Ensemble Selection from Libraries of Rich Models", Proceedings of the 21st International Conference on Machine Learning (ICML `04). .. [2] Caruana, et al, "Getting the Most Out of Ensemble Selection", Proceedings of the 6th International Conference on Data Mining (ICDM `06). """ import os import sys import sqlite3 import numpy as np from math import sqrt from cPickle import loads, dumps from collections import Counter from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.utils import check_random_state from sklearn.metrics import f1_score, roc_auc_score from sklearn.metrics import mean_squared_error, accuracy_score from sklearn.cross_validation import StratifiedKFold from sklearn.preprocessing import LabelBinarizer def _f1(y, y_bin, probs): """return f1 score""" return f1_score(y, np.argmax(probs, axis=1)) def _auc(y, y_bin, probs): """return AUC score (for binary problems only)""" return roc_auc_score(y, probs[:, 1]) def _rmse(y, y_bin, probs): """return 1-rmse since we're maximizing the score for hillclimbing""" return 1.0 - sqrt(mean_squared_error(y_bin, probs)) def _accuracy(y, y_bin, probs): """return accuracy score""" return accuracy_score(y, np.argmax(probs, axis=1)) def _mxentropy(y, y_bin, probs): """return negative mean cross entropy since we're maximizing the score for hillclimbing""" # clip away from extremes to avoid under/overflows eps = 1.0e-7 clipped = np.clip(probs, eps, 1.0 - eps) clipped /= clipped.sum(axis=1)[:, np.newaxis] return (y_bin * np.log(clipped)).sum() / y.shape[0] def _bootstraps(n, rs): """return bootstrap sample indices for given n""" bs_inds = rs.randint(n, size=(n)) return bs_inds, np.setdiff1d(range(n), bs_inds) class EnsembleSelectionClassifier(BaseEstimator, ClassifierMixin): """Caruana-style ensemble selection [1][2] Parameters: ----------- `db_file` : string Name of file for sqlite db backing store. `models` : list or None List of classifiers following sklearn fit/predict API, if None fitted models are loaded from the specified database. `n_best` : int (default: 5) Number of top models in initial ensemble. `n_folds` : int (default: 3) Number of internal cross-validation folds. `bag_fraction` : float (default: 0.25) Fraction of (post-pruning) models to randomly select for each bag. `prune_fraction` : float (default: 0.8) Fraction of worst models to prune before ensemble selection. `score_metric` : string (default: 'accuracy') Score metric to use when hillclimbing. Must be one of 'accuracy', 'xentropy', 'rmse', 'f1'. `epsilon` : float (default: 0.01) Minimum score improvement to add model to ensemble. Ignored if use_epsilon is False. `max_models` : int (default: 50) Maximum number of models to include in an ensemble. `verbose` : boolean (default: False) Turn on verbose messages. `use_bootstrap`: boolean (default: False) If True, use bootstrap sample of entire dataset for fitting, and oob samples for hillclimbing for each internal CV fold instead of StratifiedKFolds `use_epsilon` : boolean (default: False) If True, candidates models are added to ensembles until the value of the score_metric fails to improve by the value of the epsilon parameter. If False, models are added until the number of models in the cadidate ensemble reaches the value of the max_models parameter. `random_state` : int, RandomState instance or None (default=None) Control the pseudo random number generator used to select candidates for each bag. References ---------- .. [1] Caruana, et al, "Ensemble Selection from Libraries of Rich Models", Proceedings of the 21st International Conference on Machine Learning (ICML `04). .. [2] Caruana, et al, "Getting the Most Out of Ensemble Selection", Proceedings of the 6th International Conference on Data Mining (ICDM `06). """ _metrics = { 'f1': _f1, 'auc': _auc, 'rmse': _rmse, 'accuracy': _accuracy, 'xentropy': _mxentropy, } def __init__(self, db_file=None, models=None, n_best=5, n_folds=3, n_bags=20, bag_fraction=0.25, prune_fraction=0.8, score_metric='accuracy', epsilon=0.01, max_models=50, use_epsilon=False, use_bootstrap=False, verbose=False, random_state=None): self.db_file = db_file self.models = models self.n_best = n_best self.n_bags = n_bags self.n_folds = n_folds self.bag_fraction = bag_fraction self.prune_fraction = prune_fraction self.score_metric = score_metric self.epsilon = epsilon self.max_models = max_models self.use_epsilon = use_epsilon self.use_bootstrap = use_bootstrap self.verbose = verbose self.random_state = random_state self._check_params() self._folds = None self._n_models = 0 self._n_classes = 0 self._metric = None self._ensemble = Counter() self._model_scores = [] self._scored_models = [] self._fitted_models = [] self._init_db(models) def _check_params(self): """Parameter sanity checks""" if (not self.db_file): msg = "db_file parameter is required" raise ValueError(msg) if (self.epsilon < 0.0): msg = "epsilon must be >= 0.0" raise ValueError(msg) metric_names = self._metrics.keys() if (self.score_metric not in metric_names): msg = "score_metric not in %s" % metric_names raise ValueError(msg) if (self.n_best < 1): msg = "n_best must be >= 1" raise ValueError(msg) if (self.max_models < self.n_best): msg = "max_models must be >= n_best" raise ValueError(msg) if (not self.use_bootstrap): if (self.n_folds < 2): msg = "n_folds must be >= 2 for StratifiedKFolds" raise ValueError(msg) else: if (self.n_folds < 1): msg = "n_folds must be >= 1 with bootstrap" raise ValueError(msg) def _init_db(self, models): """Initialize database""" # db setup script _createTablesScript = """ create table models ( model_idx integer UNIQUE NOT NULL, pickled_model blob NOT NULL ); create table fitted_models ( model_idx integer NOT NULL, fold_idx integer NOT NULL, pickled_model blob NOT NULL ); create table model_scores ( model_idx integer UNIQUE NOT NULL, score real NOT NULL, probs blob NOT NULL ); create table ensemble ( model_idx integer NOT NULL, weight integer NOT NULL ); """ # barf if db file exists and we're making a new model if (models and os.path.exists(self.db_file)): raise ValueError("db_file '%s' already exists!" % self.db_file) db_conn = sqlite3.connect(self.db_file) with db_conn: db_conn.execute("pragma journal_mode = off") if (models): # build database with db_conn: db_conn.executescript(_createTablesScript) # populate model table insert_stmt = """insert into models (model_idx, pickled_model) values (?, ?)""" with db_conn: vals = ((i, buffer(dumps(m))) for i, m in enumerate(models)) db_conn.executemany(insert_stmt, vals) create_stmt = "create index models_index on models (model_idx)" db_conn.execute(create_stmt) self._n_models = len(models) else: curs = db_conn.cursor() curs.execute("select count(*) from models") self._n_models = curs.fetchone()[0] curs.execute("select model_idx, weight from ensemble") for k, v in curs.fetchall(): self._ensemble[k] = v # clumsy hack to get n_classes curs.execute("select probs from model_scores limit 1") r = curs.fetchone() probs = loads(str(r[0])) self._n_classes = probs.shape[1] db_conn.close() def fit(self, X, y): """Perform model fitting and ensemble building""" self.fit_models(X, y) self.build_ensemble(X, y) return self def fit_models(self, X, y): """Perform internal cross-validation fit""" if (self.verbose): sys.stderr.write('\nfitting models:\n') if (self.use_bootstrap): n = X.shape[0] rs = check_random_state(self.random_state) self._folds = [_bootstraps(n, rs) for _ in xrange(self.n_folds)] else: self._folds = list(StratifiedKFold(y, n_folds=self.n_folds)) select_stmt = "select pickled_model from models where model_idx = ?" insert_stmt = """insert into fitted_models (model_idx, fold_idx, pickled_model) values (?,?,?)""" db_conn = sqlite3.connect(self.db_file) curs = db_conn.cursor() for model_idx in xrange(self._n_models): curs.execute(select_stmt, [model_idx]) pickled_model = curs.fetchone()[0] model = loads(str(pickled_model)) model_folds = [] for fold_idx, fold in enumerate(self._folds): train_inds, _ = fold model.fit(X[train_inds], y[train_inds]) pickled_model = buffer(dumps(model)) model_folds.append((model_idx, fold_idx, pickled_model)) with db_conn: db_conn.executemany(insert_stmt, model_folds) if (self.verbose): if ((model_idx + 1) % 50 == 0): sys.stderr.write('%d\n' % (model_idx + 1)) else: sys.stderr.write('.') if (self.verbose): sys.stderr.write('\n') with db_conn: stmt = """create index fitted_models_index on fitted_models (model_idx, fold_idx)""" db_conn.execute(stmt) db_conn.close() def _score_models(self, db_conn, X, y, y_bin): """Get cross-validated test scores for each model""" self._metric = self._metrics[self.score_metric] if (self.verbose): sys.stderr.write('\nscoring models:\n') insert_stmt = """insert into model_scores (model_idx, score, probs) values (?,?,?)""" select_stmt = """select pickled_model from fitted_models where model_idx = ? and fold_idx = ?""" # nuke existing scores with db_conn: stmt = """drop index if exists model_scores_index; delete from model_scores;""" db_conn.executescript(stmt) curs = db_conn.cursor() # build probs array using the test sets for each internal CV fold for model_idx in xrange(self._n_models): probs = np.zeros((len(X), self._n_classes)) for fold_idx, fold in enumerate(self._folds): _, test_inds = fold curs.execute(select_stmt, [model_idx, fold_idx]) res = curs.fetchone() model = loads(str(res[0])) probs[test_inds] = model.predict_proba(X[test_inds]) score = self._metric(y, y_bin, probs) # save score and probs array with db_conn: vals = (model_idx, score, buffer(dumps(probs))) db_conn.execute(insert_stmt, vals) if (self.verbose): if ((model_idx + 1) % 50 == 0): sys.stderr.write('%d\n' % (model_idx + 1)) else: sys.stderr.write('.') if (self.verbose): sys.stderr.write('\n') with db_conn: stmt = """create index model_scores_index on model_scores (model_idx)""" db_conn.execute(stmt) def _get_ensemble_score(self, db_conn, ensemble, y, y_bin): """Get score for model ensemble""" n_models = float(sum(ensemble.values())) ensemble_probs = np.zeros((len(y), self._n_classes)) curs = db_conn.cursor() select_stmt = """select model_idx, probs from model_scores where model_idx in %s""" in_str = str(tuple(ensemble)).replace(',)', ')') curs.execute(select_stmt % in_str) for row in curs.fetchall(): model_idx, probs = row probs = loads(str(probs)) weight = ensemble[model_idx] ensemble_probs += probs * weight ensemble_probs /= n_models score = self._metric(y, y_bin, ensemble_probs) return score, ensemble_probs def _score_with_model(self, db_conn, y, y_bin, probs, n_models, model_idx): """compute ensemble score with specified model added""" curs = db_conn.cursor() select_stmt = """select probs from model_scores where model_idx = %d""" curs.execute(select_stmt % model_idx) row = curs.fetchone() n_models = float(n_models) new_probs = loads(str(row[0])) new_probs = (probs*n_models + new_probs)/(n_models + 1.0) score = self._metric(y, y_bin, new_probs) return score, new_probs def _ensemble_from_candidates(self, db_conn, candidates, y, y_bin): """Build an ensemble from a list of candidate models""" ensemble = Counter(candidates[:self.n_best]) ens_score, ens_probs = self._get_ensemble_score(db_conn, ensemble, y, y_bin) ens_count = sum(ensemble.values()) if (self.verbose): sys.stderr.write('%02d/%.3f ' % (ens_count, ens_score)) cand_ensembles = [] while(ens_count < self.max_models): # compute and collect scores after adding each candidate new_scores = [] for new_model_idx in candidates: score, _ = self._score_with_model(db_conn, y, y_bin, ens_probs, ens_count, new_model_idx) new_scores.append({'score': score, 'new_model_idx': new_model_idx}) new_scores.sort(key=lambda x: x['score'], reverse=True) last_ens_score = ens_score ens_score = new_scores[0]['score'] if (self.use_epsilon): # if score improvement is less than epsilon, # don't add the new model and stop score_diff = ens_score - last_ens_score if (score_diff < self.epsilon): break new_model_idx = new_scores[0]['new_model_idx'] ensemble.update({new_model_idx: 1}) _, ens_probs = self._score_with_model(db_conn, y, y_bin, ens_probs, ens_count, new_model_idx) if (not self.use_epsilon): # store current ensemble to select best later ens_copy = Counter(ensemble) cand = {'ens': ens_copy, 'score': ens_score} cand_ensembles.append(cand) ens_count = sum(ensemble.values()) if (self.verbose): if ((ens_count - self.n_best) % 8 == 0): sys.stderr.write("\n ") msg = '%02d/%.3f ' % (ens_count, ens_score) sys.stderr.write(msg) if (self.verbose): sys.stderr.write('\n') if (not self.use_epsilon and ens_count == self.max_models): cand_ensembles.sort(key=lambda x: x['score'], reverse=True) ensemble = cand_ensembles[0]['ens'] return ensemble def _get_best_model(self, curs): """perform query for best scoring model""" select_stmt = """select model_idx, pickled_model from models where model_idx = (select model_idx from model_scores order by score desc limit 1)""" curs.execute(select_stmt) row = curs.fetchone() return row[0], loads(str(row[1])) def best_model(self): """Returns best model found after CV scoring""" db_conn = sqlite3.connect(self.db_file) _, model = self._get_best_model(db_conn.cursor()) db_conn.close() return model def _print_best_results(self, curs, best_model_score): """Show best model and score""" sys.stderr.write('Best model CV score: %.5f\n' % best_model_score) _, best_model = self._get_best_model(curs) sys.stderr.write('Best model: %s\n\n' % repr(best_model)) def build_ensemble(self, X, y, rescore=True): """Generate bagged ensemble""" self._n_classes = len(np.unique(y)) db_conn = sqlite3.connect(self.db_file) curs = db_conn.cursor() # binarize if (self._n_classes > 2): y_bin = LabelBinarizer().fit_transform(y) else: y_bin = np.column_stack((1-y, y)) # get CV scores for fitted models if (rescore): self._score_models(db_conn, X, y, y_bin) # get number of best models to take n_models = int(self._n_models * (1.0 - self.prune_fraction)) bag_size = int(self.bag_fraction * n_models) if (self.verbose): sys.stderr.write('%d models left after pruning\n' % n_models) sys.stderr.write('leaving %d candidates per bag\n\n' % bag_size) # get indices and scores from DB select_stmt = """select model_idx, score from model_scores order by score desc limit %d""" curs.execute(select_stmt % n_models) ranked_model_scores = [(r[0], r[1]) for r in curs.fetchall()] # print best performing model results best_model_score = ranked_model_scores[0][1] if (self.verbose): self._print_best_results(curs, best_model_score) sys.stderr.write("Ensemble scores for each bag (size/score):\n") ensembles = [] # make bags and ensembles rs = check_random_state(self.random_state) for i in xrange(self.n_bags): # get bag_size elements at random cand_indices = rs.permutation(n_models)[:bag_size] # sort by rank candidates = [ranked_model_scores[ci][0] for ci in cand_indices] if (self.verbose): sys.stderr.write('Bag %02d): ' % (i+1)) # build an ensemble with current candidates ensemble = self._ensemble_from_candidates(db_conn, candidates, y, y_bin) ensembles.append(ensemble) # combine ensembles from each bag for e in ensembles: self._ensemble += e # push to DB insert_stmt = "insert into ensemble(model_idx, weight) values (?, ?)" with db_conn: val_gen = ((mi, w) for mi, w in self._ensemble.most_common()) db_conn.executemany(insert_stmt, val_gen) if (self.verbose): score, _ = self._get_ensemble_score(db_conn, self._ensemble, y, y_bin) fmt = "\nFinal ensemble (%d components) CV score: %.5f\n\n" sys.stderr.write(fmt % (sum(self._ensemble.values()), score)) db_conn.close() def _model_predict_proba(self, X, model_idx=0): """Get probability predictions for a model given its index""" db_conn = sqlite3.connect(self.db_file) curs = db_conn.cursor() select_stmt = """select pickled_model from fitted_models where model_idx = ? and fold_idx = ?""" # average probs over each n_folds models probs = np.zeros((len(X), self._n_classes)) for fold_idx in xrange(self.n_folds): curs.execute(select_stmt, [model_idx, fold_idx]) res = curs.fetchone() model = loads(str(res[0])) probs += model.predict_proba(X)/float(self.n_folds) db_conn.close() return probs def best_model_predict_proba(self, X): """Probability estimates for all classes (ordered by class label) using best model""" db_conn = sqlite3.connect(self.db_file) best_model_idx, _ = self._get_best_model(db_conn.cursor()) db_conn.close() return self._model_predict_proba(X, best_model_idx) def best_model_predict(self, X): """Predict class labels for samples in X using best model""" return np.argmax(self.best_model_predict_proba(X), axis=1) def predict_proba(self, X): """Probability estimates for all classes (ordered by class label)""" n_models = float(sum(self._ensemble.values())) probs = np.zeros((len(X), self._n_classes)) for model_idx, weight in self._ensemble.items(): probs += self._model_predict_proba(X, model_idx) * weight/n_models return probs def predict(self, X): """Predict class labels for samples in X.""" return np.argmax(self.predict_proba(X), axis=1)
{ "repo_name": "irwenqiang/pyensemble", "path": "ensemble.py", "copies": "3", "size": "23046", "license": "bsd-3-clause", "hash": 3291129969768070000, "line_mean": 33.0413589365, "line_max": 79, "alpha_frac": 0.5419161677, "autogenerated": false, "ratio": 4.009394572025053, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6051310739725052, "avg_score": null, "num_lines": null }
import gc, cPickle as pickle, weakref, sys, traceback # # Method 1: use weak ref to track new live objects # Advantages: we have live pointers to the new live objects. And fast # Drawbacks: doesn't track many types (such as list, dict, etc.) but # generally this is not a problem because: if they contain # sub-objects, these objects might most probably be track-able # class RefTracker(object): """ The scan() method will apply the given callback to the list of new objects created since last call to scan() (or since the construction, for the 1st time). """ def __init__(self): self._not_tracked_types = set() self._current_refs = dict() self.scan() def _get_objects(self): return gc.get_objects() def _scan(self, callback_new_object): """ This is NOT MT-safe and will not work for most builtin types """ objs = self._get_objects() # First: remove the objects that are not available anymore to_remove = [] for oid, ref in self._current_refs.iteritems(): if ref() is None: to_remove.append(oid) for oid in to_remove: del self._current_refs[oid] del to_remove # Create the list of objects that are brand new: for obj in objs: try: my_ref = self._current_refs[id(obj)] # The object was already recorded last time. # If the recorded object were not the current one, # it would mean that the recorded object had been # deallocated... this is caught by the previous loop # # Do some sanity checks, just to make sure: assert my_ref() is not None assert my_ref() == obj except KeyError: # This is a new object. Try to make a weak-ref out of it: try: wref = weakref.ref(obj) except TypeError: # Track only weak-ref-friendly objects, remember # the types of the objects we couldn't weak-reference: self._not_tracked_types.add(str(type(obj))) continue # Ok, good, we have a weak ref. Record it: self._current_refs[id(obj)] = wref # We also want to know that it's a new thing try: if callback_new_object: callback_new_object(obj) del obj except: traceback.print_exc() def scan(self, callback_new_object = None): """Call the callback on each new object""" # We need this in order to free the refs still held # by _scan due to the callback (approx explanation...) gc.collect() self._scan(callback_new_object) gc.collect() @property def not_tracked_types(self): """Return the list of type names of the objects that could not be tracked""" return self._not_tracked_types @staticmethod def _print_new_obj(obj): """Callback used by scan_and_print_new_objs""" print "New obj:", repr(obj) def scan_and_print_new_objs(self, msg = None): # Print list of new objs, making sure that the list is # correctly garbage-collected by the GC print "\n# -- %s:" % (msg or "New objects") self.scan(self._print_new_obj) print "# ---------------\n" # # Method 2: Keep track of the garbage list # Advantages: we have live pointers to the new live objects. And fast # Drawbacks: will only show the object /after/ the GC had tried to # reclaim them, not as soon as they have been # creaded. Still useful to debug leaks... But: are we sure # that lost objects are only found in cycles ??? Same # type restrictions as for method 1 ??? # class GarbageTracker(RefTracker): def _get_objects(self): return gc.garbage # # Method 3: approximate method storing signatures of objects to a file # and comparing the signatures. The signature consist of a pair # object id / str(type(obj)) # Advantages: all object types can potentially be tracked. Can allow # basic offline analysis # Drawbacks: might not see some new objects if they are at the same address # as previous ones having the same signature. Slow # first_time = True def make_gc_snapShot(filename, name): """Append the signatures to a file, giving them the given 'name'. A signature is a pair object_id / type_name""" global first_time if first_time: gc.collect() first_time = False contents = [] for o in gc.get_objects(): try: tname = o.__class__.__name__ except AttributeError: tname = str(type(o)) contents.append((id(o), tname)) del tname f = open(filename, 'a') pickle.dump((name, contents), f) f.close() del contents del f class GCSnapshot(object): """Used to read a set of signatures from the file""" def __init__(self, stream): self.name, contents = pickle.load(stream) self._contents = set(contents) def __sub__(self, other): """Give the differences between 2 sets of signatures. Return a set of pairs object_id / type_name""" return self._contents - other._contents def reach(self, ids): """ \param ids Iterable of object id, as returned by x[0], with x in the result of (snapshot2 - snapshot1) Return a dict id -> object with that id currently known. The objects recorded with these id might have been replaced by new ones... so we might end-up seeing objects that don't correspond to the original ones. This is especially true after a gc.collect() """ result = dict() for obj in gc.get_objects(): if id(obj) in ids: result[id(obj)] = obj return result def read_snapshots(filename): """Sequentially reads the sets of signatures from a file. For each set of signatures, a GCSnapshot is created with the stored name. return the dict set name -> GCSnapshot object""" result = dict() f = open(filename, 'r') while 1: try: snap = GCSnapshot(f) result[snap.name] = snap except (EOFError, pickle.UnpicklingError): break f.close() return result #### BEGIN: ONLY FOR THE TESTS class Dummy: def __init__(self): print "INFO: ctor", self def __del__(self): print "INFO: dtor", self # A pair of mutually-referencing objects with __del__ methods # See http://docs.python.org/library/gc.html#gc.garbage # for an explanation why they are not automatically reclaimable class ObjectReferencer: def __init__( self, obj ): print "INFO: ctor", self self.reference = obj def __del__(self): print "INFO: dtor", self class ReferencerCreator: def __init__( self ): print "INFO: ctor", self self.attribute = ObjectReferencer( self ) def __del__(self): print "INFO: dtor", self def break_cycle(self): # Necessary to break the cycle that prevents the GC from # doing its job print "INFO: break_cycle", self self.attribute = None def _test1(): """Tests for method 1 (RefTracker)""" print "*** Method 1 (RefTracker) ***" r = RefTracker() d = Dummy() print "del dummy now..." del d r.scan_and_print_new_objs("After creation/del of Dummy()") # Contains a cycle: will not be freed by GC... o = ReferencerCreator() print "del obj now..." del o r.scan_and_print_new_objs("After creation/del of ReferencerCreator") # The same, but we break the cycle o = ReferencerCreator() print "break_cycle now..." o.break_cycle() print "del obj now..." del o r.scan_and_print_new_objs("After creation/break_cycle/del of ReferencerCreator") print "Types not tracked:" for typ in r.not_tracked_types: print " %s" % typ print "End of test method 1." def _test2(): """Tests for method 2 (GarbageTracker)""" print "*** Method 2 (GarbageTracker) ***" r = GarbageTracker() d = Dummy() print "del dummy now..." del d r.scan_and_print_new_objs("After creation/del of Dummy()") # Contains a cycle: will not be freed by GC... o = ReferencerCreator() print "del obj now..." del o r.scan_and_print_new_objs("After creation/del of ReferencerCreator") # The same, but we break the cycle o = ReferencerCreator() print "break_cycle now..." o.break_cycle() print "del obj now..." del o r.scan_and_print_new_objs("After creation/break_cycle/del of ReferencerCreator") print "Types not tracked:" for typ in r.not_tracked_types: print " %s" % typ print "End of test method 2." def _test3(): """Tests for method 3 (compare signatures)""" import os print "*** Method 3 (compare signatures) ***" fname = "/tmp/gc-%s-snapshot" % os.environ["USER"] make_gc_snapShot(fname, "0") make_gc_snapShot(fname, "1") l = list() l.append(l) make_gc_snapShot(fname, "2") l.append(42) t = ReferencerCreator() make_gc_snapShot(fname, "3") # Now analyzing snaps = read_snapshots(fname) os.remove(fname) print "Between 2 and 1, diff is:" diff21 = snaps["2"] - snaps["1"] for d in diff21: print " ", d print "Between 2 and 1, diff as live objects is:" for obj in snaps["3"].reach([d[0] for d in diff21]).itervalues(): print " ", obj print "Between 3 and 2, diff is:" diff32 = snaps["3"] - snaps["2"] for d in diff32: print " ", d print "Between 3 and 2, diff as live objects is:" for obj in snaps["3"].reach([d[0] for d in diff32]).itervalues(): print " ", obj print "Between 3 and 1, diff is:" diff31 = snaps["3"] - snaps["1"] for d in diff31: print " ", d print "Between 3 and 1, diff as live objects is:" for obj in snaps["3"].reach([d[0] for d in diff31]).itervalues(): print " ", obj print "End of test method 3." #### END: ONLY FOR THE TESTS if __name__ == "__main__": _test1() _test2() _test3() print "Bye."
{ "repo_name": "ActiveState/code", "path": "recipes/Python/576523_Track_newunreclaimed_objects_between_2_points/recipe-576523.py", "copies": "1", "size": "10702", "license": "mit", "hash": -7523518174625081000, "line_mean": 29.9306358382, "line_max": 84, "alpha_frac": 0.5851242758, "autogenerated": false, "ratio": 3.83584229390681, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.492096656970681, "avg_score": null, "num_lines": null }
import sys, os, threading, Queue, itertools, traceback, select, struct import cPickle as pickle # Only for SimpleChannelEndpoint __all__ = ["Mux", "DeMux", "ChannelPair"] ## Magic token to mark the end of job submission by the DeMux SENTINEL = "QUIT" def is_sentinel(obj): """Predicate True when a DeMux worker thread receives a "terminate" order from the DeMux""" return type(obj) is str and obj == SENTINEL class ReceiverThread(threading.Thread): """Generic wrapper class to wait for data from a channel: handle_message() is called for each data received. Provides a stop() method to stop receiving the data. This is a thread object: call start() to start it""" def __init__(self, channel, *args, **kwds): """ \param channel is a Channel endpoint (fileno/recv/close methods expected) """ threading.Thread.__init__(self, *args, **kwds) self._channel = channel self.__terms = os.pipe() self._recv = channel.recv self._send = channel.send def run(self): """ Wait for either a call to stop() or for a data to be available on the channel and then call handle_message. And loop over. """ # Initialize poll() fd = self._channel.fileno() waitset = select.poll() eventmask = select.POLLIN | select.POLLERR \ | select.POLLHUP | select.POLLPRI waitset.register(fd, eventmask) waitset.register(self.__terms[0], eventmask) while 1: exit_loop = False for fd_, evt in waitset.poll(): if fd_ != fd: # Received sthg on the __terms pipe exit_loop = True break if evt != select.POLLIN: # Receive something on the channel, but not a normal # data (probably a HUP) exit_loop = True break if exit_loop: break # Error while receiving => term thread data = self._recv() # Call handle_message (dump the exceptions, but ignore them) try: self.handle_message(data) except: traceback.print_exc() # End while def handle_message(self, message): """Method to override: called each time a message is received""" raise NotImplementedError("Children classes expected to override it") def stop(self): """Stop receiving data. Waits until the thread is terminated. DO NOT CALL THIS from inside handle_message()""" os.write(self.__terms[1], "TERMINATION") self._channel.close() self.join() class Mux(ReceiverThread): """Thread that multiplexes calls to the transaction() method on the given channel""" def __init__(self, channel): """ \param channel is a Channel endpoint (fileno/recv/close methods expected) """ ReceiverThread.__init__(self, channel) self.__lock = threading.Lock() self.__waitq = dict() self.__idgen = itertools.count(42) def transaction(self, *args, **kwds): """Call this method to send the given args on the wire and wait for a response""" evt = threading.Event(self.__lock) # Allocate a transaction ID self.__lock.acquire() try: xid = self.__idgen.next() assert xid not in self.__waitq self.__waitq[xid] = [evt, None] # If except: means MUX stopped except AttributeError: raise EOFError("MUX has been stopped.") finally: self.__lock.release() # Send the request self._send((xid, args, kwds)) # Wait for the answer evt.wait() # Return the answer/raise the exception to the caller self.__lock.acquire() try: # Retrieve the result try: result = self.__waitq[xid][1] except (AttributeError, IndexError): raise EOFError("MUX has been stopped.") except: print "EX", self.__waitq # Work done del self.__waitq[xid] # Reformat the result xid_, result_ = result assert xid_ == xid, \ "Expected txn id %s != received (%s)" % (xid, xid_) status, details = result_ if status == "OK": return details elif status == "EXCEPTION": raise details else: raise RuntimeError("Invalid status %s !" % repr(status)) return result finally: self.__lock.release() def run(self): """Listen to the messages coming from the endpoint and dispatch them to the threads which sent them""" try: ReceiverThread.run(self) except: traceback.print_exc() # If we're here, it means that a stop has been requested: # unblock _all_ the waiting caller threads and force them # to fail in transaction() self.__lock.acquire() try: for xid, slot in self.__waitq.iteritems(): del slot[1] # Force IndexError on the waiting threads slot[0].set() del self.__waitq # Force AttributeError on next transaction() finally: self.__lock.release() def handle_message(self, msg): """Needed by the ReceiverThread object: dispatch the messages to the caller threads""" xid, result = msg self.__lock.acquire() try: slot = self.__waitq[xid] slot[1] = msg slot[0].set() # wake up the caller thread finally: self.__lock.release() class DeMux(ReceiverThread): """Thread that demultiplexes transactions coming from a multiplexer, and calls process_transaction() for each of them. The transactions are processed in parallel in different worker threads. The worker threads are either consisting in a pool of threads (when nworkers is not None), or are created on-demand when requests arrive (when nworkers is None)""" __lock = None # Lock object __workq = None # Queue object or None (in on-demand mode) __nworkers = None # Specified size of the pool of threads __workers = None # Either a list of threads (pool) or a dict xid->thread # (in on-demand mode) def __init__(self, channel, nworkers = None): """ \param channel is a Channel endpoint (fileno/recv/close methods expected) \param nworkers (integer) number of threads in the pool able to process the transaction requests, or None when threads have to be created on demand """ ReceiverThread.__init__(self, channel) self.__nworkers = nworkers self.__lock = threading.Lock() if nworkers is not None: self.__workers = [] self.__workq = Queue.Queue() for idworker in range(nworkers): thr = threading.Thread(target=self._pool_work) self.__workers.append(thr) thr.start() else: self.__workers = dict() def handle_message(self, msg): """Required by ReceiverThread""" xid, args, kwds = msg if self.__nworkers is not None: # In pool mode: send the job to the pool self.__workq.put((xid, args, kwds)) else: # In on-demand mode: spawn a new thread to do the job thr = threading.Thread(target=self._do_process_transaction, args=(xid,)+args, kwargs=kwds) # Register the thread for this transaction self.__lock.acquire() try: self.__workers[xid] = thr finally: self.__lock.release() try: thr.start() except: # Oops, cannot start worker... self.__lock.acquire() try: del self.__workers[xid] finally: self.__lock.release() # Sending exception back to sender ex = sys.exc_info()[1] if ex is not None: ex._trace = traceback.format_exc() else: ex = sys.exc_info()[0] self._send((xid, ("EXCEPTION", ex))) def _pool_work(self): """Method run by the pool worker threads in pool mode""" while 1: # Simply consume the jobs from the queue until we get the # sentinel token data = self.__workq.get() if is_sentinel(data): break xid, args, kwds = data # Will raise exception ONLY when connection problems: self._do_process_transaction(xid, *args, **kwds) def _do_process_transaction(self, xid, *args, **kwds): """Method run by the worker threads to process one transaction""" # Call process_transaction and prepare the result to send result = None try: result = ("OK", self.process_transaction(*args, **kwds)) except Exception, ex: ex._trace = traceback.format_exc result = ("EXCEPTION", ex) except: ex = sys.exc_info()[1] if ex is not None: ex._trace = traceback.format_exc() else: ex = sys.exc_info()[0] result = ("EXCEPTION", ex) finally: if result is None: ex = RuntimeError("Unexpected error !") result = ("EXCEPTION", ex) # Send response self._send((xid, result)) # Unregister the thread in on-demand mode if self.__nworkers is None: self.__lock.acquire() try: # In on-demand mode: unregister the thread for this transaction del self.__workers[xid] finally: self.__lock.release() def process_transaction(self, *args, **kwds): """Implement this method in order to generate a response from the given transaction arguments""" raise NotImplementedError("Children must implement this method") def stop(self): """Stop the worker threads and close the channel""" ReceiverThread.stop(self) # # No lock because the listening thread is dead already (no new # thread) # # Clearing job queue if self.__workq is not None: while 1: try: self.__workq.get_nowait() except Queue.Empty: break # Stopping workers if self.__nworkers is not None: for i in range(self.__nworkers): self.__workq.put(SENTINEL) for thr in self.__workers: thr.join() else: while self.__workers: xid, thr = self.__workers.popitem() thr.join() class SimpleChannelEndpoint: """Construct a channel compliant with the channel specifications from a pair of r/w file descriptors""" SZI = struct.calcsize('I') def __init__(self, fd_r, fd_w): """ \param r,w The read-write file descriptors used for this endpoint """ self._fd_r = fd_r self._fd_w = fd_w self._wlock = threading.Lock() # send() has to be thread-safe def fileno(self): """Return a file descriptor suitable for select/poll of data ready to be received in non-blocking mode (at least for the first byte)""" return self._fd_r def send(self, data): """send the given python data to the receiving party""" sdata = pickle.dumps(data) sdata = struct.pack('I', len(sdata)) + sdata self._wlock.acquire() try: os.write(self._fd_w, sdata) finally: self._wlock.release() def recv(self): """wait for python data from the sending party and return it""" (expected,) = struct.unpack('I', os.read(self._fd_r, self.SZI)) sdata = "" while 1: sdata += os.read(self._fd_r, expected - len(sdata)) assert len(sdata) <= expected if len(sdata) == expected: break return pickle.loads(sdata) def close(self): """close the endpoint in both send/receive directions""" self._wlock.acquire() try: os.close(self._fd_w) finally: self._wlock.release() os.close(self._fd_r) def ChannelPair(): """Very simple function returning a connected pair of channels""" r1, w2 = os.pipe() r2, w1 = os.pipe() return ( SimpleChannelEndpoint(r1, w1), SimpleChannelEndpoint(r2, w2) ) def _test(): """ Some tests """ import time, thread c1, c2 = ChannelPair() mux = Mux(c1) class MyDeMux(DeMux): """A demultiplexer in which each transaction is a call to sleep()""" def process_transaction(self, message_before, duration, message_after): """One trasaction is just a call to sleep""" print "[%d] BEGIN: %s (sleep %fs)" % (thread.get_ident(), message_before, duration) time.sleep(duration) print "[%d] END: %s" % (thread.get_ident(), message_after) class Submitter(threading.Thread): """A thread that submits 3 transactions to the mux object""" def run(self): """Submit 3 transactions and stop""" mux.transaction("msg1", 3, "msg2") mux.transaction("msg3", 2, "msg4") mux.transaction("msg5", 1, "msg6") try: mux.transaction("msgE", -1, "msgEE") except IOError, ex: print "Got expected exception from the DeMux: %s" % repr(ex) demux = MyDeMux(c2, 100) # demux = MyDeMux(c2) # Starting mux/demux mux.start() demux.start() # Starting as many threads that run transactions as possible children = [] for i in range(700): thr = Submitter() try: thr.start() children.append(thr) except: break print "Started %d submission threads" % len(children) # Waiting for the children for thr in children: try: thr.join() except KeyboardInterrupt: print "User interruption." break # Stopping mux/demux mux.stop() demux.stop() print "Bye." if __name__ == "__main__": _test()
{ "repo_name": "ActiveState/code", "path": "recipes/Python/576520_Multithreaded_MultiplexerDemultiplexer_allow/recipe-576520.py", "copies": "1", "size": "17495", "license": "mit", "hash": -6981440086778933000, "line_mean": 33.7813121272, "line_max": 79, "alpha_frac": 0.5636467562, "autogenerated": false, "ratio": 4.374843710927732, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5438490467127732, "avg_score": null, "num_lines": null }
__author__ = 'daviddemaris' import os import sys CWD = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(CWD, '..')) import csv escapes = ''.join([chr(char) for char in range(16, 17)]) def generateAimlFromSimpleCSV(csvData): aimlFile = '<?xml version="1.0" encoding="ISO-8859-1"?>\n' aimlFile += '<aiml>\n' state = 'init' temp_random = [] srai = [] currentMeaning = '' currentPattern = '' def processInPatternState(category, aimlFile): # build template from random, think if len(temp_random) > 1: randomString = ' <random> \n' for li in temp_random: li = li.strip() # spurious star pairs are put in during aiml2csv by bs4, strip # back to singleton randomString = randomString.replace('<star></star>', '<star/>') randomString = randomString + ' <li> ' + li + ' </li>\n' randomString = randomString + ' </random>\n' else: # single random element found so no random, li tags randomString = str(temp_random[0]).strip() # spurious star pairs are put in during aiml2csv by bs4, strip back # to singleton randomString = randomString.replace('<star></star>', '<star/>') # # spurious star pairs are put in during aiml2csv by bs4, strip back to singleton slots['Think'] = slots['Think'].replace('<star></star>', '<star/>') slots['Template'] = randomString + slots['Think'] category = category.replace("XPATTERN", slots['Pattern']) # in case that has no * if slots['That'] != '*': category = category.replace("XTHAT", slots['That']) else: category = category.replace('<that>', '') category = category.replace('</that>\n', '') # slots['That'].replace('*','') category = category.replace("XTHAT", '') category = category.replace("XTEMPLATE", slots['Template']) category = category.replace("XTOPIC", slots['Topic']) aimlFile += category # write out any accumulated srai for red in srai: category = " <category>\n <pattern>XPATTERN</pattern>\n <template>XTEMPLATE</template>\n </category>\n" # need to get rid of random and li tags from template #category = category.replace("XPATTERN",'<srai>'+red+'</srai>') category = category.replace("XPATTERN", red) category = category.replace( "XTEMPLATE", '<srai>' + slots['Pattern'] + '</srai>') # print 'reduce', red # print 'category', category aimlFile += category return aimlFile # in pattern for row in csvData: if row['Meaning'] != currentMeaning: if ('Meaning' in row) and row['Meaning'] != "": currentMeaning = row['Meaning'] # put first template # temp_random.append(row['Meaning']) category = " <category>\n <pattern>XPATTERN</pattern>\n <that>XTHAT</that>\n <template>XTEMPLATE</template>\n </category>\n" if state == 'init': state = 'inPattern' elif state == 'inPattern': # hit next meaning so create category of single and srais # pointing to it aimlFile = processInPatternState(category, aimlFile) temp_random = [] srai = [] # put first template # temp_random.append(row['Meaning']) # regardless of state, having written out last pattern or not, # initialize and read current row slots = {} slots['Pattern'] = "*" slots['That'] = "*" slots['Template'] = "" slots['Topic'] = "*" slots['Think'] = "" slots['Pattern'] = currentMeaning # temp_random=[] # srai=[] if (row['Human_says'] != ""): srai.append(row['Human_says']) # keep these around in case we put syntactic sugar in columns to recover this aiml expression #if (('That' in row ) and (row['That']!="")): slots['That']=row['That'] # assume template may be first of random #if (('Topic' in row ) and (row['Topic']!="")): slots['Topic']=row['Topic'] # f (('Think' in row ) and (row['Think']!="")): slots['Think']=row['Think'] # if ('Meaning' in row) and (row['Meaning'])!="": # slots['Pattern']==row['Meaning'] if (('Robot_says' in row) and (row['Robot_says'] != "")): temp_random.append(row['Robot_says'].replace('#Comma', ",")) # write out accumulated data for last category aimlFile = processInPatternState(category, aimlFile) aimlFile += "</aiml>" aimlFile = aimlFile.translate(None, escapes) return aimlFile def generateAimlFromLongCSV(csvData): aimlFile = '<?xml version="1.0" encoding="ISO-8859-1"?>\n' aimlFile += '<aiml>\n' state = 'init' temp_random = [] srai = [] def processInPatternState(category, aimlFile): # build template from random, think if len(temp_random) > 1: randomString = ' <random> \n' for li in temp_random: li = li.strip() # spurious star pairs are put in during aiml2csv by bs4, strip # back to singleton randomString = randomString.replace('<star></star>', '<star/>') randomString = randomString + ' <li> ' + li + ' </li>\n' randomString = randomString + ' </random>\n' else: # single random element found so no random, li tags randomString = str(temp_random[0]).strip() # spurious star pairs are put in during aiml2csv by bs4, strip back # to singleton randomString = randomString.replace('<star></star>', '<star/>') # # spurious star pairs are put in during aiml2csv by bs4, strip back to singleton slots['Think'] = slots['Think'].replace('<star></star>', '<star/>') slots['Template'] = randomString + slots['Think'] category = category.replace("XPATTERN", slots['Pattern']) # in case that has no * if slots['That'] != '*': category = category.replace("XTHAT", slots['That']) else: category = category.replace('<that>', '') category = category.replace('</that>\n', '') # slots['That'].replace('*','') category = category.replace("XTHAT", '') category = category.replace("XTEMPLATE", slots['Template']) category = category.replace("XTOPIC", slots['Topic']) aimlFile += category # write out any accumulated srai for red in srai: category = " <category>\n <pattern>XPATTERN</pattern>\n <template>XTEMPLATE</template>\n </category>\n" # need to get rid of random and li tags from template #category = category.replace("XPATTERN",'<srai>'+red+'</srai>') category = category.replace("XPATTERN", red) category = category.replace( "XTEMPLATE", '<srai>' + slots['Pattern'] + '</srai>') # print 'reduce', red # print 'category', category aimlFile += category return aimlFile # in pattern for row in csvData: # three row types pattern, alt (element of random list tag in template), srai # pattern triggers start of new category # append templates to list, append srais to a list, if row['Type'] == 'pattern': category = " <category>\n <pattern>XPATTERN</pattern>\n <that>XTHAT</that>\n <template>XTEMPLATE</template>\n </category>\n" if state == 'init': state = 'inPattern' elif state == 'inPattern': aimlFile = processInPatternState(category, aimlFile) # regardless of state, having written out last pattern or not, # initialize and read current row slots = {} slots['Type'] = "*" slots['Pattern'] = "*" slots['That'] = "*" slots['Template'] = "" slots['Topic'] = "*" slots['Think'] = "" temp_random = [] srai = [] if (row['Pattern'] != ""): slots['Pattern'] = row['Pattern'] if (('That' in row) and (row['That'] != "")): slots['That'] = row['That'] # assume template may be first of random if (('Template' in row) and (row['Template'] != "")): temp_random.append(row['Template'].replace("#Comma", ",")) if (('Topic' in row) and (row['Topic'] != "")): slots['Topic'] = row['Topic'] if (('Think' in row) and (row['Think'] != "")): slots['Think'] = row['Think'] if row['Type'] == 'alt' or row['Type'] == "": if (('Template' in row) and (row['Template'] != "")): temp_random.append(row['Template']) # use if row['Type'] == 'srai': if state == 'inPattern': # maybe should store tuple or pattern.template string if (('Template' in row) and (row['Template'] != "")): srai.append(row['Pattern']) # write out accumulated data for last category aimlFile = processInPatternState(category, aimlFile) aimlFile += "</aiml>" aimlFile = aimlFile.translate(None, escapes) return aimlFile # test if __name__ == '__main__': # logging.basicConfig() # logger=logging.getLogger().setLevel(logging.DEBUG) # open long csv file """ longtest=csv.DictReader(open('../character_aiml/sophia-personality.invert.csv','r')) aiml=generateAimlFromLongCSV(longtest) ftest=open('../character_aiml/sophia-personality.invert.xml','w') print >>ftest,aiml ftest.close() """ simpletest = csv.DictReader(open('../character_aiml/convoid419.csv', 'r')) aiml = generateAimlFromSimpleCSV(simpletest) ftest = open('../character_aiml/convoid419.invert.xml', 'w') print >>ftest, aiml ftest.close()
{ "repo_name": "hansonrobotics/chatbot", "path": "src/chatbot/server/csvUtils.py", "copies": "1", "size": "10342", "license": "mit", "hash": -3376764262327670300, "line_mean": 40.368, "line_max": 139, "alpha_frac": 0.5409011797, "autogenerated": false, "ratio": 3.993050193050193, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5033951372750193, "avg_score": null, "num_lines": null }
import random import threading import time from avatar2.message import RemoteMemoryReadMessage, BreakpointHitMessage, UpdateStateMessage from avatar2.targets import Target, TargetStates class _TargetThread(threading.Thread): """Thread that mimics a running target""" def __init__(self, target): threading.Thread.__init__(self) self.target = target self.please_stop = False self.steps = 0 def run(self): self.please_stop = False # Loops until someone (the Dummy Target) tells me to stop by # externally setting the "please_stop" variable to True while not self.please_stop: self.target.log.info("Dummy target doing Nothing..") time.sleep(1) self.steps += 1 # 10% chances of triggering a breakpoint if random.randint(0, 100) < 10: # If there are not breakpoints set, continue if len(self.target.bp) == 0: continue # Randomly pick one of the breakpoints addr = random.choice(self.target.bp) self.target.log.info("Taking a break..") # Add a message to the Avatar queue to trigger the # breakpoint self.target.avatar.queue.put(BreakpointHitMessage(self.target, 1, addr)) break # 90% chances of reading from a forwarded memory address else: # Randomly pick one forwarded range mem_range = random.choice(self.target.mranges) # Randomly pick an address in the range addr = random.randint(mem_range[0], mem_range[1] - 4) # Add a message in the Avatar queue to read the value at # that address self.target.avatar.queue.put(RemoteMemoryReadMessage(self.target, 55, addr, 4)) self.target.log.info("Avatar told me stop..") class DummyTarget(Target): """ This is a Dummy target that can be used for testing purposes. It simulates a device that randomly reads from forwarded memory ranges and triggers breakpoints. """ def __init__(self, avatar, **kwargs): super(DummyTarget, self).__init__(avatar, **kwargs) # List of breakpoints self.bp = [] # List of forwarded memory ranges self.mranges = [] self.thread = None # Avatar will try to answer to our messages (e.g., with the value # the Dummy Target tries to read from memory). To handle that # we need a memory protocol. However, here we set the protocol to # ourself (its a dirty trick) and later implement the sendResponse # method self.protocols.remote_memory = self # This is called by Avatar to initialize the target def init(self): self.log.info("Dummy Target Initialized and ready to rock") # Ack. It should actually go to INITIALIZED but then the protocol # should change that to STOPPED self.avatar.queue.put(UpdateStateMessage(self, TargetStates.STOPPED)) # We fetch from Avatar the list of memory ranges that are # configured to be forwarded for mem_range in self.avatar.memory_ranges: mem_range = mem_range.data if mem_range.forwarded: self.mranges.append((mem_range.address, mem_range.address + mem_range.size)) self.wait() # If someone ones to read memory from this target, we always return # the same value, no matter what address it is requested def read_memory(*args, **kwargs): return 0xdeadbeef # This allow Avatar to answer to our memory read requests. # However, we do not care about it def send_response(self, id, value, success): if success: self.log.debug("RemoteMemoryRequest with id %d returned 0x%x" % (id, value)) else: self.log.warning("RemoteMemoryRequest with id %d failed" % id) # We let Avatar writes to our memory.. well.. at least we let it # believe so def write_memory(self, addr, size, val, *args, **kwargs): return True # We keep tracks of breakpoints def set_breakpoint(self, line, hardware=False, temporary=False, regex=False, condition=None, ignore_count=0, thread=0): self.bp.append(line) def remove_breakpoint(self, breakpoint): # FIXME.. how do you remove a breakpoint? # sle.bp.remove(breakpoint) does not work pass # def wait(self): # self.thread.join() def cont(self): if self.state != TargetStates.RUNNING: self.avatar.queue.put(UpdateStateMessage(self, TargetStates.RUNNING)) self.thread = _TargetThread(self) self.thread.daemon = True self.thread.start() def get_status(self): if self.thread: self.status.update({"state": self.state, "steps": self.thread.steps}) else: self.status.update({"state": self.state, "steps": '-'}) return self.status # Since we set the memory protocol to ourself, this is important to avoid # an infinite recursion (otherwise by default a target would call # shutdown to all its protocols) def shutdown(self): pass def stop(self): if self.state == TargetStates.RUNNING: self.thread.please_stop = True self.avatar.queue.put(UpdateStateMessage(self, TargetStates.STOPPED)) return True
{ "repo_name": "avatartwo/avatar2", "path": "avatar2/targets/dummy_target.py", "copies": "1", "size": "5675", "license": "apache-2.0", "hash": -6352372475709813000, "line_mean": 38.1379310345, "line_max": 112, "alpha_frac": 0.6155066079, "autogenerated": false, "ratio": 4.250936329588015, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5366442937488015, "avg_score": null, "num_lines": null }
__author__ = 'davidebest' from scrapy.spider import Spider from scrapy.selector import Selector from scrapy.http import Request import urlparse import re import lxml import datetime import sys sys.path.append('/vagrant/localharvest') from items import LocalharvestItem, PickupPoint import phonenumbers class LocalHarvestSpider(Spider): name = "CodeForDayton" allowed_domains = ["localharvest.org"] start_urls = [ "http://www.localharvest.org/search.jsp?jmp&scale=9&lat=39.758948&lon=-84.191607&ty=6&p=1", "http://www.localharvest.org/search.jsp?jmp&scale=9&lat=39.758948&lon=-84.191607&ty=6&p=2" ] download_delay = 2 def parse(self, response): sel = Selector(response) links = sel.css('#content h4.inline a').xpath('@href').extract() link_req_objs = [Request(url="http://www.localharvest.org" + link, callback=self.extract) for link in links] return link_req_objs def extract(self, response): """ Takes the data out of the pages at http://www.localharvest.org/csa/* """ sel = Selector(response) pickupPoints = [] item = LocalharvestItem() pickupPoint = PickupPoint() item['name'] = sel.css('#listingbody h1 a').xpath('text()').extract()[0] item['description'] = sel.css('.textBlock p').xpath('text()').extract()[0].strip() item['data_source_url'] = response.url item['website'] = 'www.localharvest.org' item['retrieved_on'] = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y") # Get the CSA details csa_details = sel.xpath("/html[@id='csagroup']/body/div[@id='container']/div[@id='contentwrapper']/div[@id='leftcontentwrapper']/div[@id='content']/div[@id='listingbody']/div[2]/div[@class='panel fullwidth']") #season xpathVar = csa_details.xpath("//div[@class='fullwidth']/div[@class='col two-thirds']/p/span[@class='inlineblock']/b[text()='Season:']/parent::span/following-sibling::span/text()") if xpathVar: item['season'] = xpathVar.extract()[0] #csa_type xpathVar = csa_details.xpath("//div[@class='fullwidth']/div[@class='col two-thirds']/p/span[@class='inlineblock']/b[text()='Type:']/parent::span/following-sibling::span/text()") if xpathVar: item['csa_type'] = xpathVar.extract()[0] #since xpath = csa_details.xpath("//div[@class='col three-fourths']/div[@class='fullwidth']/div[@class='col one-third']/p/span[@class='inlineblock']/b[text()='Since:']/parent::span/following-sibling::span/text()") if xpathVar: item['since'] = xpathVar.extract()[0] #share_quantity xpathVar = csa_details.xpath("//div[@class='col three-fourths']/div[@class='fullwidth']/div[@class='col one-third']/p/span[@class='inlineblock']/b/nobr[text()='# of shares:']/parent::b/parent::span/following-sibling::span/text()") if xpathVar: item['share_quantity'] = xpathVar.extract()[0] #full_share_cost xpathVar = csa_details.xpath("//div[@class='col three-fourths']/p/span[@class='inlineblock']/b[text()='Full Share:']/parent::span/following-sibling::span/text()") if xpathVar: item['full_share_cost'] = xpathVar.extract()[0] #half_share_cost xpathVar = csa_details.xpath("//div[@class='col three-fourths']/p/span[@class='inlineblock']/b[text()='1/2 Share:']/parent::span/following-sibling::span/text()") if xpathVar: item['half_share_cost'] = xpathVar.extract()[0] #work_required xpathVar = csa_details.xpath("//div[@class='col three-fourths']/p/span[@class='inlineblock']/b[text()='Work Req?']/parent::span/following-sibling::span/text()") if xpathVar: item['work_required'] = xpathVar.extract()[0] #farming_practices xpathVar = csa_details.xpath("//div[@class='col one-fourth']/div/ul/li/a/text()") if xpathVar: item['farming_practices'] = xpathVar.extract() # Get the list of pickup points pickups = sel.xpath('//h4[text()="Pick Up / Drop Off Points"]/following-sibling::*').extract() for pickup in pickups: if len(pickup) > 5 and pickup.find('dottedline') == -1: #Title Line if pickup.find('img') > 0: # Get title mobj = re.search('<b>(.*?)</b>', pickup) if mobj: pickupPoint.name = mobj.groups()[0].strip() # Get days mobj = re.search('\((.*)\)</span>', pickup) if mobj: pickupPoint.days = mobj.groups()[0] # Get Description mobj = re.search('<br>\s*([]^\<\w\>]*)\s*</p>', pickup) if mobj: pickupPoint.description = mobj.groups()[0] elif pickup.find('Contact') > 0: # Get Contact mobj = re.search('</b>\s*(.*?)<br>', pickup) if mobj: pickupPoint.contact = mobj.groups()[0] # Get phone mobj = re.search('Phone:</b>\s*(.*?)<br>', pickup) if mobj: pickupPoint.phone = mobj.groups()[0] # Get address mobj = re.search('Address:</b><br>\s*(.*?)\s*<br>', pickup) if mobj: pickupPoint.address1 = mobj.groups()[0] # Get City, State, Zip mobj = re.search('<br>\s*(.*),\s(\w*)\s(\d*)', pickup) if mobj: pickupPoint.city = mobj.groups()[0] pickupPoint.state = mobj.groups()[1] pickupPoint.zip = mobj.groups()[2] elif pickup.find('Address') > 0: mobj = re.search('Address:</b><br>\s*(.*?)\s*<br>', pickup) if mobj: pickupPoint.address = mobj.groups()[0] # Get City, State, Zip mobj = re.search('<br>\s*(.*),\s(\w*)\s(\d*)', pickup) if mobj: pickupPoint.city = mobj.groups()[0] pickupPoint.state = mobj.groups()[1] pickupPoint.zip = mobj.groups()[2] elif pickup.find('dottedline') > 0: pickupPoints.append(pickupPoint) pickupPoint = PickupPoint() item['pickups'] = ([p.__dict__ for p in pickupPoints]) return item if __name__ == '__main__': #Run data extraction test on individual page urls = ['http://www.localharvest.org/csa/M17619', 'http://www.localharvest.org/csa/M61994'] import requests from scrapy.http import Request, HtmlResponse for url in urls: request = Request(url=url) response = HtmlResponse(url=url, request=request, body=requests.get(url).text, encoding='utf-8') print LocalHarvestSpider.extract(LocalHarvestSpider(), response=response)
{ "repo_name": "codefordayton/scrapers", "path": "localharvest/spiders/local_harvest_spider.py", "copies": "2", "size": "6855", "license": "unlicense", "hash": 939293468365567600, "line_mean": 45.0067114094, "line_max": 238, "alpha_frac": 0.5735959154, "autogenerated": false, "ratio": 3.5316846986089643, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5105280614008965, "avg_score": null, "num_lines": null }
__author__ = 'Davide Monfrecola' import json from phantomrestclient.phantomrequests import PhantomRequests class Domains(): def __init__(self): self.pr = PhantomRequests() def get_all(self): """Retrieve all the running domains and create a new Domain instance for each one :return: Domain list that contains all the instances created """ domains = [] domains_json = json.loads(self.pr.get_all_domains()) for domain_json in domains_json: domain = Domain() domain.load(domain_json) domains.append(domain) return domains class Domain(): def __init__(self, json=None): self.pr = PhantomRequests() self.name = None self.scaling_policy = None self.monitor_domain_sensors = None self.launch_configuration = None self.monitor_sensors = None self.id = None self.vm_count = None def load(self, json=None): if json is None: raise Exception("Incorrect JSON data!") self.name = json['name'] self.scaling_policy = json['de_name'] self.monitor_domain_sensors = json['monitor_domain_sensors'] self.launch_configuration = json['lc_name'] self.monitor_sensors = json['monitor_sensors'] self.id = json['id'] self.vm_count = json['vm_count']
{ "repo_name": "trampfox/nimbus-phantom-rest-client", "path": "phantomrestclient/domains.py", "copies": "1", "size": "1388", "license": "apache-2.0", "hash": -69052368553638640, "line_mean": 27.9375, "line_max": 89, "alpha_frac": 0.6044668588, "autogenerated": false, "ratio": 4.070381231671554, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0032798883442265794, "num_lines": 48 }
__author__ = 'Davide Monfrecola' import json from phantomrestclient.phantomrequests import PhantomRequests class Sites(): def __init__(self): self.pr = PhantomRequests() def get_all(self): """Retrieve all the sites and create a new Site instance for each one :return: Site list that contains all the instances created """ sites = [] sites_json = json.loads(self.pr.get_all_sites()) for site_json in sites_json: site = Site() site.load(site_json) sites.append(site) return sites class Site(): def __init__(self): self.id = None self.credentials = None self.instance_types = None self.uri = None self.public_images = None self.user_images = None def load(self, json=None): if json is None: raise Exception("Incorrect JSON data!") self.id = json['id'] self.credentials = Credentials(self.id) self.instance_types = json['instance_types'] self.uri = json['uri'] if 'public_images' in json: self.public_images = json['public_images'] if 'user_images' in json: self.user_images = json['user_images'] # TODO add details fields management class Credentials(): def __init__(self, cloud_name): self.cloud_name = cloud_name self.pr = PhantomRequests() try: json = self.get_credentials() self.access_key = json['access_key'] self.key_name = json['key_name'] self.secret_key = json['secret_key'] except Exception as e: pass #TODO log exception def get_credentials(self): return json.loads(self.pr.get_credentials(self.cloud_name))
{ "repo_name": "trampfox/nimbus-phantom-rest-client", "path": "phantomrestclient/sites.py", "copies": "1", "size": "1798", "license": "apache-2.0", "hash": 6337519993651312000, "line_mean": 27.109375, "line_max": 77, "alpha_frac": 0.5806451613, "autogenerated": false, "ratio": 4.00445434298441, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5085099504284409, "avg_score": null, "num_lines": null }
__author__ = 'Davide Monfrecola' import requests import json from phantomrestclient import auth class PhantomRequests(): def __init__(self): self.auth = auth.PhantomAuth() self.api_url = 'https://phantom.nimbusproject.org/api/dev' self.access_token = self.auth.read_token_from_file() def get_request(self, entity, id=""): if id is not "": url = "%s/%s/%s" % (self.api_url, entity, id) else: url = "%s/%s" % (self.api_url, entity) r = requests.get(url, headers={'Authorization': 'Basic %s' % self.access_token}) if r.status_code == requests.codes.ok: return r.text else: r.raise_for_status() def post_request(self, entity, data): r = requests.post("%s/%s" % (self.api_url, entity), data=json.dumps(data), headers={'Authorization': 'Basic %s' % self.access_token}) if r.status_code == requests.codes.ok: return r.text else: r.raise_for_status() def put_request(self, entity, id, data): r = requests.put("%s/%s/%s" % (self.api_url, entity, id), data=json.dumps(data), headers={'Authorization': 'Basic %s' % self.access_token}) if r.status_code == requests.codes.ok: return r.text else: r.raise_for_status() def delete_request(self, entity, id): r = requests.delete("%s/%s/%s" % (self.api_url, entity, id), headers={'Authorization': 'Basic %s' % self.access_token}) if r.status_code == requests.codes.ok: return r.text else: r.raise_for_status() def get_all_domains(self): return self.get_request('domains') def get_all_launchconfigurations(self): return self.get_request('launchconfigurations') def get_all_sites(self, details=True): entity = 'sites' if details is True: entity + '?details=true' return self.get_request(entity=entity) def get_credentials(self, cloud_name): return self.get_request('credentials/sites/' + cloud_name) def create_lc(self, parameters): return self.post_request(entity='launchconfigurations', data=parameters) def update_lc(self, id, parameters): return self.put_request(entity='launchconfigurations', id=id, data=parameters) def delete_lc(self, id): return self.delete_request(entity='launchconfigurations', id=id) def create_domain(self, parameters): return self.post_request(entity='domains', data=parameters) def update_domain(self, id, parameters): return self.put_request(entity='domains', id=id, data=parameters) def delete_domain(self, id): return self.delete_request(entity='domains', id=id)
{ "repo_name": "trampfox/nimbus-phantom-rest-client", "path": "phantomrestclient/phantomrequests.py", "copies": "1", "size": "2874", "license": "apache-2.0", "hash": -8147954217928078000, "line_mean": 32.8235294118, "line_max": 88, "alpha_frac": 0.5894224078, "autogenerated": false, "ratio": 3.72279792746114, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9801937892698076, "avg_score": 0.0020564885126126177, "num_lines": 85 }
__author__ = 'Davide' import pathlib import shutil import sys import argparse import logging def parseArgs(): parser = argparse.ArgumentParser(description='Apply diffs.') parser.add_argument('diff_file', type=str, help='diff file') parser.add_argument('path_from', type=str, help='src folder') parser.add_argument('path_to', type=str, help='dst folder') res = parser.parse_args(sys.argv[1:]) return res def add(line, path_from, path_to): fname = line.split(" ", 1)[1] path_from /= fname path_to /= fname if path_from.is_dir(): path_to.mkdir() logging.log(logging.INFO, "Created directory {}".format(path_to)) elif path_from.is_file(): shutil.copy2(str(path_from), str(path_to)) logging.log(logging.INFO, "Copied file from {} to {}".format(path_from, path_to)) def remove(line, path_from, path_to): path_to = path_to / line.split(" ", 1)[1] if path_to.is_dir(): path_to.rmdir() logging.log(logging.INFO, "Deleted directory {}".format(path_to)) elif path_to.is_file(): path_to.unlink() logging.log(logging.INFO, "Deleted file {}".format(path_to)) def update(line, path_from, path_to): fname = " ".join(line.split(" ")[1:-1]) path_from /= fname path_to /= fname if path_from.is_file(): shutil.copy2(str(path_from), str(path_to)) logging.info("Copied file from {} to {}".format(path_from, path_to)) def dir2file(line, path_from, path_to): fname = line.split(" ", 1)[1] path_from /= fname path_to /= fname if path_to.is_dir(): path_to.rmdir() shutil.copy2(str(path_from), str(path_to)) logging.info("Copied file from {} to {}".format(path_from, path_to)) def file2dir(line, path_from, path_to): fname = line.split(" ", 1)[1] path_from /= fname path_to /= fname if path_to.is_file(): path_to.unlink() path_to.mkdir() logging.info("Created directory {}".format(path_to)) def apply_diffs(diff_file, path_from, path_to): with diff_file.open() as f: for line in f: try: line = line.strip() if line.startswith("+"): add(line, path_from, path_to) elif line.startswith("-"): remove(line, path_from, path_to) elif line.startswith("*"): update(line, path_from, path_to) elif line.startswith("d"): dir2file(line, path_from, path_to) elif line.startswith("f"): file2dir(line, path_from, path_to) except PermissionError: pass def main(): logging.basicConfig(level=logging.INFO) args = parseArgs() path_from = pathlib.Path(args.path_from).resolve() path_to = pathlib.Path(args.path_to).resolve() diff_file = pathlib.Path(args.diff_file).resolve() apply_diffs(diff_file, path_from, path_to) if __name__ == "__main__": main()
{ "repo_name": "DavideCanton/PyComparePaths", "path": "apply_diff.py", "copies": "1", "size": "3015", "license": "mit", "hash": -2407693091903000000, "line_mean": 29.7653061224, "line_max": 89, "alpha_frac": 0.5797678275, "autogenerated": false, "ratio": 3.3914510686164228, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9469589077522318, "avg_score": 0.00032596371882086164, "num_lines": 98 }
# This is a merge of the docutils_ `rst2html` front end with an extension # suggestion taken from the pygments_ documentation. """ A front end to docutils, producing HTML with syntax colouring using pygments """ try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates (X)HTML documents from standalone reStructuredText ' 'sources. Uses `pygments` to colorize the content of' '"code-block" directives. Needs an adapted stylesheet' + default_description) # Define a new directive `code-block` that uses the `pygments` source # highlighter to render code in color. # # Code from the `pygments`_ documentation for `Using Pygments in ReST # documents`_. from docutils import nodes from docutils.parsers.rst import directives from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter pygments_formatter = HtmlFormatter() def pygments_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): try: lexer = get_lexer_by_name(arguments[0]) except ValueError: # no lexer found - use the text one instead of an exception lexer = get_lexer_by_name('text') parsed = highlight(u'\n'.join(content), lexer, pygments_formatter) return [nodes.raw('', parsed, format='html')] pygments_directive.arguments = (1, 0, 1) pygments_directive.content = 1 directives.register_directive('code-block', pygments_directive) # Call the docutils publisher to render the input as html:: publish_cmdline(writer_name='html', description=description) # .. _doctutile: http://docutils.sf.net/ # .. _pygments: http://pygments.org/ # .. _Using Pygments in ReST documents: http://pygments.org/docs/rstdirective/
{ "repo_name": "Knio/miru", "path": "docs/rst2html-pygments.py", "copies": "1", "size": "2070", "license": "mit", "hash": 1341097172472486400, "line_mean": 34.6896551724, "line_max": 78, "alpha_frac": 0.7193236715, "autogenerated": false, "ratio": 3.9731285988483687, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5192452270348369, "avg_score": null, "num_lines": null }
""" Directives for document parts. """ __docformat__ = 'reStructuredText' from docutils import nodes, languages from docutils.transforms import parts from docutils.parsers.rst import directives backlinks_values = ('top', 'entry', 'none') def backlinks(arg): value = directives.choice(arg, backlinks_values) if value == 'none': return None else: return value def contents(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """ Table of contents. The table of contents is generated in two passes: initial parse and transform. During the initial parse, a 'pending' element is generated which acts as a placeholder, storing the TOC title and any options internally. At a later stage in the processing, the 'pending' element is replaced by a 'topic' element, a title and the table of contents proper. """ if not (state_machine.match_titles or isinstance(state_machine.node, nodes.sidebar)): error = state_machine.reporter.error( 'The "%s" directive may not be used within topics ' 'or body elements.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [error] document = state_machine.document language = languages.get_language(document.settings.language_code) if arguments: title_text = arguments[0] text_nodes, messages = state.inline_text(title_text, lineno) title = nodes.title(title_text, '', *text_nodes) else: messages = [] if options.has_key('local'): title = None else: title = nodes.title('', language.labels['contents']) topic = nodes.topic(classes=['contents']) topic['classes'] += options.get('class', []) if title: name = title.astext() topic += title else: name = language.labels['contents'] name = nodes.fully_normalize_name(name) if not document.has_name(name): topic['names'].append(name) document.note_implicit_target(topic) pending = nodes.pending(parts.Contents, rawsource=block_text) pending.details.update(options) document.note_pending(pending) topic += pending return [topic] + messages contents.arguments = (0, 1, 1) contents.options = {'depth': directives.nonnegative_int, 'local': directives.flag, 'backlinks': backlinks, 'class': directives.class_option} def sectnum(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """Automatic section numbering.""" pending = nodes.pending(parts.SectNum) pending.details.update(options) state_machine.document.note_pending(pending) return [pending] sectnum.options = {'depth': int, 'start': int, 'prefix': directives.unchanged_required, 'suffix': directives.unchanged_required} def header_footer(node, name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """Contents of document header or footer.""" if not content: warning = state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % name, nodes.literal_block(block_text, block_text), line=lineno) node.append(nodes.paragraph( '', 'Problem with the "%s" directive: no content supplied.' % name)) return [warning] text = '\n'.join(content) state.nested_parse(content, content_offset, node) return [] def header(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): decoration = state_machine.document.get_decoration() node = decoration.get_header() return header_footer(node, name, arguments, options, content, lineno, content_offset, block_text, state, state_machine) header.content = 1 def footer(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): decoration = state_machine.document.get_decoration() node = decoration.get_footer() return header_footer(node, name, arguments, options, content, lineno, content_offset, block_text, state, state_machine) footer.content = 1
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/parsers/rst/directives/parts.py", "copies": "1", "size": "4676", "license": "mit", "hash": -7932214902269727000, "line_mean": 36.7096774194, "line_max": 80, "alpha_frac": 0.6454234388, "autogenerated": false, "ratio": 4.041486603284356, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5186910042084355, "avg_score": null, "num_lines": null }
""" Directives for document parts. """ __docformat__ = 'reStructuredText' from docutils import nodes, languages from docutils.transforms import parts from docutils.parsers.rst import directives backlinks_values = ('top', 'entry', 'none') def backlinks(arg): value = directives.choice(arg, backlinks_values) if value == 'none': return None else: return value def contents(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """ Table of contents. The table of contents is generated in two passes: initial parse and transform. During the initial parse, a 'pending' element is generated which acts as a placeholder, storing the TOC title and any options internally. At a later stage in the processing, the 'pending' element is replaced by a 'topic' element, a title and the table of contents proper. """ if not (state_machine.match_titles or isinstance(state_machine.node, nodes.sidebar)): error = state_machine.reporter.error( 'The "%s" directive may not be used within topics ' 'or body elements.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [error] document = state_machine.document language = languages.get_language(document.settings.language_code) if arguments: title_text = arguments[0] text_nodes, messages = state.inline_text(title_text, lineno) title = nodes.title(title_text, '', *text_nodes) else: messages = [] if options.has_key('local'): title = None else: title = nodes.title('', language.labels['contents']) topic = nodes.topic(classes=['contents']) topic['classes'] += options.get('class', []) if options.has_key('local'): topic['classes'].append('local') if title: name = title.astext() topic += title else: name = language.labels['contents'] name = nodes.fully_normalize_name(name) if not document.has_name(name): topic['names'].append(name) document.note_implicit_target(topic) pending = nodes.pending(parts.Contents, rawsource=block_text) pending.details.update(options) document.note_pending(pending) topic += pending return [topic] + messages contents.arguments = (0, 1, 1) contents.options = {'depth': directives.nonnegative_int, 'local': directives.flag, 'backlinks': backlinks, 'class': directives.class_option} def sectnum(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """Automatic section numbering.""" pending = nodes.pending(parts.SectNum) pending.details.update(options) state_machine.document.note_pending(pending) return [pending] sectnum.options = {'depth': int, 'start': int, 'prefix': directives.unchanged_required, 'suffix': directives.unchanged_required} def header_footer(node, name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """Contents of document header or footer.""" if not content: warning = state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % name, nodes.literal_block(block_text, block_text), line=lineno) node.append(nodes.paragraph( '', 'Problem with the "%s" directive: no content supplied.' % name)) return [warning] text = '\n'.join(content) state.nested_parse(content, content_offset, node) return [] def header(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): decoration = state_machine.document.get_decoration() node = decoration.get_header() return header_footer(node, name, arguments, options, content, lineno, content_offset, block_text, state, state_machine) header.content = 1 def footer(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): decoration = state_machine.document.get_decoration() node = decoration.get_footer() return header_footer(node, name, arguments, options, content, lineno, content_offset, block_text, state, state_machine) footer.content = 1
{ "repo_name": "epall/selenium", "path": "selenium/src/py/lib/docutils/parsers/rst/directives/parts.py", "copies": "5", "size": "4876", "license": "apache-2.0", "hash": 1295534037212902100, "line_mean": 36.6984126984, "line_max": 80, "alpha_frac": 0.6277686628, "autogenerated": false, "ratio": 4.097478991596638, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7225247654396638, "avg_score": null, "num_lines": null }
""" This package contains directive implementation modules. The interface for directive functions is as follows:: def directive_fn(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): code... # Set function attributes: directive_fn.arguments = ... directive_fn.options = ... direcitve_fn.content = ... Parameters: - ``name`` is the directive type or name (string). - ``arguments`` is a list of positional arguments (strings). - ``options`` is a dictionary mapping option names (strings) to values (type depends on option conversion functions; see below). - ``content`` is a list of strings, the directive content. - ``lineno`` is the line number of the first line of the directive. - ``content_offset`` is the line offset of the first line of the content from the beginning of the current input. Used when initiating a nested parse. - ``block_text`` is a string containing the entire directive. Include it as the content of a literal block in a system message if there is a problem. - ``state`` is the state which called the directive function. - ``state_machine`` is the state machine which controls the state which called the directive function. Function attributes, interpreted by the directive parser (which calls the directive function): - ``arguments``: A 3-tuple specifying the expected positional arguments, or ``None`` if the directive has no arguments. The 3 items in the tuple are ``(required, optional, whitespace OK in last argument)``: 1. The number of required arguments. 2. The number of optional arguments. 3. A boolean, indicating if the final argument may contain whitespace. Arguments are normally single whitespace-separated words. The final argument may contain whitespace if the third item in the argument spec tuple is 1/True. If the form of the arguments is more complex, specify only one argument (either required or optional) and indicate that final whitespace is OK; the client code must do any context-sensitive parsing. - ``options``: A dictionary, mapping known option names to conversion functions such as `int` or `float`. ``None`` or an empty dict implies no options to parse. Several directive option conversion functions are defined in this module. Option conversion functions take a single parameter, the option argument (a string or ``None``), validate it and/or convert it to the appropriate form. Conversion functions may raise ``ValueError`` and ``TypeError`` exceptions. - ``content``: A boolean; true if content is allowed. Client code must handle the case where content is required but not supplied (an empty content list will be supplied). Directive functions return a list of nodes which will be inserted into the document tree at the point where the directive was encountered (can be an empty list). See `Creating reStructuredText Directives`_ for more information. .. _Creating reStructuredText Directives: http://docutils.sourceforge.net/docs/howto/rst-directives.html """ __docformat__ = 'reStructuredText' import re import codecs from docutils import nodes from docutils.parsers.rst.languages import en as _fallback_language_module _directive_registry = { 'attention': ('admonitions', 'attention'), 'caution': ('admonitions', 'caution'), 'danger': ('admonitions', 'danger'), 'error': ('admonitions', 'error'), 'important': ('admonitions', 'important'), 'note': ('admonitions', 'note'), 'tip': ('admonitions', 'tip'), 'hint': ('admonitions', 'hint'), 'warning': ('admonitions', 'warning'), 'admonition': ('admonitions', 'admonition'), 'sidebar': ('body', 'sidebar'), 'topic': ('body', 'topic'), 'line-block': ('body', 'line_block'), 'parsed-literal': ('body', 'parsed_literal'), 'rubric': ('body', 'rubric'), 'epigraph': ('body', 'epigraph'), 'highlights': ('body', 'highlights'), 'pull-quote': ('body', 'pull_quote'), 'compound': ('body', 'compound'), #'questions': ('body', 'question_list'), 'table': ('tables', 'table'), 'csv-table': ('tables', 'csv_table'), 'list-table': ('tables', 'list_table'), 'image': ('images', 'image'), 'figure': ('images', 'figure'), 'contents': ('parts', 'contents'), 'sectnum': ('parts', 'sectnum'), 'header': ('parts', 'header'), 'footer': ('parts', 'footer'), #'footnotes': ('parts', 'footnotes'), #'citations': ('parts', 'citations'), 'target-notes': ('references', 'target_notes'), 'meta': ('html', 'meta'), #'imagemap': ('html', 'imagemap'), 'raw': ('misc', 'raw'), 'include': ('misc', 'include'), 'replace': ('misc', 'replace'), 'unicode': ('misc', 'unicode_directive'), 'class': ('misc', 'class_directive'), 'role': ('misc', 'role'), 'restructuredtext-test-directive': ('misc', 'directive_test_function'),} """Mapping of directive name to (module name, function name). The directive name is canonical & must be lowercase. Language-dependent names are defined in the ``language`` subpackage.""" _modules = {} """Cache of imported directive modules.""" _directives = {} """Cache of imported directive functions.""" def directive(directive_name, language_module, document): """ Locate and return a directive function from its language-dependent name. If not found in the current language, check English. Return None if the named directive cannot be found. """ normname = directive_name.lower() messages = [] msg_text = [] if _directives.has_key(normname): return _directives[normname], messages canonicalname = None try: canonicalname = language_module.directives[normname] except AttributeError, error: msg_text.append('Problem retrieving directive entry from language ' 'module %r: %s.' % (language_module, error)) except KeyError: msg_text.append('No directive entry for "%s" in module "%s".' % (directive_name, language_module.__name__)) if not canonicalname: try: canonicalname = _fallback_language_module.directives[normname] msg_text.append('Using English fallback for directive "%s".' % directive_name) except KeyError: msg_text.append('Trying "%s" as canonical directive name.' % directive_name) # The canonical name should be an English name, but just in case: canonicalname = normname if msg_text: message = document.reporter.info( '\n'.join(msg_text), line=document.current_line) messages.append(message) try: modulename, functionname = _directive_registry[canonicalname] except KeyError: messages.append(document.reporter.error( 'Directive "%s" not registered (canonical name "%s").' % (directive_name, canonicalname), line=document.current_line)) return None, messages if _modules.has_key(modulename): module = _modules[modulename] else: try: module = __import__(modulename, globals(), locals()) except ImportError, detail: messages.append(document.reporter.error( 'Error importing directive module "%s" (directive "%s"):\n%s' % (modulename, directive_name, detail), line=document.current_line)) return None, messages try: function = getattr(module, functionname) _directives[normname] = function except AttributeError: messages.append(document.reporter.error( 'No function "%s" in module "%s" (directive "%s").' % (functionname, modulename, directive_name), line=document.current_line)) return None, messages return function, messages def register_directive(name, directive_function): """ Register a nonstandard application-defined directive function. Language lookups are not needed for such functions. """ _directives[name] = directive_function def flag(argument): """ Check for a valid flag option (no argument) and return ``None``. (Directive option conversion function.) Raise ``ValueError`` if an argument is found. """ if argument and argument.strip(): raise ValueError('no argument is allowed; "%s" supplied' % argument) else: return None def unchanged_required(argument): """ Return the argument text, unchanged. (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') else: return argument # unchanged! def unchanged(argument): """ Return the argument text, unchanged. (Directive option conversion function.) No argument implies empty string (""). """ if argument is None: return u'' else: return argument # unchanged! def path(argument): """ Return the path argument unwrapped (with newlines removed). (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') else: path = ''.join([s.strip() for s in argument.splitlines()]) return path def uri(argument): """ Return the URI argument with whitespace removed. (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') else: uri = ''.join(argument.split()) return uri def nonnegative_int(argument): """ Check for a nonnegative integer argument; raise ``ValueError`` if not. (Directive option conversion function.) """ value = int(argument) if value < 0: raise ValueError('negative value; must be positive or zero') return value def class_option(argument): """ Convert the argument into a list of ID-compatible strings and return it. (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') names = argument.split() class_names = [] for name in names: class_name = nodes.make_id(name) if not class_name: raise ValueError('cannot make "%s" into a class name' % name) class_names.append(class_name) return class_names unicode_pattern = re.compile( r'(?:0x|x|\\x|U\+?|\\u)([0-9a-f]+)$|&#x([0-9a-f]+);$', re.IGNORECASE) def unicode_code(code): r""" Convert a Unicode character code to a Unicode character. (Directive option conversion function.) Codes may be decimal numbers, hexadecimal numbers (prefixed by ``0x``, ``x``, ``\x``, ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style numeric character entities (e.g. ``&#x262E;``). Other text remains as-is. Raise ValueError for illegal Unicode code values. """ try: if code.isdigit(): # decimal number return unichr(int(code)) else: match = unicode_pattern.match(code) if match: # hex number value = match.group(1) or match.group(2) return unichr(int(value, 16)) else: # other text return code except OverflowError, detail: raise ValueError('code too large (%s)' % detail) def single_char_or_unicode(argument): """ A single character is returned as-is. Unicode characters codes are converted as in `unicode_code`. (Directive option conversion function.) """ char = unicode_code(argument) if len(char) > 1: raise ValueError('%r invalid; must be a single character or ' 'a Unicode code' % char) return char def single_char_or_whitespace_or_unicode(argument): """ As with `single_char_or_unicode`, but "tab" and "space" are also supported. (Directive option conversion function.) """ if argument == 'tab': char = '\t' elif argument == 'space': char = ' ' else: char = single_char_or_unicode(argument) return char def positive_int(argument): """ Converts the argument into an integer. Raises ValueError for negative, zero, or non-integer values. (Directive option conversion function.) """ value = int(argument) if value < 1: raise ValueError('negative or zero value; must be positive') return value def positive_int_list(argument): """ Converts a space- or comma-separated list of values into a Python list of integers. (Directive option conversion function.) Raises ValueError for non-positive-integer values. """ if ',' in argument: entries = argument.split(',') else: entries = argument.split() return [positive_int(entry) for entry in entries] def encoding(argument): """ Verfies the encoding argument by lookup. (Directive option conversion function.) Raises ValueError for unknown encodings. """ try: codecs.lookup(argument) except LookupError: raise ValueError('unknown encoding: "%s"' % argument) return argument def choice(argument, values): """ Directive option utility function, supplied to enable options whose argument must be a member of a finite set of possible values (must be lower case). A custom conversion function must be written to use it. For example:: from docutils.parsers.rst import directives def yesno(argument): return directives.choice(argument, ('yes', 'no')) Raise ``ValueError`` if no argument is found or if the argument's value is not valid (not an entry in the supplied list). """ try: value = argument.lower().strip() except AttributeError: raise ValueError('must supply an argument; choose from %s' % format_values(values)) if value in values: return value else: raise ValueError('"%s" unknown; choose from %s' % (argument, format_values(values))) def format_values(values): return '%s, or "%s"' % (', '.join(['"%s"' % s for s in values[:-1]]), values[-1])
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/parsers/rst/directives/__init__.py", "copies": "1", "size": "14915", "license": "mit", "hash": -6439196709766593000, "line_mean": 34.4275534442, "line_max": 79, "alpha_frac": 0.6359369762, "autogenerated": false, "ratio": 4.2896174863387975, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5425554462538797, "avg_score": null, "num_lines": null }
""" Directives for additional body elements. See `docutils.parsers.rst.directives` for API details. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes from docutils.parsers.rst import directives from docutils.parsers.rst.roles import set_classes def topic(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine, node_class=nodes.topic): if not (state_machine.match_titles or isinstance(state_machine.node, nodes.sidebar)): error = state_machine.reporter.error( 'The "%s" directive may not be used within topics ' 'or body elements.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [error] if not content: warning = state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [warning] title_text = arguments[0] textnodes, messages = state.inline_text(title_text, lineno) titles = [nodes.title(title_text, '', *textnodes)] # sidebar uses this code if options.has_key('subtitle'): textnodes, more_messages = state.inline_text(options['subtitle'], lineno) titles.append(nodes.subtitle(options['subtitle'], '', *textnodes)) messages.extend(more_messages) text = '\n'.join(content) node = node_class(text, *(titles + messages)) node['classes'] += options.get('class', []) if text: state.nested_parse(content, content_offset, node) return [node] topic.arguments = (1, 0, 1) topic.options = {'class': directives.class_option} topic.content = 1 def sidebar(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): if isinstance(state_machine.node, nodes.sidebar): error = state_machine.reporter.error( 'The "%s" directive may not be used within a sidebar element.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [error] return topic(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine, node_class=nodes.sidebar) sidebar.arguments = (1, 0, 1) sidebar.options = {'subtitle': directives.unchanged_required, 'class': directives.class_option} sidebar.content = 1 def line_block(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): if not content: warning = state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [warning] block = nodes.line_block(classes=options.get('class', [])) node_list = [block] for line_text in content: text_nodes, messages = state.inline_text(line_text.strip(), lineno + content_offset) line = nodes.line(line_text, '', *text_nodes) if line_text.strip(): line.indent = len(line_text) - len(line_text.lstrip()) block += line node_list.extend(messages) content_offset += 1 state.nest_line_block_lines(block) return node_list line_block.options = {'class': directives.class_option} line_block.content = 1 def parsed_literal(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): set_classes(options) return block(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine, node_class=nodes.literal_block) parsed_literal.options = {'class': directives.class_option} parsed_literal.content = 1 def block(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine, node_class): if not content: warning = state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [warning] text = '\n'.join(content) text_nodes, messages = state.inline_text(text, lineno) node = node_class(text, '', *text_nodes, **options) node.line = content_offset + 1 return [node] + messages def rubric(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): rubric_text = arguments[0] textnodes, messages = state.inline_text(rubric_text, lineno) rubric = nodes.rubric(rubric_text, '', *textnodes, **options) return [rubric] + messages rubric.arguments = (1, 0, 1) rubric.options = {'class': directives.class_option} def epigraph(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): block_quote, messages = state.block_quote(content, content_offset) block_quote['classes'].append('epigraph') return [block_quote] + messages epigraph.content = 1 def highlights(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): block_quote, messages = state.block_quote(content, content_offset) block_quote['classes'].append('highlights') return [block_quote] + messages highlights.content = 1 def pull_quote(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): block_quote, messages = state.block_quote(content, content_offset) block_quote['classes'].append('pull-quote') return [block_quote] + messages pull_quote.content = 1 def compound(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): text = '\n'.join(content) if not text: error = state_machine.reporter.error( 'The "%s" directive is empty; content required.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [error] node = nodes.compound(text) node['classes'] += options.get('class', []) state.nested_parse(content, content_offset, node) return [node] compound.options = {'class': directives.class_option} compound.content = 1
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/parsers/rst/directives/body.py", "copies": "1", "size": "6680", "license": "mit", "hash": -2928877780707132400, "line_mean": 38.5266272189, "line_max": 79, "alpha_frac": 0.645508982, "autogenerated": false, "ratio": 3.8523644752018456, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4997873457201845, "avg_score": null, "num_lines": null }
""" This is the Docutils (Python Documentation Utilities) package. Package Structure ================= Modules: - __init__.py: Contains component base classes, exception classes, and Docutils `__version__`. - core.py: Contains the ``Publisher`` class and ``publish_*()`` convenience functions. - frontend.py: Runtime settings (command-line interface, configuration files) processing, for Docutils front-ends. - io.py: Provides a uniform API for low-level input and output. - nodes.py: Docutils document tree (doctree) node class library. - statemachine.py: A finite state machine specialized for regular-expression-based text filters. - urischemes.py: Contains a complete mapping of known URI addressing scheme names to descriptions. - utils.py: Contains the ``Reporter`` system warning class and miscellaneous utilities. Subpackages: - languages: Language-specific mappings of terms. - parsers: Syntax-specific input parser modules or packages. - readers: Context-specific input handlers which understand the data source and manage a parser. - transforms: Modules used by readers and writers to modify DPS doctrees. - writers: Format-specific output translators. """ __docformat__ = 'reStructuredText' __version__ = '0.3.9' """``major.minor.micro`` version number. The micro number is bumped for API changes, for new functionality, and for interim project releases. The minor number is bumped whenever there is a significant project release. The major number will be bumped when the project is feature-complete, and perhaps if there is a major change in the design.""" class ApplicationError(StandardError): pass class DataError(ApplicationError): pass class SettingsSpec: """ Runtime setting specification base class. SettingsSpec subclass objects used by `docutils.frontend.OptionParser`. """ settings_spec = () """Runtime settings specification. Override in subclasses. Defines runtime settings and associated command-line options, as used by `docutils.frontend.OptionParser`. This is a tuple of: - Option group title (string or `None` which implies no group, just a list of single options). - Description (string or `None`). - A sequence of option tuples. Each consists of: - Help text (string) - List of option strings (e.g. ``['-Q', '--quux']``). - Dictionary of keyword arguments. It contains arguments to the OptionParser/OptionGroup ``add_option`` method, possibly with the addition of a 'validator' keyword (see the `docutils.frontend.OptionParser.validators` instance attribute). Runtime settings names are derived implicitly from long option names ('--a-setting' becomes ``settings.a_setting``) or explicitly from the 'dest' keyword argument. See optparse docs for more details. - More triples of group title, description, options, as many times as needed. Thus, `settings_spec` tuples can be simply concatenated. """ settings_defaults = None """A dictionary of defaults for settings not in `settings_spec` (internal settings, intended to be inaccessible by command-line and config file). Override in subclasses.""" settings_default_overrides = None """A dictionary of auxiliary defaults, to override defaults for settings defined in other components. Override in subclasses.""" relative_path_settings = () """Settings containing filesystem paths. Override in subclasses. Settings listed here are to be interpreted relative to the current working directory.""" config_section = None """The name of the config file section specific to this component (lowercase, no brackets). Override in subclasses.""" config_section_dependencies = None """A list of names of config file sections that are to be applied before `config_section`, in order (from general to specific). In other words, the settings in `config_section` are to be overlaid on top of the settings from these sections. The "general" section is assumed implicitly. Override in subclasses.""" class TransformSpec: """ Runtime transform specification base class. TransformSpec subclass objects used by `docutils.transforms.Transformer`. """ default_transforms = () """Transforms required by this class. Override in subclasses.""" unknown_reference_resolvers = () """List of functions to try to resolve unknown references. Unknown references have a 'refname' attribute which doesn't correspond to any target in the document. Called when FinalCheckVisitor is unable to find a correct target. The list should contain functions which will try to resolve unknown references, with the following signature:: def reference_resolver(node): '''Returns boolean: true if resolved, false if not.''' If the function is able to resolve the reference, it should also remove the 'refname' attribute and mark the node as resolved:: del node['refname'] node.resolved = 1 Each function must have a "priority" attribute which will affect the order the unknown_reference_resolvers are run:: reference_resolver.priority = 100 Override in subclasses.""" class Component(SettingsSpec, TransformSpec): """Base class for Docutils components.""" component_type = None """Name of the component type ('reader', 'parser', 'writer'). Override in subclasses.""" supported = () """Names for this component. Override in subclasses.""" def supports(self, format): """ Is `format` supported by this component? To be used by transforms to ask the dependent component if it supports a certain input context or output format. """ return format in self.supported
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/__init__.py", "copies": "1", "size": "6120", "license": "mit", "hash": -3399096701683666000, "line_mean": 32.6263736264, "line_max": 81, "alpha_frac": 0.7070261438, "autogenerated": false, "ratio": 4.556962025316456, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.006294707035125154, "num_lines": 182 }
""" This module defines table parser classes,which parse plaintext-graphic tables and produce a well-formed data structure suitable for building a CALS table. :Classes: - `GridTableParser`: Parse fully-formed tables represented with a grid. - `SimpleTableParser`: Parse simple tables, delimited by top & bottom borders. :Exception class: `TableMarkupError` :Function: `update_dict_of_lists()`: Merge two dictionaries containing list values. """ __docformat__ = 'reStructuredText' import re import sys from docutils import DataError class TableMarkupError(DataError): pass class TableParser: """ Abstract superclass for the common parts of the syntax-specific parsers. """ head_body_separator_pat = None """Matches the row separator between head rows and body rows.""" def parse(self, block): """ Analyze the text `block` and return a table data structure. Given a plaintext-graphic table in `block` (list of lines of text; no whitespace padding), parse the table, construct and return the data necessary to construct a CALS table or equivalent. Raise `TableMarkupError` if there is any problem with the markup. """ self.setup(block) self.find_head_body_sep() self.parse_table() structure = self.structure_from_cells() return structure def find_head_body_sep(self): """Look for a head/body row separator line; store the line index.""" for i in range(len(self.block)): line = self.block[i] if self.head_body_separator_pat.match(line): if self.head_body_sep: raise TableMarkupError( 'Multiple head/body row separators in table (at line ' 'offset %s and %s); only one allowed.' % (self.head_body_sep, i)) else: self.head_body_sep = i self.block[i] = line.replace('=', '-') if self.head_body_sep == 0 or self.head_body_sep == (len(self.block) - 1): raise TableMarkupError('The head/body row separator may not be ' 'the first or last line of the table.') class GridTableParser(TableParser): """ Parse a grid table using `parse()`. Here's an example of a grid table:: +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | Cells may span columns. | +------------------------+------------+---------------------+ | body row 3 | Cells may | - Table cells | +------------------------+ span rows. | - contain | | body row 4 | | - body elements. | +------------------------+------------+---------------------+ Intersections use '+', row separators use '-' (except for one optional head/body row separator, which uses '='), and column separators use '|'. Passing the above table to the `parse()` method will result in the following data structure:: ([24, 12, 10, 10], [[(0, 0, 1, ['Header row, column 1']), (0, 0, 1, ['Header 2']), (0, 0, 1, ['Header 3']), (0, 0, 1, ['Header 4'])]], [[(0, 0, 3, ['body row 1, column 1']), (0, 0, 3, ['column 2']), (0, 0, 3, ['column 3']), (0, 0, 3, ['column 4'])], [(0, 0, 5, ['body row 2']), (0, 2, 5, ['Cells may span columns.']), None, None], [(0, 0, 7, ['body row 3']), (1, 0, 7, ['Cells may', 'span rows.', '']), (1, 1, 7, ['- Table cells', '- contain', '- body elements.']), None], [(0, 0, 9, ['body row 4']), None, None, None]]) The first item is a list containing column widths (colspecs). The second item is a list of head rows, and the third is a list of body rows. Each row contains a list of cells. Each cell is either None (for a cell unused because of another cell's span), or a tuple. A cell tuple contains four items: the number of extra rows used by the cell in a vertical span (morerows); the number of extra columns used by the cell in a horizontal span (morecols); the line offset of the first line of the cell contents; and the cell contents, a list of lines of text. """ head_body_separator_pat = re.compile(r'\+=[=+]+=\+ *$') def setup(self, block): self.block = block[:] # make a copy; it may be modified self.block.disconnect() # don't propagate changes to parent self.bottom = len(block) - 1 self.right = len(block[0]) - 1 self.head_body_sep = None self.done = [-1] * len(block[0]) self.cells = [] self.rowseps = {0: [0]} self.colseps = {0: [0]} def parse_table(self): """ Start with a queue of upper-left corners, containing the upper-left corner of the table itself. Trace out one rectangular cell, remember it, and add its upper-right and lower-left corners to the queue of potential upper-left corners of further cells. Process the queue in top-to-bottom order, keeping track of how much of each text column has been seen. We'll end up knowing all the row and column boundaries, cell positions and their dimensions. """ corners = [(0, 0)] while corners: top, left = corners.pop(0) if top == self.bottom or left == self.right \ or top <= self.done[left]: continue result = self.scan_cell(top, left) if not result: continue bottom, right, rowseps, colseps = result update_dict_of_lists(self.rowseps, rowseps) update_dict_of_lists(self.colseps, colseps) self.mark_done(top, left, bottom, right) cellblock = self.block.get_2D_block(top + 1, left + 1, bottom, right) cellblock.disconnect() # lines in cell can't sync with parent self.cells.append((top, left, bottom, right, cellblock)) corners.extend([(top, right), (bottom, left)]) corners.sort() if not self.check_parse_complete(): raise TableMarkupError('Malformed table; parse incomplete.') def mark_done(self, top, left, bottom, right): """For keeping track of how much of each text column has been seen.""" before = top - 1 after = bottom - 1 for col in range(left, right): assert self.done[col] == before self.done[col] = after def check_parse_complete(self): """Each text column should have been completely seen.""" last = self.bottom - 1 for col in range(self.right): if self.done[col] != last: return None return 1 def scan_cell(self, top, left): """Starting at the top-left corner, start tracing out a cell.""" assert self.block[top][left] == '+' result = self.scan_right(top, left) return result def scan_right(self, top, left): """ Look for the top-right corner of the cell, and make note of all column boundaries ('+'). """ colseps = {} line = self.block[top] for i in range(left + 1, self.right + 1): if line[i] == '+': colseps[i] = [top] result = self.scan_down(top, left, i) if result: bottom, rowseps, newcolseps = result update_dict_of_lists(colseps, newcolseps) return bottom, i, rowseps, colseps elif line[i] != '-': return None return None def scan_down(self, top, left, right): """ Look for the bottom-right corner of the cell, making note of all row boundaries. """ rowseps = {} for i in range(top + 1, self.bottom + 1): if self.block[i][right] == '+': rowseps[i] = [right] result = self.scan_left(top, left, i, right) if result: newrowseps, colseps = result update_dict_of_lists(rowseps, newrowseps) return i, rowseps, colseps elif self.block[i][right] != '|': return None return None def scan_left(self, top, left, bottom, right): """ Noting column boundaries, look for the bottom-left corner of the cell. It must line up with the starting point. """ colseps = {} line = self.block[bottom] for i in range(right - 1, left, -1): if line[i] == '+': colseps[i] = [bottom] elif line[i] != '-': return None if line[left] != '+': return None result = self.scan_up(top, left, bottom, right) if result is not None: rowseps = result return rowseps, colseps return None def scan_up(self, top, left, bottom, right): """ Noting row boundaries, see if we can return to the starting point. """ rowseps = {} for i in range(bottom - 1, top, -1): if self.block[i][left] == '+': rowseps[i] = [left] elif self.block[i][left] != '|': return None return rowseps def structure_from_cells(self): """ From the data collected by `scan_cell()`, convert to the final data structure. """ rowseps = self.rowseps.keys() # list of row boundaries rowseps.sort() rowindex = {} for i in range(len(rowseps)): rowindex[rowseps[i]] = i # row boundary -> row number mapping colseps = self.colseps.keys() # list of column boundaries colseps.sort() colindex = {} for i in range(len(colseps)): colindex[colseps[i]] = i # column boundary -> col number map colspecs = [(colseps[i] - colseps[i - 1] - 1) for i in range(1, len(colseps))] # list of column widths # prepare an empty table with the correct number of rows & columns onerow = [None for i in range(len(colseps) - 1)] rows = [onerow[:] for i in range(len(rowseps) - 1)] # keep track of # of cells remaining; should reduce to zero remaining = (len(rowseps) - 1) * (len(colseps) - 1) for top, left, bottom, right, block in self.cells: rownum = rowindex[top] colnum = colindex[left] assert rows[rownum][colnum] is None, ( 'Cell (row %s, column %s) already used.' % (rownum + 1, colnum + 1)) morerows = rowindex[bottom] - rownum - 1 morecols = colindex[right] - colnum - 1 remaining -= (morerows + 1) * (morecols + 1) # write the cell into the table rows[rownum][colnum] = (morerows, morecols, top + 1, block) assert remaining == 0, 'Unused cells remaining.' if self.head_body_sep: # separate head rows from body rows numheadrows = rowindex[self.head_body_sep] headrows = rows[:numheadrows] bodyrows = rows[numheadrows:] else: headrows = [] bodyrows = rows return (colspecs, headrows, bodyrows) class SimpleTableParser(TableParser): """ Parse a simple table using `parse()`. Here's an example of a simple table:: ===== ===== col 1 col 2 ===== ===== 1 Second column of row 1. 2 Second column of row 2. Second line of paragraph. 3 - Second column of row 3. - Second item in bullet list (row 3, column 2). 4 is a span ------------ 5 ===== ===== Top and bottom borders use '=', column span underlines use '-', column separation is indicated with spaces. Passing the above table to the `parse()` method will result in the following data structure, whose interpretation is the same as for `GridTableParser`:: ([5, 25], [[(0, 0, 1, ['col 1']), (0, 0, 1, ['col 2'])]], [[(0, 0, 3, ['1']), (0, 0, 3, ['Second column of row 1.'])], [(0, 0, 4, ['2']), (0, 0, 4, ['Second column of row 2.', 'Second line of paragraph.'])], [(0, 0, 6, ['3']), (0, 0, 6, ['- Second column of row 3.', '', '- Second item in bullet', ' list (row 3, column 2).'])], [(0, 1, 10, ['4 is a span'])], [(0, 0, 12, ['5']), (0, 0, 12, [''])]]) """ head_body_separator_pat = re.compile('=[ =]*$') span_pat = re.compile('-[ -]*$') def setup(self, block): self.block = block[:] # make a copy; it will be modified self.block.disconnect() # don't propagate changes to parent # Convert top & bottom borders to column span underlines: self.block[0] = self.block[0].replace('=', '-') self.block[-1] = self.block[-1].replace('=', '-') self.head_body_sep = None self.columns = [] self.border_end = None self.table = [] self.done = [-1] * len(block[0]) self.rowseps = {0: [0]} self.colseps = {0: [0]} def parse_table(self): """ First determine the column boundaries from the top border, then process rows. Each row may consist of multiple lines; accumulate lines until a row is complete. Call `self.parse_row` to finish the job. """ # Top border must fully describe all table columns. self.columns = self.parse_columns(self.block[0], 0) self.border_end = self.columns[-1][1] firststart, firstend = self.columns[0] offset = 1 # skip top border start = 1 text_found = None while offset < len(self.block): line = self.block[offset] if self.span_pat.match(line): # Column span underline or border; row is complete. self.parse_row(self.block[start:offset], start, (line.rstrip(), offset)) start = offset + 1 text_found = None elif line[firststart:firstend].strip(): # First column not blank, therefore it's a new row. if text_found and offset != start: self.parse_row(self.block[start:offset], start) start = offset text_found = 1 elif not text_found: start = offset + 1 offset += 1 def parse_columns(self, line, offset): """ Given a column span underline, return a list of (begin, end) pairs. """ cols = [] end = 0 while 1: begin = line.find('-', end) end = line.find(' ', begin) if begin < 0: break if end < 0: end = len(line) cols.append((begin, end)) if self.columns: if cols[-1][1] != self.border_end: raise TableMarkupError('Column span incomplete at line ' 'offset %s.' % offset) # Allow for an unbounded rightmost column: cols[-1] = (cols[-1][0], self.columns[-1][1]) return cols def init_row(self, colspec, offset): i = 0 cells = [] for start, end in colspec: morecols = 0 try: assert start == self.columns[i][0] while end != self.columns[i][1]: i += 1 morecols += 1 except (AssertionError, IndexError): raise TableMarkupError('Column span alignment problem at ' 'line offset %s.' % (offset + 1)) cells.append([0, morecols, offset, []]) i += 1 return cells def parse_row(self, lines, start, spanline=None): """ Given the text `lines` of a row, parse it and append to `self.table`. The row is parsed according to the current column spec (either `spanline` if provided or `self.columns`). For each column, extract text from each line, and check for text in column margins. Finally, adjust for insigificant whitespace. """ if not (lines or spanline): # No new row, just blank lines. return if spanline: columns = self.parse_columns(*spanline) span_offset = spanline[1] else: columns = self.columns[:] span_offset = start self.check_columns(lines, start, columns) row = self.init_row(columns, start) for i in range(len(columns)): start, end = columns[i] cellblock = lines.get_2D_block(0, start, len(lines), end) cellblock.disconnect() # lines in cell can't sync with parent row[i][3] = cellblock self.table.append(row) def check_columns(self, lines, first_line, columns): """ Check for text in column margins and text overflow in the last column. Raise TableMarkupError if anything but whitespace is in column margins. Adjust the end value for the last column if there is text overflow. """ # "Infinite" value for a dummy last column's beginning, used to # check for text overflow: columns.append((sys.maxint, None)) lastcol = len(columns) - 2 for i in range(len(columns) - 1): start, end = columns[i] nextstart = columns[i+1][0] offset = 0 for line in lines: if i == lastcol and line[end:].strip(): text = line[start:].rstrip() new_end = start + len(text) columns[i] = (start, new_end) main_start, main_end = self.columns[-1] if new_end > main_end: self.columns[-1] = (main_start, new_end) elif line[end:nextstart].strip(): raise TableMarkupError('Text in column margin at line ' 'offset %s.' % (first_line + offset)) offset += 1 columns.pop() def structure_from_cells(self): colspecs = [end - start for start, end in self.columns] first_body_row = 0 if self.head_body_sep: for i in range(len(self.table)): if self.table[i][0][2] > self.head_body_sep: first_body_row = i break return (colspecs, self.table[:first_body_row], self.table[first_body_row:]) def update_dict_of_lists(master, newdata): """ Extend the list values of `master` with those from `newdata`. Both parameters must be dictionaries containing list values. """ for key, values in newdata.items(): master.setdefault(key, []).extend(values)
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/parsers/rst/tableparser.py", "copies": "1", "size": "20160", "license": "mit", "hash": 2969488405434758000, "line_mean": 37.6206896552, "line_max": 80, "alpha_frac": 0.5150793651, "autogenerated": false, "ratio": 4.1413311421528345, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00013899408854708983, "num_lines": 522 }
""" A finite state machine specialized for regular-expression-based text filters, this module defines the following classes: - `StateMachine`, a state machine - `State`, a state superclass - `StateMachineWS`, a whitespace-sensitive version of `StateMachine` - `StateWS`, a state superclass for use with `StateMachineWS` - `SearchStateMachine`, uses `re.search()` instead of `re.match()` - `SearchStateMachineWS`, uses `re.search()` instead of `re.match()` - `ViewList`, extends standard Python lists. - `StringList`, string-specific ViewList. Exception classes: - `StateMachineError` - `UnknownStateError` - `DuplicateStateError` - `UnknownTransitionError` - `DuplicateTransitionError` - `TransitionPatternNotFound` - `TransitionMethodNotFound` - `UnexpectedIndentationError` - `TransitionCorrection`: Raised to switch to another transition. - `StateCorrection`: Raised to switch to another state & transition. Functions: - `string2lines()`: split a multi-line string into a list of one-line strings How To Use This Module ====================== (See the individual classes, methods, and attributes for details.) 1. Import it: ``import statemachine`` or ``from statemachine import ...``. You will also need to ``import re``. 2. Derive a subclass of `State` (or `StateWS`) for each state in your state machine:: class MyState(statemachine.State): Within the state's class definition: a) Include a pattern for each transition, in `State.patterns`:: patterns = {'atransition': r'pattern', ...} b) Include a list of initial transitions to be set up automatically, in `State.initial_transitions`:: initial_transitions = ['atransition', ...] c) Define a method for each transition, with the same name as the transition pattern:: def atransition(self, match, context, next_state): # do something result = [...] # a list return context, next_state, result # context, next_state may be altered Transition methods may raise an `EOFError` to cut processing short. d) You may wish to override the `State.bof()` and/or `State.eof()` implicit transition methods, which handle the beginning- and end-of-file. e) In order to handle nested processing, you may wish to override the attributes `State.nested_sm` and/or `State.nested_sm_kwargs`. If you are using `StateWS` as a base class, in order to handle nested indented blocks, you may wish to: - override the attributes `StateWS.indent_sm`, `StateWS.indent_sm_kwargs`, `StateWS.known_indent_sm`, and/or `StateWS.known_indent_sm_kwargs`; - override the `StateWS.blank()` method; and/or - override or extend the `StateWS.indent()`, `StateWS.known_indent()`, and/or `StateWS.firstknown_indent()` methods. 3. Create a state machine object:: sm = StateMachine(state_classes=[MyState, ...], initial_state='MyState') 4. Obtain the input text, which needs to be converted into a tab-free list of one-line strings. For example, to read text from a file called 'inputfile':: input_string = open('inputfile').read() input_lines = statemachine.string2lines(input_string) 5. Run the state machine on the input text and collect the results, a list:: results = sm.run(input_lines) 6. Remove any lingering circular references:: sm.unlink() """ __docformat__ = 'restructuredtext' import sys import re from types import SliceType as _SliceType class StateMachine: """ A finite state machine for text filters using regular expressions. The input is provided in the form of a list of one-line strings (no newlines). States are subclasses of the `State` class. Transitions consist of regular expression patterns and transition methods, and are defined in each state. The state machine is started with the `run()` method, which returns the results of processing in a list. """ def __init__(self, state_classes, initial_state, debug=0): """ Initialize a `StateMachine` object; add state objects. Parameters: - `state_classes`: a list of `State` (sub)classes. - `initial_state`: a string, the class name of the initial state. - `debug`: a boolean; produce verbose output if true (nonzero). """ self.input_lines = None """`StringList` of input lines (without newlines). Filled by `self.run()`.""" self.input_offset = 0 """Offset of `self.input_lines` from the beginning of the file.""" self.line = None """Current input line.""" self.line_offset = -1 """Current input line offset from beginning of `self.input_lines`.""" self.debug = debug """Debugging mode on/off.""" self.initial_state = initial_state """The name of the initial state (key to `self.states`).""" self.current_state = initial_state """The name of the current state (key to `self.states`).""" self.states = {} """Mapping of {state_name: State_object}.""" self.add_states(state_classes) self.observers = [] """List of bound methods or functions to call whenever the current line changes. Observers are called with one argument, ``self``. Cleared at the end of `run()`.""" def unlink(self): """Remove circular references to objects no longer required.""" for state in self.states.values(): state.unlink() self.states = None def run(self, input_lines, input_offset=0, context=None, input_source=None): """ Run the state machine on `input_lines`. Return results (a list). Reset `self.line_offset` and `self.current_state`. Run the beginning-of-file transition. Input one line at a time and check for a matching transition. If a match is found, call the transition method and possibly change the state. Store the context returned by the transition method to be passed on to the next transition matched. Accumulate the results returned by the transition methods in a list. Run the end-of-file transition. Finally, return the accumulated results. Parameters: - `input_lines`: a list of strings without newlines, or `StringList`. - `input_offset`: the line offset of `input_lines` from the beginning of the file. - `context`: application-specific storage. - `input_source`: name or path of source of `input_lines`. """ self.runtime_init() if isinstance(input_lines, StringList): self.input_lines = input_lines else: self.input_lines = StringList(input_lines, source=input_source) self.input_offset = input_offset self.line_offset = -1 self.current_state = self.initial_state if self.debug: print >>sys.stderr, ( '\nStateMachine.run: input_lines (line_offset=%s):\n| %s' % (self.line_offset, '\n| '.join(self.input_lines))) transitions = None results = [] state = self.get_state() try: if self.debug: print >>sys.stderr, ('\nStateMachine.run: bof transition') context, result = state.bof(context) results.extend(result) while 1: try: try: self.next_line() if self.debug: source, offset = self.input_lines.info( self.line_offset) print >>sys.stderr, ( '\nStateMachine.run: line (source=%r, ' 'offset=%r):\n| %s' % (source, offset, self.line)) context, next_state, result = self.check_line( context, state, transitions) except EOFError: if self.debug: print >>sys.stderr, ( '\nStateMachine.run: %s.eof transition' % state.__class__.__name__) result = state.eof(context) results.extend(result) break else: results.extend(result) except TransitionCorrection, exception: self.previous_line() # back up for another try transitions = (exception.args[0],) if self.debug: print >>sys.stderr, ( '\nStateMachine.run: TransitionCorrection to ' 'state "%s", transition %s.' % (state.__class__.__name__, transitions[0])) continue except StateCorrection, exception: self.previous_line() # back up for another try next_state = exception.args[0] if len(exception.args) == 1: transitions = None else: transitions = (exception.args[1],) if self.debug: print >>sys.stderr, ( '\nStateMachine.run: StateCorrection to state ' '"%s", transition %s.' % (next_state, transitions[0])) else: transitions = None state = self.get_state(next_state) except: if self.debug: self.error() raise self.observers = [] return results def get_state(self, next_state=None): """ Return current state object; set it first if `next_state` given. Parameter `next_state`: a string, the name of the next state. Exception: `UnknownStateError` raised if `next_state` unknown. """ if next_state: if self.debug and next_state != self.current_state: print >>sys.stderr, \ ('\nStateMachine.get_state: Changing state from ' '"%s" to "%s" (input line %s).' % (self.current_state, next_state, self.abs_line_number())) self.current_state = next_state try: return self.states[self.current_state] except KeyError: raise UnknownStateError(self.current_state) def next_line(self, n=1): """Load `self.line` with the `n`'th next line and return it.""" try: try: self.line_offset += n self.line = self.input_lines[self.line_offset] except IndexError: self.line = None raise EOFError return self.line finally: self.notify_observers() def is_next_line_blank(self): """Return 1 if the next line is blank or non-existant.""" try: return not self.input_lines[self.line_offset + 1].strip() except IndexError: return 1 def at_eof(self): """Return 1 if the input is at or past end-of-file.""" return self.line_offset >= len(self.input_lines) - 1 def at_bof(self): """Return 1 if the input is at or before beginning-of-file.""" return self.line_offset <= 0 def previous_line(self, n=1): """Load `self.line` with the `n`'th previous line and return it.""" self.line_offset -= n if self.line_offset < 0: self.line = None else: self.line = self.input_lines[self.line_offset] self.notify_observers() return self.line def goto_line(self, line_offset): """Jump to absolute line offset `line_offset`, load and return it.""" try: try: self.line_offset = line_offset - self.input_offset self.line = self.input_lines[self.line_offset] except IndexError: self.line = None raise EOFError return self.line finally: self.notify_observers() def get_source(self, line_offset): """Return source of line at absolute line offset `line_offset`.""" return self.input_lines.source(line_offset - self.input_offset) def abs_line_offset(self): """Return line offset of current line, from beginning of file.""" return self.line_offset + self.input_offset def abs_line_number(self): """Return line number of current line (counting from 1).""" return self.line_offset + self.input_offset + 1 def insert_input(self, input_lines, source): self.input_lines.insert(self.line_offset + 1, '', source='internal padding') self.input_lines.insert(self.line_offset + 1, '', source='internal padding') self.input_lines.insert(self.line_offset + 2, StringList(input_lines, source)) def get_text_block(self, flush_left=0): """ Return a contiguous block of text. If `flush_left` is true, raise `UnexpectedIndentationError` if an indented line is encountered before the text block ends (with a blank line). """ try: block = self.input_lines.get_text_block(self.line_offset, flush_left) self.next_line(len(block) - 1) return block except UnexpectedIndentationError, error: block, source, lineno = error self.next_line(len(block) - 1) # advance to last line of block raise def check_line(self, context, state, transitions=None): """ Examine one line of input for a transition match & execute its method. Parameters: - `context`: application-dependent storage. - `state`: a `State` object, the current state. - `transitions`: an optional ordered list of transition names to try, instead of ``state.transition_order``. Return the values returned by the transition method: - context: possibly modified from the parameter `context`; - next state name (`State` subclass name); - the result output of the transition, a list. When there is no match, ``state.no_match()`` is called and its return value is returned. """ if transitions is None: transitions = state.transition_order state_correction = None if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: state="%s", transitions=%r.' % (state.__class__.__name__, transitions)) for name in transitions: pattern, method, next_state = state.transitions[name] match = self.match(pattern) if match: if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: Matched transition ' '"%s" in state "%s".' % (name, state.__class__.__name__)) return method(match, context, next_state) else: if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: No match in state "%s".' % state.__class__.__name__) return state.no_match(context, transitions) def match(self, pattern): """ Return the result of a regular expression match. Parameter `pattern`: an `re` compiled regular expression. """ return pattern.match(self.line) def add_state(self, state_class): """ Initialize & add a `state_class` (`State` subclass) object. Exception: `DuplicateStateError` raised if `state_class` was already added. """ statename = state_class.__name__ if self.states.has_key(statename): raise DuplicateStateError(statename) self.states[statename] = state_class(self, self.debug) def add_states(self, state_classes): """ Add `state_classes` (a list of `State` subclasses). """ for state_class in state_classes: self.add_state(state_class) def runtime_init(self): """ Initialize `self.states`. """ for state in self.states.values(): state.runtime_init() def error(self): """Report error details.""" type, value, module, line, function = _exception_data() print >>sys.stderr, '%s: %s' % (type, value) print >>sys.stderr, 'input line %s' % (self.abs_line_number()) print >>sys.stderr, ('module %s, line %s, function %s' % (module, line, function)) def attach_observer(self, observer): """ The `observer` parameter is a function or bound method which takes two arguments, the source and offset of the current line. """ self.observers.append(observer) def detach_observer(self, observer): self.observers.remove(observer) def notify_observers(self): for observer in self.observers: try: info = self.input_lines.info(self.line_offset) except IndexError: info = (None, None) observer(*info) class State: """ State superclass. Contains a list of transitions, and transition methods. Transition methods all have the same signature. They take 3 parameters: - An `re` match object. ``match.string`` contains the matched input line, ``match.start()`` gives the start index of the match, and ``match.end()`` gives the end index. - A context object, whose meaning is application-defined (initial value ``None``). It can be used to store any information required by the state machine, and the retured context is passed on to the next transition method unchanged. - The name of the next state, a string, taken from the transitions list; normally it is returned unchanged, but it may be altered by the transition method if necessary. Transition methods all return a 3-tuple: - A context object, as (potentially) modified by the transition method. - The next state name (a return value of ``None`` means no state change). - The processing result, a list, which is accumulated by the state machine. Transition methods may raise an `EOFError` to cut processing short. There are two implicit transitions, and corresponding transition methods are defined: `bof()` handles the beginning-of-file, and `eof()` handles the end-of-file. These methods have non-standard signatures and return values. `bof()` returns the initial context and results, and may be used to return a header string, or do any other processing needed. `eof()` should handle any remaining context and wrap things up; it returns the final processing result. Typical applications need only subclass `State` (or a subclass), set the `patterns` and `initial_transitions` class attributes, and provide corresponding transition methods. The default object initialization will take care of constructing the list of transitions. """ patterns = None """ {Name: pattern} mapping, used by `make_transition()`. Each pattern may be a string or a compiled `re` pattern. Override in subclasses. """ initial_transitions = None """ A list of transitions to initialize when a `State` is instantiated. Each entry is either a transition name string, or a (transition name, next state name) pair. See `make_transitions()`. Override in subclasses. """ nested_sm = None """ The `StateMachine` class for handling nested processing. If left as ``None``, `nested_sm` defaults to the class of the state's controlling state machine. Override it in subclasses to avoid the default. """ nested_sm_kwargs = None """ Keyword arguments dictionary, passed to the `nested_sm` constructor. Two keys must have entries in the dictionary: - Key 'state_classes' must be set to a list of `State` classes. - Key 'initial_state' must be set to the name of the initial state class. If `nested_sm_kwargs` is left as ``None``, 'state_classes' defaults to the class of the current state, and 'initial_state' defaults to the name of the class of the current state. Override in subclasses to avoid the defaults. """ def __init__(self, state_machine, debug=0): """ Initialize a `State` object; make & add initial transitions. Parameters: - `statemachine`: the controlling `StateMachine` object. - `debug`: a boolean; produce verbose output if true (nonzero). """ self.transition_order = [] """A list of transition names in search order.""" self.transitions = {} """ A mapping of transition names to 3-tuples containing (compiled_pattern, transition_method, next_state_name). Initialized as an instance attribute dynamically (instead of as a class attribute) because it may make forward references to patterns and methods in this or other classes. """ self.add_initial_transitions() self.state_machine = state_machine """A reference to the controlling `StateMachine` object.""" self.debug = debug """Debugging mode on/off.""" if self.nested_sm is None: self.nested_sm = self.state_machine.__class__ if self.nested_sm_kwargs is None: self.nested_sm_kwargs = {'state_classes': [self.__class__], 'initial_state': self.__class__.__name__} def runtime_init(self): """ Initialize this `State` before running the state machine; called from `self.state_machine.run()`. """ pass def unlink(self): """Remove circular references to objects no longer required.""" self.state_machine = None def add_initial_transitions(self): """Make and add transitions listed in `self.initial_transitions`.""" if self.initial_transitions: names, transitions = self.make_transitions( self.initial_transitions) self.add_transitions(names, transitions) def add_transitions(self, names, transitions): """ Add a list of transitions to the start of the transition list. Parameters: - `names`: a list of transition names. - `transitions`: a mapping of names to transition tuples. Exceptions: `DuplicateTransitionError`, `UnknownTransitionError`. """ for name in names: if self.transitions.has_key(name): raise DuplicateTransitionError(name) if not transitions.has_key(name): raise UnknownTransitionError(name) self.transition_order[:0] = names self.transitions.update(transitions) def add_transition(self, name, transition): """ Add a transition to the start of the transition list. Parameter `transition`: a ready-made transition 3-tuple. Exception: `DuplicateTransitionError`. """ if self.transitions.has_key(name): raise DuplicateTransitionError(name) self.transition_order[:0] = [name] self.transitions[name] = transition def remove_transition(self, name): """ Remove a transition by `name`. Exception: `UnknownTransitionError`. """ try: del self.transitions[name] self.transition_order.remove(name) except: raise UnknownTransitionError(name) def make_transition(self, name, next_state=None): """ Make & return a transition tuple based on `name`. This is a convenience function to simplify transition creation. Parameters: - `name`: a string, the name of the transition pattern & method. This `State` object must have a method called '`name`', and a dictionary `self.patterns` containing a key '`name`'. - `next_state`: a string, the name of the next `State` object for this transition. A value of ``None`` (or absent) implies no state change (i.e., continue with the same state). Exceptions: `TransitionPatternNotFound`, `TransitionMethodNotFound`. """ if next_state is None: next_state = self.__class__.__name__ try: pattern = self.patterns[name] if not hasattr(pattern, 'match'): pattern = re.compile(pattern) except KeyError: raise TransitionPatternNotFound( '%s.patterns[%r]' % (self.__class__.__name__, name)) try: method = getattr(self, name) except AttributeError: raise TransitionMethodNotFound( '%s.%s' % (self.__class__.__name__, name)) return (pattern, method, next_state) def make_transitions(self, name_list): """ Return a list of transition names and a transition mapping. Parameter `name_list`: a list, where each entry is either a transition name string, or a 1- or 2-tuple (transition name, optional next state name). """ stringtype = type('') names = [] transitions = {} for namestate in name_list: if type(namestate) is stringtype: transitions[namestate] = self.make_transition(namestate) names.append(namestate) else: transitions[namestate[0]] = self.make_transition(*namestate) names.append(namestate[0]) return names, transitions def no_match(self, context, transitions): """ Called when there is no match from `StateMachine.check_line()`. Return the same values returned by transition methods: - context: unchanged; - next state name: ``None``; - empty result list. Override in subclasses to catch this event. """ return context, None, [] def bof(self, context): """ Handle beginning-of-file. Return unchanged `context`, empty result. Override in subclasses. Parameter `context`: application-defined storage. """ return context, [] def eof(self, context): """ Handle end-of-file. Return empty result. Override in subclasses. Parameter `context`: application-defined storage. """ return [] def nop(self, match, context, next_state): """ A "do nothing" transition method. Return unchanged `context` & `next_state`, empty result. Useful for simple state changes (actionless transitions). """ return context, next_state, [] class StateMachineWS(StateMachine): """ `StateMachine` subclass specialized for whitespace recognition. There are three methods provided for extracting indented text blocks: - `get_indented()`: use when the indent is unknown. - `get_known_indented()`: use when the indent is known for all lines. - `get_first_known_indented()`: use when only the first line's indent is known. """ def get_indented(self, until_blank=0, strip_indent=1): """ Return a block of indented lines of text, and info. Extract an indented block where the indent is unknown for all lines. :Parameters: - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip common leading indent if true (1, default). :Return: - the indented block (a list of lines of text), - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent) if indented: self.next_line(len(indented) - 1) # advance to last indented line while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, indent, offset, blank_finish def get_known_indented(self, indent, until_blank=0, strip_indent=1): """ Return an indented block and info. Extract an indented block where the indent is known for all lines. Starting with the current line, extract the entire text block with at least `indent` indentation (which must be whitespace, except for the first line). :Parameters: - `indent`: The number of indent columns/characters. - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip `indent` characters of indentation if true (1, default). :Return: - the indented block, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent, block_indent=indent) self.next_line(len(indented) - 1) # advance to last indented line while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, offset, blank_finish def get_first_known_indented(self, indent, until_blank=0, strip_indent=1, strip_top=1): """ Return an indented block and info. Extract an indented block where the indent is known for the first line and unknown for all other lines. :Parameters: - `indent`: The first line's indent (# of columns/characters). - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip `indent` characters of indentation if true (1, default). - `strip_top`: Strip blank lines from the beginning of the block. :Return: - the indented block, - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent, first_indent=indent) self.next_line(len(indented) - 1) # advance to last indented line if strip_top: while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, indent, offset, blank_finish class StateWS(State): """ State superclass specialized for whitespace (blank lines & indents). Use this class with `StateMachineWS`. The transitions 'blank' (for blank lines) and 'indent' (for indented text blocks) are added automatically, before any other transitions. The transition method `blank()` handles blank lines and `indent()` handles nested indented blocks. Indented blocks trigger a new state machine to be created by `indent()` and run. The class of the state machine to be created is in `indent_sm`, and the constructor keyword arguments are in the dictionary `indent_sm_kwargs`. The methods `known_indent()` and `firstknown_indent()` are provided for indented blocks where the indent (all lines' and first line's only, respectively) is known to the transition method, along with the attributes `known_indent_sm` and `known_indent_sm_kwargs`. Neither transition method is triggered automatically. """ indent_sm = None """ The `StateMachine` class handling indented text blocks. If left as ``None``, `indent_sm` defaults to the value of `State.nested_sm`. Override it in subclasses to avoid the default. """ indent_sm_kwargs = None """ Keyword arguments dictionary, passed to the `indent_sm` constructor. If left as ``None``, `indent_sm_kwargs` defaults to the value of `State.nested_sm_kwargs`. Override it in subclasses to avoid the default. """ known_indent_sm = None """ The `StateMachine` class handling known-indented text blocks. If left as ``None``, `known_indent_sm` defaults to the value of `indent_sm`. Override it in subclasses to avoid the default. """ known_indent_sm_kwargs = None """ Keyword arguments dictionary, passed to the `known_indent_sm` constructor. If left as ``None``, `known_indent_sm_kwargs` defaults to the value of `indent_sm_kwargs`. Override it in subclasses to avoid the default. """ ws_patterns = {'blank': ' *$', 'indent': ' +'} """Patterns for default whitespace transitions. May be overridden in subclasses.""" ws_initial_transitions = ('blank', 'indent') """Default initial whitespace transitions, added before those listed in `State.initial_transitions`. May be overridden in subclasses.""" def __init__(self, state_machine, debug=0): """ Initialize a `StateSM` object; extends `State.__init__()`. Check for indent state machine attributes, set defaults if not set. """ State.__init__(self, state_machine, debug) if self.indent_sm is None: self.indent_sm = self.nested_sm if self.indent_sm_kwargs is None: self.indent_sm_kwargs = self.nested_sm_kwargs if self.known_indent_sm is None: self.known_indent_sm = self.indent_sm if self.known_indent_sm_kwargs is None: self.known_indent_sm_kwargs = self.indent_sm_kwargs def add_initial_transitions(self): """ Add whitespace-specific transitions before those defined in subclass. Extends `State.add_initial_transitions()`. """ State.add_initial_transitions(self) if self.patterns is None: self.patterns = {} self.patterns.update(self.ws_patterns) names, transitions = self.make_transitions( self.ws_initial_transitions) self.add_transitions(names, transitions) def blank(self, match, context, next_state): """Handle blank lines. Does nothing. Override in subclasses.""" return self.nop(match, context, next_state) def indent(self, match, context, next_state): """ Handle an indented text block. Extend or override in subclasses. Recursively run the registered state machine for indented blocks (`self.indent_sm`). """ indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() sm = self.indent_sm(debug=self.debug, **self.indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results def known_indent(self, match, context, next_state): """ Handle a known-indent text block. Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. """ indented, line_offset, blank_finish = \ self.state_machine.get_known_indented(match.end()) sm = self.known_indent_sm(debug=self.debug, **self.known_indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results def first_known_indent(self, match, context, next_state): """ Handle an indented text block (first line's indent known). Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. """ indented, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) sm = self.known_indent_sm(debug=self.debug, **self.known_indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results class _SearchOverride: """ Mix-in class to override `StateMachine` regular expression behavior. Changes regular expression matching, from the default `re.match()` (succeeds only if the pattern matches at the start of `self.line`) to `re.search()` (succeeds if the pattern matches anywhere in `self.line`). When subclassing a `StateMachine`, list this class **first** in the inheritance list of the class definition. """ def match(self, pattern): """ Return the result of a regular expression search. Overrides `StateMachine.match()`. Parameter `pattern`: `re` compiled regular expression. """ return pattern.search(self.line) class SearchStateMachine(_SearchOverride, StateMachine): """`StateMachine` which uses `re.search()` instead of `re.match()`.""" pass class SearchStateMachineWS(_SearchOverride, StateMachineWS): """`StateMachineWS` which uses `re.search()` instead of `re.match()`.""" pass class ViewList: """ List with extended functionality: slices of ViewList objects are child lists, linked to their parents. Changes made to a child list also affect the parent list. A child list is effectively a "view" (in the SQL sense) of the parent list. Changes to parent lists, however, do *not* affect active child lists. If a parent list is changed, any active child lists should be recreated. The start and end of the slice can be trimmed using the `trim_start()` and `trim_end()` methods, without affecting the parent list. The link between child and parent lists can be broken by calling `disconnect()` on the child list. Also, ViewList objects keep track of the source & offset of each item. This information is accessible via the `source()`, `offset()`, and `info()` methods. """ def __init__(self, initlist=None, source=None, items=None, parent=None, parent_offset=None): self.data = [] """The actual list of data, flattened from various sources.""" self.items = [] """A list of (source, offset) pairs, same length as `self.data`: the source of each line and the offset of each line from the beginning of its source.""" self.parent = parent """The parent list.""" self.parent_offset = parent_offset """Offset of this list from the beginning of the parent list.""" if isinstance(initlist, ViewList): self.data = initlist.data[:] self.items = initlist.items[:] elif initlist is not None: self.data = list(initlist) if items: self.items = items else: self.items = [(source, i) for i in range(len(initlist))] assert len(self.data) == len(self.items), 'data mismatch' def __str__(self): return str(self.data) def __repr__(self): return '%s(%s, items=%s)' % (self.__class__.__name__, self.data, self.items) def __lt__(self, other): return self.data < self.__cast(other) def __le__(self, other): return self.data <= self.__cast(other) def __eq__(self, other): return self.data == self.__cast(other) def __ne__(self, other): return self.data != self.__cast(other) def __gt__(self, other): return self.data > self.__cast(other) def __ge__(self, other): return self.data >= self.__cast(other) def __cmp__(self, other): return cmp(self.data, self.__cast(other)) def __cast(self, other): if isinstance(other, ViewList): return other.data else: return other def __contains__(self, item): return item in self.data def __len__(self): return len(self.data) # The __getitem__()/__setitem__() methods check whether the index # is a slice first, since native list objects start supporting # them directly in Python 2.3 (no exception is raised when # indexing a list with a slice object; they just work). def __getitem__(self, i): if isinstance(i, _SliceType): assert i.step in (None, 1), 'cannot handle slice with stride' return self.__class__(self.data[i.start:i.stop], items=self.items[i.start:i.stop], parent=self, parent_offset=i.start) else: return self.data[i] def __setitem__(self, i, item): if isinstance(i, _SliceType): assert i.step in (None, 1), 'cannot handle slice with stride' if not isinstance(item, ViewList): raise TypeError('assigning non-ViewList to ViewList slice') self.data[i.start:i.stop] = item.data self.items[i.start:i.stop] = item.items assert len(self.data) == len(self.items), 'data mismatch' if self.parent: self.parent[i.start + self.parent_offset : i.stop + self.parent_offset] = item else: self.data[i] = item if self.parent: self.parent[i + self.parent_offset] = item def __delitem__(self, i): try: del self.data[i] del self.items[i] if self.parent: del self.parent[i + self.parent_offset] except TypeError: assert i.step is None, 'cannot handle slice with stride' del self.data[i.start:i.stop] del self.items[i.start:i.stop] if self.parent: del self.parent[i.start + self.parent_offset : i.stop + self.parent_offset] def __add__(self, other): if isinstance(other, ViewList): return self.__class__(self.data + other.data, items=(self.items + other.items)) else: raise TypeError('adding non-ViewList to a ViewList') def __radd__(self, other): if isinstance(other, ViewList): return self.__class__(other.data + self.data, items=(other.items + self.items)) else: raise TypeError('adding ViewList to a non-ViewList') def __iadd__(self, other): if isinstance(other, ViewList): self.data += other.data else: raise TypeError('argument to += must be a ViewList') return self def __mul__(self, n): return self.__class__(self.data * n, items=(self.items * n)) __rmul__ = __mul__ def __imul__(self, n): self.data *= n self.items *= n return self def extend(self, other): if not isinstance(other, ViewList): raise TypeError('extending a ViewList with a non-ViewList') if self.parent: self.parent.insert(len(self.data) + self.parent_offset, other) self.data.extend(other.data) self.items.extend(other.items) def append(self, item, source=None, offset=0): if source is None: self.extend(item) else: if self.parent: self.parent.insert(len(self.data) + self.parent_offset, item, source, offset) self.data.append(item) self.items.append((source, offset)) def insert(self, i, item, source=None, offset=0): if source is None: if not isinstance(item, ViewList): raise TypeError('inserting non-ViewList with no source given') self.data[i:i] = item.data self.items[i:i] = item.items if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.insert(index + self.parent_offset, item) else: self.data.insert(i, item) self.items.insert(i, (source, offset)) if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.insert(index + self.parent_offset, item, source, offset) def pop(self, i=-1): if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.pop(index + self.parent_offset) self.items.pop(i) return self.data.pop(i) def trim_start(self, n=1): """ Remove items from the start of the list, without touching the parent. """ if n > len(self.data): raise IndexError("Size of trim too large; can't trim %s items " "from a list of size %s." % (n, len(self.data))) elif n < 0: raise IndexError('Trim size must be >= 0.') del self.data[:n] del self.items[:n] if self.parent: self.parent_offset += n def trim_end(self, n=1): """ Remove items from the end of the list, without touching the parent. """ if n > len(self.data): raise IndexError("Size of trim too large; can't trim %s items " "from a list of size %s." % (n, len(self.data))) elif n < 0: raise IndexError('Trim size must be >= 0.') del self.data[-n:] del self.items[-n:] def remove(self, item): index = self.index(item) del self[index] def count(self, item): return self.data.count(item) def index(self, item): return self.data.index(item) def reverse(self): self.data.reverse() self.items.reverse() self.parent = None def sort(self, *args): tmp = zip(self.data, self.items) tmp.sort(*args) self.data = [entry[0] for entry in tmp] self.items = [entry[1] for entry in tmp] self.parent = None def info(self, i): """Return source & offset for index `i`.""" try: return self.items[i] except IndexError: if i == len(self.data): # Just past the end return self.items[i - 1][0], None else: raise def source(self, i): """Return source for index `i`.""" return self.info(i)[0] def offset(self, i): """Return offset for index `i`.""" return self.info(i)[1] def disconnect(self): """Break link between this list and parent list.""" self.parent = None class StringList(ViewList): """A `ViewList` with string-specific methods.""" def trim_left(self, length, start=0, end=sys.maxint): """ Trim `length` characters off the beginning of each item, in-place, from index `start` to `end`. No whitespace-checking is done on the trimmed text. Does not affect slice parent. """ self.data[start:end] = [line[length:] for line in self.data[start:end]] def get_text_block(self, start, flush_left=0): """ Return a contiguous block of text. If `flush_left` is true, raise `UnexpectedIndentationError` if an indented line is encountered before the text block ends (with a blank line). """ end = start last = len(self.data) while end < last: line = self.data[end] if not line.strip(): break if flush_left and (line[0] == ' '): source, offset = self.info(end) raise UnexpectedIndentationError(self[start:end], source, offset + 1) end += 1 return self[start:end] def get_indented(self, start=0, until_blank=0, strip_indent=1, block_indent=None, first_indent=None): """ Extract and return a StringList of indented lines of text. Collect all lines with indentation, determine the minimum indentation, remove the minimum indentation from all indented lines (unless `strip_indent` is false), and return them. All lines up to but not including the first unindented line will be returned. :Parameters: - `start`: The index of the first line to examine. - `until_blank`: Stop collecting at the first blank line if true. - `strip_indent`: Strip common leading indent if true (default). - `block_indent`: The indent of the entire block, if known. - `first_indent`: The indent of the first line, if known. :Return: - a StringList of indented lines with mininum indent removed; - the amount of the indent; - a boolean: did the indented block finish with a blank line or EOF? """ indent = block_indent # start with None if unknown end = start if block_indent is not None and first_indent is None: first_indent = block_indent if first_indent is not None: end += 1 last = len(self.data) while end < last: line = self.data[end] if line and (line[0] != ' ' or (block_indent is not None and line[:block_indent].strip())): # Line not indented or insufficiently indented. # Block finished properly iff the last indented line blank: blank_finish = ((end > start) and not self.data[end - 1].strip()) break stripped = line.lstrip() if not stripped: # blank line if until_blank: blank_finish = 1 break elif block_indent is None: line_indent = len(line) - len(stripped) if indent is None: indent = line_indent else: indent = min(indent, line_indent) end += 1 else: blank_finish = 1 # block ends at end of lines block = self[start:end] if first_indent is not None and block: block.data[0] = block.data[0][first_indent:] if indent and strip_indent: block.trim_left(indent, start=(first_indent is not None)) return block, indent or 0, blank_finish def get_2D_block(self, top, left, bottom, right, strip_indent=1): block = self[top:bottom] indent = right for i in range(len(block.data)): block.data[i] = line = block.data[i][left:right].rstrip() if line: indent = min(indent, len(line) - len(line.lstrip())) if strip_indent and 0 < indent < right: block.data = [line[indent:] for line in block.data] return block class StateMachineError(Exception): pass class UnknownStateError(StateMachineError): pass class DuplicateStateError(StateMachineError): pass class UnknownTransitionError(StateMachineError): pass class DuplicateTransitionError(StateMachineError): pass class TransitionPatternNotFound(StateMachineError): pass class TransitionMethodNotFound(StateMachineError): pass class UnexpectedIndentationError(StateMachineError): pass class TransitionCorrection(Exception): """ Raise from within a transition method to switch to another transition. Raise with one argument, the new transition name. """ class StateCorrection(Exception): """ Raise from within a transition method to switch to another state. Raise with one or two arguments: new state name, and an optional new transition name. """ def string2lines(astring, tab_width=8, convert_whitespace=0, whitespace=re.compile('[\v\f]')): """ Return a list of one-line strings with tabs expanded and no newlines. Each tab is expanded with between 1 and `tab_width` spaces, so that the next character's index becomes a multiple of `tab_width` (8 by default). Parameters: - `astring`: a multi-line string. - `tab_width`: the number of columns between tab stops. - `convert_whitespace`: convert form feeds and vertical tabs to spaces? """ if convert_whitespace: astring = whitespace.sub(' ', astring) return [s.expandtabs(tab_width) for s in astring.splitlines()] def _exception_data(): """ Return exception information: - the exception's class name; - the exception object; - the name of the file containing the offending code; - the line number of the offending code; - the function name of the offending code. """ type, value, traceback = sys.exc_info() while traceback.tb_next: traceback = traceback.tb_next code = traceback.tb_frame.f_code return (type.__name__, value, code.co_filename, traceback.tb_lineno, code.co_name)
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/statemachine.py", "copies": "1", "size": "54368", "license": "mit", "hash": 6972908152179150000, "line_mean": 36.0859481583, "line_max": 78, "alpha_frac": 0.5883975868, "autogenerated": false, "ratio": 4.402267206477733, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5490664793277733, "avg_score": null, "num_lines": null }
""" Parser for Python modules. Requires Python 2.2 or higher. The `parse_module()` function takes a module's text and file name, runs it through the module parser (using compiler.py and tokenize.py) and produces a parse tree of the source code, using the nodes as found in pynodes.py. For example, given this module (x.py):: # comment '''Docstring''' '''Additional docstring''' __docformat__ = 'reStructuredText' a = 1 '''Attribute docstring''' class C(Super): '''C's docstring''' class_attribute = 1 '''class_attribute's docstring''' def __init__(self, text=None): '''__init__'s docstring''' self.instance_attribute = (text * 7 + ' whaddyaknow') '''instance_attribute's docstring''' def f(x, # parameter x y=a*5, # parameter y *args): # parameter args '''f's docstring''' return [x + item for item in args] f.function_attribute = 1 '''f.function_attribute's docstring''' The module parser will produce this module documentation tree:: <module_section filename="test data"> <docstring> Docstring <docstring lineno="5"> Additional docstring <attribute lineno="7"> <object_name> __docformat__ <expression_value lineno="7"> 'reStructuredText' <attribute lineno="9"> <object_name> a <expression_value lineno="9"> 1 <docstring lineno="10"> Attribute docstring <class_section lineno="12"> <object_name> C <class_base> Super <docstring lineno="12"> C's docstring <attribute lineno="16"> <object_name> class_attribute <expression_value lineno="16"> 1 <docstring lineno="17"> class_attribute's docstring <method_section lineno="19"> <object_name> __init__ <docstring lineno="19"> __init__'s docstring <parameter_list lineno="19"> <parameter lineno="19"> <object_name> self <parameter lineno="19"> <object_name> text <parameter_default lineno="19"> None <attribute lineno="22"> <object_name> self.instance_attribute <expression_value lineno="22"> (text * 7 + ' whaddyaknow') <docstring lineno="24"> instance_attribute's docstring <function_section lineno="27"> <object_name> f <docstring lineno="27"> f's docstring <parameter_list lineno="27"> <parameter lineno="27"> <object_name> x <comment> # parameter x <parameter lineno="27"> <object_name> y <parameter_default lineno="27"> a * 5 <comment> # parameter y <parameter excess_positional="1" lineno="27"> <object_name> args <comment> # parameter args <attribute lineno="33"> <object_name> f.function_attribute <expression_value lineno="33"> 1 <docstring lineno="34"> f.function_attribute's docstring (Comments are not implemented yet.) compiler.parse() provides most of what's needed for this doctree, and "tokenize" can be used to get the rest. We can determine the line number from the compiler.parse() AST, and the TokenParser.rhs(lineno) method provides the rest. The Docutils Python reader component will transform this module doctree into a Python-specific Docutils doctree, and then a `stylist transform`_ will further transform it into a generic doctree. Namespaces will have to be compiled for each of the scopes, but I'm not certain at what stage of processing. It's very important to keep all docstring processing out of this, so that it's a completely generic and not tool-specific. > Why perform all of those transformations? Why not go from the AST to a > generic doctree? Or, even from the AST to the final output? I want the docutils.readers.python.moduleparser.parse_module() function to produce a standard documentation-oriented tree that can be used by any tool. We can develop it together without having to compromise on the rest of our design (i.e., HappyDoc doesn't have to be made to work like Docutils, and vice-versa). It would be a higher-level version of what compiler.py provides. The Python reader component transforms this generic AST into a Python-specific doctree (it knows about modules, classes, functions, etc.), but this is specific to Docutils and cannot be used by HappyDoc or others. The stylist transform does the final layout, converting Python-specific structures ("class" sections, etc.) into a generic doctree using primitives (tables, sections, lists, etc.). This generic doctree does *not* know about Python structures any more. The advantage is that this doctree can be handed off to any of the output writers to create any output format we like. The latter two transforms are separate because I want to be able to have multiple independent layout styles (multiple runtime-selectable "stylist transforms"). Each of the existing tools (HappyDoc, pydoc, epydoc, Crystal, etc.) has its own fixed format. I personally don't like the tables-based format produced by these tools, and I'd like to be able to customize the format easily. That's the goal of stylist transforms, which are independent from the Reader component itself. One stylist transform could produce HappyDoc-like output, another could produce output similar to module docs in the Python library reference manual, and so on. It's for exactly this reason: >> It's very important to keep all docstring processing out of this, so that >> it's a completely generic and not tool-specific. ... but it goes past docstring processing. It's also important to keep style decisions and tool-specific data transforms out of this module parser. Issues ====== * At what point should namespaces be computed? Should they be part of the basic AST produced by the ASTVisitor walk, or generated by another tree traversal? * At what point should a distinction be made between local variables & instance attributes in __init__ methods? * Docstrings are getting their lineno from their parents. Should the TokenParser find the real line no's? * Comments: include them? How and when? Only full-line comments, or parameter comments too? (See function "f" above for an example.) * Module could use more docstrings & refactoring in places. """ __docformat__ = 'reStructuredText' import sys import compiler import compiler.ast import tokenize import token from compiler.consts import OP_ASSIGN from compiler.visitor import ASTVisitor from types import StringType, UnicodeType, TupleType from docutils.readers.python import pynodes from docutils.nodes import Text def parse_module(module_text, filename): """Return a module documentation tree from `module_text`.""" ast = compiler.parse(module_text) token_parser = TokenParser(module_text) visitor = ModuleVisitor(filename, token_parser) compiler.walk(ast, visitor, walker=visitor) return visitor.module class BaseVisitor(ASTVisitor): def __init__(self, token_parser): ASTVisitor.__init__(self) self.token_parser = token_parser self.context = [] self.documentable = None def default(self, node, *args): self.documentable = None #print 'in default (%s)' % node.__class__.__name__ #ASTVisitor.default(self, node, *args) def default_visit(self, node, *args): #print 'in default_visit (%s)' % node.__class__.__name__ ASTVisitor.default(self, node, *args) class DocstringVisitor(BaseVisitor): def visitDiscard(self, node): if self.documentable: self.visit(node.expr) def visitConst(self, node): if self.documentable: if type(node.value) in (StringType, UnicodeType): self.documentable.append(make_docstring(node.value, node.lineno)) else: self.documentable = None def visitStmt(self, node): self.default_visit(node) class AssignmentVisitor(DocstringVisitor): def visitAssign(self, node): visitor = AttributeVisitor(self.token_parser) compiler.walk(node, visitor, walker=visitor) if visitor.attributes: self.context[-1].extend(visitor.attributes) if len(visitor.attributes) == 1: self.documentable = visitor.attributes[0] else: self.documentable = None class ModuleVisitor(AssignmentVisitor): def __init__(self, filename, token_parser): AssignmentVisitor.__init__(self, token_parser) self.filename = filename self.module = None def visitModule(self, node): self.module = module = pynodes.module_section() module['filename'] = self.filename append_docstring(module, node.doc, node.lineno) self.context.append(module) self.documentable = module self.visit(node.node) self.context.pop() def visitImport(self, node): self.context[-1] += make_import_group(names=node.names, lineno=node.lineno) self.documentable = None def visitFrom(self, node): self.context[-1].append( make_import_group(names=node.names, from_name=node.modname, lineno=node.lineno)) self.documentable = None def visitFunction(self, node): visitor = FunctionVisitor(self.token_parser, function_class=pynodes.function_section) compiler.walk(node, visitor, walker=visitor) self.context[-1].append(visitor.function) def visitClass(self, node): visitor = ClassVisitor(self.token_parser) compiler.walk(node, visitor, walker=visitor) self.context[-1].append(visitor.klass) class AttributeVisitor(BaseVisitor): def __init__(self, token_parser): BaseVisitor.__init__(self, token_parser) self.attributes = pynodes.class_attribute_section() def visitAssign(self, node): # Don't visit the expression itself, just the attribute nodes: for child in node.nodes: self.dispatch(child) expression_text = self.token_parser.rhs(node.lineno) expression = pynodes.expression_value() expression.append(Text(expression_text)) for attribute in self.attributes: attribute.append(expression) def visitAssName(self, node): self.attributes.append(make_attribute(node.name, lineno=node.lineno)) def visitAssTuple(self, node): attributes = self.attributes self.attributes = [] self.default_visit(node) n = pynodes.attribute_tuple() n.extend(self.attributes) n['lineno'] = self.attributes[0]['lineno'] attributes.append(n) self.attributes = attributes #self.attributes.append(att_tuple) def visitAssAttr(self, node): self.default_visit(node, node.attrname) def visitGetattr(self, node, suffix): self.default_visit(node, node.attrname + '.' + suffix) def visitName(self, node, suffix): self.attributes.append(make_attribute(node.name + '.' + suffix, lineno=node.lineno)) class FunctionVisitor(DocstringVisitor): in_function = 0 def __init__(self, token_parser, function_class): DocstringVisitor.__init__(self, token_parser) self.function_class = function_class def visitFunction(self, node): if self.in_function: self.documentable = None # Don't bother with nested function definitions. return self.in_function = 1 self.function = function = make_function_like_section( name=node.name, lineno=node.lineno, doc=node.doc, function_class=self.function_class) self.context.append(function) self.documentable = function self.parse_parameter_list(node) self.visit(node.code) self.context.pop() def parse_parameter_list(self, node): parameters = [] special = [] argnames = list(node.argnames) if node.kwargs: special.append(make_parameter(argnames[-1], excess_keyword=1)) argnames.pop() if node.varargs: special.append(make_parameter(argnames[-1], excess_positional=1)) argnames.pop() defaults = list(node.defaults) defaults = [None] * (len(argnames) - len(defaults)) + defaults function_parameters = self.token_parser.function_parameters( node.lineno) #print >>sys.stderr, function_parameters for argname, default in zip(argnames, defaults): if type(argname) is TupleType: parameter = pynodes.parameter_tuple() for tuplearg in argname: parameter.append(make_parameter(tuplearg)) argname = normalize_parameter_name(argname) else: parameter = make_parameter(argname) if default: n_default = pynodes.parameter_default() n_default.append(Text(function_parameters[argname])) parameter.append(n_default) parameters.append(parameter) if parameters or special: special.reverse() parameters.extend(special) parameter_list = pynodes.parameter_list() parameter_list.extend(parameters) self.function.append(parameter_list) class ClassVisitor(AssignmentVisitor): in_class = 0 def __init__(self, token_parser): AssignmentVisitor.__init__(self, token_parser) self.bases = [] def visitClass(self, node): if self.in_class: self.documentable = None # Don't bother with nested class definitions. return self.in_class = 1 #import mypdb as pdb #pdb.set_trace() for base in node.bases: self.visit(base) self.klass = klass = make_class_section(node.name, self.bases, doc=node.doc, lineno=node.lineno) self.context.append(klass) self.documentable = klass self.visit(node.code) self.context.pop() def visitGetattr(self, node, suffix=None): if suffix: name = node.attrname + '.' + suffix else: name = node.attrname self.default_visit(node, name) def visitName(self, node, suffix=None): if suffix: name = node.name + '.' + suffix else: name = node.name self.bases.append(name) def visitFunction(self, node): if node.name == '__init__': visitor = InitMethodVisitor(self.token_parser, function_class=pynodes.method_section) compiler.walk(node, visitor, walker=visitor) else: visitor = FunctionVisitor(self.token_parser, function_class=pynodes.method_section) compiler.walk(node, visitor, walker=visitor) self.context[-1].append(visitor.function) class InitMethodVisitor(FunctionVisitor, AssignmentVisitor): pass class TokenParser: def __init__(self, text): self.text = text + '\n\n' self.lines = self.text.splitlines(1) self.generator = tokenize.generate_tokens(iter(self.lines).next) self.next() def __iter__(self): return self def next(self): self.token = self.generator.next() self.type, self.string, self.start, self.end, self.line = self.token return self.token def goto_line(self, lineno): while self.start[0] < lineno: self.next() return token def rhs(self, lineno): """ Return a whitespace-normalized expression string from the right-hand side of an assignment at line `lineno`. """ self.goto_line(lineno) while self.string != '=': self.next() self.stack = None while self.type != token.NEWLINE and self.string != ';': if self.string == '=' and not self.stack: self.tokens = [] self.stack = [] self._type = None self._string = None self._backquote = 0 else: self.note_token() self.next() self.next() text = ''.join(self.tokens) return text.strip() closers = {')': '(', ']': '[', '}': '{'} openers = {'(': 1, '[': 1, '{': 1} del_ws_prefix = {'.': 1, '=': 1, ')': 1, ']': 1, '}': 1, ':': 1, ',': 1} no_ws_suffix = {'.': 1, '=': 1, '(': 1, '[': 1, '{': 1} def note_token(self): if self.type == tokenize.NL: return del_ws = self.del_ws_prefix.has_key(self.string) append_ws = not self.no_ws_suffix.has_key(self.string) if self.openers.has_key(self.string): self.stack.append(self.string) if (self._type == token.NAME or self.closers.has_key(self._string)): del_ws = 1 elif self.closers.has_key(self.string): assert self.stack[-1] == self.closers[self.string] self.stack.pop() elif self.string == '`': if self._backquote: del_ws = 1 assert self.stack[-1] == '`' self.stack.pop() else: append_ws = 0 self.stack.append('`') self._backquote = not self._backquote if del_ws and self.tokens and self.tokens[-1] == ' ': del self.tokens[-1] self.tokens.append(self.string) self._type = self.type self._string = self.string if append_ws: self.tokens.append(' ') def function_parameters(self, lineno): """ Return a dictionary mapping parameters to defaults (whitespace-normalized strings). """ self.goto_line(lineno) while self.string != 'def': self.next() while self.string != '(': self.next() name = None default = None parameter_tuple = None self.tokens = [] parameters = {} self.stack = [self.string] self.next() while 1: if len(self.stack) == 1: if parameter_tuple: # Just encountered ")". #print >>sys.stderr, 'parameter_tuple: %r' % self.tokens name = ''.join(self.tokens).strip() self.tokens = [] parameter_tuple = None if self.string in (')', ','): if name: if self.tokens: default_text = ''.join(self.tokens).strip() else: default_text = None parameters[name] = default_text self.tokens = [] name = None default = None if self.string == ')': break elif self.type == token.NAME: if name and default: self.note_token() else: assert name is None, ( 'token=%r name=%r parameters=%r stack=%r' % (self.token, name, parameters, self.stack)) name = self.string #print >>sys.stderr, 'name=%r' % name elif self.string == '=': assert name is not None, 'token=%r' % (self.token,) assert default is None, 'token=%r' % (self.token,) assert self.tokens == [], 'token=%r' % (self.token,) default = 1 self._type = None self._string = None self._backquote = 0 elif name: self.note_token() elif self.string == '(': parameter_tuple = 1 self._type = None self._string = None self._backquote = 0 self.note_token() else: # ignore these tokens: assert (self.string in ('*', '**', '\n') or self.type == tokenize.COMMENT), ( 'token=%r' % (self.token,)) else: self.note_token() self.next() return parameters def make_docstring(doc, lineno): n = pynodes.docstring() if lineno: # Really, only module docstrings don't have a line # (@@: but maybe they should) n['lineno'] = lineno n.append(Text(doc)) return n def append_docstring(node, doc, lineno): if doc: node.append(make_docstring(doc, lineno)) def make_class_section(name, bases, lineno, doc): n = pynodes.class_section() n['lineno'] = lineno n.append(make_object_name(name)) for base in bases: b = pynodes.class_base() b.append(make_object_name(base)) n.append(b) append_docstring(n, doc, lineno) return n def make_object_name(name): n = pynodes.object_name() n.append(Text(name)) return n def make_function_like_section(name, lineno, doc, function_class): n = function_class() n['lineno'] = lineno n.append(make_object_name(name)) append_docstring(n, doc, lineno) return n def make_import_group(names, lineno, from_name=None): n = pynodes.import_group() n['lineno'] = lineno if from_name: n_from = pynodes.import_from() n_from.append(Text(from_name)) n.append(n_from) for name, alias in names: n_name = pynodes.import_name() n_name.append(Text(name)) if alias: n_alias = pynodes.import_alias() n_alias.append(Text(alias)) n_name.append(n_alias) n.append(n_name) return n def make_class_attribute(name, lineno): n = pynodes.class_attribute() n['lineno'] = lineno n.append(Text(name)) return n def make_attribute(name, lineno): n = pynodes.attribute() n['lineno'] = lineno n.append(make_object_name(name)) return n def make_parameter(name, excess_keyword=0, excess_positional=0): """ excess_keyword and excess_positional must be either 1 or 0, and not both of them can be 1. """ n = pynodes.parameter() n.append(make_object_name(name)) assert not excess_keyword or not excess_positional if excess_keyword: n['excess_keyword'] = 1 if excess_positional: n['excess_positional'] = 1 return n def trim_docstring(text): """ Trim indentation and blank lines from docstring text & return it. See PEP 257. """ if not text: return text # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = text.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = sys.maxint for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxint: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed) def normalize_parameter_name(name): """ Converts a tuple like ``('a', ('b', 'c'), 'd')`` into ``'(a, (b, c), d)'`` """ if type(name) is TupleType: return '(%s)' % ', '.join([normalize_parameter_name(n) for n in name]) else: return name if __name__ == '__main__': import sys args = sys.argv[1:] if args[0] == '-v': filename = args[1] module_text = open(filename).read() ast = compiler.parse(module_text) visitor = compiler.visitor.ExampleASTVisitor() compiler.walk(ast, visitor, walker=visitor, verbose=1) else: filename = args[0] content = open(filename).read() print parse_module(content, filename).pformat()
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/readers/python/moduleparser.py", "copies": "1", "size": "25838", "license": "mit", "hash": 4695782533006103000, "line_mean": 33.0870712401, "line_max": 81, "alpha_frac": 0.5695487267, "autogenerated": false, "ratio": 4.237821879612924, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.006881399586058677, "num_lines": 758 }
""" Directives for typically HTML-specific constructs. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import states from docutils.transforms import components def meta(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): node = nodes.Element() if content: new_line_offset, blank_finish = state.nested_list_parse( content, content_offset, node, initial_state='MetaBody', blank_finish=1, state_machine_kwargs=metaSMkwargs) if (new_line_offset - content_offset) != len(content): # incomplete parse of block? error = state_machine.reporter.error( 'Invalid meta directive.', nodes.literal_block(block_text, block_text), line=lineno) node += error else: error = state_machine.reporter.error( 'Empty meta directive.', nodes.literal_block(block_text, block_text), line=lineno) node += error return node.children meta.content = 1 def imagemap(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return [] class MetaBody(states.SpecializedBody): class meta(nodes.Special, nodes.PreBibliographic, nodes.Element): """HTML-specific "meta" element.""" pass def field_marker(self, match, context, next_state): """Meta element.""" node, blank_finish = self.parsemeta(match) self.parent += node return [], next_state, [] def parsemeta(self, match): name = self.parse_field_marker(match) indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) node = self.meta() pending = nodes.pending(components.Filter, {'component': 'writer', 'format': 'html', 'nodes': [node]}) node['content'] = ' '.join(indented) if not indented: line = self.state_machine.line msg = self.reporter.info( 'No content for meta tag "%s".' % name, nodes.literal_block(line, line), line=self.state_machine.abs_line_number()) return msg, blank_finish tokens = name.split() try: attname, val = utils.extract_name_value(tokens[0])[0] node[attname.lower()] = val except utils.NameValueError: node['name'] = tokens[0] for token in tokens[1:]: try: attname, val = utils.extract_name_value(token)[0] node[attname.lower()] = val except utils.NameValueError, detail: line = self.state_machine.line msg = self.reporter.error( 'Error parsing meta tag attribute "%s": %s.' % (token, detail), nodes.literal_block(line, line), line=self.state_machine.abs_line_number()) return msg, blank_finish self.document.note_pending(pending) return pending, blank_finish metaSMkwargs = {'state_classes': (MetaBody,)}
{ "repo_name": "pombreda/django-hotclub", "path": "libs/external_libs/docutils-0.4/docutils/parsers/rst/directives/html.py", "copies": "7", "size": "3529", "license": "mit", "hash": 3944573929864380400, "line_mean": 35.7604166667, "line_max": 73, "alpha_frac": 0.5809011051, "autogenerated": false, "ratio": 4.176331360946746, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009454706178245944, "num_lines": 96 }
""" This package contains the Python Source Reader modules. It requires Python 2.2 or higher (`moduleparser` depends on the `compiler` and `tokenize` modules). """ __docformat__ = 'reStructuredText' import sys import docutils.readers from docutils.readers.python import moduleparser from docutils import parsers from docutils import nodes from docutils.readers.python import pynodes from docutils import readers class Reader(docutils.readers.Reader): config_section = 'python reader' config_section_dependencies = ('readers',) default_parser = 'restructuredtext' def parse(self): """Parse `self.input` into a document tree.""" self.document = document = self.new_document() module_section = moduleparser.parse_module(self.input, self.source.source_path) module_section.walk(DocformatVisitor(self.document)) visitor = DocstringFormattingVisitor( document=document, default_parser=self.default_parser) module_section.walk(visitor) self.document.append(module_section) class DocformatVisitor(nodes.SparseNodeVisitor): """ This sets docformat attributes in a module. Wherever an assignment to __docformat__ is found, we look for the enclosing scope -- a class, a module, or a function -- and set the docformat attribute there. We can't do this during the DocstringFormattingVisitor walking, because __docformat__ may appear below a docstring in that format (typically below the module docstring). """ def visit_attribute(self, node): assert isinstance(node[0], pynodes.object_name) name = node[0][0].data if name != '__docformat__': return value = None for child in children: if isinstance(child, pynodes.expression_value): value = child[0].data break assert value.startswith("'") or value.startswith('"'), "__docformat__ must be assigned a string literal (not %s); line: %s" % (value, node['lineno']) name = name[1:-1] looking_in = node.parent while not isinstance(looking_in, (pynodes.module_section, pynodes.function_section, pynodes.class_section)): looking_in = looking_in.parent looking_in['docformat'] = name class DocstringFormattingVisitor(nodes.SparseNodeVisitor): def __init__(self, document, default_parser): self.document = document self.default_parser = default_parser self.parsers = {} def visit_docstring(self, node): text = node[0].data docformat = self.find_docformat(node) del node[0] node['docformat'] = docformat parser = self.get_parser(docformat) parser.parse(text, self.document) for child in self.document.children: node.append(child) self.document.current_source = self.document.current_line = None del self.document[:] def get_parser(self, parser_name): """ Get a parser based on its name. We reuse parsers during this visitation, so parser instances are cached. """ parser_name = parsers._parser_aliases.get(parser_name, parser_name) if not self.parsers.has_key(parser_name): cls = parsers.get_parser_class(parser_name) self.parsers[parser_name] = cls() return self.parsers[parser_name] def find_docformat(self, node): """ Find the __docformat__ closest to this node (i.e., look in the class or module) """ while node: if node.get('docformat'): return node['docformat'] node = node.parent return self.default_parser if __name__ == '__main__': try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates pseudo-XML from Python modules ' '(for testing purposes). ' + default_description) publish_cmdline(description=description, reader=Reader())
{ "repo_name": "google-code-export/django-hotclub", "path": "libs/external_libs/docutils-0.4/docutils/readers/python/__init__.py", "copies": "7", "size": "4503", "license": "mit", "hash": 6992050536639095000, "line_mean": 33.1136363636, "line_max": 157, "alpha_frac": 0.624694648, "autogenerated": false, "ratio": 4.350724637681159, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0010250263098364363, "num_lines": 132 }
""" PEP HTML Writer. """ __docformat__ = 'reStructuredText' import sys import docutils from docutils import frontend, nodes, utils from docutils.writers import html4css1 class Writer(html4css1.Writer): settings_spec = html4css1.Writer.settings_spec + ( 'PEP/HTML-Specific Options', None, (('Specify a template file. Default is "pep-html-template".', ['--template'], {'default': 'pep-html-template', 'metavar': '<file>'}), ('Python\'s home URL. Default is ".." (parent directory).', ['--python-home'], {'default': '..', 'metavar': '<URL>'}), ('Home URL prefix for PEPs. Default is "." (current directory).', ['--pep-home'], {'default': '.', 'metavar': '<URL>'}), # For testing. (frontend.SUPPRESS_HELP, ['--no-random'], {'action': 'store_true', 'validator': frontend.validate_boolean}),)) relative_path_settings = (html4css1.Writer.relative_path_settings + ('template',)) config_section = 'pep_html writer' config_section_dependencies = ('writers', 'html4css1 writer') def __init__(self): html4css1.Writer.__init__(self) self.translator_class = HTMLTranslator def translate(self): html4css1.Writer.translate(self) settings = self.document.settings template = open(settings.template).read() # Substitutions dict for template: subs = {} subs['encoding'] = settings.output_encoding subs['version'] = docutils.__version__ subs['stylesheet'] = ''.join(self.stylesheet) pyhome = settings.python_home subs['pyhome'] = pyhome subs['pephome'] = settings.pep_home if pyhome == '..': subs['pepindex'] = '.' else: subs['pepindex'] = pyhome + '/peps/' index = self.document.first_child_matching_class(nodes.field_list) header = self.document[index] pepnum = header[0][1].astext() subs['pep'] = pepnum if settings.no_random: subs['banner'] = 0 else: import random subs['banner'] = random.randrange(64) try: subs['pepnum'] = '%04i' % int(pepnum) except ValueError: subs['pepnum'] = pepnum subs['title'] = header[1][1].astext() subs['body'] = ''.join( self.body_pre_docinfo + self.docinfo + self.body) subs['body_suffix'] = ''.join(self.body_suffix) self.output = template % subs class HTMLTranslator(html4css1.HTMLTranslator): def depart_field_list(self, node): html4css1.HTMLTranslator.depart_field_list(self, node) if 'rfc2822' in node['classes']: self.body.append('<hr />\n')
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/writers/pep_html.py", "copies": "1", "size": "3039", "license": "mit", "hash": -3558051640561936000, "line_mean": 32.7666666667, "line_max": 78, "alpha_frac": 0.5742020401, "autogenerated": false, "ratio": 3.871337579617834, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49455396197178336, "avg_score": null, "num_lines": null }
""" Python Enhancement Proposal (PEP) Reader. """ __docformat__ = 'reStructuredText' from docutils.readers import standalone from docutils.transforms import peps, references from docutils.parsers import rst class Reader(standalone.Reader): supported = ('pep',) """Contexts this reader supports.""" settings_spec = ( 'PEP Reader Option Defaults', 'The --pep-references and --rfc-references options (for the ' 'reStructuredText parser) are on by default.', ()) config_section = 'pep reader' config_section_dependencies = ('readers', 'standalone reader') default_transforms = (references.Substitutions, references.PropagateTargets, peps.Headers, peps.Contents, references.AnonymousHyperlinks, references.IndirectHyperlinks, peps.TargetNotes, references.Footnotes, references.ExternalTargets, references.InternalTargets,) settings_default_overrides = {'pep_references': 1, 'rfc_references': 1} inliner_class = rst.states.Inliner def __init__(self, parser=None, parser_name=None): """`parser` should be ``None``.""" if parser is None: parser = rst.Parser(rfc2822=1, inliner=self.inliner_class()) standalone.Reader.__init__(self, parser, '')
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/readers/pep.py", "copies": "1", "size": "1707", "license": "mit", "hash": -6795312798220825000, "line_mean": 31.8269230769, "line_max": 75, "alpha_frac": 0.6010544815, "autogenerated": false, "ratio": 4.422279792746114, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5523334274246113, "avg_score": null, "num_lines": null }
""" Transforms for PEP processing. - `Headers`: Used to transform a PEP's initial RFC-2822 header. It remains a field list, but some entries get processed. - `Contents`: Auto-inserts a table of contents. - `PEPZero`: Special processing for PEP 0. """ __docformat__ = 'reStructuredText' import sys import os import re import time from docutils import nodes, utils, languages from docutils import ApplicationError, DataError from docutils.transforms import Transform, TransformError from docutils.transforms import parts, references, misc class Headers(Transform): """ Process fields in a PEP's initial RFC-2822 header. """ default_priority = 360 pep_url = 'pep-%04d.html' pep_cvs_url = ('http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/' 'python/nondist/peps/pep-%04d.txt') rcs_keyword_substitutions = ( (re.compile(r'\$' r'RCSfile: (.+),v \$$', re.IGNORECASE), r'\1'), (re.compile(r'\$[a-zA-Z]+: (.+) \$$'), r'\1'),) def apply(self): if not len(self.document): # @@@ replace these DataErrors with proper system messages raise DataError('Document tree is empty.') header = self.document[0] if not isinstance(header, nodes.field_list) or \ 'rfc2822' not in header['classes']: raise DataError('Document does not begin with an RFC-2822 ' 'header; it is not a PEP.') pep = None for field in header: if field[0].astext().lower() == 'pep': # should be the first field value = field[1].astext() try: pep = int(value) cvs_url = self.pep_cvs_url % pep except ValueError: pep = value cvs_url = None msg = self.document.reporter.warning( '"PEP" header must contain an integer; "%s" is an ' 'invalid value.' % pep, base_node=field) msgid = self.document.set_id(msg) prb = nodes.problematic(value, value or '(none)', refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) if len(field[1]): field[1][0][:] = [prb] else: field[1] += nodes.paragraph('', '', prb) break if pep is None: raise DataError('Document does not contain an RFC-2822 "PEP" ' 'header.') if pep == 0: # Special processing for PEP 0. pending = nodes.pending(PEPZero) self.document.insert(1, pending) self.document.note_pending(pending) if len(header) < 2 or header[1][0].astext().lower() != 'title': raise DataError('No title!') for field in header: name = field[0].astext().lower() body = field[1] if len(body) > 1: raise DataError('PEP header field body contains multiple ' 'elements:\n%s' % field.pformat(level=1)) elif len(body) == 1: if not isinstance(body[0], nodes.paragraph): raise DataError('PEP header field body may only contain ' 'a single paragraph:\n%s' % field.pformat(level=1)) elif name == 'last-modified': date = time.strftime( '%d-%b-%Y', time.localtime(os.stat(self.document['source'])[8])) if cvs_url: body += nodes.paragraph( '', '', nodes.reference('', date, refuri=cvs_url)) else: # empty continue para = body[0] if name == 'author': for node in para: if isinstance(node, nodes.reference): node.parent.replace(node, mask_email(node)) elif name == 'discussions-to': for node in para: if isinstance(node, nodes.reference): node.parent.replace(node, mask_email(node, pep)) elif name in ('replaces', 'replaced-by', 'requires'): newbody = [] space = nodes.Text(' ') for refpep in re.split(',?\s+', body.astext()): pepno = int(refpep) newbody.append(nodes.reference( refpep, refpep, refuri=(self.document.settings.pep_base_url + self.pep_url % pepno))) newbody.append(space) para[:] = newbody[:-1] # drop trailing space elif name == 'last-modified': utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) if cvs_url: date = para.astext() para[:] = [nodes.reference('', date, refuri=cvs_url)] elif name == 'content-type': pep_type = para.astext() uri = self.document.settings.pep_base_url + self.pep_url % 12 para[:] = [nodes.reference('', pep_type, refuri=uri)] elif name == 'version' and len(body): utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) class Contents(Transform): """ Insert an empty table of contents topic and a transform placeholder into the document after the RFC 2822 header. """ default_priority = 380 def apply(self): language = languages.get_language(self.document.settings.language_code) name = language.labels['contents'] title = nodes.title('', name) topic = nodes.topic('', title, classes=['contents']) name = nodes.fully_normalize_name(name) if not self.document.has_name(name): topic['names'].append(name) self.document.note_implicit_target(topic) pending = nodes.pending(parts.Contents) topic += pending self.document.insert(1, topic) self.document.note_pending(pending) class TargetNotes(Transform): """ Locate the "References" section, insert a placeholder for an external target footnote insertion transform at the end, and schedule the transform to run immediately. """ default_priority = 520 def apply(self): doc = self.document i = len(doc) - 1 refsect = copyright = None while i >= 0 and isinstance(doc[i], nodes.section): title_words = doc[i][0].astext().lower().split() if 'references' in title_words: refsect = doc[i] break elif 'copyright' in title_words: copyright = i i -= 1 if not refsect: refsect = nodes.section() refsect += nodes.title('', 'References') doc.set_id(refsect) if copyright: # Put the new "References" section before "Copyright": doc.insert(copyright, refsect) else: # Put the new "References" section at end of doc: doc.append(refsect) pending = nodes.pending(references.TargetNotes) refsect.append(pending) self.document.note_pending(pending, 0) pending = nodes.pending(misc.CallBack, details={'callback': self.cleanup_callback}) refsect.append(pending) self.document.note_pending(pending, 1) def cleanup_callback(self, pending): """ Remove an empty "References" section. Called after the `references.TargetNotes` transform is complete. """ if len(pending.parent) == 2: # <title> and <pending> pending.parent.parent.remove(pending.parent) class PEPZero(Transform): """ Special processing for PEP 0. """ default_priority =760 def apply(self): visitor = PEPZeroSpecial(self.document) self.document.walk(visitor) self.startnode.parent.remove(self.startnode) class PEPZeroSpecial(nodes.SparseNodeVisitor): """ Perform the special processing needed by PEP 0: - Mask email addresses. - Link PEP numbers in the second column of 4-column tables to the PEPs themselves. """ pep_url = Headers.pep_url def unknown_visit(self, node): pass def visit_reference(self, node): node.parent.replace(node, mask_email(node)) def visit_field_list(self, node): if 'rfc2822' in node['classes']: raise nodes.SkipNode def visit_tgroup(self, node): self.pep_table = node['cols'] == 4 self.entry = 0 def visit_colspec(self, node): self.entry += 1 if self.pep_table and self.entry == 2: node['classes'].append('num') def visit_row(self, node): self.entry = 0 def visit_entry(self, node): self.entry += 1 if self.pep_table and self.entry == 2 and len(node) == 1: node['classes'].append('num') p = node[0] if isinstance(p, nodes.paragraph) and len(p) == 1: text = p.astext() try: pep = int(text) ref = (self.document.settings.pep_base_url + self.pep_url % pep) p[0] = nodes.reference(text, text, refuri=ref) except ValueError: pass non_masked_addresses = ('peps@python.org', 'python-list@python.org', 'python-dev@python.org') def mask_email(ref, pepno=None): """ Mask the email address in `ref` and return a replacement node. `ref` is returned unchanged if it contains no email address. For email addresses such as "user@host", mask the address as "user at host" (text) to thwart simple email address harvesters (except for those listed in `non_masked_addresses`). If a PEP number (`pepno`) is given, return a reference including a default email subject. """ if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'): if ref['refuri'][8:] in non_masked_addresses: replacement = ref[0] else: replacement_text = ref.astext().replace('@', '&#32;&#97;t&#32;') replacement = nodes.raw('', replacement_text, format='html') if pepno is None: return replacement else: ref['refuri'] += '?subject=PEP%%20%s' % pepno ref[:] = [replacement] return ref else: return ref
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/transforms/peps.py", "copies": "1", "size": "11116", "license": "mit", "hash": -141715861720280180, "line_mean": 35.3267973856, "line_max": 79, "alpha_frac": 0.5358042461, "autogenerated": false, "ratio": 4.242748091603054, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5278552337703053, "avg_score": null, "num_lines": null }
""" I/O classes provide a uniform API for low-level input and output. Subclasses will exist for a variety of input/output mechanisms. """ __docformat__ = 'reStructuredText' import sys try: import locale except: pass from types import UnicodeType from docutils import TransformSpec class Input(TransformSpec): """ Abstract base class for input wrappers. """ component_type = 'input' default_source_path = None def __init__(self, source=None, source_path=None, encoding=None, error_handler='strict'): self.encoding = encoding """Text encoding for the input source.""" self.error_handler = error_handler """Text decoding error handler.""" self.source = source """The source of input data.""" self.source_path = source_path """A text reference to the source.""" if not source_path: self.source_path = self.default_source_path self.successful_encoding = None """The encoding that successfully decoded the source data.""" def __repr__(self): return '%s: source=%r, source_path=%r' % (self.__class__, self.source, self.source_path) def read(self): raise NotImplementedError def decode(self, data): """ Decode a string, `data`, heuristically. Raise UnicodeError if unsuccessful. The client application should call ``locale.setlocale`` at the beginning of processing:: locale.setlocale(locale.LC_ALL, '') """ if (self.encoding and self.encoding.lower() == 'unicode' or isinstance(data, UnicodeType)): return data encodings = [self.encoding] if not self.encoding: # Apply heuristics only if no encoding is explicitly given. encodings.append('utf-8') try: encodings.append(locale.nl_langinfo(locale.CODESET)) except: pass try: encodings.append(locale.getlocale()[1]) except: pass try: encodings.append(locale.getdefaultlocale()[1]) except: pass encodings.append('latin-1') error = None error_details = '' for enc in encodings: if not enc: continue try: decoded = unicode(data, enc, self.error_handler) self.successful_encoding = enc # Return decoded, removing BOMs. return decoded.replace(u'\ufeff', u'') except (UnicodeError, LookupError), error: pass if error is not None: error_details = '\n(%s: %s)' % (error.__class__.__name__, error) raise UnicodeError( 'Unable to decode input data. Tried the following encodings: ' '%s.%s' % (', '.join([repr(enc) for enc in encodings if enc]), error_details)) class Output(TransformSpec): """ Abstract base class for output wrappers. """ component_type = 'output' default_destination_path = None def __init__(self, destination=None, destination_path=None, encoding=None, error_handler='strict'): self.encoding = encoding """Text encoding for the output destination.""" self.error_handler = error_handler or 'strict' """Text encoding error handler.""" self.destination = destination """The destination for output data.""" self.destination_path = destination_path """A text reference to the destination.""" if not destination_path: self.destination_path = self.default_destination_path def __repr__(self): return ('%s: destination=%r, destination_path=%r' % (self.__class__, self.destination, self.destination_path)) def write(self, data): """`data` is a Unicode string, to be encoded by `self.encode`.""" raise NotImplementedError def encode(self, data): if self.encoding and self.encoding.lower() == 'unicode': return data else: try: return data.encode(self.encoding, self.error_handler) except ValueError: # ValueError is raised if there are unencodable chars # in data and the error_handler isn't found. if self.error_handler == 'xmlcharrefreplace': # We are using xmlcharrefreplace with a Python # version that doesn't support it (2.1 or 2.2), so # we emulate its behavior. return ''.join([self.xmlcharref_encode(char) for char in data]) else: raise def xmlcharref_encode(self, char): """Emulate Python 2.3's 'xmlcharrefreplace' encoding error handler.""" try: return char.encode(self.encoding, 'strict') except UnicodeError: return '&#%i;' % ord(char) class FileInput(Input): """ Input for single, simple file-like objects. """ def __init__(self, source=None, source_path=None, encoding=None, error_handler='strict', autoclose=1, handle_io_errors=1): """ :Parameters: - `source`: either a file-like object (which is read directly), or `None` (which implies `sys.stdin` if no `source_path` given). - `source_path`: a path to a file, which is opened and then read. - `encoding`: the expected text encoding of the input file. - `error_handler`: the encoding error handler to use. - `autoclose`: close automatically after read (boolean); always false if `sys.stdin` is the source. - `handle_io_errors`: summarize I/O errors here, and exit? """ Input.__init__(self, source, source_path, encoding, error_handler) self.autoclose = autoclose self.handle_io_errors = handle_io_errors if source is None: if source_path: try: self.source = open(source_path) except IOError, error: if not handle_io_errors: raise print >>sys.stderr, '%s: %s' % (error.__class__.__name__, error) print >>sys.stderr, ( 'Unable to open source file for reading (%r). Exiting.' % source_path) sys.exit(1) else: self.source = sys.stdin self.autoclose = None if not source_path: try: self.source_path = self.source.name except AttributeError: pass def read(self): """ Read and decode a single file and return the data (Unicode string). """ try: data = self.source.read() finally: if self.autoclose: self.close() return self.decode(data) def close(self): self.source.close() class FileOutput(Output): """ Output for single, simple file-like objects. """ def __init__(self, destination=None, destination_path=None, encoding=None, error_handler='strict', autoclose=1, handle_io_errors=1): """ :Parameters: - `destination`: either a file-like object (which is written directly) or `None` (which implies `sys.stdout` if no `destination_path` given). - `destination_path`: a path to a file, which is opened and then written. - `autoclose`: close automatically after write (boolean); always false if `sys.stdout` is the destination. """ Output.__init__(self, destination, destination_path, encoding, error_handler) self.opened = 1 self.autoclose = autoclose self.handle_io_errors = handle_io_errors if destination is None: if destination_path: self.opened = None else: self.destination = sys.stdout self.autoclose = None if not destination_path: try: self.destination_path = self.destination.name except AttributeError: pass def open(self): try: self.destination = open(self.destination_path, 'w') except IOError, error: if not self.handle_io_errors: raise print >>sys.stderr, '%s: %s' % (error.__class__.__name__, error) print >>sys.stderr, ('Unable to open destination file for writing ' '(%r). Exiting.' % self.destination_path) sys.exit(1) self.opened = 1 def write(self, data): """Encode `data`, write it to a single file, and return it.""" output = self.encode(data) if not self.opened: self.open() try: self.destination.write(output) finally: if self.autoclose: self.close() return output def close(self): self.destination.close() self.opened = None class StringInput(Input): """ Direct string input. """ default_source_path = '<string>' def read(self): """Decode and return the source string.""" return self.decode(self.source) class StringOutput(Output): """ Direct string output. """ default_destination_path = '<string>' def write(self, data): """Encode `data`, store it in `self.destination`, and return it.""" self.destination = self.encode(data) return self.destination class NullInput(Input): """ Degenerate input: read nothing. """ default_source_path = 'null input' def read(self): """Return a null string.""" return u'' class NullOutput(Output): """ Degenerate output: write nothing. """ default_destination_path = 'null output' def write(self, data): """Do nothing ([don't even] send data to the bit bucket).""" pass
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/io.py", "copies": "1", "size": "10762", "license": "mit", "hash": 2093321180601020400, "line_mean": 30.0144092219, "line_max": 83, "alpha_frac": 0.5419067088, "autogenerated": false, "ratio": 4.575680272108843, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009237090393711483, "num_lines": 347 }
""" Transforms for resolving references. """ __docformat__ = 'reStructuredText' import sys import re from docutils import nodes, utils from docutils.transforms import TransformError, Transform class PropagateTargets(Transform): """ Propagate empty internal targets to the next element. Given the following nodes:: <target ids="internal1" names="internal1"> <target anonymous="1" ids="id1"> <target ids="internal2" names="internal2"> <paragraph> This is a test. PropagateTargets propagates the ids and names of the internal targets preceding the paragraph to the paragraph itself:: <target refid="internal1"> <target anonymous="1" refid="id1"> <target refid="internal2"> <paragraph ids="internal2 id1 internal1" names="internal2 internal1"> This is a test. """ default_priority = 260 def apply(self): for target in self.document.internal_targets: if not (len(target) == 0 and not (target.attributes.has_key('refid') or target.attributes.has_key('refuri') or target.attributes.has_key('refname'))): continue next_node = target.next_node(ascend=1) # Do not move names and ids into Invisibles (we'd lose the # attributes) or different Targetables (e.g. footnotes). if (next_node is not None and ((not isinstance(next_node, nodes.Invisible) and not isinstance(next_node, nodes.Targetable)) or isinstance(next_node, nodes.target))): next_node['ids'].extend(target['ids']) next_node['names'].extend(target['names']) # Set defaults for next_node.expect_referenced_by_name/id. if not hasattr(next_node, 'expect_referenced_by_name'): next_node.expect_referenced_by_name = {} if not hasattr(next_node, 'expect_referenced_by_id'): next_node.expect_referenced_by_id = {} for id in target['ids']: # Update IDs to node mapping. self.document.ids[id] = next_node # If next_node is referenced by id ``id``, this # target shall be marked as referenced. next_node.expect_referenced_by_id[id] = target for name in target['names']: next_node.expect_referenced_by_name[name] = target # If there are any expect_referenced_by_... attributes # in target set, copy them to next_node. next_node.expect_referenced_by_name.update( getattr(target, 'expect_referenced_by_name', {})) next_node.expect_referenced_by_id.update( getattr(target, 'expect_referenced_by_id', {})) # Set refid to point to the first former ID of target # which is now an ID of next_node. target['refid'] = target['ids'][0] # Clear ids and names; they have been moved to # next_node. target['ids'] = [] target['names'] = [] self.document.note_refid(target) self.document.note_internal_target(next_node) class AnonymousHyperlinks(Transform): """ Link anonymous references to targets. Given:: <paragraph> <reference anonymous="1"> internal <reference anonymous="1"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> Corresponding references are linked via "refid" or resolved via "refuri":: <paragraph> <reference anonymous="1" refid="id1"> text <reference anonymous="1" refuri="http://external"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> """ default_priority = 440 def apply(self): if len(self.document.anonymous_refs) \ != len(self.document.anonymous_targets): msg = self.document.reporter.error( 'Anonymous hyperlink mismatch: %s references but %s ' 'targets.\nSee "backrefs" attribute for IDs.' % (len(self.document.anonymous_refs), len(self.document.anonymous_targets))) msgid = self.document.set_id(msg) for ref in self.document.anonymous_refs: prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.parent.replace(ref, prb) for target in self.document.anonymous_targets: # Assume that all anonymous targets have been # referenced to avoid generating lots of # system_messages. target.referenced = 1 return for ref, target in zip(self.document.anonymous_refs, self.document.anonymous_targets): target.referenced = 1 while 1: if target.hasattr('refuri'): ref['refuri'] = target['refuri'] ref.resolved = 1 break else: if not target['ids']: # Propagated target. target = self.document.ids[target['refid']] continue ref['refid'] = target['ids'][0] self.document.note_refid(ref) break class IndirectHyperlinks(Transform): """ a) Indirect external references:: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refname="direct external"> The "refuri" attribute is migrated back to all indirect targets from the final direct target (i.e. a target not referring to another indirect target):: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refuri="http://indirect"> Once the attribute is migrated, the preexisting "refname" attribute is dropped. b) Indirect internal references:: <target id="id1" name="final target"> <paragraph> <reference refname="indirect internal"> indirect internal <target id="id2" name="indirect internal 2" refname="final target"> <target id="id3" name="indirect internal" refname="indirect internal 2"> Targets which indirectly refer to an internal target become one-hop indirect (their "refid" attributes are directly set to the internal target's "id"). References which indirectly refer to an internal target become direct internal references:: <target id="id1" name="final target"> <paragraph> <reference refid="id1"> indirect internal <target id="id2" name="indirect internal 2" refid="id1"> <target id="id3" name="indirect internal" refid="id1"> """ default_priority = 460 def apply(self): for target in self.document.indirect_targets: if not target.resolved: self.resolve_indirect_target(target) self.resolve_indirect_references(target) def resolve_indirect_target(self, target): refname = target.get('refname') if refname is None: reftarget_id = target['refid'] else: reftarget_id = self.document.nameids.get(refname) if not reftarget_id: # Check the unknown_reference_resolvers for resolver_function in \ self.document.transformer.unknown_reference_resolvers: if resolver_function(target): break else: self.nonexistent_indirect_target(target) return reftarget = self.document.ids[reftarget_id] reftarget.note_referenced_by(id=reftarget_id) if isinstance(reftarget, nodes.target) \ and not reftarget.resolved and reftarget.hasattr('refname'): if hasattr(target, 'multiply_indirect'): #and target.multiply_indirect): #del target.multiply_indirect self.circular_indirect_reference(target) return target.multiply_indirect = 1 self.resolve_indirect_target(reftarget) # multiply indirect del target.multiply_indirect if reftarget.hasattr('refuri'): target['refuri'] = reftarget['refuri'] if target['names']: self.document.note_external_target(target) if target.has_key('refid'): del target['refid'] elif reftarget.hasattr('refid'): target['refid'] = reftarget['refid'] self.document.note_refid(target) else: if reftarget['ids']: target['refid'] = reftarget_id self.document.note_refid(target) else: self.nonexistent_indirect_target(target) return if refname is not None: del target['refname'] target.resolved = 1 def nonexistent_indirect_target(self, target): if self.document.nameids.has_key(target['refname']): self.indirect_target_error(target, 'which is a duplicate, and ' 'cannot be used as a unique reference') else: self.indirect_target_error(target, 'which does not exist') def circular_indirect_reference(self, target): self.indirect_target_error(target, 'forming a circular reference') def indirect_target_error(self, target, explanation): naming = '' reflist = [] if target['names']: naming = '"%s" ' % target['names'][0] for name in target['names']: reflist.extend(self.document.refnames.get(name, [])) for id in target['ids']: reflist.extend(self.document.refids.get(id, [])) naming += '(id="%s")' % target['ids'][0] msg = self.document.reporter.error( 'Indirect hyperlink target %s refers to target "%s", %s.' % (naming, target['refname'], explanation), base_node=target) msgid = self.document.set_id(msg) for ref in uniq(reflist): prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.parent.replace(ref, prb) target.resolved = 1 def resolve_indirect_references(self, target): if target.hasattr('refid'): attname = 'refid' call_if_named = 0 call_method = self.document.note_refid elif target.hasattr('refuri'): attname = 'refuri' call_if_named = 1 call_method = self.document.note_external_target else: return attval = target[attname] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref[attname] = attval if not call_if_named or ref['names']: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) for id in target['ids']: reflist = self.document.refids.get(id, []) if reflist: target.note_referenced_by(id=id) for ref in reflist: if ref.resolved: continue del ref['refid'] ref[attname] = attval if not call_if_named or ref['names']: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) class ExternalTargets(Transform): """ Given:: <paragraph> <reference refname="direct external"> direct external <target id="id1" name="direct external" refuri="http://direct"> The "refname" attribute is replaced by the direct "refuri" attribute:: <paragraph> <reference refuri="http://direct"> direct external <target id="id1" name="direct external" refuri="http://direct"> """ default_priority = 640 def apply(self): for target in self.document.external_targets: if target.hasattr('refuri'): refuri = target['refuri'] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refuri'] = refuri ref.resolved = 1 class InternalTargets(Transform): default_priority = 660 def apply(self): for target in self.document.internal_targets: self.resolve_reference_ids(target) def resolve_reference_ids(self, target): """ Given:: <paragraph> <reference refname="direct internal"> direct internal <target id="id1" name="direct internal"> The "refname" attribute is replaced by "refid" linking to the target's "id":: <paragraph> <reference refid="id1"> direct internal <target id="id1" name="direct internal"> """ if target.hasattr('refuri') or target.hasattr('refid') \ or not target['names']: return for name in target['names']: refid = self.document.nameids[name] reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refid'] = refid ref.resolved = 1 class Footnotes(Transform): """ Assign numbers to autonumbered footnotes, and resolve links to footnotes, citations, and their references. Given the following ``document`` as input:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refname="footnote"> <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2"> <footnote auto="1" id="id3"> <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote"> <paragraph> Labeled autonumbered footnote. Auto-numbered footnotes have attribute ``auto="1"`` and no label. Auto-numbered footnote_references have no reference text (they're empty elements). When resolving the numbering, a ``label`` element is added to the beginning of the ``footnote``, and reference text to the ``footnote_reference``. The transformed result will be:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refid="footnote"> 2 <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2" refid="id3"> 1 <footnote auto="1" id="id3" backrefs="id2"> <label> 1 <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote" backrefs="id1"> <label> 2 <paragraph> Labeled autonumbered footnote. Note that the footnotes are not in the same order as the references. The labels and reference text are added to the auto-numbered ``footnote`` and ``footnote_reference`` elements. Footnote elements are backlinked to their references via "refids" attributes. References are assigned "id" and "refid" attributes. After adding labels and reference text, the "auto" attributes can be ignored. """ default_priority = 620 autofootnote_labels = None """Keep track of unlabeled autonumbered footnotes.""" symbols = [ # Entries 1-4 and 6 below are from section 12.51 of # The Chicago Manual of Style, 14th edition. '*', # asterisk/star u'\u2020', # dagger &dagger; u'\u2021', # double dagger &Dagger; u'\u00A7', # section mark &sect; u'\u00B6', # paragraph mark (pilcrow) &para; # (parallels ['||'] in CMoS) '#', # number sign # The entries below were chosen arbitrarily. u'\u2660', # spade suit &spades; u'\u2665', # heart suit &hearts; u'\u2666', # diamond suit &diams; u'\u2663', # club suit &clubs; ] def apply(self): self.autofootnote_labels = [] startnum = self.document.autofootnote_start self.document.autofootnote_start = self.number_footnotes(startnum) self.number_footnote_references(startnum) self.symbolize_footnotes() self.resolve_footnotes_and_citations() def number_footnotes(self, startnum): """ Assign numbers to autonumbered footnotes. For labeled autonumbered footnotes, copy the number over to corresponding footnote references. """ for footnote in self.document.autofootnotes: while 1: label = str(startnum) startnum += 1 if not self.document.nameids.has_key(label): break footnote.insert(0, nodes.label('', label)) for name in footnote['names']: for ref in self.document.footnote_refs.get(name, []): ref += nodes.Text(label) ref.delattr('refname') assert len(footnote['ids']) == len(ref['ids']) == 1 ref['refid'] = footnote['ids'][0] footnote.add_backref(ref['ids'][0]) self.document.note_refid(ref) ref.resolved = 1 if not footnote['names'] and not footnote['dupnames']: footnote['names'].append(label) self.document.note_explicit_target(footnote, footnote) self.autofootnote_labels.append(label) return startnum def number_footnote_references(self, startnum): """Assign numbers to autonumbered footnote references.""" i = 0 for ref in self.document.autofootnote_refs: if ref.resolved or ref.hasattr('refid'): continue try: label = self.autofootnote_labels[i] except IndexError: msg = self.document.reporter.error( 'Too many autonumbered footnote references: only %s ' 'corresponding footnotes available.' % len(self.autofootnote_labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.autofootnote_refs[i:]: if ref.resolved or ref.hasattr('refname'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.parent.replace(ref, prb) break ref += nodes.Text(label) id = self.document.nameids[label] footnote = self.document.ids[id] ref['refid'] = id self.document.note_refid(ref) assert len(ref['ids']) == 1 footnote.add_backref(ref['ids'][0]) ref.resolved = 1 i += 1 def symbolize_footnotes(self): """Add symbols indexes to "[*]"-style footnotes and references.""" labels = [] for footnote in self.document.symbol_footnotes: reps, index = divmod(self.document.symbol_footnote_start, len(self.symbols)) labeltext = self.symbols[index] * (reps + 1) labels.append(labeltext) footnote.insert(0, nodes.label('', labeltext)) self.document.symbol_footnote_start += 1 self.document.set_id(footnote) i = 0 for ref in self.document.symbol_footnote_refs: try: ref += nodes.Text(labels[i]) except IndexError: msg = self.document.reporter.error( 'Too many symbol footnote references: only %s ' 'corresponding footnotes available.' % len(labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.symbol_footnote_refs[i:]: if ref.resolved or ref.hasattr('refid'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.parent.replace(ref, prb) break footnote = self.document.symbol_footnotes[i] assert len(footnote['ids']) == 1 ref['refid'] = footnote['ids'][0] self.document.note_refid(ref) footnote.add_backref(ref['ids'][0]) i += 1 def resolve_footnotes_and_citations(self): """ Link manually-labeled footnotes and citations to/from their references. """ for footnote in self.document.footnotes: for label in footnote['names']: if self.document.footnote_refs.has_key(label): reflist = self.document.footnote_refs[label] self.resolve_references(footnote, reflist) for citation in self.document.citations: for label in citation['names']: if self.document.citation_refs.has_key(label): reflist = self.document.citation_refs[label] self.resolve_references(citation, reflist) def resolve_references(self, note, reflist): assert len(note['ids']) == 1 id = note['ids'][0] for ref in reflist: if ref.resolved: continue ref.delattr('refname') ref['refid'] = id assert len(ref['ids']) == 1 note.add_backref(ref['ids'][0]) ref.resolved = 1 note.resolved = 1 class Substitutions(Transform): """ Given the following ``document`` as input:: <document> <paragraph> The <substitution_reference refname="biohazard"> biohazard symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> The ``substitution_reference`` will simply be replaced by the contents of the corresponding ``substitution_definition``. The transformed result will be:: <document> <paragraph> The <image alt="biohazard" uri="biohazard.png"> symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> """ default_priority = 220 """The Substitutions transform has to be applied very early, before `docutils.tranforms.frontmatter.DocTitle` and others.""" def apply(self): defs = self.document.substitution_defs normed = self.document.substitution_names subreflist = self.document.substitution_refs.items() subreflist.sort() for refname, refs in subreflist: for ref in refs: key = None if defs.has_key(refname): key = refname else: normed_name = refname.lower() if normed.has_key(normed_name): key = normed[normed_name] if key is None: msg = self.document.reporter.error( 'Undefined substitution referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.parent.replace(ref, prb) else: subdef = defs[key] parent = ref.parent index = parent.index(ref) if (subdef.attributes.has_key('ltrim') or subdef.attributes.has_key('trim')): if index > 0 and isinstance(parent[index - 1], nodes.Text): parent.replace(parent[index - 1], parent[index - 1].rstrip()) if (subdef.attributes.has_key('rtrim') or subdef.attributes.has_key('trim')): if (len(parent) > index + 1 and isinstance(parent[index + 1], nodes.Text)): parent.replace(parent[index + 1], parent[index + 1].lstrip()) parent.replace(ref, subdef.children) self.document.substitution_refs = None # release replaced references class TargetNotes(Transform): """ Creates a footnote for each external target in the text, and corresponding footnote references after each reference. """ default_priority = 540 """The TargetNotes transform has to be applied after `IndirectHyperlinks` but before `Footnotes`.""" def apply(self): notes = {} nodelist = [] for target in self.document.external_targets: names = target['names'] # Only named targets. assert names refs = [] for name in names: refs.extend(self.document.refnames.get(name, [])) if not refs: continue footnote = self.make_target_footnote(target, refs, notes) if not notes.has_key(target['refuri']): notes[target['refuri']] = footnote nodelist.append(footnote) if len(self.document.anonymous_targets) \ == len(self.document.anonymous_refs): for target, ref in zip(self.document.anonymous_targets, self.document.anonymous_refs): if target.hasattr('refuri'): footnote = self.make_target_footnote(target, [ref], notes) if not notes.has_key(target['refuri']): notes[target['refuri']] = footnote nodelist.append(footnote) self.startnode.parent.replace(self.startnode, nodelist) def make_target_footnote(self, target, refs, notes): refuri = target['refuri'] if notes.has_key(refuri): # duplicate? footnote = notes[refuri] assert len(footnote['names']) == 1 footnote_name = footnote['names'][0] else: # original footnote = nodes.footnote() footnote_id = self.document.set_id(footnote) # Use uppercase letters and a colon; they can't be # produced inside names by the parser. footnote_name = 'TARGET_NOTE: ' + footnote_id footnote['auto'] = 1 footnote['names'] = [footnote_name] footnote_paragraph = nodes.paragraph() footnote_paragraph += nodes.reference('', refuri, refuri=refuri) footnote += footnote_paragraph self.document.note_autofootnote(footnote) self.document.note_explicit_target(footnote, footnote) for ref in refs: if isinstance(ref, nodes.target): continue refnode = nodes.footnote_reference( refname=footnote_name, auto=1) self.document.note_autofootnote_ref(refnode) self.document.note_footnote_ref(refnode) index = ref.parent.index(ref) + 1 reflist = [refnode] if not utils.get_trim_footnote_ref_space(self.document.settings): reflist.insert(0, nodes.Text(' ')) ref.parent.insert(index, reflist) return footnote def uniq(L): r = [] for item in L: if not item in r: r.append(item) return r
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/transforms/references.py", "copies": "1", "size": "31082", "license": "mit", "hash": 382468510926927740, "line_mean": 38.5445292621, "line_max": 78, "alpha_frac": 0.5316581945, "autogenerated": false, "ratio": 4.545481134834747, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5577139329334747, "avg_score": null, "num_lines": null }
""" Miscellaneous transforms. """ __docformat__ = 'reStructuredText' from docutils import nodes from docutils.transforms import Transform, TransformError class CallBack(Transform): """ Inserts a callback into a document. The callback is called when the transform is applied, which is determined by its priority. For use with `nodes.pending` elements. Requires a ``details['callback']`` entry, a bound method or function which takes one parameter: the pending node. Other data can be stored in the ``details`` attribute or in the object hosting the callback method. """ default_priority = 990 def apply(self): pending = self.startnode pending.details['callback'](pending) pending.parent.remove(pending) class ClassAttribute(Transform): """ Move the "class" attribute specified in the "pending" node into the immediately following non-comment element. """ default_priority = 210 def apply(self): pending = self.startnode parent = pending.parent child = pending while parent: # Check for appropriate following siblings: for index in range(parent.index(child) + 1, len(parent)): element = parent[index] if (isinstance(element, nodes.Invisible) or isinstance(element, nodes.system_message)): continue element['classes'] += pending.details['class'] pending.parent.remove(pending) return else: # At end of section or container; apply to sibling child = parent parent = parent.parent error = self.document.reporter.error( 'No suitable element following "%s" directive' % pending.details['directive'], nodes.literal_block(pending.rawsource, pending.rawsource), line=pending.line) pending.parent.replace(pending, error)
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/transforms/misc.py", "copies": "1", "size": "2235", "license": "mit", "hash": -7800025356639077000, "line_mean": 31.3913043478, "line_max": 78, "alpha_frac": 0.6308724832, "autogenerated": false, "ratio": 4.579918032786885, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5710790515986885, "avg_score": null, "num_lines": null }
""" This is ``docutils.parsers.rst`` package. It exports a single class, `Parser`, the reStructuredText parser. Usage ===== 1. Create a parser:: parser = docutils.parsers.rst.Parser() Several optional arguments may be passed to modify the parser's behavior. Please see `Customizing the Parser`_ below for details. 2. Gather input (a multi-line string), by reading a file or the standard input:: input = sys.stdin.read() 3. Create a new empty `docutils.nodes.document` tree:: document = docutils.utils.new_document(source, settings) See `docutils.utils.new_document()` for parameter details. 4. Run the parser, populating the document tree:: parser.parse(input, document) Parser Overview =============== The reStructuredText parser is implemented as a state machine, examining its input one line at a time. To understand how the parser works, please first become familiar with the `docutils.statemachine` module, then see the `states` module. Customizing the Parser ---------------------- Anything that isn't already customizable is that way simply because that type of customizability hasn't been implemented yet. Patches welcome! When instantiating an object of the `Parser` class, two parameters may be passed: ``rfc2822`` and ``inliner``. Pass ``rfc2822=1`` to enable an initial RFC-2822 style header block, parsed as a "field_list" element (with "class" attribute set to "rfc2822"). Currently this is the only body-level element which is customizable without subclassing. (Tip: subclass `Parser` and change its "state_classes" and "initial_state" attributes to refer to new classes. Contact the author if you need more details.) The ``inliner`` parameter takes an instance of `states.Inliner` or a subclass. It handles inline markup recognition. A common extension is the addition of further implicit hyperlinks, like "RFC 2822". This can be done by subclassing `states.Inliner`, adding a new method for the implicit markup, and adding a ``(pattern, method)`` pair to the "implicit_dispatch" attribute of the subclass. See `states.Inliner.implicit_inline()` for details. Explicit inline markup can be customized in a `states.Inliner` subclass via the ``patterns.initial`` and ``dispatch`` attributes (and new methods as appropriate). """ __docformat__ = 'reStructuredText' import docutils.parsers import docutils.statemachine from docutils.parsers.rst import states from docutils import frontend class Parser(docutils.parsers.Parser): """The reStructuredText parser.""" supported = ('restructuredtext', 'rst', 'rest', 'restx', 'rtxt', 'rstx') """Aliases this parser supports.""" settings_spec = ( 'reStructuredText Parser Options', None, (('Recognize and link to standalone PEP references (like "PEP 258").', ['--pep-references'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Base URL for PEP references ' '(default "http://www.python.org/peps/").', ['--pep-base-url'], {'metavar': '<URL>', 'default': 'http://www.python.org/peps/', 'validator': frontend.validate_url_trailing_slash}), ('Recognize and link to standalone RFC references (like "RFC 822").', ['--rfc-references'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Base URL for RFC references (default "http://www.faqs.org/rfcs/").', ['--rfc-base-url'], {'metavar': '<URL>', 'default': 'http://www.faqs.org/rfcs/', 'validator': frontend.validate_url_trailing_slash}), ('Set number of spaces for tab expansion (default 8).', ['--tab-width'], {'metavar': '<width>', 'type': 'int', 'default': 8}), ('Remove spaces before footnote references.', ['--trim-footnote-reference-space'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Leave spaces before footnote references.', ['--leave-footnote-reference-space'], {'action': 'store_false', 'dest': 'trim_footnote_reference_space', 'validator': frontend.validate_boolean}), ('Disable directives that insert the contents of external file ' '("include" & "raw"); replaced with a "warning" system message.', ['--no-file-insertion'], {'action': 'store_false', 'default': 1, 'dest': 'file_insertion_enabled'}), ('Enable directives that insert the contents of external file ' '("include" & "raw"). Enabled by default.', ['--file-insertion-enabled'], {'action': 'store_true', 'dest': 'file_insertion_enabled'}), ('Disable the "raw" directives; replaced with a "warning" ' 'system message.', ['--no-raw'], {'action': 'store_false', 'default': 1, 'dest': 'raw_enabled'}), ('Enable the "raw" directive. Enabled by default.', ['--raw-enabled'], {'action': 'store_true', 'dest': 'raw_enabled'}),)) config_section = 'restructuredtext parser' config_section_dependencies = ('parsers',) def __init__(self, rfc2822=None, inliner=None): if rfc2822: self.initial_state = 'RFC2822Body' else: self.initial_state = 'Body' self.state_classes = states.state_classes self.inliner = inliner def parse(self, inputstring, document): """Parse `inputstring` and populate `document`, a document tree.""" self.setup_parse(inputstring, document) self.statemachine = states.RSTStateMachine( state_classes=self.state_classes, initial_state=self.initial_state, debug=document.reporter.debug_flag) inputlines = docutils.statemachine.string2lines( inputstring, tab_width=document.settings.tab_width, convert_whitespace=1) self.statemachine.run(inputlines, document, inliner=self.inliner) self.finish_parse()
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/parsers/rst/__init__.py", "copies": "1", "size": "6270", "license": "mit", "hash": 111347807604688660, "line_mean": 39.4516129032, "line_max": 79, "alpha_frac": 0.6507177033, "autogenerated": false, "ratio": 4.071428571428571, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 155 }
""" Miscellaneous utilities for the documentation utilities. """ __docformat__ = 'reStructuredText' import sys import os import os.path import warnings from types import StringType, UnicodeType from docutils import ApplicationError, DataError from docutils import frontend, nodes class SystemMessage(ApplicationError): def __init__(self, system_message, level): Exception.__init__(self, system_message.astext()) self.level = level class SystemMessagePropagation(ApplicationError): pass class Reporter: """ Info/warning/error reporter and ``system_message`` element generator. Five levels of system messages are defined, along with corresponding methods: `debug()`, `info()`, `warning()`, `error()`, and `severe()`. There is typically one Reporter object per process. A Reporter object is instantiated with thresholds for reporting (generating warnings) and halting processing (raising exceptions), a switch to turn debug output on or off, and an I/O stream for warnings. These are stored as instance attributes. When a system message is generated, its level is compared to the stored thresholds, and a warning or error is generated as appropriate. Debug messages are produced iff the stored debug switch is on, independently of other thresholds. Message output is sent to the stored warning stream if not set to ''. The Reporter class also employs a modified form of the "Observer" pattern [GoF95]_ to track system messages generated. The `attach_observer` method should be called before parsing, with a bound method or function which accepts system messages. The observer can be removed with `detach_observer`, and another added in its place. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA, 1995. """ levels = 'DEBUG INFO WARNING ERROR SEVERE'.split() """List of names for system message levels, indexed by level.""" def __init__(self, source, report_level, halt_level, stream=None, debug=0, encoding='ascii', error_handler='replace'): """ :Parameters: - `source`: The path to or description of the source data. - `report_level`: The level at or above which warning output will be sent to `stream`. - `halt_level`: The level at or above which `SystemMessage` exceptions will be raised, halting execution. - `debug`: Show debug (level=0) system messages? - `stream`: Where warning output is sent. Can be file-like (has a ``.write`` method), a string (file name, opened for writing), '' (empty string, for discarding all stream messages) or `None` (implies `sys.stderr`; default). - `encoding`: The encoding for stderr output. - `error_handler`: The error handler for stderr output encoding. """ self.source = source """The path to or description of the source data.""" self.encoding = encoding """The character encoding for the stderr output.""" self.error_handler = error_handler """The character encoding error handler.""" self.debug_flag = debug """Show debug (level=0) system messages?""" self.report_level = report_level """The level at or above which warning output will be sent to `self.stream`.""" self.halt_level = halt_level """The level at or above which `SystemMessage` exceptions will be raised, halting execution.""" if stream is None: stream = sys.stderr elif type(stream) in (StringType, UnicodeType): # Leave stream untouched if it's ''. if stream != '': if type(stream) == StringType: stream = open(stream, 'w') elif type(stream) == UnicodeType: stream = open(stream.encode(), 'w') self.stream = stream """Where warning output is sent.""" self.observers = [] """List of bound methods or functions to call with each system_message created.""" self.max_level = -1 """The highest level system message generated so far.""" def set_conditions(self, category, report_level, halt_level, stream=None, debug=0): warnings.warn('docutils.utils.Reporter.set_conditions deprecated; ' 'set attributes via configuration settings or directly', DeprecationWarning, stacklevel=2) self.report_level = report_level self.halt_level = halt_level if stream is None: stream = sys.stderr self.stream = stream self.debug = debug def attach_observer(self, observer): """ The `observer` parameter is a function or bound method which takes one argument, a `nodes.system_message` instance. """ self.observers.append(observer) def detach_observer(self, observer): self.observers.remove(observer) def notify_observers(self, message): for observer in self.observers: observer(message) def system_message(self, level, message, *children, **kwargs): """ Return a system_message object. Raise an exception or generate a warning if appropriate. """ attributes = kwargs.copy() if kwargs.has_key('base_node'): source, line = get_source_line(kwargs['base_node']) del attributes['base_node'] if source is not None: attributes.setdefault('source', source) if line is not None: attributes.setdefault('line', line) attributes.setdefault('source', self.source) msg = nodes.system_message(message, level=level, type=self.levels[level], *children, **attributes) if self.stream and (level >= self.report_level or self.debug_flag and level == 0): msgtext = msg.astext().encode(self.encoding, self.error_handler) print >>self.stream, msgtext if level >= self.halt_level: raise SystemMessage(msg, level) if level > 0 or self.debug_flag: self.notify_observers(msg) self.max_level = max(level, self.max_level) return msg def debug(self, *args, **kwargs): """ Level-0, "DEBUG": an internal reporting issue. Typically, there is no effect on the processing. Level-0 system messages are handled separately from the others. """ if self.debug_flag: return self.system_message(0, *args, **kwargs) def info(self, *args, **kwargs): """ Level-1, "INFO": a minor issue that can be ignored. Typically there is no effect on processing, and level-1 system messages are not reported. """ return self.system_message(1, *args, **kwargs) def warning(self, *args, **kwargs): """ Level-2, "WARNING": an issue that should be addressed. If ignored, there may be unpredictable problems with the output. """ return self.system_message(2, *args, **kwargs) def error(self, *args, **kwargs): """ Level-3, "ERROR": an error that should be addressed. If ignored, the output will contain errors. """ return self.system_message(3, *args, **kwargs) def severe(self, *args, **kwargs): """ Level-4, "SEVERE": a severe error that must be addressed. If ignored, the output will contain severe errors. Typically level-4 system messages are turned into exceptions which halt processing. """ return self.system_message(4, *args, **kwargs) class ExtensionOptionError(DataError): pass class BadOptionError(ExtensionOptionError): pass class BadOptionDataError(ExtensionOptionError): pass class DuplicateOptionError(ExtensionOptionError): pass def extract_extension_options(field_list, options_spec): """ Return a dictionary mapping extension option names to converted values. :Parameters: - `field_list`: A flat field list without field arguments, where each field body consists of a single paragraph only. - `options_spec`: Dictionary mapping known option names to a conversion function such as `int` or `float`. :Exceptions: - `KeyError` for unknown option names. - `ValueError` for invalid option values (raised by the conversion function). - `TypeError` for invalid option value types (raised by conversion function). - `DuplicateOptionError` for duplicate options. - `BadOptionError` for invalid fields. - `BadOptionDataError` for invalid option data (missing name, missing data, bad quotes, etc.). """ option_list = extract_options(field_list) option_dict = assemble_option_dict(option_list, options_spec) return option_dict def extract_options(field_list): """ Return a list of option (name, value) pairs from field names & bodies. :Parameter: `field_list`: A flat field list, where each field name is a single word and each field body consists of a single paragraph only. :Exceptions: - `BadOptionError` for invalid fields. - `BadOptionDataError` for invalid option data (missing name, missing data, bad quotes, etc.). """ option_list = [] for field in field_list: if len(field[0].astext().split()) != 1: raise BadOptionError( 'extension option field name may not contain multiple words') name = str(field[0].astext().lower()) body = field[1] if len(body) == 0: data = None elif len(body) > 1 or not isinstance(body[0], nodes.paragraph) \ or len(body[0]) != 1 or not isinstance(body[0][0], nodes.Text): raise BadOptionDataError( 'extension option field body may contain\n' 'a single paragraph only (option "%s")' % name) else: data = body[0][0].astext() option_list.append((name, data)) return option_list def assemble_option_dict(option_list, options_spec): """ Return a mapping of option names to values. :Parameters: - `option_list`: A list of (name, value) pairs (the output of `extract_options()`). - `options_spec`: Dictionary mapping known option names to a conversion function such as `int` or `float`. :Exceptions: - `KeyError` for unknown option names. - `DuplicateOptionError` for duplicate options. - `ValueError` for invalid option values (raised by conversion function). - `TypeError` for invalid option value types (raised by conversion function). """ options = {} for name, value in option_list: convertor = options_spec[name] # raises KeyError if unknown if convertor is None: raise KeyError(name) # or if explicitly disabled if options.has_key(name): raise DuplicateOptionError('duplicate option "%s"' % name) try: options[name] = convertor(value) except (ValueError, TypeError), detail: raise detail.__class__('(option: "%s"; value: %r)\n%s' % (name, value, ' '.join(detail.args))) return options class NameValueError(DataError): pass def extract_name_value(line): """ Return a list of (name, value) from a line of the form "name=value ...". :Exception: `NameValueError` for invalid input (missing name, missing data, bad quotes, etc.). """ attlist = [] while line: equals = line.find('=') if equals == -1: raise NameValueError('missing "="') attname = line[:equals].strip() if equals == 0 or not attname: raise NameValueError( 'missing attribute name before "="') line = line[equals+1:].lstrip() if not line: raise NameValueError( 'missing value after "%s="' % attname) if line[0] in '\'"': endquote = line.find(line[0], 1) if endquote == -1: raise NameValueError( 'attribute "%s" missing end quote (%s)' % (attname, line[0])) if len(line) > endquote + 1 and line[endquote + 1].strip(): raise NameValueError( 'attribute "%s" end quote (%s) not followed by ' 'whitespace' % (attname, line[0])) data = line[1:endquote] line = line[endquote+1:].lstrip() else: space = line.find(' ') if space == -1: data = line line = '' else: data = line[:space] line = line[space+1:].lstrip() attlist.append((attname.lower(), data)) return attlist def new_document(source, settings=None): """ Return a new empty document object. :Parameters: `source` : string The path to or description of the source text of the document. `settings` : optparse.Values object Runtime settings. If none provided, a default set will be used. """ if settings is None: settings = frontend.OptionParser().get_default_values() reporter = Reporter(source, settings.report_level, settings.halt_level, stream=settings.warning_stream, debug=settings.debug, encoding=settings.error_encoding, error_handler=settings.error_encoding_error_handler) document = nodes.document(settings, reporter, source=source) document.note_source(source, -1) return document def clean_rcs_keywords(paragraph, keyword_substitutions): if len(paragraph) == 1 and isinstance(paragraph[0], nodes.Text): textnode = paragraph[0] for pattern, substitution in keyword_substitutions: match = pattern.search(textnode.data) if match: textnode.data = pattern.sub(substitution, textnode.data) return def relative_path(source, target): """ Build and return a path to `target`, relative to `source` (both files). If there is no common prefix, return the absolute path to `target`. """ source_parts = os.path.abspath(source or 'dummy_file').split(os.sep) target_parts = os.path.abspath(target).split(os.sep) # Check first 2 parts because '/dir'.split('/') == ['', 'dir']: if source_parts[:2] != target_parts[:2]: # Nothing in common between paths. # Return absolute path, using '/' for URLs: return '/'.join(target_parts) source_parts.reverse() target_parts.reverse() while (source_parts and target_parts and source_parts[-1] == target_parts[-1]): # Remove path components in common: source_parts.pop() target_parts.pop() target_parts.reverse() parts = ['..'] * (len(source_parts) - 1) + target_parts return '/'.join(parts) def get_stylesheet_reference(settings, relative_to=None): """ Retrieve a stylesheet reference from the settings object. """ if settings.stylesheet_path: assert not settings.stylesheet, \ 'stylesheet and stylesheet_path are mutually exclusive.' if relative_to == None: relative_to = settings._destination return relative_path(relative_to, settings.stylesheet_path) else: return settings.stylesheet def get_trim_footnote_ref_space(settings): """ Return whether or not to trim footnote space. If trim_footnote_reference_space is not None, return it. If trim_footnote_reference_space is None, return False unless the footnote reference style is 'superscript'. """ if settings.trim_footnote_reference_space is None: return hasattr(settings, 'footnote_references') and \ settings.footnote_references == 'superscript' else: return settings.trim_footnote_reference_space def get_source_line(node): """ Return the "source" and "line" attributes from the `node` given or from its closest ancestor. """ while node: if node.source or node.line: return node.source, node.line node = node.parent return None, None def escape2null(text): """Return a string with escape-backslashes converted to nulls.""" parts = [] start = 0 while 1: found = text.find('\\', start) if found == -1: parts.append(text[start:]) return ''.join(parts) parts.append(text[start:found]) parts.append('\x00' + text[found+1:found+2]) start = found + 2 # skip character after escape def unescape(text, restore_backslashes=0): """ Return a string with nulls removed or restored to backslashes. Backslash-escaped spaces are also removed. """ if restore_backslashes: return text.replace('\x00', '\\') else: for sep in ['\x00 ', '\x00\n', '\x00']: text = ''.join(text.split(sep)) return text class DependencyList: """ List of dependencies, with file recording support. Note that the output file is not automatically closed. You have to explicitly call the close() method. """ def __init__(self, output_file=None, dependencies=[]): """ Initialize the dependency list, automatically setting the output file to `output_file` (see `set_output()`) and adding all supplied dependencies. """ self.set_output(output_file) for i in dependencies: self.add(i) def set_output(self, output_file): """ Set the output file and clear the list of already added dependencies. `output_file` must be a string. The specified file is immediately overwritten. If output_file is '-', the output will be written to stdout. If it is None, no file output is done when calling add(). """ self.list = [] if output_file == '-': self.file = sys.stdout elif output_file: self.file = open(output_file, 'w') else: self.file = None def add(self, filename): """ If the dependency `filename` has not already been added, append it to self.list and print it to self.file if self.file is not None. """ if not filename in self.list: self.list.append(filename) if self.file is not None: print >>self.file, filename def close(self): """ Close the output file. """ self.file.close() self.file = None def __repr__(self): if self.file: output_file = self.file.name else: output_file = None return '%s(%r, %s)' % (self.__class__.__name__, output_file, self.list)
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/utils.py", "copies": "1", "size": "19699", "license": "mit", "hash": 5781615408089193000, "line_mean": 35.547309833, "line_max": 79, "alpha_frac": 0.6029747703, "autogenerated": false, "ratio": 4.368817919716124, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009519910298659539, "num_lines": 539 }
""" This is the ``docutils.parsers.restructuredtext.states`` module, the core of the reStructuredText parser. It defines the following: :Classes: - `RSTStateMachine`: reStructuredText parser's entry point. - `NestedStateMachine`: recursive StateMachine. - `RSTState`: reStructuredText State superclass. - `Inliner`: For parsing inline markup. - `Body`: Generic classifier of the first line of a block. - `SpecializedBody`: Superclass for compound element members. - `BulletList`: Second and subsequent bullet_list list_items - `DefinitionList`: Second+ definition_list_items. - `EnumeratedList`: Second+ enumerated_list list_items. - `FieldList`: Second+ fields. - `OptionList`: Second+ option_list_items. - `RFC2822List`: Second+ RFC2822-style fields. - `ExtensionOptions`: Parses directive option fields. - `Explicit`: Second+ explicit markup constructs. - `SubstitutionDef`: For embedded directives in substitution definitions. - `Text`: Classifier of second line of a text block. - `SpecializedText`: Superclass for continuation lines of Text-variants. - `Definition`: Second line of potential definition_list_item. - `Line`: Second line of overlined section title or transition marker. - `Struct`: An auxiliary collection class. :Exception classes: - `MarkupError` - `ParserError` - `MarkupMismatch` :Functions: - `escape2null()`: Return a string, escape-backslashes converted to nulls. - `unescape()`: Return a string, nulls removed or restored to backslashes. :Attributes: - `state_classes`: set of State classes used with `RSTStateMachine`. Parser Overview =============== The reStructuredText parser is implemented as a recursive state machine, examining its input one line at a time. To understand how the parser works, please first become familiar with the `docutils.statemachine` module. In the description below, references are made to classes defined in this module; please see the individual classes for details. Parsing proceeds as follows: 1. The state machine examines each line of input, checking each of the transition patterns of the state `Body`, in order, looking for a match. The implicit transitions (blank lines and indentation) are checked before any others. The 'text' transition is a catch-all (matches anything). 2. The method associated with the matched transition pattern is called. A. Some transition methods are self-contained, appending elements to the document tree (`Body.doctest` parses a doctest block). The parser's current line index is advanced to the end of the element, and parsing continues with step 1. B. Other transition methods trigger the creation of a nested state machine, whose job is to parse a compound construct ('indent' does a block quote, 'bullet' does a bullet list, 'overline' does a section [first checking for a valid section header], etc.). - In the case of lists and explicit markup, a one-off state machine is created and run to parse contents of the first item. - A new state machine is created and its initial state is set to the appropriate specialized state (`BulletList` in the case of the 'bullet' transition; see `SpecializedBody` for more detail). This state machine is run to parse the compound element (or series of explicit markup elements), and returns as soon as a non-member element is encountered. For example, the `BulletList` state machine ends as soon as it encounters an element which is not a list item of that bullet list. The optional omission of inter-element blank lines is enabled by this nested state machine. - The current line index is advanced to the end of the elements parsed, and parsing continues with step 1. C. The result of the 'text' transition depends on the next line of text. The current state is changed to `Text`, under which the second line is examined. If the second line is: - Indented: The element is a definition list item, and parsing proceeds similarly to step 2.B, using the `DefinitionList` state. - A line of uniform punctuation characters: The element is a section header; again, parsing proceeds as in step 2.B, and `Body` is still used. - Anything else: The element is a paragraph, which is examined for inline markup and appended to the parent element. Processing continues with step 1. """ __docformat__ = 'reStructuredText' import sys import re import roman from types import TupleType from docutils import nodes, statemachine, utils, urischemes from docutils import ApplicationError, DataError from docutils.statemachine import StateMachineWS, StateWS from docutils.nodes import fully_normalize_name as normalize_name from docutils.nodes import whitespace_normalize_name from docutils.utils import escape2null, unescape from docutils.parsers.rst import directives, languages, tableparser, roles from docutils.parsers.rst.languages import en as _fallback_language_module class MarkupError(DataError): pass class UnknownInterpretedRoleError(DataError): pass class InterpretedRoleNotImplementedError(DataError): pass class ParserError(ApplicationError): pass class MarkupMismatch(Exception): pass class Struct: """Stores data attributes for dotted-attribute access.""" def __init__(self, **keywordargs): self.__dict__.update(keywordargs) class RSTStateMachine(StateMachineWS): """ reStructuredText's master StateMachine. The entry point to reStructuredText parsing is the `run()` method. """ def run(self, input_lines, document, input_offset=0, match_titles=1, inliner=None): """ Parse `input_lines` and modify the `document` node in place. Extend `StateMachineWS.run()`: set up parse-global data and run the StateMachine. """ self.language = languages.get_language( document.settings.language_code) self.match_titles = match_titles if inliner is None: inliner = Inliner() inliner.init_customizations(document.settings) self.memo = Struct(document=document, reporter=document.reporter, language=self.language, title_styles=[], section_level=0, section_bubble_up_kludge=0, inliner=inliner) self.document = document self.attach_observer(document.note_source) self.reporter = self.memo.reporter self.node = document results = StateMachineWS.run(self, input_lines, input_offset, input_source=document['source']) assert results == [], 'RSTStateMachine.run() results should be empty!' self.node = self.memo = None # remove unneeded references class NestedStateMachine(StateMachineWS): """ StateMachine run from within other StateMachine runs, to parse nested document structures. """ def run(self, input_lines, input_offset, memo, node, match_titles=1): """ Parse `input_lines` and populate a `docutils.nodes.document` instance. Extend `StateMachineWS.run()`: set up document-wide data. """ self.match_titles = match_titles self.memo = memo self.document = memo.document self.attach_observer(self.document.note_source) self.reporter = memo.reporter self.language = memo.language self.node = node results = StateMachineWS.run(self, input_lines, input_offset) assert results == [], ('NestedStateMachine.run() results should be ' 'empty!') return results class RSTState(StateWS): """ reStructuredText State superclass. Contains methods used by all State subclasses. """ nested_sm = NestedStateMachine def __init__(self, state_machine, debug=0): self.nested_sm_kwargs = {'state_classes': state_classes, 'initial_state': 'Body'} StateWS.__init__(self, state_machine, debug) def runtime_init(self): StateWS.runtime_init(self) memo = self.state_machine.memo self.memo = memo self.reporter = memo.reporter self.inliner = memo.inliner self.document = memo.document self.parent = self.state_machine.node def goto_line(self, abs_line_offset): """ Jump to input line `abs_line_offset`, ignoring jumps past the end. """ try: self.state_machine.goto_line(abs_line_offset) except EOFError: pass def no_match(self, context, transitions): """ Override `StateWS.no_match` to generate a system message. This code should never be run. """ self.reporter.severe( 'Internal error: no transition pattern match. State: "%s"; ' 'transitions: %s; context: %s; current line: %r.' % (self.__class__.__name__, transitions, context, self.state_machine.line), line=self.state_machine.abs_line_number()) return context, None, [] def bof(self, context): """Called at beginning of file.""" return [], [] def nested_parse(self, block, input_offset, node, match_titles=0, state_machine_class=None, state_machine_kwargs=None): """ Create a new StateMachine rooted at `node` and run it over the input `block`. """ if state_machine_class is None: state_machine_class = self.nested_sm if state_machine_kwargs is None: state_machine_kwargs = self.nested_sm_kwargs block_length = len(block) state_machine = state_machine_class(debug=self.debug, **state_machine_kwargs) state_machine.run(block, input_offset, memo=self.memo, node=node, match_titles=match_titles) state_machine.unlink() new_offset = state_machine.abs_line_offset() # No `block.parent` implies disconnected -- lines aren't in sync: if block.parent and (len(block) - block_length) != 0: # Adjustment for block if modified in nested parse: self.state_machine.next_line(len(block) - block_length) return new_offset def nested_list_parse(self, block, input_offset, node, initial_state, blank_finish, blank_finish_state=None, extra_settings={}, match_titles=0, state_machine_class=None, state_machine_kwargs=None): """ Create a new StateMachine rooted at `node` and run it over the input `block`. Also keep track of optional intermediate blank lines and the required final one. """ if state_machine_class is None: state_machine_class = self.nested_sm if state_machine_kwargs is None: state_machine_kwargs = self.nested_sm_kwargs.copy() state_machine_kwargs['initial_state'] = initial_state state_machine = state_machine_class(debug=self.debug, **state_machine_kwargs) if blank_finish_state is None: blank_finish_state = initial_state state_machine.states[blank_finish_state].blank_finish = blank_finish for key, value in extra_settings.items(): setattr(state_machine.states[initial_state], key, value) state_machine.run(block, input_offset, memo=self.memo, node=node, match_titles=match_titles) blank_finish = state_machine.states[blank_finish_state].blank_finish state_machine.unlink() return state_machine.abs_line_offset(), blank_finish def section(self, title, source, style, lineno, messages): """Check for a valid subsection and create one if it checks out.""" if self.check_subsection(source, style, lineno): self.new_subsection(title, lineno, messages) def check_subsection(self, source, style, lineno): """ Check for a valid subsection header. Return 1 (true) or None (false). When a new section is reached that isn't a subsection of the current section, back up the line count (use ``previous_line(-x)``), then ``raise EOFError``. The current StateMachine will finish, then the calling StateMachine can re-examine the title. This will work its way back up the calling chain until the correct section level isreached. @@@ Alternative: Evaluate the title, store the title info & level, and back up the chain until that level is reached. Store in memo? Or return in results? :Exception: `EOFError` when a sibling or supersection encountered. """ memo = self.memo title_styles = memo.title_styles mylevel = memo.section_level try: # check for existing title style level = title_styles.index(style) + 1 except ValueError: # new title style if len(title_styles) == memo.section_level: # new subsection title_styles.append(style) return 1 else: # not at lowest level self.parent += self.title_inconsistent(source, lineno) return None if level <= mylevel: # sibling or supersection memo.section_level = level # bubble up to parent section if len(style) == 2: memo.section_bubble_up_kludge = 1 # back up 2 lines for underline title, 3 for overline title self.state_machine.previous_line(len(style) + 1) raise EOFError # let parent section re-evaluate if level == mylevel + 1: # immediate subsection return 1 else: # invalid subsection self.parent += self.title_inconsistent(source, lineno) return None def title_inconsistent(self, sourcetext, lineno): error = self.reporter.severe( 'Title level inconsistent:', nodes.literal_block('', sourcetext), line=lineno) return error def new_subsection(self, title, lineno, messages): """Append new subsection to document tree. On return, check level.""" memo = self.memo mylevel = memo.section_level memo.section_level += 1 section_node = nodes.section() self.parent += section_node textnodes, title_messages = self.inline_text(title, lineno) titlenode = nodes.title(title, '', *textnodes) name = normalize_name(titlenode.astext()) section_node['names'].append(name) section_node += titlenode section_node += messages section_node += title_messages self.document.note_implicit_target(section_node, section_node) offset = self.state_machine.line_offset + 1 absoffset = self.state_machine.abs_line_offset() + 1 newabsoffset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=absoffset, node=section_node, match_titles=1) self.goto_line(newabsoffset) if memo.section_level <= mylevel: # can't handle next section? raise EOFError # bubble up to supersection # reset section_level; next pass will detect it properly memo.section_level = mylevel def paragraph(self, lines, lineno): """ Return a list (paragraph & messages) & a boolean: literal_block next? """ data = '\n'.join(lines).rstrip() if data[-2:] == '::': if len(data) == 2: return [], 1 elif data[-3] in ' \n': text = data[:-3].rstrip() else: text = data[:-1] literalnext = 1 else: text = data literalnext = 0 textnodes, messages = self.inline_text(text, lineno) p = nodes.paragraph(data, '', *textnodes) p.line = lineno return [p] + messages, literalnext def inline_text(self, text, lineno): """ Return 2 lists: nodes (text and inline elements), and system_messages. """ return self.inliner.parse(text, lineno, self.memo, self.parent) def unindent_warning(self, node_name): return self.reporter.warning( '%s ends without a blank line; unexpected unindent.' % node_name, line=(self.state_machine.abs_line_number() + 1)) def build_regexp(definition, compile=1): """ Build, compile and return a regular expression based on `definition`. :Parameter: `definition`: a 4-tuple (group name, prefix, suffix, parts), where "parts" is a list of regular expressions and/or regular expression definitions to be joined into an or-group. """ name, prefix, suffix, parts = definition part_strings = [] for part in parts: if type(part) is TupleType: part_strings.append(build_regexp(part, None)) else: part_strings.append(part) or_group = '|'.join(part_strings) regexp = '%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s' % locals() if compile: return re.compile(regexp, re.UNICODE) else: return regexp class Inliner: """ Parse inline markup; call the `parse()` method. """ def __init__(self, roles=None): """ `roles` is a mapping of canonical role name to role function or bound method, which enables additional interpreted text roles. """ self.implicit_dispatch = [(self.patterns.uri, self.standalone_uri),] """List of (pattern, bound method) tuples, used by `self.implicit_inline`.""" def init_customizations(self, settings): """Setting-based customizations; run when parsing begins.""" if settings.pep_references: self.implicit_dispatch.append((self.patterns.pep, self.pep_reference)) if settings.rfc_references: self.implicit_dispatch.append((self.patterns.rfc, self.rfc_reference)) def parse(self, text, lineno, memo, parent): # Needs to be refactored for nested inline markup. # Add nested_parse() method? """ Return 2 lists: nodes (text and inline elements), and system_messages. Using `self.patterns.initial`, a pattern which matches start-strings (emphasis, strong, interpreted, phrase reference, literal, substitution reference, and inline target) and complete constructs (simple reference, footnote reference), search for a candidate. When one is found, check for validity (e.g., not a quoted '*' character). If valid, search for the corresponding end string if applicable, and check it for validity. If not found or invalid, generate a warning and ignore the start-string. Implicit inline markup (e.g. standalone URIs) is found last. """ self.reporter = memo.reporter self.document = memo.document self.language = memo.language self.parent = parent pattern_search = self.patterns.initial.search dispatch = self.dispatch remaining = escape2null(text) processed = [] unprocessed = [] messages = [] while remaining: match = pattern_search(remaining) if match: groups = match.groupdict() method = dispatch[groups['start'] or groups['backquote'] or groups['refend'] or groups['fnend']] before, inlines, remaining, sysmessages = method(self, match, lineno) unprocessed.append(before) messages += sysmessages if inlines: processed += self.implicit_inline(''.join(unprocessed), lineno) processed += inlines unprocessed = [] else: break remaining = ''.join(unprocessed) + remaining if remaining: processed += self.implicit_inline(remaining, lineno) return processed, messages openers = '\'"([{<' closers = '\'")]}>' start_string_prefix = (r'((?<=^)|(?<=[-/: \n%s]))' % re.escape(openers)) end_string_suffix = (r'((?=$)|(?=[-/:.,;!? \n\x00%s]))' % re.escape(closers)) non_whitespace_before = r'(?<![ \n])' non_whitespace_escape_before = r'(?<![ \n\x00])' non_whitespace_after = r'(?![ \n])' # Alphanumerics with isolated internal [-._] chars (i.e. not 2 together): simplename = r'(?:(?!_)\w)+(?:[-._](?:(?!_)\w)+)*' # Valid URI characters (see RFC 2396 & RFC 2732); # final \x00 allows backslash escapes in URIs: uric = r"""[-_.!~*'()[\];/:@&=+$,%a-zA-Z0-9\x00]""" # Delimiter indicating the end of a URI (not part of the URI): uri_end_delim = r"""[>]""" # Last URI character; same as uric but no punctuation: urilast = r"""[_~*/=+a-zA-Z0-9]""" # End of a URI (either 'urilast' or 'uric followed by a # uri_end_delim'): uri_end = r"""(?:%(urilast)s|%(uric)s(?=%(uri_end_delim)s))""" % locals() emailc = r"""[-_!~*'{|}/#?^`&=+$%a-zA-Z0-9\x00]""" email_pattern = r""" %(emailc)s+(?:\.%(emailc)s+)* # name (?<!\x00)@ # at %(emailc)s+(?:\.%(emailc)s*)* # host %(uri_end)s # final URI char """ parts = ('initial_inline', start_string_prefix, '', [('start', '', non_whitespace_after, # simple start-strings [r'\*\*', # strong r'\*(?!\*)', # emphasis but not strong r'``', # literal r'_`', # inline internal target r'\|(?!\|)'] # substitution reference ), ('whole', '', end_string_suffix, # whole constructs [# reference name & end-string r'(?P<refname>%s)(?P<refend>__?)' % simplename, ('footnotelabel', r'\[', r'(?P<fnend>\]_)', [r'[0-9]+', # manually numbered r'\#(%s)?' % simplename, # auto-numbered (w/ label?) r'\*', # auto-symbol r'(?P<citationlabel>%s)' % simplename] # citation reference ) ] ), ('backquote', # interpreted text or phrase reference '(?P<role>(:%s:)?)' % simplename, # optional role non_whitespace_after, ['`(?!`)'] # but not literal ) ] ) patterns = Struct( initial=build_regexp(parts), emphasis=re.compile(non_whitespace_escape_before + r'(\*)' + end_string_suffix), strong=re.compile(non_whitespace_escape_before + r'(\*\*)' + end_string_suffix), interpreted_or_phrase_ref=re.compile( r""" %(non_whitespace_escape_before)s ( ` (?P<suffix> (?P<role>:%(simplename)s:)? (?P<refend>__?)? ) ) %(end_string_suffix)s """ % locals(), re.VERBOSE | re.UNICODE), embedded_uri=re.compile( r""" ( (?:[ \n]+|^) # spaces or beginning of line/string < # open bracket %(non_whitespace_after)s ([^<>\x00]+) # anything but angle brackets & nulls %(non_whitespace_before)s > # close bracket w/o whitespace before ) $ # end of string """ % locals(), re.VERBOSE), literal=re.compile(non_whitespace_before + '(``)' + end_string_suffix), target=re.compile(non_whitespace_escape_before + r'(`)' + end_string_suffix), substitution_ref=re.compile(non_whitespace_escape_before + r'(\|_{0,2})' + end_string_suffix), email=re.compile(email_pattern % locals() + '$', re.VERBOSE), uri=re.compile( (r""" %(start_string_prefix)s (?P<whole> (?P<absolute> # absolute URI (?P<scheme> # scheme (http, ftp, mailto) [a-zA-Z][a-zA-Z0-9.+-]* ) : ( ( # either: (//?)? # hierarchical URI %(uric)s* # URI characters %(uri_end)s # final URI char ) ( # optional query \?%(uric)s* %(uri_end)s )? ( # optional fragment \#%(uric)s* %(uri_end)s )? ) ) | # *OR* (?P<email> # email address """ + email_pattern + r""" ) ) %(end_string_suffix)s """) % locals(), re.VERBOSE), pep=re.compile( r""" %(start_string_prefix)s ( (pep-(?P<pepnum1>\d+)(.txt)?) # reference to source file | (PEP\s+(?P<pepnum2>\d+)) # reference by name ) %(end_string_suffix)s""" % locals(), re.VERBOSE), rfc=re.compile( r""" %(start_string_prefix)s (RFC(-|\s+)?(?P<rfcnum>\d+)) %(end_string_suffix)s""" % locals(), re.VERBOSE)) def quoted_start(self, match): """Return 1 if inline markup start-string is 'quoted', 0 if not.""" string = match.string start = match.start() end = match.end() if start == 0: # start-string at beginning of text return 0 prestart = string[start - 1] try: poststart = string[end] if self.openers.index(prestart) \ == self.closers.index(poststart): # quoted return 1 except IndexError: # start-string at end of text return 1 except ValueError: # not quoted pass return 0 def inline_obj(self, match, lineno, end_pattern, nodeclass, restore_backslashes=0): string = match.string matchstart = match.start('start') matchend = match.end('start') if self.quoted_start(match): return (string[:matchend], [], string[matchend:], [], '') endmatch = end_pattern.search(string[matchend:]) if endmatch and endmatch.start(1): # 1 or more chars text = unescape(endmatch.string[:endmatch.start(1)], restore_backslashes) textend = matchend + endmatch.end(1) rawsource = unescape(string[matchstart:textend], 1) return (string[:matchstart], [nodeclass(rawsource, text)], string[textend:], [], endmatch.group(1)) msg = self.reporter.warning( 'Inline %s start-string without end-string.' % nodeclass.__name__, line=lineno) text = unescape(string[matchstart:matchend], 1) rawsource = unescape(string[matchstart:matchend], 1) prb = self.problematic(text, rawsource, msg) return string[:matchstart], [prb], string[matchend:], [msg], '' def problematic(self, text, rawsource, message): msgid = self.document.set_id(message, self.parent) problematic = nodes.problematic(rawsource, text, refid=msgid) prbid = self.document.set_id(problematic) message.add_backref(prbid) return problematic def emphasis(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.emphasis, nodes.emphasis) return before, inlines, remaining, sysmessages def strong(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.strong, nodes.strong) return before, inlines, remaining, sysmessages def interpreted_or_phrase_ref(self, match, lineno): end_pattern = self.patterns.interpreted_or_phrase_ref string = match.string matchstart = match.start('backquote') matchend = match.end('backquote') rolestart = match.start('role') role = match.group('role') position = '' if role: role = role[1:-1] position = 'prefix' elif self.quoted_start(match): return (string[:matchend], [], string[matchend:], []) endmatch = end_pattern.search(string[matchend:]) if endmatch and endmatch.start(1): # 1 or more chars textend = matchend + endmatch.end() if endmatch.group('role'): if role: msg = self.reporter.warning( 'Multiple roles in interpreted text (both ' 'prefix and suffix present; only one allowed).', line=lineno) text = unescape(string[rolestart:textend], 1) prb = self.problematic(text, text, msg) return string[:rolestart], [prb], string[textend:], [msg] role = endmatch.group('suffix')[1:-1] position = 'suffix' escaped = endmatch.string[:endmatch.start(1)] rawsource = unescape(string[matchstart:textend], 1) if rawsource[-1:] == '_': if role: msg = self.reporter.warning( 'Mismatch: both interpreted text role %s and ' 'reference suffix.' % position, line=lineno) text = unescape(string[rolestart:textend], 1) prb = self.problematic(text, text, msg) return string[:rolestart], [prb], string[textend:], [msg] return self.phrase_ref(string[:matchstart], string[textend:], rawsource, escaped, unescape(escaped)) else: rawsource = unescape(string[rolestart:textend], 1) nodelist, messages = self.interpreted(rawsource, escaped, role, lineno) return (string[:rolestart], nodelist, string[textend:], messages) msg = self.reporter.warning( 'Inline interpreted text or phrase reference start-string ' 'without end-string.', line=lineno) text = unescape(string[matchstart:matchend], 1) prb = self.problematic(text, text, msg) return string[:matchstart], [prb], string[matchend:], [msg] def phrase_ref(self, before, after, rawsource, escaped, text): match = self.patterns.embedded_uri.search(escaped) if match: text = unescape(escaped[:match.start(0)]) uri_text = match.group(2) uri = ''.join(uri_text.split()) uri = self.adjust_uri(uri) if uri: target = nodes.target(match.group(1), refuri=uri) else: raise ApplicationError('problem with URI: %r' % uri_text) if not text: text = uri else: target = None refname = normalize_name(text) reference = nodes.reference(rawsource, text, name=whitespace_normalize_name(text)) node_list = [reference] if rawsource[-2:] == '__': if target: reference['refuri'] = uri else: reference['anonymous'] = 1 self.document.note_anonymous_ref(reference) else: if target: reference['refuri'] = uri target['names'].append(refname) self.document.note_external_target(target) self.document.note_explicit_target(target, self.parent) node_list.append(target) else: reference['refname'] = refname self.document.note_refname(reference) return before, node_list, after, [] def adjust_uri(self, uri): match = self.patterns.email.match(uri) if match: return 'mailto:' + uri else: return uri def interpreted(self, rawsource, text, role, lineno): role_fn, messages = roles.role(role, self.language, lineno, self.reporter) if role_fn: nodes, messages2 = role_fn(role, rawsource, text, lineno, self) return nodes, messages + messages2 else: msg = self.reporter.error( 'Unknown interpreted text role "%s".' % role, line=lineno) return ([self.problematic(rawsource, rawsource, msg)], messages + [msg]) def literal(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.literal, nodes.literal, restore_backslashes=1) return before, inlines, remaining, sysmessages def inline_internal_target(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.target, nodes.target) if inlines and isinstance(inlines[0], nodes.target): assert len(inlines) == 1 target = inlines[0] name = normalize_name(target.astext()) target['names'].append(name) self.document.note_explicit_target(target, self.parent) return before, inlines, remaining, sysmessages def substitution_reference(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.substitution_ref, nodes.substitution_reference) if len(inlines) == 1: subref_node = inlines[0] if isinstance(subref_node, nodes.substitution_reference): subref_text = subref_node.astext() self.document.note_substitution_ref(subref_node, subref_text) if endstring[-1:] == '_': reference_node = nodes.reference( '|%s%s' % (subref_text, endstring), '') if endstring[-2:] == '__': reference_node['anonymous'] = 1 self.document.note_anonymous_ref( reference_node) else: reference_node['refname'] = normalize_name(subref_text) self.document.note_refname(reference_node) reference_node += subref_node inlines = [reference_node] return before, inlines, remaining, sysmessages def footnote_reference(self, match, lineno): """ Handles `nodes.footnote_reference` and `nodes.citation_reference` elements. """ label = match.group('footnotelabel') refname = normalize_name(label) string = match.string before = string[:match.start('whole')] remaining = string[match.end('whole'):] if match.group('citationlabel'): refnode = nodes.citation_reference('[%s]_' % label, refname=refname) refnode += nodes.Text(label) self.document.note_citation_ref(refnode) else: refnode = nodes.footnote_reference('[%s]_' % label) if refname[0] == '#': refname = refname[1:] refnode['auto'] = 1 self.document.note_autofootnote_ref(refnode) elif refname == '*': refname = '' refnode['auto'] = '*' self.document.note_symbol_footnote_ref( refnode) else: refnode += nodes.Text(label) if refname: refnode['refname'] = refname self.document.note_footnote_ref(refnode) if utils.get_trim_footnote_ref_space(self.document.settings): before = before.rstrip() return (before, [refnode], remaining, []) def reference(self, match, lineno, anonymous=None): referencename = match.group('refname') refname = normalize_name(referencename) referencenode = nodes.reference( referencename + match.group('refend'), referencename, name=whitespace_normalize_name(referencename)) if anonymous: referencenode['anonymous'] = 1 self.document.note_anonymous_ref(referencenode) else: referencenode['refname'] = refname self.document.note_refname(referencenode) string = match.string matchstart = match.start('whole') matchend = match.end('whole') return (string[:matchstart], [referencenode], string[matchend:], []) def anonymous_reference(self, match, lineno): return self.reference(match, lineno, anonymous=1) def standalone_uri(self, match, lineno): if not match.group('scheme') or urischemes.schemes.has_key( match.group('scheme').lower()): if match.group('email'): addscheme = 'mailto:' else: addscheme = '' text = match.group('whole') unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=addscheme + unescaped)] else: # not a valid scheme raise MarkupMismatch pep_url = 'pep-%04d.html' def pep_reference(self, match, lineno): text = match.group(0) if text.startswith('pep-'): pepnum = int(match.group('pepnum1')) elif text.startswith('PEP'): pepnum = int(match.group('pepnum2')) else: raise MarkupMismatch ref = self.document.settings.pep_base_url + self.pep_url % pepnum unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)] rfc_url = 'rfc%d.html' def rfc_reference(self, match, lineno): text = match.group(0) if text.startswith('RFC'): rfcnum = int(match.group('rfcnum')) ref = self.document.settings.rfc_base_url + self.rfc_url % rfcnum else: raise MarkupMismatch unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)] def implicit_inline(self, text, lineno): """ Check each of the patterns in `self.implicit_dispatch` for a match, and dispatch to the stored method for the pattern. Recursively check the text before and after the match. Return a list of `nodes.Text` and inline element nodes. """ if not text: return [] for pattern, method in self.implicit_dispatch: match = pattern.search(text) if match: try: # Must recurse on strings before *and* after the match; # there may be multiple patterns. return (self.implicit_inline(text[:match.start()], lineno) + method(match, lineno) + self.implicit_inline(text[match.end():], lineno)) except MarkupMismatch: pass return [nodes.Text(unescape(text), rawsource=unescape(text, 1))] dispatch = {'*': emphasis, '**': strong, '`': interpreted_or_phrase_ref, '``': literal, '_`': inline_internal_target, ']_': footnote_reference, '|': substitution_reference, '_': reference, '__': anonymous_reference} class Body(RSTState): """ Generic classifier of the first line of a block. """ enum = Struct() """Enumerated list parsing information.""" enum.formatinfo = { 'parens': Struct(prefix='(', suffix=')', start=1, end=-1), 'rparen': Struct(prefix='', suffix=')', start=0, end=-1), 'period': Struct(prefix='', suffix='.', start=0, end=-1)} enum.formats = enum.formatinfo.keys() enum.sequences = ['arabic', 'loweralpha', 'upperalpha', 'lowerroman', 'upperroman'] # ORDERED! enum.sequencepats = {'arabic': '[0-9]+', 'loweralpha': '[a-z]', 'upperalpha': '[A-Z]', 'lowerroman': '[ivxlcdm]+', 'upperroman': '[IVXLCDM]+',} enum.converters = {'arabic': int, 'loweralpha': lambda s, zero=(ord('a')-1): ord(s) - zero, 'upperalpha': lambda s, zero=(ord('A')-1): ord(s) - zero, 'lowerroman': lambda s: roman.fromRoman(s.upper()), 'upperroman': roman.fromRoman} enum.sequenceregexps = {} for sequence in enum.sequences: enum.sequenceregexps[sequence] = re.compile( enum.sequencepats[sequence] + '$') grid_table_top_pat = re.compile(r'\+-[-+]+-\+ *$') """Matches the top (& bottom) of a full table).""" simple_table_top_pat = re.compile('=+( +=+)+ *$') """Matches the top of a simple table.""" simple_table_border_pat = re.compile('=+[ =]*$') """Matches the bottom & header bottom of a simple table.""" pats = {} """Fragments of patterns used by transitions.""" pats['nonalphanum7bit'] = '[!-/:-@[-`{-~]' pats['alpha'] = '[a-zA-Z]' pats['alphanum'] = '[a-zA-Z0-9]' pats['alphanumplus'] = '[a-zA-Z0-9_-]' pats['enum'] = ('(%(arabic)s|%(loweralpha)s|%(upperalpha)s|%(lowerroman)s' '|%(upperroman)s|#)' % enum.sequencepats) pats['optname'] = '%(alphanum)s%(alphanumplus)s*' % pats # @@@ Loosen up the pattern? Allow Unicode? pats['optarg'] = '(%(alpha)s%(alphanumplus)s*|<[^<>]+>)' % pats pats['shortopt'] = r'(-|\+)%(alphanum)s( ?%(optarg)s)?' % pats pats['longopt'] = r'(--|/)%(optname)s([ =]%(optarg)s)?' % pats pats['option'] = r'(%(shortopt)s|%(longopt)s)' % pats for format in enum.formats: pats[format] = '(?P<%s>%s%s%s)' % ( format, re.escape(enum.formatinfo[format].prefix), pats['enum'], re.escape(enum.formatinfo[format].suffix)) patterns = { 'bullet': r'[-+*]( +|$)', 'enumerator': r'(%(parens)s|%(rparen)s|%(period)s)( +|$)' % pats, 'field_marker': r':[^: ]([^:]*[^: ])?:( +|$)', 'option_marker': r'%(option)s(, %(option)s)*( +| ?$)' % pats, 'doctest': r'>>>( +|$)', 'line_block': r'\|( +|$)', 'grid_table_top': grid_table_top_pat, 'simple_table_top': simple_table_top_pat, 'explicit_markup': r'\.\.( +|$)', 'anonymous': r'__( +|$)', 'line': r'(%(nonalphanum7bit)s)\1* *$' % pats, 'text': r''} initial_transitions = ( 'bullet', 'enumerator', 'field_marker', 'option_marker', 'doctest', 'line_block', 'grid_table_top', 'simple_table_top', 'explicit_markup', 'anonymous', 'line', 'text') def indent(self, match, context, next_state): """Block quote.""" indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() blockquote, messages = self.block_quote(indented, line_offset) self.parent += blockquote self.parent += messages if not blank_finish: self.parent += self.unindent_warning('Block quote') return context, next_state, [] def block_quote(self, indented, line_offset): blockquote_lines, attribution_lines, attribution_offset = \ self.check_attribution(indented, line_offset) blockquote = nodes.block_quote() self.nested_parse(blockquote_lines, line_offset, blockquote) messages = [] if attribution_lines: attribution, messages = self.parse_attribution(attribution_lines, attribution_offset) blockquote += attribution return blockquote, messages # u'\u2014' is an em-dash: attribution_pattern = re.compile(ur'(---?(?!-)|\u2014) *(?=[^ \n])') def check_attribution(self, indented, line_offset): """ Check for an attribution in the last contiguous block of `indented`. * First line after last blank line must begin with "--" (etc.). * Every line after that must have consistent indentation. Return a 3-tuple: (block quote lines, attribution lines, attribution offset). """ blank = None nonblank_seen = None indent = 0 for i in range(len(indented) - 1, 0, -1): # don't check first line this_line_blank = not indented[i].strip() if nonblank_seen and this_line_blank: match = self.attribution_pattern.match(indented[i + 1]) if match: blank = i break elif not this_line_blank: nonblank_seen = 1 if blank and len(indented) - blank > 2: # multi-line attribution indent = (len(indented[blank + 2]) - len(indented[blank + 2].lstrip())) for j in range(blank + 3, len(indented)): if indent != (len(indented[j]) - len(indented[j].lstrip())): # bad shape blank = None break if blank: a_lines = indented[blank + 1:] a_lines.trim_left(match.end(), end=1) a_lines.trim_left(indent, start=1) return (indented[:blank], a_lines, line_offset + blank + 1) else: return (indented, None, None) def parse_attribution(self, indented, line_offset): text = '\n'.join(indented).rstrip() lineno = self.state_machine.abs_line_number() + line_offset textnodes, messages = self.inline_text(text, lineno) node = nodes.attribution(text, '', *textnodes) node.line = lineno return node, messages def bullet(self, match, context, next_state): """Bullet list item.""" bulletlist = nodes.bullet_list() self.parent += bulletlist bulletlist['bullet'] = match.string[0] i, blank_finish = self.list_item(match.end()) bulletlist += i offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=bulletlist, initial_state='BulletList', blank_finish=blank_finish) self.goto_line(new_line_offset) if not blank_finish: self.parent += self.unindent_warning('Bullet list') return [], next_state, [] def list_item(self, indent): indented, line_offset, blank_finish = \ self.state_machine.get_known_indented(indent) listitem = nodes.list_item('\n'.join(indented)) if indented: self.nested_parse(indented, input_offset=line_offset, node=listitem) return listitem, blank_finish def enumerator(self, match, context, next_state): """Enumerated List Item""" format, sequence, text, ordinal = self.parse_enumerator(match) if not self.is_enumerated_list_item(ordinal, sequence, format): raise statemachine.TransitionCorrection('text') enumlist = nodes.enumerated_list() self.parent += enumlist if sequence == '#': enumlist['enumtype'] = 'arabic' else: enumlist['enumtype'] = sequence enumlist['prefix'] = self.enum.formatinfo[format].prefix enumlist['suffix'] = self.enum.formatinfo[format].suffix if ordinal != 1: enumlist['start'] = ordinal msg = self.reporter.info( 'Enumerated list start value not ordinal-1: "%s" (ordinal %s)' % (text, ordinal), line=self.state_machine.abs_line_number()) self.parent += msg listitem, blank_finish = self.list_item(match.end()) enumlist += listitem offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=enumlist, initial_state='EnumeratedList', blank_finish=blank_finish, extra_settings={'lastordinal': ordinal, 'format': format, 'auto': sequence == '#'}) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Enumerated list') return [], next_state, [] def parse_enumerator(self, match, expected_sequence=None): """ Analyze an enumerator and return the results. :Return: - the enumerator format ('period', 'parens', or 'rparen'), - the sequence used ('arabic', 'loweralpha', 'upperroman', etc.), - the text of the enumerator, stripped of formatting, and - the ordinal value of the enumerator ('a' -> 1, 'ii' -> 2, etc.; ``None`` is returned for invalid enumerator text). The enumerator format has already been determined by the regular expression match. If `expected_sequence` is given, that sequence is tried first. If not, we check for Roman numeral 1. This way, single-character Roman numerals (which are also alphabetical) can be matched. If no sequence has been matched, all sequences are checked in order. """ groupdict = match.groupdict() sequence = '' for format in self.enum.formats: if groupdict[format]: # was this the format matched? break # yes; keep `format` else: # shouldn't happen raise ParserError('enumerator format not matched') text = groupdict[format][self.enum.formatinfo[format].start :self.enum.formatinfo[format].end] if text == '#': sequence = '#' elif expected_sequence: try: if self.enum.sequenceregexps[expected_sequence].match(text): sequence = expected_sequence except KeyError: # shouldn't happen raise ParserError('unknown enumerator sequence: %s' % sequence) elif text == 'i': sequence = 'lowerroman' elif text == 'I': sequence = 'upperroman' if not sequence: for sequence in self.enum.sequences: if self.enum.sequenceregexps[sequence].match(text): break else: # shouldn't happen raise ParserError('enumerator sequence not matched') if sequence == '#': ordinal = 1 else: try: ordinal = self.enum.converters[sequence](text) except roman.InvalidRomanNumeralError: ordinal = None return format, sequence, text, ordinal def is_enumerated_list_item(self, ordinal, sequence, format): """ Check validity based on the ordinal value and the second line. Return true iff the ordinal is valid and the second line is blank, indented, or starts with the next enumerator or an auto-enumerator. """ if ordinal is None: return None try: next_line = self.state_machine.next_line() except EOFError: # end of input lines self.state_machine.previous_line() return 1 else: self.state_machine.previous_line() if not next_line[:1].strip(): # blank or indented return 1 next_enumerator, auto_enumerator = self.make_enumerator( ordinal + 1, sequence, format) try: if ( next_line.startswith(next_enumerator) or next_line.startswith(auto_enumerator) ): return 1 except TypeError: pass return None def make_enumerator(self, ordinal, sequence, format): """ Construct and return the next enumerated list item marker, and an auto-enumerator ("#" instead of the regular enumerator). Return ``None`` for invalid (out of range) ordinals. """ #" if sequence == '#': enumerator = '#' elif sequence == 'arabic': enumerator = str(ordinal) else: if sequence.endswith('alpha'): if ordinal > 26: return None enumerator = chr(ordinal + ord('a') - 1) elif sequence.endswith('roman'): try: enumerator = roman.toRoman(ordinal) except roman.RomanError: return None else: # shouldn't happen raise ParserError('unknown enumerator sequence: "%s"' % sequence) if sequence.startswith('lower'): enumerator = enumerator.lower() elif sequence.startswith('upper'): enumerator = enumerator.upper() else: # shouldn't happen raise ParserError('unknown enumerator sequence: "%s"' % sequence) formatinfo = self.enum.formatinfo[format] next_enumerator = (formatinfo.prefix + enumerator + formatinfo.suffix + ' ') auto_enumerator = formatinfo.prefix + '#' + formatinfo.suffix + ' ' return next_enumerator, auto_enumerator def field_marker(self, match, context, next_state): """Field list item.""" field_list = nodes.field_list() self.parent += field_list field, blank_finish = self.field(match) field_list += field offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=field_list, initial_state='FieldList', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Field list') return [], next_state, [] def field(self, match): name = self.parse_field_marker(match) lineno = self.state_machine.abs_line_number() indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) field_node = nodes.field() field_node.line = lineno name_nodes, name_messages = self.inline_text(name, lineno) field_node += nodes.field_name(name, '', *name_nodes) field_body = nodes.field_body('\n'.join(indented), *name_messages) field_node += field_body if indented: self.parse_field_body(indented, line_offset, field_body) return field_node, blank_finish def parse_field_marker(self, match): """Extract & return field name from a field marker match.""" field = match.string[1:] # strip off leading ':' field = field[:field.find(':')] # strip off trailing ':' etc. return field def parse_field_body(self, indented, offset, node): self.nested_parse(indented, input_offset=offset, node=node) def option_marker(self, match, context, next_state): """Option list item.""" optionlist = nodes.option_list() try: listitem, blank_finish = self.option_list_item(match) except MarkupError, (message, lineno): # This shouldn't happen; pattern won't match. msg = self.reporter.error( 'Invalid option list marker: %s' % message, line=lineno) self.parent += msg indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) blockquote, messages = self.block_quote(indented, line_offset) self.parent += blockquote self.parent += messages if not blank_finish: self.parent += self.unindent_warning('Option list') return [], next_state, [] self.parent += optionlist optionlist += listitem offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=optionlist, initial_state='OptionList', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Option list') return [], next_state, [] def option_list_item(self, match): offset = self.state_machine.abs_line_offset() options = self.parse_option_marker(match) indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) if not indented: # not an option list item self.goto_line(offset) raise statemachine.TransitionCorrection('text') option_group = nodes.option_group('', *options) description = nodes.description('\n'.join(indented)) option_list_item = nodes.option_list_item('', option_group, description) if indented: self.nested_parse(indented, input_offset=line_offset, node=description) return option_list_item, blank_finish def parse_option_marker(self, match): """ Return a list of `node.option` and `node.option_argument` objects, parsed from an option marker match. :Exception: `MarkupError` for invalid option markers. """ optlist = [] optionstrings = match.group().rstrip().split(', ') for optionstring in optionstrings: tokens = optionstring.split() delimiter = ' ' firstopt = tokens[0].split('=') if len(firstopt) > 1: # "--opt=value" form tokens[:1] = firstopt delimiter = '=' elif (len(tokens[0]) > 2 and ((tokens[0].startswith('-') and not tokens[0].startswith('--')) or tokens[0].startswith('+'))): # "-ovalue" form tokens[:1] = [tokens[0][:2], tokens[0][2:]] delimiter = '' if len(tokens) > 1 and (tokens[1].startswith('<') and tokens[-1].endswith('>')): # "-o <value1 value2>" form; join all values into one token tokens[1:] = [' '.join(tokens[1:])] if 0 < len(tokens) <= 2: option = nodes.option(optionstring) option += nodes.option_string(tokens[0], tokens[0]) if len(tokens) > 1: option += nodes.option_argument(tokens[1], tokens[1], delimiter=delimiter) optlist.append(option) else: raise MarkupError( 'wrong number of option tokens (=%s), should be 1 or 2: ' '"%s"' % (len(tokens), optionstring), self.state_machine.abs_line_number() + 1) return optlist def doctest(self, match, context, next_state): data = '\n'.join(self.state_machine.get_text_block()) self.parent += nodes.doctest_block(data, data) return [], next_state, [] def line_block(self, match, context, next_state): """First line of a line block.""" block = nodes.line_block() self.parent += block lineno = self.state_machine.abs_line_number() line, messages, blank_finish = self.line_block_line(match, lineno) block += line self.parent += messages if not blank_finish: offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=block, initial_state='LineBlock', blank_finish=0) self.goto_line(new_line_offset) if not blank_finish: self.parent += self.reporter.warning( 'Line block ends without a blank line.', line=(self.state_machine.abs_line_number() + 1)) if len(block): if block[0].indent is None: block[0].indent = 0 self.nest_line_block_lines(block) return [], next_state, [] def line_block_line(self, match, lineno): """Return one line element of a line_block.""" indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), until_blank=1) text = u'\n'.join(indented) text_nodes, messages = self.inline_text(text, lineno) line = nodes.line(text, '', *text_nodes) if match.string.rstrip() != '|': # not empty line.indent = len(match.group(1)) - 1 return line, messages, blank_finish def nest_line_block_lines(self, block): for index in range(1, len(block)): if block[index].indent is None: block[index].indent = block[index - 1].indent self.nest_line_block_segment(block) def nest_line_block_segment(self, block): indents = [item.indent for item in block] least = min(indents) new_items = [] new_block = nodes.line_block() for item in block: if item.indent > least: new_block.append(item) else: if len(new_block): self.nest_line_block_segment(new_block) new_items.append(new_block) new_block = nodes.line_block() new_items.append(item) if len(new_block): self.nest_line_block_segment(new_block) new_items.append(new_block) block[:] = new_items def grid_table_top(self, match, context, next_state): """Top border of a full table.""" return self.table_top(match, context, next_state, self.isolate_grid_table, tableparser.GridTableParser) def simple_table_top(self, match, context, next_state): """Top border of a simple table.""" return self.table_top(match, context, next_state, self.isolate_simple_table, tableparser.SimpleTableParser) def table_top(self, match, context, next_state, isolate_function, parser_class): """Top border of a generic table.""" nodelist, blank_finish = self.table(isolate_function, parser_class) self.parent += nodelist if not blank_finish: msg = self.reporter.warning( 'Blank line required after table.', line=self.state_machine.abs_line_number() + 1) self.parent += msg return [], next_state, [] def table(self, isolate_function, parser_class): """Parse a table.""" block, messages, blank_finish = isolate_function() if block: try: parser = parser_class() tabledata = parser.parse(block) tableline = (self.state_machine.abs_line_number() - len(block) + 1) table = self.build_table(tabledata, tableline) nodelist = [table] + messages except tableparser.TableMarkupError, detail: nodelist = self.malformed_table( block, ' '.join(detail.args)) + messages else: nodelist = messages return nodelist, blank_finish def isolate_grid_table(self): messages = [] blank_finish = 1 try: block = self.state_machine.get_text_block(flush_left=1) except statemachine.UnexpectedIndentationError, instance: block, source, lineno = instance.args messages.append(self.reporter.error('Unexpected indentation.', source=source, line=lineno)) blank_finish = 0 block.disconnect() width = len(block[0].strip()) for i in range(len(block)): block[i] = block[i].strip() if block[i][0] not in '+|': # check left edge blank_finish = 0 self.state_machine.previous_line(len(block) - i) del block[i:] break if not self.grid_table_top_pat.match(block[-1]): # find bottom blank_finish = 0 # from second-last to third line of table: for i in range(len(block) - 2, 1, -1): if self.grid_table_top_pat.match(block[i]): self.state_machine.previous_line(len(block) - i + 1) del block[i+1:] break else: messages.extend(self.malformed_table(block)) return [], messages, blank_finish for i in range(len(block)): # check right edge if len(block[i]) != width or block[i][-1] not in '+|': messages.extend(self.malformed_table(block)) return [], messages, blank_finish return block, messages, blank_finish def isolate_simple_table(self): start = self.state_machine.line_offset lines = self.state_machine.input_lines limit = len(lines) - 1 toplen = len(lines[start].strip()) pattern_match = self.simple_table_border_pat.match found = 0 found_at = None i = start + 1 while i <= limit: line = lines[i] match = pattern_match(line) if match: if len(line.strip()) != toplen: self.state_machine.next_line(i - start) messages = self.malformed_table( lines[start:i+1], 'Bottom/header table border does ' 'not match top border.') return [], messages, i == limit or not lines[i+1].strip() found += 1 found_at = i if found == 2 or i == limit or not lines[i+1].strip(): end = i break i += 1 else: # reached end of input_lines if found: extra = ' or no blank line after table bottom' self.state_machine.next_line(found_at - start) block = lines[start:found_at+1] else: extra = '' self.state_machine.next_line(i - start - 1) block = lines[start:] messages = self.malformed_table( block, 'No bottom table border found%s.' % extra) return [], messages, not extra self.state_machine.next_line(end - start) block = lines[start:end+1] return block, [], end == limit or not lines[end+1].strip() def malformed_table(self, block, detail=''): data = '\n'.join(block) message = 'Malformed table.' lineno = self.state_machine.abs_line_number() - len(block) + 1 if detail: message += '\n' + detail error = self.reporter.error(message, nodes.literal_block(data, data), line=lineno) return [error] def build_table(self, tabledata, tableline, stub_columns=0): colwidths, headrows, bodyrows = tabledata table = nodes.table() tgroup = nodes.tgroup(cols=len(colwidths)) table += tgroup for colwidth in colwidths: colspec = nodes.colspec(colwidth=colwidth) if stub_columns: colspec.attributes['stub'] = 1 stub_columns -= 1 tgroup += colspec if headrows: thead = nodes.thead() tgroup += thead for row in headrows: thead += self.build_table_row(row, tableline) tbody = nodes.tbody() tgroup += tbody for row in bodyrows: tbody += self.build_table_row(row, tableline) return table def build_table_row(self, rowdata, tableline): row = nodes.row() for cell in rowdata: if cell is None: continue morerows, morecols, offset, cellblock = cell attributes = {} if morerows: attributes['morerows'] = morerows if morecols: attributes['morecols'] = morecols entry = nodes.entry(**attributes) row += entry if ''.join(cellblock): self.nested_parse(cellblock, input_offset=tableline+offset, node=entry) return row explicit = Struct() """Patterns and constants used for explicit markup recognition.""" explicit.patterns = Struct( target=re.compile(r""" ( _ # anonymous target | # *OR* (?P<quote>`?) # optional open quote (?![ `]) # first char. not space or # backquote (?P<name> # reference name .+? ) %(non_whitespace_escape_before)s (?P=quote) # close quote if open quote used ) %(non_whitespace_escape_before)s [ ]? # optional space : # end of reference name ([ ]+|$) # followed by whitespace """ % vars(Inliner), re.VERBOSE), reference=re.compile(r""" ( (?P<simple>%(simplename)s)_ | # *OR* ` # open backquote (?![ ]) # not space (?P<phrase>.+?) # hyperlink phrase %(non_whitespace_escape_before)s `_ # close backquote, # reference mark ) $ # end of string """ % vars(Inliner), re.VERBOSE | re.UNICODE), substitution=re.compile(r""" ( (?![ ]) # first char. not space (?P<name>.+?) # substitution text %(non_whitespace_escape_before)s \| # close delimiter ) ([ ]+|$) # followed by whitespace """ % vars(Inliner), re.VERBOSE),) def footnote(self, match): lineno = self.state_machine.abs_line_number() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) label = match.group(1) name = normalize_name(label) footnote = nodes.footnote('\n'.join(indented)) footnote.line = lineno if name[0] == '#': # auto-numbered name = name[1:] # autonumber label footnote['auto'] = 1 if name: footnote['names'].append(name) self.document.note_autofootnote(footnote) elif name == '*': # auto-symbol name = '' footnote['auto'] = '*' self.document.note_symbol_footnote(footnote) else: # manually numbered footnote += nodes.label('', label) footnote['names'].append(name) self.document.note_footnote(footnote) if name: self.document.note_explicit_target(footnote, footnote) else: self.document.set_id(footnote, footnote) if indented: self.nested_parse(indented, input_offset=offset, node=footnote) return [footnote], blank_finish def citation(self, match): lineno = self.state_machine.abs_line_number() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) label = match.group(1) name = normalize_name(label) citation = nodes.citation('\n'.join(indented)) citation.line = lineno citation += nodes.label('', label) citation['names'].append(name) self.document.note_citation(citation) self.document.note_explicit_target(citation, citation) if indented: self.nested_parse(indented, input_offset=offset, node=citation) return [citation], blank_finish def hyperlink_target(self, match): pattern = self.explicit.patterns.target lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented( match.end(), until_blank=1, strip_indent=0) blocktext = match.string[:match.end()] + '\n'.join(block) block = [escape2null(line) for line in block] escaped = block[0] blockindex = 0 while 1: targetmatch = pattern.match(escaped) if targetmatch: break blockindex += 1 try: escaped += block[blockindex] except IndexError: raise MarkupError('malformed hyperlink target.', lineno) del block[:blockindex] block[0] = (block[0] + ' ')[targetmatch.end()-len(escaped)-1:].strip() target = self.make_target(block, blocktext, lineno, targetmatch.group('name')) return [target], blank_finish def make_target(self, block, block_text, lineno, target_name): target_type, data = self.parse_target(block, block_text, lineno) if target_type == 'refname': target = nodes.target(block_text, '', refname=normalize_name(data)) self.add_target(target_name, '', target, lineno) self.document.note_indirect_target(target) return target elif target_type == 'refuri': target = nodes.target(block_text, '') self.add_target(target_name, data, target, lineno) return target else: return data def parse_target(self, block, block_text, lineno): """ Determine the type of reference of a target. :Return: A 2-tuple, one of: - 'refname' and the indirect reference name - 'refuri' and the URI - 'malformed' and a system_message node """ if block and block[-1].strip()[-1:] == '_': # possible indirect target reference = ' '.join([line.strip() for line in block]) refname = self.is_reference(reference) if refname: return 'refname', refname reference = ''.join([''.join(line.split()) for line in block]) return 'refuri', unescape(reference) def is_reference(self, reference): match = self.explicit.patterns.reference.match( whitespace_normalize_name(reference)) if not match: return None return unescape(match.group('simple') or match.group('phrase')) def add_target(self, targetname, refuri, target, lineno): target.line = lineno if targetname: name = normalize_name(unescape(targetname)) target['names'].append(name) if refuri: uri = self.inliner.adjust_uri(refuri) if uri: target['refuri'] = uri self.document.note_external_target(target) else: raise ApplicationError('problem with URI: %r' % refuri) else: self.document.note_internal_target(target) self.document.note_explicit_target(target, self.parent) else: # anonymous target if refuri: target['refuri'] = refuri else: self.document.note_internal_target(target) target['anonymous'] = 1 self.document.note_anonymous_target(target) def substitution_def(self, match): pattern = self.explicit.patterns.substitution lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), strip_indent=0) blocktext = (match.string[:match.end()] + '\n'.join(block)) block.disconnect() escaped = escape2null(block[0].rstrip()) blockindex = 0 while 1: subdefmatch = pattern.match(escaped) if subdefmatch: break blockindex += 1 try: escaped = escaped + ' ' + escape2null(block[blockindex].strip()) except IndexError: raise MarkupError('malformed substitution definition.', lineno) del block[:blockindex] # strip out the substitution marker block[0] = (block[0].strip() + ' ')[subdefmatch.end()-len(escaped)-1:-1] if not block[0]: del block[0] offset += 1 while block and not block[-1].strip(): block.pop() subname = subdefmatch.group('name') substitution_node = nodes.substitution_definition(blocktext) substitution_node.line = lineno self.document.note_substitution_def( substitution_node,subname, self.parent) if block: block[0] = block[0].strip() new_abs_offset, blank_finish = self.nested_list_parse( block, input_offset=offset, node=substitution_node, initial_state='SubstitutionDef', blank_finish=blank_finish) i = 0 for node in substitution_node[:]: if not (isinstance(node, nodes.Inline) or isinstance(node, nodes.Text)): self.parent += substitution_node[i] del substitution_node[i] else: i += 1 if len(substitution_node) == 0: msg = self.reporter.warning( 'Substitution definition "%s" empty or invalid.' % subname, nodes.literal_block(blocktext, blocktext), line=lineno) return [msg], blank_finish else: return [substitution_node], blank_finish else: msg = self.reporter.warning( 'Substitution definition "%s" missing contents.' % subname, nodes.literal_block(blocktext, blocktext), line=lineno) return [msg], blank_finish def directive(self, match, **option_presets): """Returns a 2-tuple: list of nodes, and a "blank finish" boolean.""" type_name = match.group(1) directive_function, messages = directives.directive( type_name, self.memo.language, self.document) self.parent += messages if directive_function: return self.run_directive( directive_function, match, type_name, option_presets) else: return self.unknown_directive(type_name) def run_directive(self, directive_fn, match, type_name, option_presets): """ Parse a directive then run its directive function. Parameters: - `directive_fn`: The function implementing the directive. Uses function attributes ``arguments``, ``options``, and/or ``content`` if present. - `match`: A regular expression match object which matched the first line of the directive. - `type_name`: The directive name, as used in the source text. - `option_presets`: A dictionary of preset options, defaults for the directive options. Currently, only an "alt" option is passed by substitution definitions (value: the substitution name), which may be used by an embedded image directive. Returns a 2-tuple: list of nodes, and a "blank finish" boolean. """ lineno = self.state_machine.abs_line_number() initial_line_offset = self.state_machine.line_offset indented, indent, line_offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), strip_top=0) block_text = '\n'.join(self.state_machine.input_lines[ initial_line_offset : self.state_machine.line_offset + 1]) try: arguments, options, content, content_offset = ( self.parse_directive_block(indented, line_offset, directive_fn, option_presets)) except MarkupError, detail: error = self.reporter.error( 'Error in "%s" directive:\n%s.' % (type_name, ' '.join(detail.args)), nodes.literal_block(block_text, block_text), line=lineno) return [error], blank_finish result = directive_fn(type_name, arguments, options, content, lineno, content_offset, block_text, self, self.state_machine) return (result, blank_finish or self.state_machine.is_next_line_blank()) def parse_directive_block(self, indented, line_offset, directive_fn, option_presets): arguments = [] options = {} argument_spec = getattr(directive_fn, 'arguments', None) if argument_spec and argument_spec[:2] == (0, 0): argument_spec = None option_spec = getattr(directive_fn, 'options', None) content_spec = getattr(directive_fn, 'content', None) if indented and not indented[0].strip(): indented.trim_start() line_offset += 1 while indented and not indented[-1].strip(): indented.trim_end() if indented and (argument_spec or option_spec): for i in range(len(indented)): if not indented[i].strip(): break else: i += 1 arg_block = indented[:i] content = indented[i+1:] content_offset = line_offset + i + 1 else: content = indented content_offset = line_offset arg_block = [] while content and not content[0].strip(): content.trim_start() content_offset += 1 if option_spec: options, arg_block = self.parse_directive_options( option_presets, option_spec, arg_block) if arg_block and not argument_spec: raise MarkupError('no arguments permitted; blank line ' 'required before content block') if argument_spec: arguments = self.parse_directive_arguments( argument_spec, arg_block) if content and not content_spec: raise MarkupError('no content permitted') return (arguments, options, content, content_offset) def parse_directive_options(self, option_presets, option_spec, arg_block): options = option_presets.copy() for i in range(len(arg_block)): if arg_block[i][:1] == ':': opt_block = arg_block[i:] arg_block = arg_block[:i] break else: opt_block = [] if opt_block: success, data = self.parse_extension_options(option_spec, opt_block) if success: # data is a dict of options options.update(data) else: # data is an error string raise MarkupError(data) return options, arg_block def parse_directive_arguments(self, argument_spec, arg_block): required, optional, last_whitespace = argument_spec arg_text = '\n'.join(arg_block) arguments = arg_text.split() if len(arguments) < required: raise MarkupError('%s argument(s) required, %s supplied' % (required, len(arguments))) elif len(arguments) > required + optional: if last_whitespace: arguments = arg_text.split(None, required + optional - 1) else: raise MarkupError( 'maximum %s argument(s) allowed, %s supplied' % (required + optional, len(arguments))) return arguments def parse_extension_options(self, option_spec, datalines): """ Parse `datalines` for a field list containing extension options matching `option_spec`. :Parameters: - `option_spec`: a mapping of option name to conversion function, which should raise an exception on bad input. - `datalines`: a list of input strings. :Return: - Success value, 1 or 0. - An option dictionary on success, an error string on failure. """ node = nodes.field_list() newline_offset, blank_finish = self.nested_list_parse( datalines, 0, node, initial_state='ExtensionOptions', blank_finish=1) if newline_offset != len(datalines): # incomplete parse of block return 0, 'invalid option block' try: options = utils.extract_extension_options(node, option_spec) except KeyError, detail: return 0, ('unknown option: "%s"' % detail.args[0]) except (ValueError, TypeError), detail: return 0, ('invalid option value: %s' % ' '.join(detail.args)) except utils.ExtensionOptionError, detail: return 0, ('invalid option data: %s' % ' '.join(detail.args)) if blank_finish: return 1, options else: return 0, 'option data incompletely parsed' def unknown_directive(self, type_name): lineno = self.state_machine.abs_line_number() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(0, strip_indent=0) text = '\n'.join(indented) error = self.reporter.error( 'Unknown directive type "%s".' % type_name, nodes.literal_block(text, text), line=lineno) return [error], blank_finish def comment(self, match): if not match.string[match.end():].strip() \ and self.state_machine.is_next_line_blank(): # an empty comment? return [nodes.comment()], 1 # "A tiny but practical wart." indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) while indented and not indented[-1].strip(): indented.trim_end() text = '\n'.join(indented) return [nodes.comment(text, text)], blank_finish explicit.constructs = [ (footnote, re.compile(r""" \.\.[ ]+ # explicit markup start \[ ( # footnote label: [0-9]+ # manually numbered footnote | # *OR* \# # anonymous auto-numbered footnote | # *OR* \#%s # auto-number ed?) footnote label | # *OR* \* # auto-symbol footnote ) \] ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE)), (citation, re.compile(r""" \.\.[ ]+ # explicit markup start \[(%s)\] # citation label ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE)), (hyperlink_target, re.compile(r""" \.\.[ ]+ # explicit markup start _ # target indicator (?![ ]|$) # first char. not space or EOL """, re.VERBOSE)), (substitution_def, re.compile(r""" \.\.[ ]+ # explicit markup start \| # substitution indicator (?![ ]|$) # first char. not space or EOL """, re.VERBOSE)), (directive, re.compile(r""" \.\.[ ]+ # explicit markup start (%s) # directive name [ ]? # optional space :: # directive delimiter ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE))] def explicit_markup(self, match, context, next_state): """Footnotes, hyperlink targets, directives, comments.""" nodelist, blank_finish = self.explicit_construct(match) self.parent += nodelist self.explicit_list(blank_finish) return [], next_state, [] def explicit_construct(self, match): """Determine which explicit construct this is, parse & return it.""" errors = [] for method, pattern in self.explicit.constructs: expmatch = pattern.match(match.string) if expmatch: try: return method(self, expmatch) except MarkupError, (message, lineno): # never reached? errors.append(self.reporter.warning(message, line=lineno)) break nodelist, blank_finish = self.comment(match) return nodelist + errors, blank_finish def explicit_list(self, blank_finish): """ Create a nested state machine for a series of explicit markup constructs (including anonymous hyperlink targets). """ offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=self.parent, initial_state='Explicit', blank_finish=blank_finish, match_titles=self.state_machine.match_titles) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Explicit markup') def anonymous(self, match, context, next_state): """Anonymous hyperlink targets.""" nodelist, blank_finish = self.anonymous_target(match) self.parent += nodelist self.explicit_list(blank_finish) return [], next_state, [] def anonymous_target(self, match): lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), until_blank=1) blocktext = match.string[:match.end()] + '\n'.join(block) block = [escape2null(line) for line in block] target = self.make_target(block, blocktext, lineno, '') return [target], blank_finish def line(self, match, context, next_state): """Section title overline or transition marker.""" if self.state_machine.match_titles: return [match.string], 'Line', [] elif match.string.strip() == '::': raise statemachine.TransitionCorrection('text') elif len(match.string.strip()) < 4: msg = self.reporter.info( 'Unexpected possible title overline or transition.\n' "Treating it as ordinary text because it's so short.", line=self.state_machine.abs_line_number()) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = self.state_machine.line msg = self.reporter.severe( 'Unexpected section title or transition.', nodes.literal_block(blocktext, blocktext), line=self.state_machine.abs_line_number()) self.parent += msg return [], next_state, [] def text(self, match, context, next_state): """Titles, definition lists, paragraphs.""" return [match.string], 'Text', [] class RFC2822Body(Body): """ RFC2822 headers are only valid as the first constructs in documents. As soon as anything else appears, the `Body` state should take over. """ patterns = Body.patterns.copy() # can't modify the original patterns['rfc2822'] = r'[!-9;-~]+:( +|$)' initial_transitions = [(name, 'Body') for name in Body.initial_transitions] initial_transitions.insert(-1, ('rfc2822', 'Body')) # just before 'text' def rfc2822(self, match, context, next_state): """RFC2822-style field list item.""" fieldlist = nodes.field_list(classes=['rfc2822']) self.parent += fieldlist field, blank_finish = self.rfc2822_field(match) fieldlist += field offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=fieldlist, initial_state='RFC2822List', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning( 'RFC2822-style field list') return [], next_state, [] def rfc2822_field(self, match): name = match.string[:match.string.find(':')] indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), until_blank=1) fieldnode = nodes.field() fieldnode += nodes.field_name(name, name) fieldbody = nodes.field_body('\n'.join(indented)) fieldnode += fieldbody if indented: self.nested_parse(indented, input_offset=line_offset, node=fieldbody) return fieldnode, blank_finish class SpecializedBody(Body): """ Superclass for second and subsequent compound element members. Compound elements are lists and list-like constructs. All transition methods are disabled (redefined as `invalid_input`). Override individual methods in subclasses to re-enable. For example, once an initial bullet list item, say, is recognized, the `BulletList` subclass takes over, with a "bullet_list" node as its container. Upon encountering the initial bullet list item, `Body.bullet` calls its ``self.nested_list_parse`` (`RSTState.nested_list_parse`), which starts up a nested parsing session with `BulletList` as the initial state. Only the ``bullet`` transition method is enabled in `BulletList`; as long as only bullet list items are encountered, they are parsed and inserted into the container. The first construct which is *not* a bullet list item triggers the `invalid_input` method, which ends the nested parse and closes the container. `BulletList` needs to recognize input that is invalid in the context of a bullet list, which means everything *other than* bullet list items, so it inherits the transition list created in `Body`. """ def invalid_input(self, match=None, context=None, next_state=None): """Not a compound element member. Abort this state machine.""" self.state_machine.previous_line() # back up so parent SM can reassess raise EOFError indent = invalid_input bullet = invalid_input enumerator = invalid_input field_marker = invalid_input option_marker = invalid_input doctest = invalid_input line_block = invalid_input grid_table_top = invalid_input simple_table_top = invalid_input explicit_markup = invalid_input anonymous = invalid_input line = invalid_input text = invalid_input class BulletList(SpecializedBody): """Second and subsequent bullet_list list_items.""" def bullet(self, match, context, next_state): """Bullet list item.""" if match.string[0] != self.parent['bullet']: # different bullet: new list self.invalid_input() listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish return [], next_state, [] class DefinitionList(SpecializedBody): """Second and subsequent definition_list_items.""" def text(self, match, context, next_state): """Definition lists.""" return [match.string], 'Definition', [] class EnumeratedList(SpecializedBody): """Second and subsequent enumerated_list list_items.""" def enumerator(self, match, context, next_state): """Enumerated list item.""" format, sequence, text, ordinal = self.parse_enumerator( match, self.parent['enumtype']) if ( format != self.format or (sequence != '#' and (sequence != self.parent['enumtype'] or self.auto or ordinal != (self.lastordinal + 1))) or not self.is_enumerated_list_item(ordinal, sequence, format)): # different enumeration: new list self.invalid_input() if sequence == '#': self.auto = 1 listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish self.lastordinal = ordinal return [], next_state, [] class FieldList(SpecializedBody): """Second and subsequent field_list fields.""" def field_marker(self, match, context, next_state): """Field list field.""" field, blank_finish = self.field(match) self.parent += field self.blank_finish = blank_finish return [], next_state, [] class OptionList(SpecializedBody): """Second and subsequent option_list option_list_items.""" def option_marker(self, match, context, next_state): """Option list item.""" try: option_list_item, blank_finish = self.option_list_item(match) except MarkupError, (message, lineno): self.invalid_input() self.parent += option_list_item self.blank_finish = blank_finish return [], next_state, [] class RFC2822List(SpecializedBody, RFC2822Body): """Second and subsequent RFC2822-style field_list fields.""" patterns = RFC2822Body.patterns initial_transitions = RFC2822Body.initial_transitions def rfc2822(self, match, context, next_state): """RFC2822-style field list item.""" field, blank_finish = self.rfc2822_field(match) self.parent += field self.blank_finish = blank_finish return [], 'RFC2822List', [] blank = SpecializedBody.invalid_input class ExtensionOptions(FieldList): """ Parse field_list fields for extension options. No nested parsing is done (including inline markup parsing). """ def parse_field_body(self, indented, offset, node): """Override `Body.parse_field_body` for simpler parsing.""" lines = [] for line in list(indented) + ['']: if line.strip(): lines.append(line) elif lines: text = '\n'.join(lines) node += nodes.paragraph(text, text) lines = [] class LineBlock(SpecializedBody): """Second and subsequent lines of a line_block.""" blank = SpecializedBody.invalid_input def line_block(self, match, context, next_state): """New line of line block.""" lineno = self.state_machine.abs_line_number() line, messages, blank_finish = self.line_block_line(match, lineno) self.parent += line self.parent.parent += messages self.blank_finish = blank_finish return [], next_state, [] class Explicit(SpecializedBody): """Second and subsequent explicit markup construct.""" def explicit_markup(self, match, context, next_state): """Footnotes, hyperlink targets, directives, comments.""" nodelist, blank_finish = self.explicit_construct(match) self.parent += nodelist self.blank_finish = blank_finish return [], next_state, [] def anonymous(self, match, context, next_state): """Anonymous hyperlink targets.""" nodelist, blank_finish = self.anonymous_target(match) self.parent += nodelist self.blank_finish = blank_finish return [], next_state, [] blank = SpecializedBody.invalid_input class SubstitutionDef(Body): """ Parser for the contents of a substitution_definition element. """ patterns = { 'embedded_directive': re.compile(r'(%s)::( +|$)' % Inliner.simplename, re.UNICODE), 'text': r''} initial_transitions = ['embedded_directive', 'text'] def embedded_directive(self, match, context, next_state): nodelist, blank_finish = self.directive(match, alt=self.parent['names'][0]) self.parent += nodelist if not self.state_machine.at_eof(): self.blank_finish = blank_finish raise EOFError def text(self, match, context, next_state): if not self.state_machine.at_eof(): self.blank_finish = self.state_machine.is_next_line_blank() raise EOFError class Text(RSTState): """ Classifier of second line of a text block. Could be a paragraph, a definition list item, or a title. """ patterns = {'underline': Body.patterns['line'], 'text': r''} initial_transitions = [('underline', 'Body'), ('text', 'Body')] def blank(self, match, context, next_state): """End of paragraph.""" paragraph, literalnext = self.paragraph( context, self.state_machine.abs_line_number() - 1) self.parent += paragraph if literalnext: self.parent += self.literal_block() return [], 'Body', [] def eof(self, context): if context: self.blank(None, context, None) return [] def indent(self, match, context, next_state): """Definition list item.""" definitionlist = nodes.definition_list() definitionlistitem, blank_finish = self.definition_list_item(context) definitionlist += definitionlistitem self.parent += definitionlist offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=definitionlist, initial_state='DefinitionList', blank_finish=blank_finish, blank_finish_state='Definition') self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Definition list') return [], 'Body', [] def underline(self, match, context, next_state): """Section title.""" lineno = self.state_machine.abs_line_number() title = context[0].rstrip() underline = match.string.rstrip() source = title + '\n' + underline messages = [] if len(title) > len(underline): if len(underline) < 4: if self.state_machine.match_titles: msg = self.reporter.info( 'Possible title underline, too short for the title.\n' "Treating it as ordinary text because it's so short.", line=lineno) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = context[0] + '\n' + self.state_machine.line msg = self.reporter.warning( 'Title underline too short.', nodes.literal_block(blocktext, blocktext), line=lineno) messages.append(msg) if not self.state_machine.match_titles: blocktext = context[0] + '\n' + self.state_machine.line msg = self.reporter.severe( 'Unexpected section title.', nodes.literal_block(blocktext, blocktext), line=lineno) self.parent += messages self.parent += msg return [], next_state, [] style = underline[0] context[:] = [] self.section(title, source, style, lineno - 1, messages) return [], next_state, [] def text(self, match, context, next_state): """Paragraph.""" startline = self.state_machine.abs_line_number() - 1 msg = None try: block = self.state_machine.get_text_block(flush_left=1) except statemachine.UnexpectedIndentationError, instance: block, source, lineno = instance.args msg = self.reporter.error('Unexpected indentation.', source=source, line=lineno) lines = context + list(block) paragraph, literalnext = self.paragraph(lines, startline) self.parent += paragraph self.parent += msg if literalnext: try: self.state_machine.next_line() except EOFError: pass self.parent += self.literal_block() return [], next_state, [] def literal_block(self): """Return a list of nodes.""" indented, indent, offset, blank_finish = \ self.state_machine.get_indented() while indented and not indented[-1].strip(): indented.trim_end() if not indented: return self.quoted_literal_block() data = '\n'.join(indented) literal_block = nodes.literal_block(data, data) literal_block.line = offset + 1 nodelist = [literal_block] if not blank_finish: nodelist.append(self.unindent_warning('Literal block')) return nodelist def quoted_literal_block(self): abs_line_offset = self.state_machine.abs_line_offset() offset = self.state_machine.line_offset parent_node = nodes.Element() new_abs_offset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=abs_line_offset, node=parent_node, match_titles=0, state_machine_kwargs={'state_classes': (QuotedLiteralBlock,), 'initial_state': 'QuotedLiteralBlock'}) self.goto_line(new_abs_offset) return parent_node.children def definition_list_item(self, termline): indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() definitionlistitem = nodes.definition_list_item( '\n'.join(termline + list(indented))) lineno = self.state_machine.abs_line_number() - 1 definitionlistitem.line = lineno termlist, messages = self.term(termline, lineno) definitionlistitem += termlist definition = nodes.definition('', *messages) definitionlistitem += definition if termline[0][-2:] == '::': definition += self.reporter.info( 'Blank line missing before literal block (after the "::")? ' 'Interpreted as a definition list item.', line=line_offset+1) self.nested_parse(indented, input_offset=line_offset, node=definition) return definitionlistitem, blank_finish classifier_delimiter = re.compile(' +: +') def term(self, lines, lineno): """Return a definition_list's term and optional classifiers.""" assert len(lines) == 1 text_nodes, messages = self.inline_text(lines[0], lineno) term_node = nodes.term() node_list = [term_node] for i in range(len(text_nodes)): node = text_nodes[i] if isinstance(node, nodes.Text): parts = self.classifier_delimiter.split(node.rawsource) if len(parts) == 1: node_list[-1] += node else: node_list[-1] += nodes.Text(parts[0].rstrip()) for part in parts[1:]: classifier_node = nodes.classifier('', part) node_list.append(classifier_node) else: node_list[-1] += node return node_list, messages class SpecializedText(Text): """ Superclass for second and subsequent lines of Text-variants. All transition methods are disabled. Override individual methods in subclasses to re-enable. """ def eof(self, context): """Incomplete construct.""" return [] def invalid_input(self, match=None, context=None, next_state=None): """Not a compound element member. Abort this state machine.""" raise EOFError blank = invalid_input indent = invalid_input underline = invalid_input text = invalid_input class Definition(SpecializedText): """Second line of potential definition_list_item.""" def eof(self, context): """Not a definition.""" self.state_machine.previous_line(2) # so parent SM can reassess return [] def indent(self, match, context, next_state): """Definition list item.""" definitionlistitem, blank_finish = self.definition_list_item(context) self.parent += definitionlistitem self.blank_finish = blank_finish return [], 'DefinitionList', [] class Line(SpecializedText): """ Second line of over- & underlined section title or transition marker. """ eofcheck = 1 # @@@ ??? """Set to 0 while parsing sections, so that we don't catch the EOF.""" def eof(self, context): """Transition marker at end of section or document.""" marker = context[0].strip() if self.memo.section_bubble_up_kludge: self.memo.section_bubble_up_kludge = 0 elif len(marker) < 4: self.state_correction(context) if self.eofcheck: # ignore EOFError with sections lineno = self.state_machine.abs_line_number() - 1 transition = nodes.transition(rawsource=context[0]) transition.line = lineno self.parent += transition self.eofcheck = 1 return [] def blank(self, match, context, next_state): """Transition marker.""" lineno = self.state_machine.abs_line_number() - 1 marker = context[0].strip() if len(marker) < 4: self.state_correction(context) transition = nodes.transition(rawsource=marker) transition.line = lineno self.parent += transition return [], 'Body', [] def text(self, match, context, next_state): """Potential over- & underlined title.""" lineno = self.state_machine.abs_line_number() - 1 overline = context[0] title = match.string underline = '' try: underline = self.state_machine.next_line() except EOFError: blocktext = overline + '\n' + title if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Incomplete section title.', nodes.literal_block(blocktext, blocktext), line=lineno) self.parent += msg return [], 'Body', [] source = '%s\n%s\n%s' % (overline, title, underline) overline = overline.rstrip() underline = underline.rstrip() if not self.transitions['underline'][0].match(underline): blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Missing matching underline for section title overline.', nodes.literal_block(source, source), line=lineno) self.parent += msg return [], 'Body', [] elif overline != underline: blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Title overline & underline mismatch.', nodes.literal_block(source, source), line=lineno) self.parent += msg return [], 'Body', [] title = title.rstrip() messages = [] if len(title) > len(overline): blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.warning( 'Title overline too short.', nodes.literal_block(source, source), line=lineno) messages.append(msg) style = (overline[0], underline[0]) self.eofcheck = 0 # @@@ not sure this is correct self.section(title.lstrip(), source, style, lineno + 1, messages) self.eofcheck = 1 return [], 'Body', [] indent = text # indented title def underline(self, match, context, next_state): overline = context[0] blocktext = overline + '\n' + self.state_machine.line lineno = self.state_machine.abs_line_number() - 1 if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 1) msg = self.reporter.error( 'Invalid section title or transition marker.', nodes.literal_block(blocktext, blocktext), line=lineno) self.parent += msg return [], 'Body', [] def short_overline(self, context, blocktext, lineno, lines=1): msg = self.reporter.info( 'Possible incomplete section title.\nTreating the overline as ' "ordinary text because it's so short.", line=lineno) self.parent += msg self.state_correction(context, lines) def state_correction(self, context, lines=1): self.state_machine.previous_line(lines) context[:] = [] raise statemachine.StateCorrection('Body', 'text') class QuotedLiteralBlock(RSTState): """ Nested parse handler for quoted (unindented) literal blocks. Special-purpose. Not for inclusion in `state_classes`. """ patterns = {'initial_quoted': r'(%(nonalphanum7bit)s)' % Body.pats, 'text': r''} initial_transitions = ('initial_quoted', 'text') def __init__(self, state_machine, debug=0): RSTState.__init__(self, state_machine, debug) self.messages = [] self.initial_lineno = None def blank(self, match, context, next_state): if context: raise EOFError else: return context, next_state, [] def eof(self, context): if context: text = '\n'.join(context) literal_block = nodes.literal_block(text, text) literal_block.line = self.initial_lineno self.parent += literal_block else: self.parent += self.reporter.warning( 'Literal block expected; none found.', line=self.state_machine.abs_line_number()) self.state_machine.previous_line() self.parent += self.messages return [] def indent(self, match, context, next_state): assert context, ('QuotedLiteralBlock.indent: context should not ' 'be empty!') self.messages.append( self.reporter.error('Unexpected indentation.', line=self.state_machine.abs_line_number())) self.state_machine.previous_line() raise EOFError def initial_quoted(self, match, context, next_state): """Match arbitrary quote character on the first line only.""" self.remove_transition('initial_quoted') quote = match.string[0] pattern = re.compile(re.escape(quote)) # New transition matches consistent quotes only: self.add_transition('quoted', (pattern, self.quoted, self.__class__.__name__)) self.initial_lineno = self.state_machine.abs_line_number() return [match.string], next_state, [] def quoted(self, match, context, next_state): """Match consistent quotes on subsequent lines.""" context.append(match.string) return context, next_state, [] def text(self, match, context, next_state): if context: self.messages.append( self.reporter.error('Inconsistent literal block quoting.', line=self.state_machine.abs_line_number())) self.state_machine.previous_line() raise EOFError state_classes = (Body, BulletList, DefinitionList, EnumeratedList, FieldList, OptionList, LineBlock, ExtensionOptions, Explicit, Text, Definition, Line, SubstitutionDef, RFC2822Body, RFC2822List) """Standard set of State classes used to start `RSTStateMachine`."""
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/parsers/rst/states.py", "copies": "1", "size": "122877", "license": "mit", "hash": -8558198870518176000, "line_mean": 41.0523613963, "line_max": 80, "alpha_frac": 0.5459199036, "autogenerated": false, "ratio": 4.397101449275362, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5443021352875361, "avg_score": null, "num_lines": null }
""" Directives for figures and simple images. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import directives, states from docutils.nodes import fully_normalize_name from docutils.parsers.rst.roles import set_classes try: import Image # PIL except ImportError: Image = None align_h_values = ('left', 'center', 'right') align_v_values = ('top', 'middle', 'bottom') align_values = align_v_values + align_h_values def align(argument): return directives.choice(argument, align_values) def image(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): if options.has_key('align'): # check for align_v values only if isinstance(state, states.SubstitutionDef): if options['align'] not in align_v_values: error = state_machine.reporter.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option within a substitution definition. ' 'Valid values for "align" are: "%s".' % (name, options['align'], '", "'.join(align_v_values)), nodes.literal_block(block_text, block_text), line=lineno) return [error] elif options['align'] not in align_h_values: error = state_machine.reporter.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option. Valid values for "align" are: "%s".' % (name, options['align'], '", "'.join(align_h_values)), nodes.literal_block(block_text, block_text), line=lineno) return [error] messages = [] reference = directives.uri(arguments[0]) options['uri'] = reference reference_node = None if options.has_key('target'): block = states.escape2null(options['target']).splitlines() block = [line for line in block] target_type, data = state.parse_target(block, block_text, lineno) if target_type == 'refuri': reference_node = nodes.reference(refuri=data) elif target_type == 'refname': reference_node = nodes.reference(refname=data, name=fully_normalize_name(options['target'])) state.document.note_refname(reference_node) else: # malformed target messages.append(data) # data is a system message del options['target'] set_classes(options) image_node = nodes.image(block_text, **options) if reference_node: reference_node += image_node return messages + [reference_node] else: return messages + [image_node] image.arguments = (1, 0, 1) image.options = {'alt': directives.unchanged, 'height': directives.nonnegative_int, 'width': directives.nonnegative_int, 'scale': directives.nonnegative_int, 'align': align, 'target': directives.unchanged_required, 'class': directives.class_option} def figure_align(argument): return directives.choice(argument, align_h_values) def figure(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): figwidth = options.setdefault('figwidth') figclasses = options.setdefault('figclass') align = options.setdefault('align') del options['figwidth'] del options['figclass'] del options['align'] (image_node,) = image(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine) if isinstance(image_node, nodes.system_message): return [image_node] figure_node = nodes.figure('', image_node) if figwidth == 'image': if Image and state.document.settings.file_insertion_enabled: # PIL doesn't like Unicode paths: try: i = Image.open(str(image_node['uri'])) except (IOError, UnicodeError): pass else: state.document.settings.record_dependencies.add(image_node['uri']) figure_node['width'] = i.size[0] elif figwidth is not None: figure_node['width'] = figwidth if figclasses: figure_node['classes'] += figclasses if align: figure_node['align'] = align if content: node = nodes.Element() # anonymous container for parsing state.nested_parse(content, content_offset, node) first_node = node[0] if isinstance(first_node, nodes.paragraph): caption = nodes.caption(first_node.rawsource, '', *first_node.children) figure_node += caption elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0): error = state_machine.reporter.error( 'Figure caption must be a paragraph or empty comment.', nodes.literal_block(block_text, block_text), line=lineno) return [figure_node, error] if len(node) > 1: figure_node += nodes.legend('', *node[1:]) return [figure_node] def figwidth_value(argument): if argument.lower() == 'image': return 'image' else: return directives.nonnegative_int(argument) figure.arguments = (1, 0, 1) figure.options = {'figwidth': figwidth_value, 'figclass': directives.class_option} figure.options.update(image.options) figure.options['align'] = figure_align figure.content = 1
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/parsers/rst/directives/images.py", "copies": "1", "size": "5907", "license": "mit", "hash": 1207976256779817200, "line_mean": 39.1836734694, "line_max": 82, "alpha_frac": 0.5999661419, "autogenerated": false, "ratio": 4.082239115411196, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0022141190980942676, "num_lines": 147 }
""" Standalone file Reader for the reStructuredText markup syntax. """ __docformat__ = 'reStructuredText' import sys from docutils import frontend, readers from docutils.transforms import frontmatter, references class Reader(readers.Reader): supported = ('standalone',) """Contexts this reader supports.""" document = None """A single document tree.""" settings_spec = ( 'Standalone Reader', None, (('Disable the promotion of a lone top-level section title to ' 'document title (and subsequent section title to document ' 'subtitle promotion; enabled by default).', ['--no-doc-title'], {'dest': 'doctitle_xform', 'action': 'store_false', 'default': 1, 'validator': frontend.validate_boolean}), ('Disable the bibliographic field list transform (enabled by ' 'default).', ['--no-doc-info'], {'dest': 'docinfo_xform', 'action': 'store_false', 'default': 1, 'validator': frontend.validate_boolean}), ('Activate the promotion of lone subsection titles to ' 'section subtitles (disabled by default).', ['--section-subtitles'], {'dest': 'sectsubtitle_xform', 'action': 'store_true', 'default': 0, 'validator': frontend.validate_boolean}), ('Deactivate the promotion of lone subsection titles.', ['--no-section-subtitles'], {'dest': 'sectsubtitle_xform', 'action': 'store_false', 'validator': frontend.validate_boolean}), )) config_section = 'standalone reader' config_section_dependencies = ('readers',) default_transforms = (references.Substitutions, references.PropagateTargets, frontmatter.DocTitle, frontmatter.SectionSubTitle, frontmatter.DocInfo, references.AnonymousHyperlinks, references.IndirectHyperlinks, references.Footnotes, references.ExternalTargets, references.InternalTargets,)
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/readers/standalone.py", "copies": "1", "size": "2409", "license": "mit", "hash": 3679823216690645500, "line_mean": 36.640625, "line_max": 78, "alpha_frac": 0.5919468659, "autogenerated": false, "ratio": 4.6238003838771595, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 64 }
""" Docutils document tree element class library. Classes in CamelCase are abstract base classes or auxiliary classes. The one exception is `Text`, for a text (PCDATA) node; uppercase is used to differentiate from element classes. Classes in lower_case_with_underscores are element classes, matching the XML element generic identifiers in the DTD_. The position of each node (the level at which it can occur) is significant and is represented by abstract base classes (`Root`, `Structural`, `Body`, `Inline`, etc.). Certain transformations will be easier because we can use ``isinstance(node, base_class)`` to determine the position of the node in the hierarchy. .. _DTD: http://docutils.sourceforge.net/docs/ref/docutils.dtd """ __docformat__ = 'reStructuredText' import sys import os import re import copy import warnings import xml.dom.minidom from types import IntType, SliceType, StringType, UnicodeType, \ TupleType, ListType from UserString import UserString # ============================== # Functional Node Base Classes # ============================== class Node: """Abstract base class of nodes in a document tree.""" parent = None """Back-reference to the Node immediately containing this Node.""" document = None """The `document` node at the root of the tree containing this Node.""" source = None """Path or description of the input source which generated this Node.""" line = None """The line number (1-based) of the beginning of this Node in `source`.""" def __nonzero__(self): """ Node instances are always true, even if they're empty. A node is more than a simple container. Its boolean "truth" does not depend on having one or more subnodes in the doctree. Use `len()` to check node length. Use `None` to represent a boolean false value. """ return 1 def asdom(self, dom=xml.dom.minidom): """Return a DOM **fragment** representation of this Node.""" domroot = dom.Document() return self._dom_node(domroot) def pformat(self, indent=' ', level=0): """ Return an indented pseudo-XML representation, for test purposes. Override in subclasses. """ raise NotImplementedError def copy(self): """Return a copy of self.""" raise NotImplementedError def setup_child(self, child): child.parent = self if self.document: child.document = self.document if child.source is None: child.source = self.document.current_source if child.line is None: child.line = self.document.current_line def walk(self, visitor): """ Traverse a tree of `Node` objects, calling the `dispatch_visit()` method of `visitor` when entering each node. (The `walkabout()` method is similar, except it also calls the `dispatch_departure()` method before exiting each node.) This tree traversal supports limited in-place tree modifications. Replacing one node with one or more nodes is OK, as is removing an element. However, if the node removed or replaced occurs after the current node, the old node will still be traversed, and any new nodes will not. Within ``visit`` methods (and ``depart`` methods for `walkabout()`), `TreePruningException` subclasses may be raised (`SkipChildren`, `SkipSiblings`, `SkipNode`, `SkipDeparture`). Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` implementation for each `Node` subclass encountered. """ visitor.document.reporter.debug( 'docutils.nodes.Node.walk calling dispatch_visit for %s' % self.__class__.__name__) try: visitor.dispatch_visit(self) except (SkipChildren, SkipNode): return except SkipDeparture: # not applicable; ignore pass children = self.children try: for child in children[:]: child.walk(visitor) except SkipSiblings: pass def walkabout(self, visitor): """ Perform a tree traversal similarly to `Node.walk()` (which see), except also call the `dispatch_departure()` method before exiting each node. Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` and ``depart`` implementation for each `Node` subclass encountered. """ call_depart = 1 visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except SkipNode: return except SkipDeparture: call_depart = 0 children = self.children try: for child in children[:]: child.walkabout(visitor) except SkipSiblings: pass except SkipChildren: pass if call_depart: visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_departure ' 'for %s' % self.__class__.__name__) visitor.dispatch_departure(self) def traverse(self, condition=None, include_self=1, descend=1, siblings=0, ascend=0): """ Return an iterable containing * self (if include_self is true) * all descendants in tree traversal order (if descend is true) * all siblings (if siblings is true) and their descendants (if also descend is true) * the siblings of the parent (if ascend is true) and their descendants (if also descend is true), and so on If ascend is true, assume siblings to be true as well. For example, given the following tree:: <paragraph> <emphasis> <--- emphasis.traverse() and <strong> <--- strong.traverse() are called. Foo Bar <reference name="Baz" refid="baz"> Baz Then list(emphasis.traverse()) equals :: [<emphasis>, <strong>, <#text: Foo>, <#text: Bar>] and list(strong.traverse(ascend=1)) equals :: [<strong>, <#text: Foo>, <#text: Bar>, <reference>, <#text: Baz>] """ r = [] if ascend: siblings=1 if include_self and (condition is None or condition(self)): r.append(self) if descend and len(self.children): for child in self: r.extend(child.traverse( include_self=1, descend=1, siblings=0, ascend=0, condition=condition)) if siblings or ascend: node = self while node.parent: index = node.parent.index(node) for sibling in node.parent[index+1:]: r.extend(sibling.traverse(include_self=1, descend=descend, siblings=0, ascend=0, condition=condition)) if not ascend: break else: node = node.parent return r def next_node(self, condition=None, include_self=0, descend=1, siblings=0, ascend=0): """ Return the first node in the iterable returned by traverse(), or None if the iterable is empty. Parameter list is the same as of traverse. Note that include_self defaults to 0, though. """ iterable = self.traverse(condition=condition, include_self=include_self, descend=descend, siblings=siblings, ascend=ascend) try: return iterable[0] except IndexError: return None class Text(Node, UserString): """ Instances are terminal nodes (leaves) containing text only; no child nodes or attributes. Initialize by passing a string to the constructor. Access the text itself with the `astext` method. """ tagname = '#text' children = () """Text nodes have no children, and cannot have children.""" def __init__(self, data, rawsource=''): UserString.__init__(self, data) self.rawsource = rawsource """The raw text from which this element was constructed.""" def __repr__(self): data = repr(self.data) if len(data) > 70: data = repr(self.data[:64] + ' ...') return '<%s: %s>' % (self.tagname, data) def __len__(self): return len(self.data) def shortrepr(self): data = repr(self.data) if len(data) > 20: data = repr(self.data[:16] + ' ...') return '<%s: %s>' % (self.tagname, data) def _dom_node(self, domroot): return domroot.createTextNode(self.data) def astext(self): return self.data def copy(self): return self.__class__(self.data) def pformat(self, indent=' ', level=0): result = [] indent = indent * level for line in self.data.splitlines(): result.append(indent + line + '\n') return ''.join(result) class Element(Node): """ `Element` is the superclass to all specific elements. Elements contain attributes and child nodes. Elements emulate dictionaries for attributes, indexing by attribute name (a string). To set the attribute 'att' to 'value', do:: element['att'] = 'value' There are two special attributes: 'ids' and 'names'. Both are lists of unique identifiers, and names serve as human interfaces to IDs. Names are case- and whitespace-normalized (see the fully_normalize_name() function), and IDs conform to the regular expression ``[a-z](-?[a-z0-9]+)*`` (see the make_id() function). Elements also emulate lists for child nodes (element nodes and/or text nodes), indexing by integer. To get the first child node, use:: element[0] Elements may be constructed using the ``+=`` operator. To add one new child node to element, do:: element += node This is equivalent to ``element.append(node)``. To add a list of multiple child nodes at once, use the same ``+=`` operator:: element += [node1, node2] This is equivalent to ``element.extend([node1, node2])``. """ attr_defaults = {'ids': [], 'classes': [], 'names': [], 'dupnames': [], 'backrefs': []} """Default attributes.""" tagname = None """The element generic identifier. If None, it is set as an instance attribute to the name of the class.""" child_text_separator = '\n\n' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', *children, **attributes): self.rawsource = rawsource """The raw text from which this element was constructed.""" self.children = [] """List of child nodes (elements and/or `Text`).""" self.extend(children) # maintain parent info self.attributes = copy.deepcopy(self.attr_defaults) """Dictionary of attribute {name: value}.""" for att, value in attributes.items(): self.attributes[att.lower()] = value if self.tagname is None: self.tagname = self.__class__.__name__ def _dom_node(self, domroot): element = domroot.createElement(self.tagname) for attribute, value in self.attlist(): if isinstance(value, ListType): value = ' '.join(['%s' % v for v in value]) element.setAttribute(attribute, '%s' % value) for child in self.children: element.appendChild(child._dom_node(domroot)) return element def __repr__(self): data = '' for c in self.children: data += c.shortrepr() if len(data) > 60: data = data[:56] + ' ...' break if self['names']: return '<%s "%s": %s>' % (self.__class__.__name__, '; '.join(self['names']), data) else: return '<%s: %s>' % (self.__class__.__name__, data) def shortrepr(self): if self['names']: return '<%s "%s"...>' % (self.__class__.__name__, '; '.join(self['names'])) else: return '<%s...>' % self.tagname def __str__(self): return self.__unicode__().encode('raw_unicode_escape') def __unicode__(self): if self.children: return u'%s%s%s' % (self.starttag(), ''.join([str(c) for c in self.children]), self.endtag()) else: return self.emptytag() def starttag(self): parts = [self.tagname] for name, value in self.attlist(): if value is None: # boolean attribute parts.append(name) elif isinstance(value, ListType): values = ['%s' % v for v in value] parts.append('%s="%s"' % (name, ' '.join(values))) else: parts.append('%s="%s"' % (name, value)) return '<%s>' % ' '.join(parts) def endtag(self): return '</%s>' % self.tagname def emptytag(self): return u'<%s/>' % ' '.join([self.tagname] + ['%s="%s"' % (n, v) for n, v in self.attlist()]) def __len__(self): return len(self.children) def __getitem__(self, key): if isinstance(key, UnicodeType) or isinstance(key, StringType): return self.attributes[key] elif isinstance(key, IntType): return self.children[key] elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' return self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __setitem__(self, key, item): if isinstance(key, UnicodeType) or isinstance(key, StringType): self.attributes[str(key)] = item elif isinstance(key, IntType): self.setup_child(item) self.children[key] = item elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' for node in item: self.setup_child(node) self.children[key.start:key.stop] = item else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __delitem__(self, key): if isinstance(key, UnicodeType) or isinstance(key, StringType): del self.attributes[key] elif isinstance(key, IntType): del self.children[key] elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' del self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a simple ' 'slice, or an attribute name string') def __add__(self, other): return self.children + other def __radd__(self, other): return other + self.children def __iadd__(self, other): """Append a node or a list of nodes to `self.children`.""" if isinstance(other, Node): self.append(other) elif other is not None: self.extend(other) return self def astext(self): return self.child_text_separator.join( [child.astext() for child in self.children]) def non_default_attributes(self): atts = {} for key, value in self.attributes.items(): if self.is_not_default(key): atts[key] = value return atts def attlist(self): attlist = self.non_default_attributes().items() attlist.sort() return attlist def get(self, key, failobj=None): return self.attributes.get(key, failobj) def hasattr(self, attr): return self.attributes.has_key(attr) def delattr(self, attr): if self.attributes.has_key(attr): del self.attributes[attr] def setdefault(self, key, failobj=None): return self.attributes.setdefault(key, failobj) has_key = hasattr def append(self, item): self.setup_child(item) self.children.append(item) def extend(self, item): for node in item: self.append(node) def insert(self, index, item): if isinstance(item, Node): self.setup_child(item) self.children.insert(index, item) elif item is not None: self[index:index] = item def pop(self, i=-1): return self.children.pop(i) def remove(self, item): self.children.remove(item) def index(self, item): return self.children.index(item) def is_not_default(self, key): try: return self[key] != self.attr_defaults[key] except KeyError: return 1 def clear(self): self.children = [] def replace(self, old, new): """Replace one child `Node` with another child or children.""" index = self.index(old) if isinstance(new, Node): self.setup_child(new) self[index] = new elif new is not None: self[index:index+1] = new def first_child_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class exactly matches. Parameters: - `childclass`: A `Node` subclass to search for, or a tuple of `Node` classes. If a tuple, any of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, TupleType): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self[index], c): return index return None def first_child_not_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class does *not* match. Parameters: - `childclass`: A `Node` subclass to skip, or a tuple of `Node` classes. If a tuple, none of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, TupleType): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self.children[index], c): break else: return index return None def pformat(self, indent=' ', level=0): return ''.join(['%s%s\n' % (indent * level, self.starttag())] + [child.pformat(indent, level+1) for child in self.children]) def copy(self): return self.__class__(**self.attributes) def set_class(self, name): """Add a new class to the "classes" attribute.""" warnings.warn('docutils.nodes.Element.set_class deprecated; ' "append to Element['classes'] list attribute directly", DeprecationWarning, stacklevel=2) assert ' ' not in name self['classes'].append(name.lower()) def note_referenced_by(self, name=None, id=None): """Note that this Element has been referenced by its name `name` or id `id`.""" self.referenced = 1 # Element.expect_referenced_by_* dictionaries map names or ids # to nodes whose ``referenced`` attribute is set to true as # soon as this node is referenced by the given name or id. # Needed for target propagation. by_name = getattr(self, 'expect_referenced_by_name', {}).get(name) by_id = getattr(self, 'expect_referenced_by_id', {}).get(id) if by_name: assert name is not None by_name.referenced = 1 if by_id: assert id is not None by_id.referenced = 1 class TextElement(Element): """ An element which directly contains text. Its children are all `Text` or `Inline` subclass nodes. You can check whether an element's context is inline simply by checking whether its immediate parent is a `TextElement` instance (including subclasses). This is handy for nodes like `image` that can appear both inline and as standalone body elements. If passing children to `__init__()`, make sure to set `text` to ``''`` or some other suitable value. """ child_text_separator = '' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', text='', *children, **attributes): if text != '': textnode = Text(text) Element.__init__(self, rawsource, textnode, *children, **attributes) else: Element.__init__(self, rawsource, *children, **attributes) class FixedTextElement(TextElement): """An element which directly contains preformatted text.""" def __init__(self, rawsource='', text='', *children, **attributes): TextElement.__init__(self, rawsource, text, *children, **attributes) self.attributes['xml:space'] = 'preserve' # ======== # Mixins # ======== class Resolvable: resolved = 0 class BackLinkable: def add_backref(self, refid): self['backrefs'].append(refid) # ==================== # Element Categories # ==================== class Root: pass class Titular: pass class PreBibliographic: """Category of Node which may occur before Bibliographic Nodes.""" class Bibliographic: pass class Decorative(PreBibliographic): pass class Structural: pass class Body: pass class General(Body): pass class Sequential(Body): """List-like elements.""" class Admonition(Body): pass class Special(Body): """Special internal body elements.""" class Invisible(PreBibliographic): """Internal elements that don't appear in output.""" class Part: pass class Inline: pass class Referential(Resolvable): pass class Targetable(Resolvable): referenced = 0 class Labeled: """Contains a `label` as its first element.""" # ============== # Root Element # ============== class document(Root, Structural, Element): def __init__(self, settings, reporter, *args, **kwargs): Element.__init__(self, *args, **kwargs) self.current_source = None """Path to or description of the input source being processed.""" self.current_line = None """Line number (1-based) of `current_source`.""" self.settings = settings """Runtime settings data record.""" self.reporter = reporter """System message generator.""" self.external_targets = [] """List of external target nodes.""" self.internal_targets = [] """List of internal target nodes.""" self.indirect_targets = [] """List of indirect target nodes.""" self.substitution_defs = {} """Mapping of substitution names to substitution_definition nodes.""" self.substitution_names = {} """Mapping of case-normalized substitution names to case-sensitive names.""" self.refnames = {} """Mapping of names to lists of referencing nodes.""" self.refids = {} """Mapping of ids to lists of referencing nodes.""" self.nameids = {} """Mapping of names to unique id's.""" self.nametypes = {} """Mapping of names to hyperlink type (boolean: True => explicit, False => implicit.""" self.ids = {} """Mapping of ids to nodes.""" self.substitution_refs = {} """Mapping of substitution names to lists of substitution_reference nodes.""" self.footnote_refs = {} """Mapping of footnote labels to lists of footnote_reference nodes.""" self.citation_refs = {} """Mapping of citation labels to lists of citation_reference nodes.""" self.anonymous_targets = [] """List of anonymous target nodes.""" self.anonymous_refs = [] """List of anonymous reference nodes.""" self.autofootnotes = [] """List of auto-numbered footnote nodes.""" self.autofootnote_refs = [] """List of auto-numbered footnote_reference nodes.""" self.symbol_footnotes = [] """List of symbol footnote nodes.""" self.symbol_footnote_refs = [] """List of symbol footnote_reference nodes.""" self.footnotes = [] """List of manually-numbered footnote nodes.""" self.citations = [] """List of citation nodes.""" self.autofootnote_start = 1 """Initial auto-numbered footnote number.""" self.symbol_footnote_start = 0 """Initial symbol footnote symbol index.""" self.id_start = 1 """Initial ID number.""" self.parse_messages = [] """System messages generated while parsing.""" self.transform_messages = [] """System messages generated while applying transforms.""" import docutils.transforms self.transformer = docutils.transforms.Transformer(self) """Storage for transforms to be applied to this document.""" self.decoration = None """Document's `decoration` node.""" self.document = self def asdom(self, dom=xml.dom.minidom): """Return a DOM representation of this document.""" domroot = dom.Document() domroot.appendChild(self._dom_node(domroot)) return domroot def set_id(self, node, msgnode=None): for id in node['ids']: if self.ids.has_key(id) and self.ids[id] is not node: msg = self.reporter.severe('Duplicate ID: "%s".' % id) if msgnode != None: msgnode += msg if not node['ids']: for name in node['names']: id = self.settings.id_prefix + make_id(name) if id and not self.ids.has_key(id): break else: id = '' while not id or self.ids.has_key(id): id = (self.settings.id_prefix + self.settings.auto_id_prefix + str(self.id_start)) self.id_start += 1 node['ids'].append(id) self.ids[id] = node return id def set_name_id_map(self, node, id, msgnode=None, explicit=None): """ `self.nameids` maps names to IDs, while `self.nametypes` maps names to booleans representing hyperlink type (True==explicit, False==implicit). This method updates the mappings. The following state transition table shows how `self.nameids` ("ids") and `self.nametypes` ("types") change with new input (a call to this method), and what actions are performed: ==== ===== ======== ======== ======= ==== ===== ===== Old State Input Action New State Notes ----------- -------- ----------------- ----------- ----- ids types new type sys.msg. dupname ids types ==== ===== ======== ======== ======= ==== ===== ===== -- -- explicit -- -- new True -- -- implicit -- -- new False None False explicit -- -- new True old False explicit implicit old new True None True explicit explicit new None True old True explicit explicit new,old None True [#]_ None False implicit implicit new None False old False implicit implicit new,old None False None True implicit implicit new None True old True implicit implicit new old True ==== ===== ======== ======== ======= ==== ===== ===== .. [#] Do not clear the name-to-id map or invalidate the old target if both old and new targets are external and refer to identical URIs. The new target is invalidated regardless. """ for name in node['names']: if self.nameids.has_key(name): self.set_duplicate_name_id(node, id, name, msgnode, explicit) else: self.nameids[name] = id self.nametypes[name] = explicit def set_duplicate_name_id(self, node, id, name, msgnode, explicit): old_id = self.nameids[name] old_explicit = self.nametypes[name] self.nametypes[name] = old_explicit or explicit if explicit: if old_explicit: level = 2 if old_id is not None: old_node = self.ids[old_id] if node.has_key('refuri'): refuri = node['refuri'] if old_node['names'] \ and old_node.has_key('refuri') \ and old_node['refuri'] == refuri: level = 1 # just inform if refuri's identical if level > 1: dupname(old_node, name) self.nameids[name] = None msg = self.reporter.system_message( level, 'Duplicate explicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg dupname(node, name) else: self.nameids[name] = id if old_id is not None: old_node = self.ids[old_id] dupname(old_node, name) else: if old_id is not None and not old_explicit: self.nameids[name] = None old_node = self.ids[old_id] dupname(old_node, name) dupname(node, name) if not explicit or (not old_explicit and old_id is not None): msg = self.reporter.info( 'Duplicate implicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg def has_name(self, name): return self.nameids.has_key(name) # "note" here is an imperative verb: "take note of". def note_implicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=None) def note_explicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=1) def note_refname(self, node): self.refnames.setdefault(node['refname'], []).append(node) def note_refid(self, node): self.refids.setdefault(node['refid'], []).append(node) def note_external_target(self, target): self.external_targets.append(target) def note_internal_target(self, target): self.internal_targets.append(target) def note_indirect_target(self, target): self.indirect_targets.append(target) if target['names']: self.note_refname(target) def note_anonymous_target(self, target): self.set_id(target) self.anonymous_targets.append(target) def note_anonymous_ref(self, ref): self.anonymous_refs.append(ref) def note_autofootnote(self, footnote): self.set_id(footnote) self.autofootnotes.append(footnote) def note_autofootnote_ref(self, ref): self.set_id(ref) self.autofootnote_refs.append(ref) def note_symbol_footnote(self, footnote): self.set_id(footnote) self.symbol_footnotes.append(footnote) def note_symbol_footnote_ref(self, ref): self.set_id(ref) self.symbol_footnote_refs.append(ref) def note_footnote(self, footnote): self.set_id(footnote) self.footnotes.append(footnote) def note_footnote_ref(self, ref): self.set_id(ref) self.footnote_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_citation(self, citation): self.citations.append(citation) def note_citation_ref(self, ref): self.set_id(ref) self.citation_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_substitution_def(self, subdef, def_name, msgnode=None): name = whitespace_normalize_name(def_name) subdef['names'].append(name) if self.substitution_defs.has_key(name): msg = self.reporter.error( 'Duplicate substitution definition name: "%s".' % name, base_node=subdef) if msgnode != None: msgnode += msg oldnode = self.substitution_defs[name] dupname(oldnode, name) # keep only the last definition: self.substitution_defs[name] = subdef # case-insensitive mapping: self.substitution_names[fully_normalize_name(name)] = name def note_substitution_ref(self, subref, refname): name = subref['refname'] = whitespace_normalize_name(refname) self.substitution_refs.setdefault(name, []).append(subref) def note_pending(self, pending, priority=None): self.transformer.add_pending(pending, priority) def note_parse_message(self, message): self.parse_messages.append(message) def note_transform_message(self, message): self.transform_messages.append(message) def note_source(self, source, offset): self.current_source = source if offset is None: self.current_line = offset else: self.current_line = offset + 1 def copy(self): return self.__class__(self.settings, self.reporter, **self.attributes) def get_decoration(self): if not self.decoration: self.decoration = decoration() index = self.first_child_not_matching_class(Titular) if index is None: self.append(self.decoration) else: self.insert(index, self.decoration) return self.decoration # ================ # Title Elements # ================ class title(Titular, PreBibliographic, TextElement): pass class subtitle(Titular, PreBibliographic, TextElement): pass class rubric(Titular, TextElement): pass # ======================== # Bibliographic Elements # ======================== class docinfo(Bibliographic, Element): pass class author(Bibliographic, TextElement): pass class authors(Bibliographic, Element): pass class organization(Bibliographic, TextElement): pass class address(Bibliographic, FixedTextElement): pass class contact(Bibliographic, TextElement): pass class version(Bibliographic, TextElement): pass class revision(Bibliographic, TextElement): pass class status(Bibliographic, TextElement): pass class date(Bibliographic, TextElement): pass class copyright(Bibliographic, TextElement): pass # ===================== # Decorative Elements # ===================== class decoration(Decorative, Element): def get_header(self): if not len(self.children) or not isinstance(self.children[0], header): self.insert(0, header()) return self.children[0] def get_footer(self): if not len(self.children) or not isinstance(self.children[-1], footer): self.append(footer()) return self.children[-1] class header(Decorative, Element): pass class footer(Decorative, Element): pass # ===================== # Structural Elements # ===================== class section(Structural, Element): pass class topic(Structural, Element): """ Topics are terminal, "leaf" mini-sections, like block quotes with titles, or textual figures. A topic is just like a section, except that it has no subsections, and it doesn't have to conform to section placement rules. Topics are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Topics cannot nest inside topics, sidebars, or body elements; you can't have a topic inside a table, list, block quote, etc. """ class sidebar(Structural, Element): """ Sidebars are like miniature, parallel documents that occur inside other documents, providing related or reference material. A sidebar is typically offset by a border and "floats" to the side of the page; the document's main text may flow around it. Sidebars can also be likened to super-footnotes; their content is outside of the flow of the document's main text. Sidebars are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Sidebars cannot nest inside sidebars, topics, or body elements; you can't have a sidebar inside a table, list, block quote, etc. """ class transition(Structural, Element): pass # =============== # Body Elements # =============== class paragraph(General, TextElement): pass class compound(General, Element): pass class bullet_list(Sequential, Element): pass class enumerated_list(Sequential, Element): pass class list_item(Part, Element): pass class definition_list(Sequential, Element): pass class definition_list_item(Part, Element): pass class term(Part, TextElement): pass class classifier(Part, TextElement): pass class definition(Part, Element): pass class field_list(Sequential, Element): pass class field(Part, Element): pass class field_name(Part, TextElement): pass class field_body(Part, Element): pass class option(Part, Element): child_text_separator = '' class option_argument(Part, TextElement): def astext(self): return self.get('delimiter', ' ') + TextElement.astext(self) class option_group(Part, Element): child_text_separator = ', ' class option_list(Sequential, Element): pass class option_list_item(Part, Element): child_text_separator = ' ' class option_string(Part, TextElement): pass class description(Part, Element): pass class literal_block(General, FixedTextElement): pass class doctest_block(General, FixedTextElement): pass class line_block(General, Element): pass class line(Part, TextElement): indent = None class block_quote(General, Element): pass class attribution(Part, TextElement): pass class attention(Admonition, Element): pass class caution(Admonition, Element): pass class danger(Admonition, Element): pass class error(Admonition, Element): pass class important(Admonition, Element): pass class note(Admonition, Element): pass class tip(Admonition, Element): pass class hint(Admonition, Element): pass class warning(Admonition, Element): pass class admonition(Admonition, Element): pass class comment(Special, Invisible, FixedTextElement): pass class substitution_definition(Special, Invisible, TextElement): pass class target(Special, Invisible, Inline, TextElement, Targetable): pass class footnote(General, BackLinkable, Element, Labeled, Targetable): pass class citation(General, BackLinkable, Element, Labeled, Targetable): pass class label(Part, TextElement): pass class figure(General, Element): pass class caption(Part, TextElement): pass class legend(Part, Element): pass class table(General, Element): pass class tgroup(Part, Element): pass class colspec(Part, Element): pass class thead(Part, Element): pass class tbody(Part, Element): pass class row(Part, Element): pass class entry(Part, Element): pass class system_message(Special, BackLinkable, PreBibliographic, Element): def __init__(self, message=None, *children, **attributes): if message: p = paragraph('', message) children = (p,) + children try: Element.__init__(self, '', *children, **attributes) except: print 'system_message: children=%r' % (children,) raise def astext(self): line = self.get('line', '') return u'%s:%s: (%s/%s) %s' % (self['source'], line, self['type'], self['level'], Element.astext(self)) class pending(Special, Invisible, Element): """ The "pending" element is used to encapsulate a pending operation: the operation (transform), the point at which to apply it, and any data it requires. Only the pending operation's location within the document is stored in the public document tree (by the "pending" object itself); the operation and its data are stored in the "pending" object's internal instance attributes. For example, say you want a table of contents in your reStructuredText document. The easiest way to specify where to put it is from within the document, with a directive:: .. contents:: But the "contents" directive can't do its work until the entire document has been parsed and possibly transformed to some extent. So the directive code leaves a placeholder behind that will trigger the second phase of its processing, something like this:: <pending ...public attributes...> + internal attributes Use `document.note_pending()` so that the `docutils.transforms.Transformer` stage of processing can run all pending transforms. """ def __init__(self, transform, details=None, rawsource='', *children, **attributes): Element.__init__(self, rawsource, *children, **attributes) self.transform = transform """The `docutils.transforms.Transform` class implementing the pending operation.""" self.details = details or {} """Detail data (dictionary) required by the pending operation.""" def pformat(self, indent=' ', level=0): internals = [ '.. internal attributes:', ' .transform: %s.%s' % (self.transform.__module__, self.transform.__name__), ' .details:'] details = self.details.items() details.sort() for key, value in details: if isinstance(value, Node): internals.append('%7s%s:' % ('', key)) internals.extend(['%9s%s' % ('', line) for line in value.pformat().splitlines()]) elif value and isinstance(value, ListType) \ and isinstance(value[0], Node): internals.append('%7s%s:' % ('', key)) for v in value: internals.extend(['%9s%s' % ('', line) for line in v.pformat().splitlines()]) else: internals.append('%7s%s: %r' % ('', key, value)) return (Element.pformat(self, indent, level) + ''.join([(' %s%s\n' % (indent * level, line)) for line in internals])) def copy(self): return self.__class__(self.transform, self.details, self.rawsource, **self.attributes) class raw(Special, Inline, PreBibliographic, FixedTextElement): """ Raw data that is to be passed untouched to the Writer. """ pass # ================= # Inline Elements # ================= class emphasis(Inline, TextElement): pass class strong(Inline, TextElement): pass class literal(Inline, TextElement): pass class reference(General, Inline, Referential, TextElement): pass class footnote_reference(Inline, Referential, TextElement): pass class citation_reference(Inline, Referential, TextElement): pass class substitution_reference(Inline, TextElement): pass class title_reference(Inline, TextElement): pass class abbreviation(Inline, TextElement): pass class acronym(Inline, TextElement): pass class superscript(Inline, TextElement): pass class subscript(Inline, TextElement): pass class image(General, Inline, Element): def astext(self): return self.get('alt', '') class inline(Inline, TextElement): pass class problematic(Inline, TextElement): pass class generated(Inline, TextElement): pass # ======================================== # Auxiliary Classes, Functions, and Data # ======================================== node_class_names = """ Text abbreviation acronym address admonition attention attribution author authors block_quote bullet_list caption caution citation citation_reference classifier colspec comment compound contact copyright danger date decoration definition definition_list definition_list_item description docinfo doctest_block document emphasis entry enumerated_list error field field_body field_list field_name figure footer footnote footnote_reference generated header hint image important inline label legend line line_block list_item literal literal_block note option option_argument option_group option_list option_list_item option_string organization paragraph pending problematic raw reference revision row rubric section sidebar status strong subscript substitution_definition substitution_reference subtitle superscript system_message table target tbody term tgroup thead tip title title_reference topic transition version warning""".split() """A list of names of all concrete Node subclasses.""" class NodeVisitor: """ "Visitor" pattern [GoF95]_ abstract superclass implementation for document tree traversals. Each node class has corresponding methods, doing nothing by default; override individual methods for specific and useful behaviour. The `dispatch_visit()` method is called by `Node.walk()` upon entering a node. `Node.walkabout()` also calls the `dispatch_departure()` method before exiting a node. The dispatch methods call "``visit_`` + node class name" or "``depart_`` + node class name", resp. This is a base class for visitors whose ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types encountered (such as for `docutils.writers.Writer` subclasses). Unimplemented methods will raise exceptions. For sparse traversals, where only certain node types are of interest, subclass `SparseNodeVisitor` instead. When (mostly or entirely) uniform processing is desired, subclass `GenericNodeVisitor`. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA, 1995. """ optional = () """ Tuple containing node class names (as strings). No exception will be raised if writers do not implement visit or departure functions for these node classes. Used to ensure transitional compatibility with existing 3rd-party writers. """ def __init__(self, document): self.document = document def dispatch_visit(self, node): """ Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit. """ node_name = node.__class__.__name__ method = getattr(self, 'visit_' + node_name, self.unknown_visit) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_visit calling %s for %s' % (method.__name__, node_name)) return method(node) def dispatch_departure(self, node): """ Call self."``depart_`` + node class name" with `node` as parameter. If the ``depart_...`` method does not exist, call self.unknown_departure. """ node_name = node.__class__.__name__ method = getattr(self, 'depart_' + node_name, self.unknown_departure) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_departure calling %s for %s' % (method.__name__, node_name)) return method(node) def unknown_visit(self, node): """ Called when entering unknown `Node` types. Raise an exception unless overridden. """ if (node.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s visiting unknown node type: %s' % (self.__class__, node.__class__.__name__)) def unknown_departure(self, node): """ Called before exiting unknown `Node` types. Raise exception unless overridden. """ if (node.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s departing unknown node type: %s' % (self.__class__, node.__class__.__name__)) class SparseNodeVisitor(NodeVisitor): """ Base class for sparse traversals, where only certain node types are of interest. When ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types (such as for `docutils.writers.Writer` subclasses), subclass `NodeVisitor` instead. """ class GenericNodeVisitor(NodeVisitor): """ Generic "Visitor" abstract superclass, for simple traversals. Unless overridden, each ``visit_...`` method calls `default_visit()`, and each ``depart_...`` method (when using `Node.walkabout()`) calls `default_departure()`. `default_visit()` (and `default_departure()`) must be overridden in subclasses. Define fully generic visitors by overriding `default_visit()` (and `default_departure()`) only. Define semi-generic visitors by overriding individual ``visit_...()`` (and ``depart_...()``) methods also. `NodeVisitor.unknown_visit()` (`NodeVisitor.unknown_departure()`) should be overridden for default behavior. """ def default_visit(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def default_departure(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def _call_default_visit(self, node): self.default_visit(node) def _call_default_departure(self, node): self.default_departure(node) def _nop(self, node): pass def _add_node_class_names(names): """Save typing with dynamic assignments:""" for _name in names: setattr(GenericNodeVisitor, "visit_" + _name, _call_default_visit) setattr(GenericNodeVisitor, "depart_" + _name, _call_default_departure) setattr(SparseNodeVisitor, 'visit_' + _name, _nop) setattr(SparseNodeVisitor, 'depart_' + _name, _nop) _add_node_class_names(node_class_names) class TreeCopyVisitor(GenericNodeVisitor): """ Make a complete copy of a tree or branch, including element attributes. """ def __init__(self, document): GenericNodeVisitor.__init__(self, document) self.parent_stack = [] self.parent = [] def get_tree_copy(self): return self.parent[0] def default_visit(self, node): """Copy the current node, and make it the new acting parent.""" newnode = node.copy() self.parent.append(newnode) self.parent_stack.append(self.parent) self.parent = newnode def default_departure(self, node): """Restore the previous acting parent.""" self.parent = self.parent_stack.pop() class TreePruningException(Exception): """ Base class for `NodeVisitor`-related tree pruning exceptions. Raise subclasses from within ``visit_...`` or ``depart_...`` methods called from `Node.walk()` and `Node.walkabout()` tree traversals to prune the tree traversed. """ pass class SkipChildren(TreePruningException): """ Do not visit any children of the current node. The current node's siblings and ``depart_...`` method are not affected. """ pass class SkipSiblings(TreePruningException): """ Do not visit any more siblings (to the right) of the current node. The current node's children and its ``depart_...`` method are not affected. """ pass class SkipNode(TreePruningException): """ Do not visit the current node's children, and do not call the current node's ``depart_...`` method. """ pass class SkipDeparture(TreePruningException): """ Do not call the current node's ``depart_...`` method. The current node's children and siblings are not affected. """ pass class NodeFound(TreePruningException): """ Raise to indicate that the target of a search has been found. This exception must be caught by the client; it is not caught by the traversal code. """ pass def make_id(string): """ Convert `string` into an identifier and return it. Docutils identifiers will conform to the regular expression ``[a-z](-?[a-z0-9]+)*``. For CSS compatibility, identifiers (the "class" and "id" attributes) should have no underscores, colons, or periods. Hyphens may be used. - The `HTML 4.01 spec`_ defines identifiers based on SGML tokens: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). - However the `CSS1 spec`_ defines identifiers based on the "name" token, a tighter interpretation ("flex" tokenizer notation; "latin1" and "escape" 8-bit characters have been replaced with entities):: unicode \\[0-9a-f]{1,4} latin1 [&iexcl;-&yuml;] escape {unicode}|\\[ -~&iexcl;-&yuml;] nmchar [-a-z0-9]|{latin1}|{escape} name {nmchar}+ The CSS1 "nmchar" rule does not include underscores ("_"), colons (":"), or periods ("."), therefore "class" and "id" attributes should not contain these characters. They should be replaced with hyphens ("-"). Combined with HTML's requirements (the first character must be a letter; no "unicode", "latin1", or "escape" characters), this results in the ``[a-z](-?[a-z0-9]+)*`` pattern. .. _HTML 4.01 spec: http://www.w3.org/TR/html401 .. _CSS1 spec: http://www.w3.org/TR/REC-CSS1 """ id = _non_id_chars.sub('-', ' '.join(string.lower().split())) id = _non_id_at_ends.sub('', id) return str(id) _non_id_chars = re.compile('[^a-z0-9]+') _non_id_at_ends = re.compile('^[-0-9]+|-+$') def dupname(node, name): node['dupnames'].append(name) node['names'].remove(name) # Assume that this method is referenced, even though it isn't; we # don't want to throw unnecessary system_messages. node.referenced = 1 def fully_normalize_name(name): """Return a case- and whitespace-normalized name.""" return ' '.join(name.lower().split()) def whitespace_normalize_name(name): """Return a whitespace-normalized name.""" return ' '.join(name.split())
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/nodes.py", "copies": "1", "size": "56434", "license": "mit", "hash": -1425636128552595500, "line_mean": 32.5118764846, "line_max": 79, "alpha_frac": 0.5955806783, "autogenerated": false, "ratio": 4.219679976072977, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002362675975002129, "num_lines": 1684 }
""" Simple HyperText Markup Language document tree Writer. The output conforms to the HTML 4.01 Transitional DTD and to the Extensible HTML version 1.0 Transitional DTD (*almost* strict). The output contains a minimum of formatting information. A cascading style sheet ("default.css" by default) is required for proper viewing with a modern graphical browser. """ __docformat__ = 'reStructuredText' import sys import os import os.path import time import re from types import ListType try: import Image # check for the Python Imaging Library except ImportError: Image = None import docutils from docutils import frontend, nodes, utils, writers, languages class Writer(writers.Writer): supported = ('html', 'html4css1', 'xhtml') """Formats this writer supports.""" settings_spec = ( 'HTML-Specific Options', None, (('Specify a stylesheet URL, used verbatim. Default is ' '"default.css". Overrides --stylesheet-path.', ['--stylesheet'], {'default': 'default.css', 'metavar': '<URL>', 'overrides': 'stylesheet_path'}), ('Specify a stylesheet file, relative to the current working ' 'directory. The path is adjusted relative to the output HTML ' 'file. Overrides --stylesheet.', ['--stylesheet-path'], {'metavar': '<file>', 'overrides': 'stylesheet'}), ('Link to the stylesheet in the output HTML file. This is the ' 'default.', ['--link-stylesheet'], {'dest': 'embed_stylesheet', 'action': 'store_false', 'validator': frontend.validate_boolean}), ('Embed the stylesheet in the output HTML file. The stylesheet ' 'file must be accessible during processing (--stylesheet-path is ' 'recommended). Default: link the stylesheet, do not embed it.', ['--embed-stylesheet'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Specify the initial header level. Default is 1 for "<h1>". ' 'Does not affect document title & subtitle (see --no-doc-title).', ['--initial-header-level'], {'choices': '1 2 3 4 5 6'.split(), 'default': '1', 'metavar': '<level>'}), ('Specify the maximum width (in characters) for one-column field ' 'names. Longer field names will span an entire row of the table ' 'used to render the field list. Default is 14 characters. ' 'Use 0 for "no limit".', ['--field-name-limit'], {'default': 14, 'metavar': '<level>', 'validator': frontend.validate_nonnegative_int}), ('Specify the maximum width (in characters) for options in option ' 'lists. Longer options will span an entire row of the table used ' 'to render the option list. Default is 14 characters. ' 'Use 0 for "no limit".', ['--option-limit'], {'default': 14, 'metavar': '<level>', 'validator': frontend.validate_nonnegative_int}), ('Format for footnote references: one of "superscript" or ' '"brackets". Default is "brackets".', ['--footnote-references'], {'choices': ['superscript', 'brackets'], 'default': 'brackets', 'metavar': '<format>', 'overrides': 'trim_footnote_reference_space'}), ('Format for block quote attributions: one of "dash" (em-dash ' 'prefix), "parentheses"/"parens", or "none". Default is "dash".', ['--attribution'], {'choices': ['dash', 'parentheses', 'parens', 'none'], 'default': 'dash', 'metavar': '<format>'}), ('Remove extra vertical whitespace between items of bullet lists ' 'and enumerated lists, when list items are "simple" (i.e., all ' 'items each contain one paragraph and/or one "simple" sublist ' 'only). Default: enabled.', ['--compact-lists'], {'default': 1, 'action': 'store_true', 'validator': frontend.validate_boolean}), ('Disable compact simple bullet and enumerated lists.', ['--no-compact-lists'], {'dest': 'compact_lists', 'action': 'store_false'}), ('Omit the XML declaration. Use with caution.', ['--no-xml-declaration'], {'dest': 'xml_declaration', 'default': 1, 'action': 'store_false', 'validator': frontend.validate_boolean}), ('Scramble email addresses to confuse harvesters. ' 'For example, "abc@example.org" will become ' '``<a href="mailto:%61%62%63%40...">abc at example dot org</a>``.', ['--cloak-email-addresses'], {'action': 'store_true', 'validator': frontend.validate_boolean}),)) relative_path_settings = ('stylesheet_path',) config_section = 'html4css1 writer' config_section_dependencies = ('writers',) def __init__(self): writers.Writer.__init__(self) self.translator_class = HTMLTranslator def translate(self): self.visitor = visitor = self.translator_class(self.document) self.document.walkabout(visitor) self.output = visitor.astext() for attr in ('head_prefix', 'stylesheet', 'head', 'body_prefix', 'body_pre_docinfo', 'docinfo', 'body', 'fragment', 'body_suffix'): setattr(self, attr, getattr(visitor, attr)) def assemble_parts(self): writers.Writer.assemble_parts(self) for part in ('title', 'subtitle', 'docinfo', 'body', 'header', 'footer', 'meta', 'stylesheet', 'fragment', 'html_prolog', 'html_head', 'html_title', 'html_subtitle', 'html_body'): self.parts[part] = ''.join(getattr(self.visitor, part)) class HTMLTranslator(nodes.NodeVisitor): """ This HTML writer has been optimized to produce visually compact lists (less vertical whitespace). HTML's mixed content models allow list items to contain "<li><p>body elements</p></li>" or "<li>just text</li>" or even "<li>text<p>and body elements</p>combined</li>", each with different effects. It would be best to stick with strict body elements in list items, but they affect vertical spacing in browsers (although they really shouldn't). Here is an outline of the optimization: - Check for and omit <p> tags in "simple" lists: list items contain either a single paragraph, a nested simple list, or a paragraph followed by a nested simple list. This means that this list can be compact: - Item 1. - Item 2. But this list cannot be compact: - Item 1. This second paragraph forces space between list items. - Item 2. - In non-list contexts, omit <p> tags on a paragraph if that paragraph is the only child of its parent (footnotes & citations are allowed a label first). - Regardless of the above, in definitions, table cells, field bodies, option descriptions, and list items, mark the first child with 'class="first"' and the last child with 'class="last"'. The stylesheet sets the margins (top & bottom respectively) to 0 for these elements. The ``no_compact_lists`` setting (``--no-compact-lists`` command-line option) disables list whitespace optimization. """ xml_declaration = '<?xml version="1.0" encoding="%s" ?>\n' doctype = ('<!DOCTYPE html' ' PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' ' "http://www.w3.org/TR/xhtml1/DTD/' 'xhtml1-transitional.dtd">\n') head_prefix_template = ('<html xmlns="http://www.w3.org/1999/xhtml"' ' xml:lang="%s" lang="%s">\n<head>\n') content_type = ('<meta http-equiv="Content-Type"' ' content="text/html; charset=%s" />\n') generator = ('<meta name="generator" content="Docutils %s: ' 'http://docutils.sourceforge.net/" />\n') stylesheet_link = '<link rel="stylesheet" href="%s" type="text/css" />\n' embedded_stylesheet = '<style type="text/css">\n\n%s\n</style>\n' named_tags = ['a', 'applet', 'form', 'frame', 'iframe', 'img', 'map'] words_and_spaces = re.compile(r'\S+| +|\n') def __init__(self, document): nodes.NodeVisitor.__init__(self, document) self.settings = settings = document.settings lcode = settings.language_code self.language = languages.get_language(lcode) self.meta = [self.content_type % settings.output_encoding, self.generator % docutils.__version__] self.head_prefix = [] self.html_prolog = [] if settings.xml_declaration: self.head_prefix.append(self.xml_declaration % settings.output_encoding) # encoding not interpolated: self.html_prolog.append(self.xml_declaration) self.head_prefix.extend([self.doctype, self.head_prefix_template % (lcode, lcode)]) self.html_prolog.append(self.doctype) self.head = self.meta[:] if settings.embed_stylesheet: stylesheet = utils.get_stylesheet_reference(settings, os.path.join(os.getcwd(), 'dummy')) settings.record_dependencies.add(stylesheet) stylesheet_text = open(stylesheet).read() self.stylesheet = [self.embedded_stylesheet % stylesheet_text] else: stylesheet = utils.get_stylesheet_reference(settings) if stylesheet: self.stylesheet = [self.stylesheet_link % self.encode(stylesheet)] else: self.stylesheet = [] self.body_prefix = ['</head>\n<body>\n'] # document title, subtitle display self.body_pre_docinfo = [] # author, date, etc. self.docinfo = [] self.body = [] self.fragment = [] self.body_suffix = ['</body>\n</html>\n'] self.section_level = 0 self.initial_header_level = int(settings.initial_header_level) # A heterogenous stack used in conjunction with the tree traversal. # Make sure that the pops correspond to the pushes: self.context = [] self.topic_classes = [] self.colspecs = [] self.compact_p = 1 self.compact_simple = None self.in_docinfo = None self.in_sidebar = None self.title = [] self.subtitle = [] self.header = [] self.footer = [] self.html_head = [self.content_type] # charset not interpolated self.html_title = [] self.html_subtitle = [] self.html_body = [] self.in_document_title = 0 self.in_mailto = 0 def astext(self): return ''.join(self.head_prefix + self.head + self.stylesheet + self.body_prefix + self.body_pre_docinfo + self.docinfo + self.body + self.body_suffix) def encode(self, text): """Encode special characters in `text` & return.""" # @@@ A codec to do these and all other HTML entities would be nice. text = text.replace("&", "&amp;") text = text.replace("<", "&lt;") text = text.replace('"', "&quot;") text = text.replace(">", "&gt;") text = text.replace("@", "&#64;") # may thwart some address harvesters # Replace the non-breaking space character with the HTML entity: text = text.replace(u'\u00a0', "&nbsp;") return text def cloak_mailto(self, uri): """Try to hide a mailto: URL from harvesters.""" addr = uri.split(':', 1)[1] if '?' in addr: addr, query = addr.split('?', 1) query = '?' + query else: query = '' escaped = ['%%%02X' % ord(c) for c in addr] return 'mailto:%s%s' % (''.join(escaped), query) def cloak_email(self, addr): return addr.replace('@', ' at ').replace('.', ' dot ') def attval(self, text, whitespace=re.compile('[\n\r\t\v\f]')): """Cleanse, HTML encode, and return attribute value text.""" return self.encode(whitespace.sub(' ', text)) def starttag(self, node, tagname, suffix='\n', infix='', **attributes): """ Construct and return a start tag given a node (id & class attributes are extracted), tag name, and optional attributes. """ tagname = tagname.lower() prefix = [] atts = {} for (name, value) in attributes.items(): atts[name.lower()] = value classes = node.get('classes', []) if atts.has_key('class'): classes.append(atts['class']) if classes: atts['class'] = ' '.join(classes) assert not atts.has_key('id') if node.get('ids'): atts['id'] = node['ids'][0] for id in node['ids'][1:]: prefix.append('<span id="%s"></span>' % id) if atts.has_key('id') and tagname in self.named_tags: atts['name'] = atts['id'] # for compatibility with old browsers attlist = atts.items() attlist.sort() parts = [tagname] for name, value in attlist: # value=None was used for boolean attributes without # value, but this isn't supported by XHTML. assert value is not None if isinstance(value, ListType): values = [unicode(v) for v in value] parts.append('%s="%s"' % (name.lower(), self.attval(' '.join(values)))) else: try: uval = unicode(value) except TypeError: # for Python 2.1 compatibility: uval = unicode(str(value)) parts.append('%s="%s"' % (name.lower(), self.attval(uval))) return ''.join(prefix) + '<%s%s>' % (' '.join(parts), infix) + suffix def emptytag(self, node, tagname, suffix='\n', **attributes): """Construct and return an XML-compatible empty tag.""" return self.starttag(node, tagname, suffix, infix=' /', **attributes) def set_first_last(self, node): children = [n for n in node if not isinstance(n, nodes.Invisible)] if children: children[0]['classes'].append('first') children[-1]['classes'].append('last') def visit_Text(self, node): text = node.astext() if self.in_mailto and self.settings.cloak_email_addresses: text = self.cloak_email(text) self.body.append(self.encode(text)) def depart_Text(self, node): pass def visit_abbreviation(self, node): # @@@ implementation incomplete ("title" attribute) self.body.append(self.starttag(node, 'abbr', '')) def depart_abbreviation(self, node): self.body.append('</abbr>') def visit_acronym(self, node): # @@@ implementation incomplete ("title" attribute) self.body.append(self.starttag(node, 'acronym', '')) def depart_acronym(self, node): self.body.append('</acronym>') def visit_address(self, node): self.visit_docinfo_item(node, 'address', meta=None) self.body.append(self.starttag(node, 'pre', CLASS='address')) def depart_address(self, node): self.body.append('\n</pre>\n') self.depart_docinfo_item() def visit_admonition(self, node, name=''): self.body.append(self.starttag(node, 'div', CLASS=(name or 'admonition'))) if name: node.insert(0, nodes.title(name, self.language.labels[name])) self.set_first_last(node) def depart_admonition(self, node=None): self.body.append('</div>\n') def visit_attention(self, node): self.visit_admonition(node, 'attention') def depart_attention(self, node): self.depart_admonition() attribution_formats = {'dash': ('&mdash;', ''), 'parentheses': ('(', ')'), 'parens': ('(', ')'), 'none': ('', '')} def visit_attribution(self, node): prefix, suffix = self.attribution_formats[self.settings.attribution] self.context.append(suffix) self.body.append( self.starttag(node, 'p', prefix, CLASS='attribution')) def depart_attribution(self, node): self.body.append(self.context.pop() + '</p>\n') def visit_author(self, node): self.visit_docinfo_item(node, 'author') def depart_author(self, node): self.depart_docinfo_item() def visit_authors(self, node): pass def depart_authors(self, node): pass def visit_block_quote(self, node): self.body.append(self.starttag(node, 'blockquote')) def depart_block_quote(self, node): self.body.append('</blockquote>\n') def check_simple_list(self, node): """Check for a simple list that can be rendered compactly.""" visitor = SimpleListChecker(self.document) try: node.walk(visitor) except nodes.NodeFound: return None else: return 1 def visit_bullet_list(self, node): atts = {} old_compact_simple = self.compact_simple self.context.append((self.compact_simple, self.compact_p)) self.compact_p = None self.compact_simple = (self.settings.compact_lists and (self.compact_simple or self.topic_classes == ['contents'] or self.check_simple_list(node))) if self.compact_simple and not old_compact_simple: atts['class'] = 'simple' self.body.append(self.starttag(node, 'ul', **atts)) def depart_bullet_list(self, node): self.compact_simple, self.compact_p = self.context.pop() self.body.append('</ul>\n') def visit_caption(self, node): self.body.append(self.starttag(node, 'p', '', CLASS='caption')) def depart_caption(self, node): self.body.append('</p>\n') def visit_caution(self, node): self.visit_admonition(node, 'caution') def depart_caution(self, node): self.depart_admonition() def visit_citation(self, node): self.body.append(self.starttag(node, 'table', CLASS='docutils citation', frame="void", rules="none")) self.body.append('<colgroup><col class="label" /><col /></colgroup>\n' '<tbody valign="top">\n' '<tr>') self.footnote_backrefs(node) def depart_citation(self, node): self.body.append('</td></tr>\n' '</tbody>\n</table>\n') def visit_citation_reference(self, node): href = '#' + node['refid'] self.body.append(self.starttag( node, 'a', '[', CLASS='citation-reference', href=href)) def depart_citation_reference(self, node): self.body.append(']</a>') def visit_classifier(self, node): self.body.append(' <span class="classifier-delimiter">:</span> ') self.body.append(self.starttag(node, 'span', '', CLASS='classifier')) def depart_classifier(self, node): self.body.append('</span>') def visit_colspec(self, node): self.colspecs.append(node) # "stubs" list is an attribute of the tgroup element: node.parent.stubs.append(node.attributes.get('stub')) def depart_colspec(self, node): pass def write_colspecs(self): width = 0 for node in self.colspecs: width += node['colwidth'] for node in self.colspecs: colwidth = int(node['colwidth'] * 100.0 / width + 0.5) self.body.append(self.emptytag(node, 'col', width='%i%%' % colwidth)) self.colspecs = [] def visit_comment(self, node, sub=re.compile('-(?=-)').sub): """Escape double-dashes in comment text.""" self.body.append('<!-- %s -->\n' % sub('- ', node.astext())) # Content already processed: raise nodes.SkipNode def visit_compound(self, node): self.body.append(self.starttag(node, 'div', CLASS='compound')) if len(node) > 1: node[0]['classes'].append('compound-first') node[-1]['classes'].append('compound-last') for child in node[1:-1]: child['classes'].append('compound-middle') def depart_compound(self, node): self.body.append('</div>\n') def visit_contact(self, node): self.visit_docinfo_item(node, 'contact', meta=None) def depart_contact(self, node): self.depart_docinfo_item() def visit_copyright(self, node): self.visit_docinfo_item(node, 'copyright') def depart_copyright(self, node): self.depart_docinfo_item() def visit_danger(self, node): self.visit_admonition(node, 'danger') def depart_danger(self, node): self.depart_admonition() def visit_date(self, node): self.visit_docinfo_item(node, 'date') def depart_date(self, node): self.depart_docinfo_item() def visit_decoration(self, node): pass def depart_decoration(self, node): pass def visit_definition(self, node): self.body.append('</dt>\n') self.body.append(self.starttag(node, 'dd', '')) self.set_first_last(node) def depart_definition(self, node): self.body.append('</dd>\n') def visit_definition_list(self, node): self.body.append(self.starttag(node, 'dl', CLASS='docutils')) def depart_definition_list(self, node): self.body.append('</dl>\n') def visit_definition_list_item(self, node): pass def depart_definition_list_item(self, node): pass def visit_description(self, node): self.body.append(self.starttag(node, 'td', '')) self.set_first_last(node) def depart_description(self, node): self.body.append('</td>') def visit_docinfo(self, node): self.context.append(len(self.body)) self.body.append(self.starttag(node, 'table', CLASS='docinfo', frame="void", rules="none")) self.body.append('<col class="docinfo-name" />\n' '<col class="docinfo-content" />\n' '<tbody valign="top">\n') self.in_docinfo = 1 def depart_docinfo(self, node): self.body.append('</tbody>\n</table>\n') self.in_docinfo = None start = self.context.pop() self.docinfo = self.body[start:] self.body = [] def visit_docinfo_item(self, node, name, meta=1): if meta: meta_tag = '<meta name="%s" content="%s" />\n' \ % (name, self.attval(node.astext())) self.add_meta(meta_tag) self.body.append(self.starttag(node, 'tr', '')) self.body.append('<th class="docinfo-name">%s:</th>\n<td>' % self.language.labels[name]) if len(node): if isinstance(node[0], nodes.Element): node[0]['classes'].append('first') if isinstance(node[-1], nodes.Element): node[-1]['classes'].append('last') def depart_docinfo_item(self): self.body.append('</td></tr>\n') def visit_doctest_block(self, node): self.body.append(self.starttag(node, 'pre', CLASS='doctest-block')) def depart_doctest_block(self, node): self.body.append('\n</pre>\n') def visit_document(self, node): # empty or untitled document? if not len(node) or not isinstance(node[0], nodes.title): # for XHTML conformance, modulo IE6 appeasement: self.head.append('<title></title>\n') def depart_document(self, node): self.fragment.extend(self.body) self.body_prefix.append(self.starttag(node, 'div', CLASS='document')) self.body_suffix.insert(0, '</div>\n') # skip content-type meta tag with interpolated charset value: self.html_head.extend(self.head[1:]) self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo + self.docinfo + self.body + self.body_suffix[:-1]) def visit_emphasis(self, node): self.body.append('<em>') def depart_emphasis(self, node): self.body.append('</em>') def visit_entry(self, node): atts = {'class': []} if isinstance(node.parent.parent, nodes.thead): atts['class'].append('head') if node.parent.parent.parent.stubs[node.parent.column]: # "stubs" list is an attribute of the tgroup element atts['class'].append('stub') if atts['class']: tagname = 'th' atts['class'] = ' '.join(atts['class']) else: tagname = 'td' del atts['class'] node.parent.column += 1 if node.has_key('morerows'): atts['rowspan'] = node['morerows'] + 1 if node.has_key('morecols'): atts['colspan'] = node['morecols'] + 1 node.parent.column += node['morecols'] self.body.append(self.starttag(node, tagname, '', **atts)) self.context.append('</%s>\n' % tagname.lower()) if len(node) == 0: # empty cell self.body.append('&nbsp;') self.set_first_last(node) def depart_entry(self, node): self.body.append(self.context.pop()) def visit_enumerated_list(self, node): """ The 'start' attribute does not conform to HTML 4.01's strict.dtd, but CSS1 doesn't help. CSS2 isn't widely enough supported yet to be usable. """ atts = {} if node.has_key('start'): atts['start'] = node['start'] if node.has_key('enumtype'): atts['class'] = node['enumtype'] # @@@ To do: prefix, suffix. How? Change prefix/suffix to a # single "format" attribute? Use CSS2? old_compact_simple = self.compact_simple self.context.append((self.compact_simple, self.compact_p)) self.compact_p = None self.compact_simple = (self.settings.compact_lists and (self.compact_simple or self.topic_classes == ['contents'] or self.check_simple_list(node))) if self.compact_simple and not old_compact_simple: atts['class'] = (atts.get('class', '') + ' simple').strip() self.body.append(self.starttag(node, 'ol', **atts)) def depart_enumerated_list(self, node): self.compact_simple, self.compact_p = self.context.pop() self.body.append('</ol>\n') def visit_error(self, node): self.visit_admonition(node, 'error') def depart_error(self, node): self.depart_admonition() def visit_field(self, node): self.body.append(self.starttag(node, 'tr', '', CLASS='field')) def depart_field(self, node): self.body.append('</tr>\n') def visit_field_body(self, node): self.body.append(self.starttag(node, 'td', '', CLASS='field-body')) self.set_first_last(node) def depart_field_body(self, node): self.body.append('</td>\n') def visit_field_list(self, node): self.body.append(self.starttag(node, 'table', frame='void', rules='none', CLASS='docutils field-list')) self.body.append('<col class="field-name" />\n' '<col class="field-body" />\n' '<tbody valign="top">\n') def depart_field_list(self, node): self.body.append('</tbody>\n</table>\n') def visit_field_name(self, node): atts = {} if self.in_docinfo: atts['class'] = 'docinfo-name' else: atts['class'] = 'field-name' if ( self.settings.field_name_limit and len(node.astext()) > self.settings.field_name_limit): atts['colspan'] = 2 self.context.append('</tr>\n<tr><td>&nbsp;</td>') else: self.context.append('') self.body.append(self.starttag(node, 'th', '', **atts)) def depart_field_name(self, node): self.body.append(':</th>') self.body.append(self.context.pop()) def visit_figure(self, node): atts = {'class': 'figure'} if node.get('width'): atts['style'] = 'width: %spx' % node['width'] if node.get('align'): atts['align'] = node['align'] self.body.append(self.starttag(node, 'div', **atts)) def depart_figure(self, node): self.body.append('</div>\n') def visit_footer(self, node): self.context.append(len(self.body)) def depart_footer(self, node): start = self.context.pop() footer = [self.starttag(node, 'div', CLASS='footer'), '<hr class="footer" />\n'] footer.extend(self.body[start:]) footer.append('\n</div>\n') self.footer.extend(footer) self.body_suffix[:0] = footer del self.body[start:] def visit_footnote(self, node): self.body.append(self.starttag(node, 'table', CLASS='docutils footnote', frame="void", rules="none")) self.body.append('<colgroup><col class="label" /><col /></colgroup>\n' '<tbody valign="top">\n' '<tr>') self.footnote_backrefs(node) def footnote_backrefs(self, node): backlinks = [] backrefs = node['backrefs'] if self.settings.footnote_backlinks and backrefs: if len(backrefs) == 1: self.context.append('') self.context.append( '<a class="fn-backref" href="#%s" name="%s">' % (backrefs[0], node['ids'][0])) else: i = 1 for backref in backrefs: backlinks.append('<a class="fn-backref" href="#%s">%s</a>' % (backref, i)) i += 1 self.context.append('<em>(%s)</em> ' % ', '.join(backlinks)) self.context.append('<a name="%s">' % node['ids'][0]) else: self.context.append('') self.context.append('<a name="%s">' % node['ids'][0]) # If the node does not only consist of a label. if len(node) > 1: # If there are preceding backlinks, we do not set class # 'first', because we need to retain the top-margin. if not backlinks: node[1]['classes'].append('first') node[-1]['classes'].append('last') def depart_footnote(self, node): self.body.append('</td></tr>\n' '</tbody>\n</table>\n') def visit_footnote_reference(self, node): href = '#' + node['refid'] format = self.settings.footnote_references if format == 'brackets': suffix = '[' self.context.append(']') else: assert format == 'superscript' suffix = '<sup>' self.context.append('</sup>') self.body.append(self.starttag(node, 'a', suffix, CLASS='footnote-reference', href=href)) def depart_footnote_reference(self, node): self.body.append(self.context.pop() + '</a>') def visit_generated(self, node): pass def depart_generated(self, node): pass def visit_header(self, node): self.context.append(len(self.body)) def depart_header(self, node): start = self.context.pop() header = [self.starttag(node, 'div', CLASS='header')] header.extend(self.body[start:]) header.append('\n<hr class="header"/>\n</div>\n') self.body_prefix.extend(header) self.header.extend(header) del self.body[start:] def visit_hint(self, node): self.visit_admonition(node, 'hint') def depart_hint(self, node): self.depart_admonition() def visit_image(self, node): atts = node.non_default_attributes() if atts.has_key('classes'): del atts['classes'] # prevent duplication with node attrs atts['src'] = atts['uri'] del atts['uri'] if atts.has_key('scale'): if Image and not (atts.has_key('width') and atts.has_key('height')): try: im = Image.open(str(atts['src'])) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. pass else: if not atts.has_key('width'): atts['width'] = im.size[0] if not atts.has_key('height'): atts['height'] = im.size[1] del im if atts.has_key('width'): atts['width'] = int(round(atts['width'] * (float(atts['scale']) / 100))) if atts.has_key('height'): atts['height'] = int(round(atts['height'] * (float(atts['scale']) / 100))) del atts['scale'] if not atts.has_key('alt'): atts['alt'] = atts['src'] if isinstance(node.parent, nodes.TextElement): self.context.append('') else: div_atts = self.image_div_atts(node) self.body.append(self.starttag({}, 'div', '', **div_atts)) self.context.append('</div>\n') self.body.append(self.emptytag(node, 'img', '', **atts)) def image_div_atts(self, image_node): div_atts = {} div_atts['class'] = ' '.join(['image'] + image_node['classes']) if image_node.attributes.has_key('align'): div_atts['align'] = self.attval(image_node.attributes['align']) div_atts['class'] += ' align-%s' % div_atts['align'] return div_atts def depart_image(self, node): self.body.append(self.context.pop()) def visit_important(self, node): self.visit_admonition(node, 'important') def depart_important(self, node): self.depart_admonition() def visit_inline(self, node): self.body.append(self.starttag(node, 'span', '')) def depart_inline(self, node): self.body.append('</span>') def visit_label(self, node): self.body.append(self.starttag(node, 'td', '%s[' % self.context.pop(), CLASS='label')) def depart_label(self, node): self.body.append(']</a></td><td>%s' % self.context.pop()) def visit_legend(self, node): self.body.append(self.starttag(node, 'div', CLASS='legend')) def depart_legend(self, node): self.body.append('</div>\n') def visit_line(self, node): self.body.append(self.starttag(node, 'div', suffix='', CLASS='line')) if not len(node): self.body.append('<br />') def depart_line(self, node): self.body.append('</div>\n') def visit_line_block(self, node): self.body.append(self.starttag(node, 'div', CLASS='line-block')) def depart_line_block(self, node): self.body.append('</div>\n') def visit_list_item(self, node): self.body.append(self.starttag(node, 'li', '')) if len(node): node[0]['classes'].append('first') def depart_list_item(self, node): self.body.append('</li>\n') def visit_literal(self, node): """Process text to prevent tokens from wrapping.""" self.body.append( self.starttag(node, 'tt', '', CLASS='docutils literal')) text = node.astext() for token in self.words_and_spaces.findall(text): if token.strip(): # Protect text like "--an-option" from bad line wrapping: self.body.append('<span class="pre">%s</span>' % self.encode(token)) elif token in ('\n', ' '): # Allow breaks at whitespace: self.body.append(token) else: # Protect runs of multiple spaces; the last space can wrap: self.body.append('&nbsp;' * (len(token) - 1) + ' ') self.body.append('</tt>') # Content already processed: raise nodes.SkipNode def visit_literal_block(self, node): self.body.append(self.starttag(node, 'pre', CLASS='literal-block')) def depart_literal_block(self, node): self.body.append('\n</pre>\n') def visit_meta(self, node): meta = self.emptytag(node, 'meta', **node.non_default_attributes()) self.add_meta(meta) def depart_meta(self, node): pass def add_meta(self, tag): self.meta.append(tag) self.head.append(tag) def visit_note(self, node): self.visit_admonition(node, 'note') def depart_note(self, node): self.depart_admonition() def visit_option(self, node): if self.context[-1]: self.body.append(', ') self.body.append(self.starttag(node, 'span', '', CLASS='option')) def depart_option(self, node): self.body.append('</span>') self.context[-1] += 1 def visit_option_argument(self, node): self.body.append(node.get('delimiter', ' ')) self.body.append(self.starttag(node, 'var', '')) def depart_option_argument(self, node): self.body.append('</var>') def visit_option_group(self, node): atts = {} if ( self.settings.option_limit and len(node.astext()) > self.settings.option_limit): atts['colspan'] = 2 self.context.append('</tr>\n<tr><td>&nbsp;</td>') else: self.context.append('') self.body.append( self.starttag(node, 'td', CLASS='option-group', **atts)) self.body.append('<kbd>') self.context.append(0) # count number of options def depart_option_group(self, node): self.context.pop() self.body.append('</kbd></td>\n') self.body.append(self.context.pop()) def visit_option_list(self, node): self.body.append( self.starttag(node, 'table', CLASS='docutils option-list', frame="void", rules="none")) self.body.append('<col class="option" />\n' '<col class="description" />\n' '<tbody valign="top">\n') def depart_option_list(self, node): self.body.append('</tbody>\n</table>\n') def visit_option_list_item(self, node): self.body.append(self.starttag(node, 'tr', '')) def depart_option_list_item(self, node): self.body.append('</tr>\n') def visit_option_string(self, node): pass def depart_option_string(self, node): pass def visit_organization(self, node): self.visit_docinfo_item(node, 'organization') def depart_organization(self, node): self.depart_docinfo_item() def should_be_compact_paragraph(self, node): """ Determine if the <p> tags around paragraph ``node`` can be omitted. """ if (isinstance(node.parent, nodes.document) or isinstance(node.parent, nodes.compound)): # Never compact paragraphs in document or compound. return 0 for key, value in node.attlist(): if (node.is_not_default(key) and not (key == 'classes' and value in ([], ['first'], ['last'], ['first', 'last']))): # Attribute which needs to survive. return 0 if (self.compact_simple or self.compact_p and (len(node.parent) == 1 or len(node.parent) == 2 and isinstance(node.parent[0], nodes.label))): return 1 return 0 def visit_paragraph(self, node): if self.should_be_compact_paragraph(node): self.context.append('') else: self.body.append(self.starttag(node, 'p', '')) self.context.append('</p>\n') def depart_paragraph(self, node): self.body.append(self.context.pop()) def visit_problematic(self, node): if node.hasattr('refid'): self.body.append('<a href="#%s" name="%s">' % (node['refid'], node['ids'][0])) self.context.append('</a>') else: self.context.append('') self.body.append(self.starttag(node, 'span', '', CLASS='problematic')) def depart_problematic(self, node): self.body.append('</span>') self.body.append(self.context.pop()) def visit_raw(self, node): if 'html' in node.get('format', '').split(): t = isinstance(node.parent, nodes.TextElement) and 'span' or 'div' if node['classes']: self.body.append(self.starttag(node, t, suffix='')) self.body.append(node.astext()) if node['classes']: self.body.append('</%s>' % t) # Keep non-HTML raw text out of output: raise nodes.SkipNode def visit_reference(self, node): if isinstance(node.parent, nodes.TextElement): self.context.append('') else: # contains an image assert len(node) == 1 and isinstance(node[0], nodes.image) div_atts = self.image_div_atts(node[0]) div_atts['class'] += ' image-reference' self.body.append(self.starttag({}, 'div', '', **div_atts)) self.context.append('</div>\n') if node.has_key('refuri'): href = node['refuri'] if ( self.settings.cloak_email_addresses and href.startswith('mailto:')): href = self.cloak_mailto(href) self.in_mailto = 1 else: assert node.has_key('refid'), \ 'References must have "refuri" or "refid" attribute.' href = '#' + node['refid'] self.body.append(self.starttag(node, 'a', '', CLASS='reference', href=href)) def depart_reference(self, node): self.body.append('</a>') self.body.append(self.context.pop()) self.in_mailto = 0 def visit_revision(self, node): self.visit_docinfo_item(node, 'revision', meta=None) def depart_revision(self, node): self.depart_docinfo_item() def visit_row(self, node): self.body.append(self.starttag(node, 'tr', '')) node.column = 0 def depart_row(self, node): self.body.append('</tr>\n') def visit_rubric(self, node): self.body.append(self.starttag(node, 'p', '', CLASS='rubric')) def depart_rubric(self, node): self.body.append('</p>\n') def visit_section(self, node): self.section_level += 1 self.body.append(self.starttag(node, 'div', CLASS='section')) def depart_section(self, node): self.section_level -= 1 self.body.append('</div>\n') def visit_sidebar(self, node): self.body.append(self.starttag(node, 'div', CLASS='sidebar')) self.set_first_last(node) self.in_sidebar = 1 def depart_sidebar(self, node): self.body.append('</div>\n') self.in_sidebar = None def visit_status(self, node): self.visit_docinfo_item(node, 'status', meta=None) def depart_status(self, node): self.depart_docinfo_item() def visit_strong(self, node): self.body.append('<strong>') def depart_strong(self, node): self.body.append('</strong>') def visit_subscript(self, node): self.body.append(self.starttag(node, 'sub', '')) def depart_subscript(self, node): self.body.append('</sub>') def visit_substitution_definition(self, node): """Internal only.""" raise nodes.SkipNode def visit_substitution_reference(self, node): self.unimplemented_visit(node) def visit_subtitle(self, node): if isinstance(node.parent, nodes.sidebar): self.body.append(self.starttag(node, 'p', '', CLASS='sidebar-subtitle')) self.context.append('</p>\n') elif isinstance(node.parent, nodes.document): self.body.append(self.starttag(node, 'h2', '', CLASS='subtitle')) self.context.append('</h2>\n') self.in_document_title = len(self.body) elif isinstance(node.parent, nodes.section): tag = 'h%s' % (self.section_level + self.initial_header_level - 1) self.body.append( self.starttag(node, tag, '', CLASS='section-subtitle') + self.starttag({}, 'span', '', CLASS='section-subtitle')) self.context.append('</span></%s>\n' % tag) def depart_subtitle(self, node): self.body.append(self.context.pop()) if self.in_document_title: self.subtitle = self.body[self.in_document_title:-1] self.in_document_title = 0 self.body_pre_docinfo.extend(self.body) self.html_subtitle.extend(self.body) del self.body[:] def visit_superscript(self, node): self.body.append(self.starttag(node, 'sup', '')) def depart_superscript(self, node): self.body.append('</sup>') def visit_system_message(self, node): if node['level'] < self.document.reporter.report_level: # Level is too low to display: raise nodes.SkipNode self.body.append(self.starttag(node, 'div', CLASS='system-message')) self.body.append('<p class="system-message-title">') attr = {} backref_text = '' if node['ids']: attr['name'] = node['ids'][0] if len(node['backrefs']): backrefs = node['backrefs'] if len(backrefs) == 1: backref_text = ('; <em><a href="#%s">backlink</a></em>' % backrefs[0]) else: i = 1 backlinks = [] for backref in backrefs: backlinks.append('<a href="#%s">%s</a>' % (backref, i)) i += 1 backref_text = ('; <em>backlinks: %s</em>' % ', '.join(backlinks)) if node.hasattr('line'): line = ', line %s' % node['line'] else: line = '' if attr: a_start = self.starttag({}, 'a', '', **attr) a_end = '</a>' else: a_start = a_end = '' self.body.append('System Message: %s%s/%s%s ' '(<tt class="docutils">%s</tt>%s)%s</p>\n' % (a_start, node['type'], node['level'], a_end, self.encode(node['source']), line, backref_text)) def depart_system_message(self, node): self.body.append('</div>\n') def visit_table(self, node): self.body.append( self.starttag(node, 'table', CLASS='docutils', border="1")) def depart_table(self, node): self.body.append('</table>\n') def visit_target(self, node): if not (node.has_key('refuri') or node.has_key('refid') or node.has_key('refname')): self.body.append(self.starttag(node, 'span', '', CLASS='target')) self.context.append('</span>') else: self.context.append('') def depart_target(self, node): self.body.append(self.context.pop()) def visit_tbody(self, node): self.write_colspecs() self.body.append(self.context.pop()) # '</colgroup>\n' or '' self.body.append(self.starttag(node, 'tbody', valign='top')) def depart_tbody(self, node): self.body.append('</tbody>\n') def visit_term(self, node): self.body.append(self.starttag(node, 'dt', '')) def depart_term(self, node): """ Leave the end tag to `self.visit_definition()`, in case there's a classifier. """ pass def visit_tgroup(self, node): # Mozilla needs <colgroup>: self.body.append(self.starttag(node, 'colgroup')) # Appended by thead or tbody: self.context.append('</colgroup>\n') node.stubs = [] def depart_tgroup(self, node): pass def visit_thead(self, node): self.write_colspecs() self.body.append(self.context.pop()) # '</colgroup>\n' # There may or may not be a <thead>; this is for <tbody> to use: self.context.append('') self.body.append(self.starttag(node, 'thead', valign='bottom')) def depart_thead(self, node): self.body.append('</thead>\n') def visit_tip(self, node): self.visit_admonition(node, 'tip') def depart_tip(self, node): self.depart_admonition() def visit_title(self, node): """Only 6 section levels are supported by HTML.""" check_id = 0 close_tag = '</p>\n' if isinstance(node.parent, nodes.topic): self.body.append( self.starttag(node, 'p', '', CLASS='topic-title first')) check_id = 1 elif isinstance(node.parent, nodes.sidebar): self.body.append( self.starttag(node, 'p', '', CLASS='sidebar-title')) check_id = 1 elif isinstance(node.parent, nodes.Admonition): self.body.append( self.starttag(node, 'p', '', CLASS='admonition-title')) check_id = 1 elif isinstance(node.parent, nodes.table): self.body.append( self.starttag(node, 'caption', '')) check_id = 1 close_tag = '</caption>\n' elif self.section_level == 0: assert node.parent is self.document # document title self.head.append('<title>%s</title>\n' % self.encode(node.astext())) self.body.append(self.starttag(node, 'h1', '', CLASS='title')) self.context.append('</h1>\n') self.in_document_title = len(self.body) else: assert isinstance(node.parent, nodes.section) h_level = self.section_level + self.initial_header_level - 1 atts = {} if (len(node.parent) >= 2 and isinstance(node.parent[1], nodes.subtitle)): atts['CLASS'] = 'with-subtitle' self.body.append( self.starttag(node, 'h%s' % h_level, '', **atts)) atts = {} if node.parent['ids']: atts['name'] = node.parent['ids'][0] if node.hasattr('refid'): atts['class'] = 'toc-backref' atts['href'] = '#' + node['refid'] self.body.append(self.starttag({}, 'a', '', **atts)) self.context.append('</a></h%s>\n' % (h_level)) if check_id: if node.parent['ids']: self.body.append( self.starttag({}, 'a', '', name=node.parent['ids'][0])) self.context.append('</a>' + close_tag) else: self.context.append(close_tag) def depart_title(self, node): self.body.append(self.context.pop()) if self.in_document_title: self.title = self.body[self.in_document_title:-1] self.in_document_title = 0 self.body_pre_docinfo.extend(self.body) self.html_title.extend(self.body) del self.body[:] def visit_title_reference(self, node): self.body.append(self.starttag(node, 'cite', '')) def depart_title_reference(self, node): self.body.append('</cite>') def visit_topic(self, node): self.body.append(self.starttag(node, 'div', CLASS='topic')) self.topic_classes = node['classes'] def depart_topic(self, node): self.body.append('</div>\n') self.topic_classes = [] def visit_transition(self, node): self.body.append(self.emptytag(node, 'hr', CLASS='docutils')) def depart_transition(self, node): pass def visit_version(self, node): self.visit_docinfo_item(node, 'version', meta=None) def depart_version(self, node): self.depart_docinfo_item() def visit_warning(self, node): self.visit_admonition(node, 'warning') def depart_warning(self, node): self.depart_admonition() def unimplemented_visit(self, node): raise NotImplementedError('visiting unimplemented node type: %s' % node.__class__.__name__) class SimpleListChecker(nodes.GenericNodeVisitor): """ Raise `nodes.NodeFound` if non-simple list item is encountered. Here "simple" means a list item containing nothing other than a single paragraph, a simple list, or a paragraph followed by a simple list. """ def default_visit(self, node): raise nodes.NodeFound def visit_bullet_list(self, node): pass def visit_enumerated_list(self, node): pass def visit_list_item(self, node): children = [] for child in node.children: if not isinstance(child, nodes.Invisible): children.append(child) if (children and isinstance(children[0], nodes.paragraph) and (isinstance(children[-1], nodes.bullet_list) or isinstance(children[-1], nodes.enumerated_list))): children.pop() if len(children) <= 1: return else: raise nodes.NodeFound def visit_paragraph(self, node): raise nodes.SkipNode def invisible_visit(self, node): """Invisible nodes should be ignored.""" raise nodes.SkipNode visit_comment = invisible_visit visit_substitution_definition = invisible_visit visit_target = invisible_visit visit_pending = invisible_visit
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/writers/html4css1.py", "copies": "1", "size": "55256", "license": "mit", "hash": 4577987746982337000, "line_mean": 36.4616949153, "line_max": 79, "alpha_frac": 0.5473432749, "autogenerated": false, "ratio": 3.9389791844881663, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9984051009640895, "avg_score": 0.00045428994945421694, "num_lines": 1475 }
""" This is ``docutils.parsers.rst`` package. It exports a single class, `Parser`, the reStructuredText parser. Usage ===== 1. Create a parser:: parser = docutils.parsers.rst.Parser() Several optional arguments may be passed to modify the parser's behavior. Please see `Customizing the Parser`_ below for details. 2. Gather input (a multi-line string), by reading a file or the standard input:: input = sys.stdin.read() 3. Create a new empty `docutils.nodes.document` tree:: document = docutils.utils.new_document(source, settings) See `docutils.utils.new_document()` for parameter details. 4. Run the parser, populating the document tree:: parser.parse(input, document) Parser Overview =============== The reStructuredText parser is implemented as a state machine, examining its input one line at a time. To understand how the parser works, please first become familiar with the `docutils.statemachine` module, then see the `states` module. Customizing the Parser ---------------------- Anything that isn't already customizable is that way simply because that type of customizability hasn't been implemented yet. Patches welcome! When instantiating an object of the `Parser` class, two parameters may be passed: ``rfc2822`` and ``inliner``. Pass ``rfc2822=1`` to enable an initial RFC-2822 style header block, parsed as a "field_list" element (with "class" attribute set to "rfc2822"). Currently this is the only body-level element which is customizable without subclassing. (Tip: subclass `Parser` and change its "state_classes" and "initial_state" attributes to refer to new classes. Contact the author if you need more details.) The ``inliner`` parameter takes an instance of `states.Inliner` or a subclass. It handles inline markup recognition. A common extension is the addition of further implicit hyperlinks, like "RFC 2822". This can be done by subclassing `states.Inliner`, adding a new method for the implicit markup, and adding a ``(pattern, method)`` pair to the "implicit_dispatch" attribute of the subclass. See `states.Inliner.implicit_inline()` for details. Explicit inline markup can be customized in a `states.Inliner` subclass via the ``patterns.initial`` and ``dispatch`` attributes (and new methods as appropriate). """ __docformat__ = 'reStructuredText' import docutils.parsers import docutils.statemachine from docutils.parsers.rst import states from docutils import frontend class Parser(docutils.parsers.Parser): """The reStructuredText parser.""" supported = ('restructuredtext', 'rst', 'rest', 'restx', 'rtxt', 'rstx') """Aliases this parser supports.""" settings_spec = ( 'reStructuredText Parser Options', None, (('Recognize and link to standalone PEP references (like "PEP 258").', ['--pep-references'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Base URL for PEP references ' '(default "http://www.python.org/peps/").', ['--pep-base-url'], {'metavar': '<URL>', 'default': 'http://www.python.org/peps/', 'validator': frontend.validate_url_trailing_slash}), ('Recognize and link to standalone RFC references (like "RFC 822").', ['--rfc-references'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Base URL for RFC references (default "http://www.faqs.org/rfcs/").', ['--rfc-base-url'], {'metavar': '<URL>', 'default': 'http://www.faqs.org/rfcs/', 'validator': frontend.validate_url_trailing_slash}), ('Set number of spaces for tab expansion (default 8).', ['--tab-width'], {'metavar': '<width>', 'type': 'int', 'default': 8, 'validator': frontend.validate_nonnegative_int}), ('Remove spaces before footnote references.', ['--trim-footnote-reference-space'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Leave spaces before footnote references.', ['--leave-footnote-reference-space'], {'action': 'store_false', 'dest': 'trim_footnote_reference_space', 'validator': frontend.validate_boolean}), ('Disable directives that insert the contents of external file ' '("include" & "raw"); replaced with a "warning" system message.', ['--no-file-insertion'], {'action': 'store_false', 'default': 1, 'dest': 'file_insertion_enabled'}), ('Enable directives that insert the contents of external file ' '("include" & "raw"). Enabled by default.', ['--file-insertion-enabled'], {'action': 'store_true', 'dest': 'file_insertion_enabled'}), ('Disable the "raw" directives; replaced with a "warning" ' 'system message.', ['--no-raw'], {'action': 'store_false', 'default': 1, 'dest': 'raw_enabled'}), ('Enable the "raw" directive. Enabled by default.', ['--raw-enabled'], {'action': 'store_true', 'dest': 'raw_enabled'}),)) config_section = 'restructuredtext parser' config_section_dependencies = ('parsers',) def __init__(self, rfc2822=None, inliner=None): if rfc2822: self.initial_state = 'RFC2822Body' else: self.initial_state = 'Body' self.state_classes = states.state_classes self.inliner = inliner def parse(self, inputstring, document): """Parse `inputstring` and populate `document`, a document tree.""" self.setup_parse(inputstring, document) self.statemachine = states.RSTStateMachine( state_classes=self.state_classes, initial_state=self.initial_state, debug=document.reporter.debug_flag) inputlines = docutils.statemachine.string2lines( inputstring, tab_width=document.settings.tab_width, convert_whitespace=1) self.statemachine.run(inputlines, document, inliner=self.inliner) self.finish_parse()
{ "repo_name": "pombreda/django-hotclub", "path": "libs/external_libs/docutils-0.4/docutils/parsers/rst/__init__.py", "copies": "6", "size": "6329", "license": "mit", "hash": 5417372759955751000, "line_mean": 39.5705128205, "line_max": 79, "alpha_frac": 0.6508137146, "autogenerated": false, "ratio": 4.07533805537669, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.772615176997669, "avg_score": null, "num_lines": null }
""" Standalone file Reader for the reStructuredText markup syntax. """ __docformat__ = 'reStructuredText' import sys from docutils import frontend, readers from docutils.transforms import frontmatter, references, misc class Reader(readers.Reader): supported = ('standalone',) """Contexts this reader supports.""" document = None """A single document tree.""" settings_spec = ( 'Standalone Reader', None, (('Disable the promotion of a lone top-level section title to ' 'document title (and subsequent section title to document ' 'subtitle promotion; enabled by default).', ['--no-doc-title'], {'dest': 'doctitle_xform', 'action': 'store_false', 'default': 1, 'validator': frontend.validate_boolean}), ('Disable the bibliographic field list transform (enabled by ' 'default).', ['--no-doc-info'], {'dest': 'docinfo_xform', 'action': 'store_false', 'default': 1, 'validator': frontend.validate_boolean}), ('Activate the promotion of lone subsection titles to ' 'section subtitles (disabled by default).', ['--section-subtitles'], {'dest': 'sectsubtitle_xform', 'action': 'store_true', 'default': 0, 'validator': frontend.validate_boolean}), ('Deactivate the promotion of lone subsection titles.', ['--no-section-subtitles'], {'dest': 'sectsubtitle_xform', 'action': 'store_false', 'validator': frontend.validate_boolean}), )) config_section = 'standalone reader' config_section_dependencies = ('readers',) def get_transforms(self): return readers.Reader.get_transforms(self) + [ references.Substitutions, references.PropagateTargets, frontmatter.DocTitle, frontmatter.SectionSubTitle, frontmatter.DocInfo, references.AnonymousHyperlinks, references.IndirectHyperlinks, references.Footnotes, references.ExternalTargets, references.InternalTargets, references.DanglingReferences, misc.Transitions, ]
{ "repo_name": "indro/t2c", "path": "libs/external_libs/docutils-0.4/docutils/readers/standalone.py", "copies": "6", "size": "2446", "license": "mit", "hash": 5865114134493468000, "line_mean": 34.4492753623, "line_max": 78, "alpha_frac": 0.618152085, "autogenerated": false, "ratio": 4.391382405745063, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8009534490745062, "avg_score": null, "num_lines": null }
""" Docutils component-related transforms. """ __docformat__ = 'reStructuredText' import sys import os import re import time from docutils import nodes, utils from docutils import ApplicationError, DataError from docutils.transforms import Transform, TransformError class Filter(Transform): """ Include or exclude elements which depend on a specific Docutils component. For use with `nodes.pending` elements. A "pending" element's dictionary attribute ``details`` must contain the keys "component" and "format". The value of ``details['component']`` must match the type name of the component the elements depend on (e.g. "writer"). The value of ``details['format']`` is the name of a specific format or context of that component (e.g. "html"). If the matching Docutils component supports that format or context, the "pending" element is replaced by the contents of ``details['nodes']`` (a list of nodes); otherwise, the "pending" element is removed. For example, the reStructuredText "meta" directive creates a "pending" element containing a "meta" element (in ``pending.details['nodes']``). Only writers (``pending.details['component'] == 'writer'``) supporting the "html" format (``pending.details['format'] == 'html'``) will include the "meta" element; it will be deleted from the output of all other writers. """ default_priority = 780 def apply(self): pending = self.startnode component_type = pending.details['component'] # 'reader' or 'writer' format = pending.details['format'] component = self.document.transformer.components[component_type] if component.supports(format): pending.replace_self(pending.details['nodes']) else: pending.parent.remove(pending)
{ "repo_name": "santisiri/popego", "path": "envs/ALPHA-POPEGO/lib/python2.5/site-packages/docutils-0.4-py2.5.egg/docutils/transforms/components.py", "copies": "6", "size": "2048", "license": "bsd-3-clause", "hash": 6767429614682201000, "line_mean": 36.9259259259, "line_max": 78, "alpha_frac": 0.6962890625, "autogenerated": false, "ratio": 4.137373737373737, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7833662799873737, "avg_score": null, "num_lines": null }
""" Transforms for PEP processing. - `Headers`: Used to transform a PEP's initial RFC-2822 header. It remains a field list, but some entries get processed. - `Contents`: Auto-inserts a table of contents. - `PEPZero`: Special processing for PEP 0. """ __docformat__ = 'reStructuredText' import sys import os import re import time from docutils import nodes, utils, languages from docutils import ApplicationError, DataError from docutils.transforms import Transform, TransformError from docutils.transforms import parts, references, misc class Headers(Transform): """ Process fields in a PEP's initial RFC-2822 header. """ default_priority = 360 pep_url = 'pep-%04d.html' pep_cvs_url = ('http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/' 'python/nondist/peps/pep-%04d.txt') rcs_keyword_substitutions = ( (re.compile(r'\$' r'RCSfile: (.+),v \$$', re.IGNORECASE), r'\1'), (re.compile(r'\$[a-zA-Z]+: (.+) \$$'), r'\1'),) def apply(self): if not len(self.document): # @@@ replace these DataErrors with proper system messages raise DataError('Document tree is empty.') header = self.document[0] if not isinstance(header, nodes.field_list) or \ 'rfc2822' not in header['classes']: raise DataError('Document does not begin with an RFC-2822 ' 'header; it is not a PEP.') pep = None for field in header: if field[0].astext().lower() == 'pep': # should be the first field value = field[1].astext() try: pep = int(value) cvs_url = self.pep_cvs_url % pep except ValueError: pep = value cvs_url = None msg = self.document.reporter.warning( '"PEP" header must contain an integer; "%s" is an ' 'invalid value.' % pep, base_node=field) msgid = self.document.set_id(msg) prb = nodes.problematic(value, value or '(none)', refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) if len(field[1]): field[1][0][:] = [prb] else: field[1] += nodes.paragraph('', '', prb) break if pep is None: raise DataError('Document does not contain an RFC-2822 "PEP" ' 'header.') if pep == 0: # Special processing for PEP 0. pending = nodes.pending(PEPZero) self.document.insert(1, pending) self.document.note_pending(pending) if len(header) < 2 or header[1][0].astext().lower() != 'title': raise DataError('No title!') for field in header: name = field[0].astext().lower() body = field[1] if len(body) > 1: raise DataError('PEP header field body contains multiple ' 'elements:\n%s' % field.pformat(level=1)) elif len(body) == 1: if not isinstance(body[0], nodes.paragraph): raise DataError('PEP header field body may only contain ' 'a single paragraph:\n%s' % field.pformat(level=1)) elif name == 'last-modified': date = time.strftime( '%d-%b-%Y', time.localtime(os.stat(self.document['source'])[8])) if cvs_url: body += nodes.paragraph( '', '', nodes.reference('', date, refuri=cvs_url)) else: # empty continue para = body[0] if name == 'author': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node)) elif name == 'discussions-to': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node, pep)) elif name in ('replaces', 'replaced-by', 'requires'): newbody = [] space = nodes.Text(' ') for refpep in re.split(',?\s+', body.astext()): pepno = int(refpep) newbody.append(nodes.reference( refpep, refpep, refuri=(self.document.settings.pep_base_url + self.pep_url % pepno))) newbody.append(space) para[:] = newbody[:-1] # drop trailing space elif name == 'last-modified': utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) if cvs_url: date = para.astext() para[:] = [nodes.reference('', date, refuri=cvs_url)] elif name == 'content-type': pep_type = para.astext() uri = self.document.settings.pep_base_url + self.pep_url % 12 para[:] = [nodes.reference('', pep_type, refuri=uri)] elif name == 'version' and len(body): utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) class Contents(Transform): """ Insert an empty table of contents topic and a transform placeholder into the document after the RFC 2822 header. """ default_priority = 380 def apply(self): language = languages.get_language(self.document.settings.language_code) name = language.labels['contents'] title = nodes.title('', name) topic = nodes.topic('', title, classes=['contents']) name = nodes.fully_normalize_name(name) if not self.document.has_name(name): topic['names'].append(name) self.document.note_implicit_target(topic) pending = nodes.pending(parts.Contents) topic += pending self.document.insert(1, topic) self.document.note_pending(pending) class TargetNotes(Transform): """ Locate the "References" section, insert a placeholder for an external target footnote insertion transform at the end, and schedule the transform to run immediately. """ default_priority = 520 def apply(self): doc = self.document i = len(doc) - 1 refsect = copyright = None while i >= 0 and isinstance(doc[i], nodes.section): title_words = doc[i][0].astext().lower().split() if 'references' in title_words: refsect = doc[i] break elif 'copyright' in title_words: copyright = i i -= 1 if not refsect: refsect = nodes.section() refsect += nodes.title('', 'References') doc.set_id(refsect) if copyright: # Put the new "References" section before "Copyright": doc.insert(copyright, refsect) else: # Put the new "References" section at end of doc: doc.append(refsect) pending = nodes.pending(references.TargetNotes) refsect.append(pending) self.document.note_pending(pending, 0) pending = nodes.pending(misc.CallBack, details={'callback': self.cleanup_callback}) refsect.append(pending) self.document.note_pending(pending, 1) def cleanup_callback(self, pending): """ Remove an empty "References" section. Called after the `references.TargetNotes` transform is complete. """ if len(pending.parent) == 2: # <title> and <pending> pending.parent.parent.remove(pending.parent) class PEPZero(Transform): """ Special processing for PEP 0. """ default_priority =760 def apply(self): visitor = PEPZeroSpecial(self.document) self.document.walk(visitor) self.startnode.parent.remove(self.startnode) class PEPZeroSpecial(nodes.SparseNodeVisitor): """ Perform the special processing needed by PEP 0: - Mask email addresses. - Link PEP numbers in the second column of 4-column tables to the PEPs themselves. """ pep_url = Headers.pep_url def unknown_visit(self, node): pass def visit_reference(self, node): node.replace_self(mask_email(node)) def visit_field_list(self, node): if 'rfc2822' in node['classes']: raise nodes.SkipNode def visit_tgroup(self, node): self.pep_table = node['cols'] == 4 self.entry = 0 def visit_colspec(self, node): self.entry += 1 if self.pep_table and self.entry == 2: node['classes'].append('num') def visit_row(self, node): self.entry = 0 def visit_entry(self, node): self.entry += 1 if self.pep_table and self.entry == 2 and len(node) == 1: node['classes'].append('num') p = node[0] if isinstance(p, nodes.paragraph) and len(p) == 1: text = p.astext() try: pep = int(text) ref = (self.document.settings.pep_base_url + self.pep_url % pep) p[0] = nodes.reference(text, text, refuri=ref) except ValueError: pass non_masked_addresses = ('peps@python.org', 'python-list@python.org', 'python-dev@python.org') def mask_email(ref, pepno=None): """ Mask the email address in `ref` and return a replacement node. `ref` is returned unchanged if it contains no email address. For email addresses such as "user@host", mask the address as "user at host" (text) to thwart simple email address harvesters (except for those listed in `non_masked_addresses`). If a PEP number (`pepno`) is given, return a reference including a default email subject. """ if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'): if ref['refuri'][8:] in non_masked_addresses: replacement = ref[0] else: replacement_text = ref.astext().replace('@', '&#32;&#97;t&#32;') replacement = nodes.raw('', replacement_text, format='html') if pepno is None: return replacement else: ref['refuri'] += '?subject=PEP%%20%s' % pepno ref[:] = [replacement] return ref else: return ref
{ "repo_name": "indro/t2c", "path": "libs/external_libs/docutils-0.4/docutils/transforms/peps.py", "copies": "6", "size": "11092", "license": "mit", "hash": -1807713685569763600, "line_mean": 35.2483660131, "line_max": 79, "alpha_frac": 0.5353407862, "autogenerated": false, "ratio": 4.2416826003824095, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7777023386582409, "avg_score": null, "num_lines": null }
""" A finite state machine specialized for regular-expression-based text filters, this module defines the following classes: - `StateMachine`, a state machine - `State`, a state superclass - `StateMachineWS`, a whitespace-sensitive version of `StateMachine` - `StateWS`, a state superclass for use with `StateMachineWS` - `SearchStateMachine`, uses `re.search()` instead of `re.match()` - `SearchStateMachineWS`, uses `re.search()` instead of `re.match()` - `ViewList`, extends standard Python lists. - `StringList`, string-specific ViewList. Exception classes: - `StateMachineError` - `UnknownStateError` - `DuplicateStateError` - `UnknownTransitionError` - `DuplicateTransitionError` - `TransitionPatternNotFound` - `TransitionMethodNotFound` - `UnexpectedIndentationError` - `TransitionCorrection`: Raised to switch to another transition. - `StateCorrection`: Raised to switch to another state & transition. Functions: - `string2lines()`: split a multi-line string into a list of one-line strings How To Use This Module ====================== (See the individual classes, methods, and attributes for details.) 1. Import it: ``import statemachine`` or ``from statemachine import ...``. You will also need to ``import re``. 2. Derive a subclass of `State` (or `StateWS`) for each state in your state machine:: class MyState(statemachine.State): Within the state's class definition: a) Include a pattern for each transition, in `State.patterns`:: patterns = {'atransition': r'pattern', ...} b) Include a list of initial transitions to be set up automatically, in `State.initial_transitions`:: initial_transitions = ['atransition', ...] c) Define a method for each transition, with the same name as the transition pattern:: def atransition(self, match, context, next_state): # do something result = [...] # a list return context, next_state, result # context, next_state may be altered Transition methods may raise an `EOFError` to cut processing short. d) You may wish to override the `State.bof()` and/or `State.eof()` implicit transition methods, which handle the beginning- and end-of-file. e) In order to handle nested processing, you may wish to override the attributes `State.nested_sm` and/or `State.nested_sm_kwargs`. If you are using `StateWS` as a base class, in order to handle nested indented blocks, you may wish to: - override the attributes `StateWS.indent_sm`, `StateWS.indent_sm_kwargs`, `StateWS.known_indent_sm`, and/or `StateWS.known_indent_sm_kwargs`; - override the `StateWS.blank()` method; and/or - override or extend the `StateWS.indent()`, `StateWS.known_indent()`, and/or `StateWS.firstknown_indent()` methods. 3. Create a state machine object:: sm = StateMachine(state_classes=[MyState, ...], initial_state='MyState') 4. Obtain the input text, which needs to be converted into a tab-free list of one-line strings. For example, to read text from a file called 'inputfile':: input_string = open('inputfile').read() input_lines = statemachine.string2lines(input_string) 5. Run the state machine on the input text and collect the results, a list:: results = sm.run(input_lines) 6. Remove any lingering circular references:: sm.unlink() """ __docformat__ = 'restructuredtext' import sys import re import types import unicodedata class StateMachine: """ A finite state machine for text filters using regular expressions. The input is provided in the form of a list of one-line strings (no newlines). States are subclasses of the `State` class. Transitions consist of regular expression patterns and transition methods, and are defined in each state. The state machine is started with the `run()` method, which returns the results of processing in a list. """ def __init__(self, state_classes, initial_state, debug=0): """ Initialize a `StateMachine` object; add state objects. Parameters: - `state_classes`: a list of `State` (sub)classes. - `initial_state`: a string, the class name of the initial state. - `debug`: a boolean; produce verbose output if true (nonzero). """ self.input_lines = None """`StringList` of input lines (without newlines). Filled by `self.run()`.""" self.input_offset = 0 """Offset of `self.input_lines` from the beginning of the file.""" self.line = None """Current input line.""" self.line_offset = -1 """Current input line offset from beginning of `self.input_lines`.""" self.debug = debug """Debugging mode on/off.""" self.initial_state = initial_state """The name of the initial state (key to `self.states`).""" self.current_state = initial_state """The name of the current state (key to `self.states`).""" self.states = {} """Mapping of {state_name: State_object}.""" self.add_states(state_classes) self.observers = [] """List of bound methods or functions to call whenever the current line changes. Observers are called with one argument, ``self``. Cleared at the end of `run()`.""" def unlink(self): """Remove circular references to objects no longer required.""" for state in self.states.values(): state.unlink() self.states = None def run(self, input_lines, input_offset=0, context=None, input_source=None): """ Run the state machine on `input_lines`. Return results (a list). Reset `self.line_offset` and `self.current_state`. Run the beginning-of-file transition. Input one line at a time and check for a matching transition. If a match is found, call the transition method and possibly change the state. Store the context returned by the transition method to be passed on to the next transition matched. Accumulate the results returned by the transition methods in a list. Run the end-of-file transition. Finally, return the accumulated results. Parameters: - `input_lines`: a list of strings without newlines, or `StringList`. - `input_offset`: the line offset of `input_lines` from the beginning of the file. - `context`: application-specific storage. - `input_source`: name or path of source of `input_lines`. """ self.runtime_init() if isinstance(input_lines, StringList): self.input_lines = input_lines else: self.input_lines = StringList(input_lines, source=input_source) self.input_offset = input_offset self.line_offset = -1 self.current_state = self.initial_state if self.debug: print >>sys.stderr, ( '\nStateMachine.run: input_lines (line_offset=%s):\n| %s' % (self.line_offset, '\n| '.join(self.input_lines))) transitions = None results = [] state = self.get_state() try: if self.debug: print >>sys.stderr, ('\nStateMachine.run: bof transition') context, result = state.bof(context) results.extend(result) while 1: try: try: self.next_line() if self.debug: source, offset = self.input_lines.info( self.line_offset) print >>sys.stderr, ( '\nStateMachine.run: line (source=%r, ' 'offset=%r):\n| %s' % (source, offset, self.line)) context, next_state, result = self.check_line( context, state, transitions) except EOFError: if self.debug: print >>sys.stderr, ( '\nStateMachine.run: %s.eof transition' % state.__class__.__name__) result = state.eof(context) results.extend(result) break else: results.extend(result) except TransitionCorrection, exception: self.previous_line() # back up for another try transitions = (exception.args[0],) if self.debug: print >>sys.stderr, ( '\nStateMachine.run: TransitionCorrection to ' 'state "%s", transition %s.' % (state.__class__.__name__, transitions[0])) continue except StateCorrection, exception: self.previous_line() # back up for another try next_state = exception.args[0] if len(exception.args) == 1: transitions = None else: transitions = (exception.args[1],) if self.debug: print >>sys.stderr, ( '\nStateMachine.run: StateCorrection to state ' '"%s", transition %s.' % (next_state, transitions[0])) else: transitions = None state = self.get_state(next_state) except: if self.debug: self.error() raise self.observers = [] return results def get_state(self, next_state=None): """ Return current state object; set it first if `next_state` given. Parameter `next_state`: a string, the name of the next state. Exception: `UnknownStateError` raised if `next_state` unknown. """ if next_state: if self.debug and next_state != self.current_state: print >>sys.stderr, \ ('\nStateMachine.get_state: Changing state from ' '"%s" to "%s" (input line %s).' % (self.current_state, next_state, self.abs_line_number())) self.current_state = next_state try: return self.states[self.current_state] except KeyError: raise UnknownStateError(self.current_state) def next_line(self, n=1): """Load `self.line` with the `n`'th next line and return it.""" try: try: self.line_offset += n self.line = self.input_lines[self.line_offset] except IndexError: self.line = None raise EOFError return self.line finally: self.notify_observers() def is_next_line_blank(self): """Return 1 if the next line is blank or non-existant.""" try: return not self.input_lines[self.line_offset + 1].strip() except IndexError: return 1 def at_eof(self): """Return 1 if the input is at or past end-of-file.""" return self.line_offset >= len(self.input_lines) - 1 def at_bof(self): """Return 1 if the input is at or before beginning-of-file.""" return self.line_offset <= 0 def previous_line(self, n=1): """Load `self.line` with the `n`'th previous line and return it.""" self.line_offset -= n if self.line_offset < 0: self.line = None else: self.line = self.input_lines[self.line_offset] self.notify_observers() return self.line def goto_line(self, line_offset): """Jump to absolute line offset `line_offset`, load and return it.""" try: try: self.line_offset = line_offset - self.input_offset self.line = self.input_lines[self.line_offset] except IndexError: self.line = None raise EOFError return self.line finally: self.notify_observers() def get_source(self, line_offset): """Return source of line at absolute line offset `line_offset`.""" return self.input_lines.source(line_offset - self.input_offset) def abs_line_offset(self): """Return line offset of current line, from beginning of file.""" return self.line_offset + self.input_offset def abs_line_number(self): """Return line number of current line (counting from 1).""" return self.line_offset + self.input_offset + 1 def insert_input(self, input_lines, source): self.input_lines.insert(self.line_offset + 1, '', source='internal padding') self.input_lines.insert(self.line_offset + 1, '', source='internal padding') self.input_lines.insert(self.line_offset + 2, StringList(input_lines, source)) def get_text_block(self, flush_left=0): """ Return a contiguous block of text. If `flush_left` is true, raise `UnexpectedIndentationError` if an indented line is encountered before the text block ends (with a blank line). """ try: block = self.input_lines.get_text_block(self.line_offset, flush_left) self.next_line(len(block) - 1) return block except UnexpectedIndentationError, error: block, source, lineno = error self.next_line(len(block) - 1) # advance to last line of block raise def check_line(self, context, state, transitions=None): """ Examine one line of input for a transition match & execute its method. Parameters: - `context`: application-dependent storage. - `state`: a `State` object, the current state. - `transitions`: an optional ordered list of transition names to try, instead of ``state.transition_order``. Return the values returned by the transition method: - context: possibly modified from the parameter `context`; - next state name (`State` subclass name); - the result output of the transition, a list. When there is no match, ``state.no_match()`` is called and its return value is returned. """ if transitions is None: transitions = state.transition_order state_correction = None if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: state="%s", transitions=%r.' % (state.__class__.__name__, transitions)) for name in transitions: pattern, method, next_state = state.transitions[name] match = self.match(pattern) if match: if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: Matched transition ' '"%s" in state "%s".' % (name, state.__class__.__name__)) return method(match, context, next_state) else: if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: No match in state "%s".' % state.__class__.__name__) return state.no_match(context, transitions) def match(self, pattern): """ Return the result of a regular expression match. Parameter `pattern`: an `re` compiled regular expression. """ return pattern.match(self.line) def add_state(self, state_class): """ Initialize & add a `state_class` (`State` subclass) object. Exception: `DuplicateStateError` raised if `state_class` was already added. """ statename = state_class.__name__ if self.states.has_key(statename): raise DuplicateStateError(statename) self.states[statename] = state_class(self, self.debug) def add_states(self, state_classes): """ Add `state_classes` (a list of `State` subclasses). """ for state_class in state_classes: self.add_state(state_class) def runtime_init(self): """ Initialize `self.states`. """ for state in self.states.values(): state.runtime_init() def error(self): """Report error details.""" type, value, module, line, function = _exception_data() print >>sys.stderr, '%s: %s' % (type, value) print >>sys.stderr, 'input line %s' % (self.abs_line_number()) print >>sys.stderr, ('module %s, line %s, function %s' % (module, line, function)) def attach_observer(self, observer): """ The `observer` parameter is a function or bound method which takes two arguments, the source and offset of the current line. """ self.observers.append(observer) def detach_observer(self, observer): self.observers.remove(observer) def notify_observers(self): for observer in self.observers: try: info = self.input_lines.info(self.line_offset) except IndexError: info = (None, None) observer(*info) class State: """ State superclass. Contains a list of transitions, and transition methods. Transition methods all have the same signature. They take 3 parameters: - An `re` match object. ``match.string`` contains the matched input line, ``match.start()`` gives the start index of the match, and ``match.end()`` gives the end index. - A context object, whose meaning is application-defined (initial value ``None``). It can be used to store any information required by the state machine, and the retured context is passed on to the next transition method unchanged. - The name of the next state, a string, taken from the transitions list; normally it is returned unchanged, but it may be altered by the transition method if necessary. Transition methods all return a 3-tuple: - A context object, as (potentially) modified by the transition method. - The next state name (a return value of ``None`` means no state change). - The processing result, a list, which is accumulated by the state machine. Transition methods may raise an `EOFError` to cut processing short. There are two implicit transitions, and corresponding transition methods are defined: `bof()` handles the beginning-of-file, and `eof()` handles the end-of-file. These methods have non-standard signatures and return values. `bof()` returns the initial context and results, and may be used to return a header string, or do any other processing needed. `eof()` should handle any remaining context and wrap things up; it returns the final processing result. Typical applications need only subclass `State` (or a subclass), set the `patterns` and `initial_transitions` class attributes, and provide corresponding transition methods. The default object initialization will take care of constructing the list of transitions. """ patterns = None """ {Name: pattern} mapping, used by `make_transition()`. Each pattern may be a string or a compiled `re` pattern. Override in subclasses. """ initial_transitions = None """ A list of transitions to initialize when a `State` is instantiated. Each entry is either a transition name string, or a (transition name, next state name) pair. See `make_transitions()`. Override in subclasses. """ nested_sm = None """ The `StateMachine` class for handling nested processing. If left as ``None``, `nested_sm` defaults to the class of the state's controlling state machine. Override it in subclasses to avoid the default. """ nested_sm_kwargs = None """ Keyword arguments dictionary, passed to the `nested_sm` constructor. Two keys must have entries in the dictionary: - Key 'state_classes' must be set to a list of `State` classes. - Key 'initial_state' must be set to the name of the initial state class. If `nested_sm_kwargs` is left as ``None``, 'state_classes' defaults to the class of the current state, and 'initial_state' defaults to the name of the class of the current state. Override in subclasses to avoid the defaults. """ def __init__(self, state_machine, debug=0): """ Initialize a `State` object; make & add initial transitions. Parameters: - `statemachine`: the controlling `StateMachine` object. - `debug`: a boolean; produce verbose output if true (nonzero). """ self.transition_order = [] """A list of transition names in search order.""" self.transitions = {} """ A mapping of transition names to 3-tuples containing (compiled_pattern, transition_method, next_state_name). Initialized as an instance attribute dynamically (instead of as a class attribute) because it may make forward references to patterns and methods in this or other classes. """ self.add_initial_transitions() self.state_machine = state_machine """A reference to the controlling `StateMachine` object.""" self.debug = debug """Debugging mode on/off.""" if self.nested_sm is None: self.nested_sm = self.state_machine.__class__ if self.nested_sm_kwargs is None: self.nested_sm_kwargs = {'state_classes': [self.__class__], 'initial_state': self.__class__.__name__} def runtime_init(self): """ Initialize this `State` before running the state machine; called from `self.state_machine.run()`. """ pass def unlink(self): """Remove circular references to objects no longer required.""" self.state_machine = None def add_initial_transitions(self): """Make and add transitions listed in `self.initial_transitions`.""" if self.initial_transitions: names, transitions = self.make_transitions( self.initial_transitions) self.add_transitions(names, transitions) def add_transitions(self, names, transitions): """ Add a list of transitions to the start of the transition list. Parameters: - `names`: a list of transition names. - `transitions`: a mapping of names to transition tuples. Exceptions: `DuplicateTransitionError`, `UnknownTransitionError`. """ for name in names: if self.transitions.has_key(name): raise DuplicateTransitionError(name) if not transitions.has_key(name): raise UnknownTransitionError(name) self.transition_order[:0] = names self.transitions.update(transitions) def add_transition(self, name, transition): """ Add a transition to the start of the transition list. Parameter `transition`: a ready-made transition 3-tuple. Exception: `DuplicateTransitionError`. """ if self.transitions.has_key(name): raise DuplicateTransitionError(name) self.transition_order[:0] = [name] self.transitions[name] = transition def remove_transition(self, name): """ Remove a transition by `name`. Exception: `UnknownTransitionError`. """ try: del self.transitions[name] self.transition_order.remove(name) except: raise UnknownTransitionError(name) def make_transition(self, name, next_state=None): """ Make & return a transition tuple based on `name`. This is a convenience function to simplify transition creation. Parameters: - `name`: a string, the name of the transition pattern & method. This `State` object must have a method called '`name`', and a dictionary `self.patterns` containing a key '`name`'. - `next_state`: a string, the name of the next `State` object for this transition. A value of ``None`` (or absent) implies no state change (i.e., continue with the same state). Exceptions: `TransitionPatternNotFound`, `TransitionMethodNotFound`. """ if next_state is None: next_state = self.__class__.__name__ try: pattern = self.patterns[name] if not hasattr(pattern, 'match'): pattern = re.compile(pattern) except KeyError: raise TransitionPatternNotFound( '%s.patterns[%r]' % (self.__class__.__name__, name)) try: method = getattr(self, name) except AttributeError: raise TransitionMethodNotFound( '%s.%s' % (self.__class__.__name__, name)) return (pattern, method, next_state) def make_transitions(self, name_list): """ Return a list of transition names and a transition mapping. Parameter `name_list`: a list, where each entry is either a transition name string, or a 1- or 2-tuple (transition name, optional next state name). """ stringtype = type('') names = [] transitions = {} for namestate in name_list: if type(namestate) is stringtype: transitions[namestate] = self.make_transition(namestate) names.append(namestate) else: transitions[namestate[0]] = self.make_transition(*namestate) names.append(namestate[0]) return names, transitions def no_match(self, context, transitions): """ Called when there is no match from `StateMachine.check_line()`. Return the same values returned by transition methods: - context: unchanged; - next state name: ``None``; - empty result list. Override in subclasses to catch this event. """ return context, None, [] def bof(self, context): """ Handle beginning-of-file. Return unchanged `context`, empty result. Override in subclasses. Parameter `context`: application-defined storage. """ return context, [] def eof(self, context): """ Handle end-of-file. Return empty result. Override in subclasses. Parameter `context`: application-defined storage. """ return [] def nop(self, match, context, next_state): """ A "do nothing" transition method. Return unchanged `context` & `next_state`, empty result. Useful for simple state changes (actionless transitions). """ return context, next_state, [] class StateMachineWS(StateMachine): """ `StateMachine` subclass specialized for whitespace recognition. There are three methods provided for extracting indented text blocks: - `get_indented()`: use when the indent is unknown. - `get_known_indented()`: use when the indent is known for all lines. - `get_first_known_indented()`: use when only the first line's indent is known. """ def get_indented(self, until_blank=0, strip_indent=1): """ Return a block of indented lines of text, and info. Extract an indented block where the indent is unknown for all lines. :Parameters: - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip common leading indent if true (1, default). :Return: - the indented block (a list of lines of text), - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent) if indented: self.next_line(len(indented) - 1) # advance to last indented line while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, indent, offset, blank_finish def get_known_indented(self, indent, until_blank=0, strip_indent=1): """ Return an indented block and info. Extract an indented block where the indent is known for all lines. Starting with the current line, extract the entire text block with at least `indent` indentation (which must be whitespace, except for the first line). :Parameters: - `indent`: The number of indent columns/characters. - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip `indent` characters of indentation if true (1, default). :Return: - the indented block, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent, block_indent=indent) self.next_line(len(indented) - 1) # advance to last indented line while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, offset, blank_finish def get_first_known_indented(self, indent, until_blank=0, strip_indent=1, strip_top=1): """ Return an indented block and info. Extract an indented block where the indent is known for the first line and unknown for all other lines. :Parameters: - `indent`: The first line's indent (# of columns/characters). - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip `indent` characters of indentation if true (1, default). - `strip_top`: Strip blank lines from the beginning of the block. :Return: - the indented block, - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent, first_indent=indent) self.next_line(len(indented) - 1) # advance to last indented line if strip_top: while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, indent, offset, blank_finish class StateWS(State): """ State superclass specialized for whitespace (blank lines & indents). Use this class with `StateMachineWS`. The transitions 'blank' (for blank lines) and 'indent' (for indented text blocks) are added automatically, before any other transitions. The transition method `blank()` handles blank lines and `indent()` handles nested indented blocks. Indented blocks trigger a new state machine to be created by `indent()` and run. The class of the state machine to be created is in `indent_sm`, and the constructor keyword arguments are in the dictionary `indent_sm_kwargs`. The methods `known_indent()` and `firstknown_indent()` are provided for indented blocks where the indent (all lines' and first line's only, respectively) is known to the transition method, along with the attributes `known_indent_sm` and `known_indent_sm_kwargs`. Neither transition method is triggered automatically. """ indent_sm = None """ The `StateMachine` class handling indented text blocks. If left as ``None``, `indent_sm` defaults to the value of `State.nested_sm`. Override it in subclasses to avoid the default. """ indent_sm_kwargs = None """ Keyword arguments dictionary, passed to the `indent_sm` constructor. If left as ``None``, `indent_sm_kwargs` defaults to the value of `State.nested_sm_kwargs`. Override it in subclasses to avoid the default. """ known_indent_sm = None """ The `StateMachine` class handling known-indented text blocks. If left as ``None``, `known_indent_sm` defaults to the value of `indent_sm`. Override it in subclasses to avoid the default. """ known_indent_sm_kwargs = None """ Keyword arguments dictionary, passed to the `known_indent_sm` constructor. If left as ``None``, `known_indent_sm_kwargs` defaults to the value of `indent_sm_kwargs`. Override it in subclasses to avoid the default. """ ws_patterns = {'blank': ' *$', 'indent': ' +'} """Patterns for default whitespace transitions. May be overridden in subclasses.""" ws_initial_transitions = ('blank', 'indent') """Default initial whitespace transitions, added before those listed in `State.initial_transitions`. May be overridden in subclasses.""" def __init__(self, state_machine, debug=0): """ Initialize a `StateSM` object; extends `State.__init__()`. Check for indent state machine attributes, set defaults if not set. """ State.__init__(self, state_machine, debug) if self.indent_sm is None: self.indent_sm = self.nested_sm if self.indent_sm_kwargs is None: self.indent_sm_kwargs = self.nested_sm_kwargs if self.known_indent_sm is None: self.known_indent_sm = self.indent_sm if self.known_indent_sm_kwargs is None: self.known_indent_sm_kwargs = self.indent_sm_kwargs def add_initial_transitions(self): """ Add whitespace-specific transitions before those defined in subclass. Extends `State.add_initial_transitions()`. """ State.add_initial_transitions(self) if self.patterns is None: self.patterns = {} self.patterns.update(self.ws_patterns) names, transitions = self.make_transitions( self.ws_initial_transitions) self.add_transitions(names, transitions) def blank(self, match, context, next_state): """Handle blank lines. Does nothing. Override in subclasses.""" return self.nop(match, context, next_state) def indent(self, match, context, next_state): """ Handle an indented text block. Extend or override in subclasses. Recursively run the registered state machine for indented blocks (`self.indent_sm`). """ indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() sm = self.indent_sm(debug=self.debug, **self.indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results def known_indent(self, match, context, next_state): """ Handle a known-indent text block. Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. """ indented, line_offset, blank_finish = \ self.state_machine.get_known_indented(match.end()) sm = self.known_indent_sm(debug=self.debug, **self.known_indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results def first_known_indent(self, match, context, next_state): """ Handle an indented text block (first line's indent known). Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. """ indented, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) sm = self.known_indent_sm(debug=self.debug, **self.known_indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results class _SearchOverride: """ Mix-in class to override `StateMachine` regular expression behavior. Changes regular expression matching, from the default `re.match()` (succeeds only if the pattern matches at the start of `self.line`) to `re.search()` (succeeds if the pattern matches anywhere in `self.line`). When subclassing a `StateMachine`, list this class **first** in the inheritance list of the class definition. """ def match(self, pattern): """ Return the result of a regular expression search. Overrides `StateMachine.match()`. Parameter `pattern`: `re` compiled regular expression. """ return pattern.search(self.line) class SearchStateMachine(_SearchOverride, StateMachine): """`StateMachine` which uses `re.search()` instead of `re.match()`.""" pass class SearchStateMachineWS(_SearchOverride, StateMachineWS): """`StateMachineWS` which uses `re.search()` instead of `re.match()`.""" pass class ViewList: """ List with extended functionality: slices of ViewList objects are child lists, linked to their parents. Changes made to a child list also affect the parent list. A child list is effectively a "view" (in the SQL sense) of the parent list. Changes to parent lists, however, do *not* affect active child lists. If a parent list is changed, any active child lists should be recreated. The start and end of the slice can be trimmed using the `trim_start()` and `trim_end()` methods, without affecting the parent list. The link between child and parent lists can be broken by calling `disconnect()` on the child list. Also, ViewList objects keep track of the source & offset of each item. This information is accessible via the `source()`, `offset()`, and `info()` methods. """ def __init__(self, initlist=None, source=None, items=None, parent=None, parent_offset=None): self.data = [] """The actual list of data, flattened from various sources.""" self.items = [] """A list of (source, offset) pairs, same length as `self.data`: the source of each line and the offset of each line from the beginning of its source.""" self.parent = parent """The parent list.""" self.parent_offset = parent_offset """Offset of this list from the beginning of the parent list.""" if isinstance(initlist, ViewList): self.data = initlist.data[:] self.items = initlist.items[:] elif initlist is not None: self.data = list(initlist) if items: self.items = items else: self.items = [(source, i) for i in range(len(initlist))] assert len(self.data) == len(self.items), 'data mismatch' def __str__(self): return str(self.data) def __repr__(self): return '%s(%s, items=%s)' % (self.__class__.__name__, self.data, self.items) def __lt__(self, other): return self.data < self.__cast(other) def __le__(self, other): return self.data <= self.__cast(other) def __eq__(self, other): return self.data == self.__cast(other) def __ne__(self, other): return self.data != self.__cast(other) def __gt__(self, other): return self.data > self.__cast(other) def __ge__(self, other): return self.data >= self.__cast(other) def __cmp__(self, other): return cmp(self.data, self.__cast(other)) def __cast(self, other): if isinstance(other, ViewList): return other.data else: return other def __contains__(self, item): return item in self.data def __len__(self): return len(self.data) # The __getitem__()/__setitem__() methods check whether the index # is a slice first, since native list objects start supporting # them directly in Python 2.3 (no exception is raised when # indexing a list with a slice object; they just work). def __getitem__(self, i): if isinstance(i, types.SliceType): assert i.step in (None, 1), 'cannot handle slice with stride' return self.__class__(self.data[i.start:i.stop], items=self.items[i.start:i.stop], parent=self, parent_offset=i.start) else: return self.data[i] def __setitem__(self, i, item): if isinstance(i, types.SliceType): assert i.step in (None, 1), 'cannot handle slice with stride' if not isinstance(item, ViewList): raise TypeError('assigning non-ViewList to ViewList slice') self.data[i.start:i.stop] = item.data self.items[i.start:i.stop] = item.items assert len(self.data) == len(self.items), 'data mismatch' if self.parent: self.parent[i.start + self.parent_offset : i.stop + self.parent_offset] = item else: self.data[i] = item if self.parent: self.parent[i + self.parent_offset] = item def __delitem__(self, i): try: del self.data[i] del self.items[i] if self.parent: del self.parent[i + self.parent_offset] except TypeError: assert i.step is None, 'cannot handle slice with stride' del self.data[i.start:i.stop] del self.items[i.start:i.stop] if self.parent: del self.parent[i.start + self.parent_offset : i.stop + self.parent_offset] def __add__(self, other): if isinstance(other, ViewList): return self.__class__(self.data + other.data, items=(self.items + other.items)) else: raise TypeError('adding non-ViewList to a ViewList') def __radd__(self, other): if isinstance(other, ViewList): return self.__class__(other.data + self.data, items=(other.items + self.items)) else: raise TypeError('adding ViewList to a non-ViewList') def __iadd__(self, other): if isinstance(other, ViewList): self.data += other.data else: raise TypeError('argument to += must be a ViewList') return self def __mul__(self, n): return self.__class__(self.data * n, items=(self.items * n)) __rmul__ = __mul__ def __imul__(self, n): self.data *= n self.items *= n return self def extend(self, other): if not isinstance(other, ViewList): raise TypeError('extending a ViewList with a non-ViewList') if self.parent: self.parent.insert(len(self.data) + self.parent_offset, other) self.data.extend(other.data) self.items.extend(other.items) def append(self, item, source=None, offset=0): if source is None: self.extend(item) else: if self.parent: self.parent.insert(len(self.data) + self.parent_offset, item, source, offset) self.data.append(item) self.items.append((source, offset)) def insert(self, i, item, source=None, offset=0): if source is None: if not isinstance(item, ViewList): raise TypeError('inserting non-ViewList with no source given') self.data[i:i] = item.data self.items[i:i] = item.items if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.insert(index + self.parent_offset, item) else: self.data.insert(i, item) self.items.insert(i, (source, offset)) if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.insert(index + self.parent_offset, item, source, offset) def pop(self, i=-1): if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.pop(index + self.parent_offset) self.items.pop(i) return self.data.pop(i) def trim_start(self, n=1): """ Remove items from the start of the list, without touching the parent. """ if n > len(self.data): raise IndexError("Size of trim too large; can't trim %s items " "from a list of size %s." % (n, len(self.data))) elif n < 0: raise IndexError('Trim size must be >= 0.') del self.data[:n] del self.items[:n] if self.parent: self.parent_offset += n def trim_end(self, n=1): """ Remove items from the end of the list, without touching the parent. """ if n > len(self.data): raise IndexError("Size of trim too large; can't trim %s items " "from a list of size %s." % (n, len(self.data))) elif n < 0: raise IndexError('Trim size must be >= 0.') del self.data[-n:] del self.items[-n:] def remove(self, item): index = self.index(item) del self[index] def count(self, item): return self.data.count(item) def index(self, item): return self.data.index(item) def reverse(self): self.data.reverse() self.items.reverse() self.parent = None def sort(self, *args): tmp = zip(self.data, self.items) tmp.sort(*args) self.data = [entry[0] for entry in tmp] self.items = [entry[1] for entry in tmp] self.parent = None def info(self, i): """Return source & offset for index `i`.""" try: return self.items[i] except IndexError: if i == len(self.data): # Just past the end return self.items[i - 1][0], None else: raise def source(self, i): """Return source for index `i`.""" return self.info(i)[0] def offset(self, i): """Return offset for index `i`.""" return self.info(i)[1] def disconnect(self): """Break link between this list and parent list.""" self.parent = None class StringList(ViewList): """A `ViewList` with string-specific methods.""" def trim_left(self, length, start=0, end=sys.maxint): """ Trim `length` characters off the beginning of each item, in-place, from index `start` to `end`. No whitespace-checking is done on the trimmed text. Does not affect slice parent. """ self.data[start:end] = [line[length:] for line in self.data[start:end]] def get_text_block(self, start, flush_left=0): """ Return a contiguous block of text. If `flush_left` is true, raise `UnexpectedIndentationError` if an indented line is encountered before the text block ends (with a blank line). """ end = start last = len(self.data) while end < last: line = self.data[end] if not line.strip(): break if flush_left and (line[0] == ' '): source, offset = self.info(end) raise UnexpectedIndentationError(self[start:end], source, offset + 1) end += 1 return self[start:end] def get_indented(self, start=0, until_blank=0, strip_indent=1, block_indent=None, first_indent=None): """ Extract and return a StringList of indented lines of text. Collect all lines with indentation, determine the minimum indentation, remove the minimum indentation from all indented lines (unless `strip_indent` is false), and return them. All lines up to but not including the first unindented line will be returned. :Parameters: - `start`: The index of the first line to examine. - `until_blank`: Stop collecting at the first blank line if true. - `strip_indent`: Strip common leading indent if true (default). - `block_indent`: The indent of the entire block, if known. - `first_indent`: The indent of the first line, if known. :Return: - a StringList of indented lines with mininum indent removed; - the amount of the indent; - a boolean: did the indented block finish with a blank line or EOF? """ indent = block_indent # start with None if unknown end = start if block_indent is not None and first_indent is None: first_indent = block_indent if first_indent is not None: end += 1 last = len(self.data) while end < last: line = self.data[end] if line and (line[0] != ' ' or (block_indent is not None and line[:block_indent].strip())): # Line not indented or insufficiently indented. # Block finished properly iff the last indented line blank: blank_finish = ((end > start) and not self.data[end - 1].strip()) break stripped = line.lstrip() if not stripped: # blank line if until_blank: blank_finish = 1 break elif block_indent is None: line_indent = len(line) - len(stripped) if indent is None: indent = line_indent else: indent = min(indent, line_indent) end += 1 else: blank_finish = 1 # block ends at end of lines block = self[start:end] if first_indent is not None and block: block.data[0] = block.data[0][first_indent:] if indent and strip_indent: block.trim_left(indent, start=(first_indent is not None)) return block, indent or 0, blank_finish def get_2D_block(self, top, left, bottom, right, strip_indent=1): block = self[top:bottom] indent = right for i in range(len(block.data)): block.data[i] = line = block.data[i][left:right].rstrip() if line: indent = min(indent, len(line) - len(line.lstrip())) if strip_indent and 0 < indent < right: block.data = [line[indent:] for line in block.data] return block def pad_double_width(self, pad_char): """ Pad all double-width characters in self by appending `pad_char` to each. For East Asian language support. """ if hasattr(unicodedata, 'east_asian_width'): east_asian_width = unicodedata.east_asian_width else: return # new in Python 2.4 for i in range(len(self.data)): line = self.data[i] if isinstance(line, types.UnicodeType): new = [] for char in line: new.append(char) if east_asian_width(char) in 'WF': # 'W'ide & 'F'ull-width new.append(pad_char) self.data[i] = ''.join(new) def replace(self, old, new): """Replace all occurrences of substring `old` with `new`.""" for i in range(len(self.data)): self.data[i] = self.data[i].replace(old, new) class StateMachineError(Exception): pass class UnknownStateError(StateMachineError): pass class DuplicateStateError(StateMachineError): pass class UnknownTransitionError(StateMachineError): pass class DuplicateTransitionError(StateMachineError): pass class TransitionPatternNotFound(StateMachineError): pass class TransitionMethodNotFound(StateMachineError): pass class UnexpectedIndentationError(StateMachineError): pass class TransitionCorrection(Exception): """ Raise from within a transition method to switch to another transition. Raise with one argument, the new transition name. """ class StateCorrection(Exception): """ Raise from within a transition method to switch to another state. Raise with one or two arguments: new state name, and an optional new transition name. """ def string2lines(astring, tab_width=8, convert_whitespace=0, whitespace=re.compile('[\v\f]')): """ Return a list of one-line strings with tabs expanded, no newlines, and trailing whitespace stripped. Each tab is expanded with between 1 and `tab_width` spaces, so that the next character's index becomes a multiple of `tab_width` (8 by default). Parameters: - `astring`: a multi-line string. - `tab_width`: the number of columns between tab stops. - `convert_whitespace`: convert form feeds and vertical tabs to spaces? """ if convert_whitespace: astring = whitespace.sub(' ', astring) return [s.expandtabs(tab_width).rstrip() for s in astring.splitlines()] def _exception_data(): """ Return exception information: - the exception's class name; - the exception object; - the name of the file containing the offending code; - the line number of the offending code; - the function name of the offending code. """ type, value, traceback = sys.exc_info() while traceback.tb_next: traceback = traceback.tb_next code = traceback.tb_frame.f_code return (type.__name__, value, code.co_filename, traceback.tb_lineno, code.co_name)
{ "repo_name": "google-code-export/django-hotclub", "path": "libs/external_libs/docutils-0.4/docutils/statemachine.py", "copies": "6", "size": "55377", "license": "mit", "hash": -7642328904357389000, "line_mean": 36.1159517426, "line_max": 80, "alpha_frac": 0.5871210069, "autogenerated": false, "ratio": 4.395, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7982121006899999, "avg_score": null, "num_lines": null }
""" This module defines table parser classes,which parse plaintext-graphic tables and produce a well-formed data structure suitable for building a CALS table. :Classes: - `GridTableParser`: Parse fully-formed tables represented with a grid. - `SimpleTableParser`: Parse simple tables, delimited by top & bottom borders. :Exception class: `TableMarkupError` :Function: `update_dict_of_lists()`: Merge two dictionaries containing list values. """ __docformat__ = 'reStructuredText' import re import sys from docutils import DataError class TableMarkupError(DataError): pass class TableParser: """ Abstract superclass for the common parts of the syntax-specific parsers. """ head_body_separator_pat = None """Matches the row separator between head rows and body rows.""" double_width_pad_char = '\x00' """Padding character for East Asian double-width text.""" def parse(self, block): """ Analyze the text `block` and return a table data structure. Given a plaintext-graphic table in `block` (list of lines of text; no whitespace padding), parse the table, construct and return the data necessary to construct a CALS table or equivalent. Raise `TableMarkupError` if there is any problem with the markup. """ self.setup(block) self.find_head_body_sep() self.parse_table() structure = self.structure_from_cells() return structure def find_head_body_sep(self): """Look for a head/body row separator line; store the line index.""" for i in range(len(self.block)): line = self.block[i] if self.head_body_separator_pat.match(line): if self.head_body_sep: raise TableMarkupError( 'Multiple head/body row separators in table (at line ' 'offset %s and %s); only one allowed.' % (self.head_body_sep, i)) else: self.head_body_sep = i self.block[i] = line.replace('=', '-') if self.head_body_sep == 0 or self.head_body_sep == (len(self.block) - 1): raise TableMarkupError('The head/body row separator may not be ' 'the first or last line of the table.') class GridTableParser(TableParser): """ Parse a grid table using `parse()`. Here's an example of a grid table:: +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | Cells may span columns. | +------------------------+------------+---------------------+ | body row 3 | Cells may | - Table cells | +------------------------+ span rows. | - contain | | body row 4 | | - body elements. | +------------------------+------------+---------------------+ Intersections use '+', row separators use '-' (except for one optional head/body row separator, which uses '='), and column separators use '|'. Passing the above table to the `parse()` method will result in the following data structure:: ([24, 12, 10, 10], [[(0, 0, 1, ['Header row, column 1']), (0, 0, 1, ['Header 2']), (0, 0, 1, ['Header 3']), (0, 0, 1, ['Header 4'])]], [[(0, 0, 3, ['body row 1, column 1']), (0, 0, 3, ['column 2']), (0, 0, 3, ['column 3']), (0, 0, 3, ['column 4'])], [(0, 0, 5, ['body row 2']), (0, 2, 5, ['Cells may span columns.']), None, None], [(0, 0, 7, ['body row 3']), (1, 0, 7, ['Cells may', 'span rows.', '']), (1, 1, 7, ['- Table cells', '- contain', '- body elements.']), None], [(0, 0, 9, ['body row 4']), None, None, None]]) The first item is a list containing column widths (colspecs). The second item is a list of head rows, and the third is a list of body rows. Each row contains a list of cells. Each cell is either None (for a cell unused because of another cell's span), or a tuple. A cell tuple contains four items: the number of extra rows used by the cell in a vertical span (morerows); the number of extra columns used by the cell in a horizontal span (morecols); the line offset of the first line of the cell contents; and the cell contents, a list of lines of text. """ head_body_separator_pat = re.compile(r'\+=[=+]+=\+ *$') def setup(self, block): self.block = block[:] # make a copy; it may be modified self.block.disconnect() # don't propagate changes to parent self.bottom = len(block) - 1 self.right = len(block[0]) - 1 self.head_body_sep = None self.done = [-1] * len(block[0]) self.cells = [] self.rowseps = {0: [0]} self.colseps = {0: [0]} def parse_table(self): """ Start with a queue of upper-left corners, containing the upper-left corner of the table itself. Trace out one rectangular cell, remember it, and add its upper-right and lower-left corners to the queue of potential upper-left corners of further cells. Process the queue in top-to-bottom order, keeping track of how much of each text column has been seen. We'll end up knowing all the row and column boundaries, cell positions and their dimensions. """ corners = [(0, 0)] while corners: top, left = corners.pop(0) if top == self.bottom or left == self.right \ or top <= self.done[left]: continue result = self.scan_cell(top, left) if not result: continue bottom, right, rowseps, colseps = result update_dict_of_lists(self.rowseps, rowseps) update_dict_of_lists(self.colseps, colseps) self.mark_done(top, left, bottom, right) cellblock = self.block.get_2D_block(top + 1, left + 1, bottom, right) cellblock.disconnect() # lines in cell can't sync with parent cellblock.replace(self.double_width_pad_char, '') self.cells.append((top, left, bottom, right, cellblock)) corners.extend([(top, right), (bottom, left)]) corners.sort() if not self.check_parse_complete(): raise TableMarkupError('Malformed table; parse incomplete.') def mark_done(self, top, left, bottom, right): """For keeping track of how much of each text column has been seen.""" before = top - 1 after = bottom - 1 for col in range(left, right): assert self.done[col] == before self.done[col] = after def check_parse_complete(self): """Each text column should have been completely seen.""" last = self.bottom - 1 for col in range(self.right): if self.done[col] != last: return None return 1 def scan_cell(self, top, left): """Starting at the top-left corner, start tracing out a cell.""" assert self.block[top][left] == '+' result = self.scan_right(top, left) return result def scan_right(self, top, left): """ Look for the top-right corner of the cell, and make note of all column boundaries ('+'). """ colseps = {} line = self.block[top] for i in range(left + 1, self.right + 1): if line[i] == '+': colseps[i] = [top] result = self.scan_down(top, left, i) if result: bottom, rowseps, newcolseps = result update_dict_of_lists(colseps, newcolseps) return bottom, i, rowseps, colseps elif line[i] != '-': return None return None def scan_down(self, top, left, right): """ Look for the bottom-right corner of the cell, making note of all row boundaries. """ rowseps = {} for i in range(top + 1, self.bottom + 1): if self.block[i][right] == '+': rowseps[i] = [right] result = self.scan_left(top, left, i, right) if result: newrowseps, colseps = result update_dict_of_lists(rowseps, newrowseps) return i, rowseps, colseps elif self.block[i][right] != '|': return None return None def scan_left(self, top, left, bottom, right): """ Noting column boundaries, look for the bottom-left corner of the cell. It must line up with the starting point. """ colseps = {} line = self.block[bottom] for i in range(right - 1, left, -1): if line[i] == '+': colseps[i] = [bottom] elif line[i] != '-': return None if line[left] != '+': return None result = self.scan_up(top, left, bottom, right) if result is not None: rowseps = result return rowseps, colseps return None def scan_up(self, top, left, bottom, right): """ Noting row boundaries, see if we can return to the starting point. """ rowseps = {} for i in range(bottom - 1, top, -1): if self.block[i][left] == '+': rowseps[i] = [left] elif self.block[i][left] != '|': return None return rowseps def structure_from_cells(self): """ From the data collected by `scan_cell()`, convert to the final data structure. """ rowseps = self.rowseps.keys() # list of row boundaries rowseps.sort() rowindex = {} for i in range(len(rowseps)): rowindex[rowseps[i]] = i # row boundary -> row number mapping colseps = self.colseps.keys() # list of column boundaries colseps.sort() colindex = {} for i in range(len(colseps)): colindex[colseps[i]] = i # column boundary -> col number map colspecs = [(colseps[i] - colseps[i - 1] - 1) for i in range(1, len(colseps))] # list of column widths # prepare an empty table with the correct number of rows & columns onerow = [None for i in range(len(colseps) - 1)] rows = [onerow[:] for i in range(len(rowseps) - 1)] # keep track of # of cells remaining; should reduce to zero remaining = (len(rowseps) - 1) * (len(colseps) - 1) for top, left, bottom, right, block in self.cells: rownum = rowindex[top] colnum = colindex[left] assert rows[rownum][colnum] is None, ( 'Cell (row %s, column %s) already used.' % (rownum + 1, colnum + 1)) morerows = rowindex[bottom] - rownum - 1 morecols = colindex[right] - colnum - 1 remaining -= (morerows + 1) * (morecols + 1) # write the cell into the table rows[rownum][colnum] = (morerows, morecols, top + 1, block) assert remaining == 0, 'Unused cells remaining.' if self.head_body_sep: # separate head rows from body rows numheadrows = rowindex[self.head_body_sep] headrows = rows[:numheadrows] bodyrows = rows[numheadrows:] else: headrows = [] bodyrows = rows return (colspecs, headrows, bodyrows) class SimpleTableParser(TableParser): """ Parse a simple table using `parse()`. Here's an example of a simple table:: ===== ===== col 1 col 2 ===== ===== 1 Second column of row 1. 2 Second column of row 2. Second line of paragraph. 3 - Second column of row 3. - Second item in bullet list (row 3, column 2). 4 is a span ------------ 5 ===== ===== Top and bottom borders use '=', column span underlines use '-', column separation is indicated with spaces. Passing the above table to the `parse()` method will result in the following data structure, whose interpretation is the same as for `GridTableParser`:: ([5, 25], [[(0, 0, 1, ['col 1']), (0, 0, 1, ['col 2'])]], [[(0, 0, 3, ['1']), (0, 0, 3, ['Second column of row 1.'])], [(0, 0, 4, ['2']), (0, 0, 4, ['Second column of row 2.', 'Second line of paragraph.'])], [(0, 0, 6, ['3']), (0, 0, 6, ['- Second column of row 3.', '', '- Second item in bullet', ' list (row 3, column 2).'])], [(0, 1, 10, ['4 is a span'])], [(0, 0, 12, ['5']), (0, 0, 12, [''])]]) """ head_body_separator_pat = re.compile('=[ =]*$') span_pat = re.compile('-[ -]*$') def setup(self, block): self.block = block[:] # make a copy; it will be modified self.block.disconnect() # don't propagate changes to parent # Convert top & bottom borders to column span underlines: self.block[0] = self.block[0].replace('=', '-') self.block[-1] = self.block[-1].replace('=', '-') self.head_body_sep = None self.columns = [] self.border_end = None self.table = [] self.done = [-1] * len(block[0]) self.rowseps = {0: [0]} self.colseps = {0: [0]} def parse_table(self): """ First determine the column boundaries from the top border, then process rows. Each row may consist of multiple lines; accumulate lines until a row is complete. Call `self.parse_row` to finish the job. """ # Top border must fully describe all table columns. self.columns = self.parse_columns(self.block[0], 0) self.border_end = self.columns[-1][1] firststart, firstend = self.columns[0] offset = 1 # skip top border start = 1 text_found = None while offset < len(self.block): line = self.block[offset] if self.span_pat.match(line): # Column span underline or border; row is complete. self.parse_row(self.block[start:offset], start, (line.rstrip(), offset)) start = offset + 1 text_found = None elif line[firststart:firstend].strip(): # First column not blank, therefore it's a new row. if text_found and offset != start: self.parse_row(self.block[start:offset], start) start = offset text_found = 1 elif not text_found: start = offset + 1 offset += 1 def parse_columns(self, line, offset): """ Given a column span underline, return a list of (begin, end) pairs. """ cols = [] end = 0 while 1: begin = line.find('-', end) end = line.find(' ', begin) if begin < 0: break if end < 0: end = len(line) cols.append((begin, end)) if self.columns: if cols[-1][1] != self.border_end: raise TableMarkupError('Column span incomplete at line ' 'offset %s.' % offset) # Allow for an unbounded rightmost column: cols[-1] = (cols[-1][0], self.columns[-1][1]) return cols def init_row(self, colspec, offset): i = 0 cells = [] for start, end in colspec: morecols = 0 try: assert start == self.columns[i][0] while end != self.columns[i][1]: i += 1 morecols += 1 except (AssertionError, IndexError): raise TableMarkupError('Column span alignment problem at ' 'line offset %s.' % (offset + 1)) cells.append([0, morecols, offset, []]) i += 1 return cells def parse_row(self, lines, start, spanline=None): """ Given the text `lines` of a row, parse it and append to `self.table`. The row is parsed according to the current column spec (either `spanline` if provided or `self.columns`). For each column, extract text from each line, and check for text in column margins. Finally, adjust for insigificant whitespace. """ if not (lines or spanline): # No new row, just blank lines. return if spanline: columns = self.parse_columns(*spanline) span_offset = spanline[1] else: columns = self.columns[:] span_offset = start self.check_columns(lines, start, columns) row = self.init_row(columns, start) for i in range(len(columns)): start, end = columns[i] cellblock = lines.get_2D_block(0, start, len(lines), end) cellblock.disconnect() # lines in cell can't sync with parent cellblock.replace(self.double_width_pad_char, '') row[i][3] = cellblock self.table.append(row) def check_columns(self, lines, first_line, columns): """ Check for text in column margins and text overflow in the last column. Raise TableMarkupError if anything but whitespace is in column margins. Adjust the end value for the last column if there is text overflow. """ # "Infinite" value for a dummy last column's beginning, used to # check for text overflow: columns.append((sys.maxint, None)) lastcol = len(columns) - 2 for i in range(len(columns) - 1): start, end = columns[i] nextstart = columns[i+1][0] offset = 0 for line in lines: if i == lastcol and line[end:].strip(): text = line[start:].rstrip() new_end = start + len(text) columns[i] = (start, new_end) main_start, main_end = self.columns[-1] if new_end > main_end: self.columns[-1] = (main_start, new_end) elif line[end:nextstart].strip(): raise TableMarkupError('Text in column margin at line ' 'offset %s.' % (first_line + offset)) offset += 1 columns.pop() def structure_from_cells(self): colspecs = [end - start for start, end in self.columns] first_body_row = 0 if self.head_body_sep: for i in range(len(self.table)): if self.table[i][0][2] > self.head_body_sep: first_body_row = i break return (colspecs, self.table[:first_body_row], self.table[first_body_row:]) def update_dict_of_lists(master, newdata): """ Extend the list values of `master` with those from `newdata`. Both parameters must be dictionaries containing list values. """ for key, values in newdata.items(): master.setdefault(key, []).extend(values)
{ "repo_name": "indro/t2c", "path": "libs/external_libs/docutils-0.4/docutils/parsers/rst/tableparser.py", "copies": "6", "size": "20382", "license": "mit", "hash": -8906025234095204000, "line_mean": 37.6755218216, "line_max": 80, "alpha_frac": 0.5163379452, "autogenerated": false, "ratio": 4.13511868533171, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.765145663053171, "avg_score": null, "num_lines": null }
""" Simple HyperText Markup Language document tree Writer. The output conforms to the XHTML version 1.0 Transitional DTD (*almost* strict). The output contains a minimum of formatting information. The cascading style sheet "html4css1.css" is required for proper viewing with a modern graphical browser. """ __docformat__ = 'reStructuredText' import sys import os import os.path import time import re from types import ListType try: import Image # check for the Python Imaging Library except ImportError: Image = None import docutils from docutils import frontend, nodes, utils, writers, languages class Writer(writers.Writer): supported = ('html', 'html4css1', 'xhtml') """Formats this writer supports.""" default_stylesheet = 'html4css1.css' default_stylesheet_path = utils.relative_path( os.path.join(os.getcwd(), 'dummy'), os.path.join(os.path.dirname(__file__), default_stylesheet)) settings_spec = ( 'HTML-Specific Options', None, (('Specify a stylesheet URL, used verbatim. Overrides ' '--stylesheet-path.', ['--stylesheet'], {'metavar': '<URL>', 'overrides': 'stylesheet_path'}), ('Specify a stylesheet file, relative to the current working ' 'directory. The path is adjusted relative to the output HTML ' 'file. Overrides --stylesheet. Default: "%s"' % default_stylesheet_path, ['--stylesheet-path'], {'metavar': '<file>', 'overrides': 'stylesheet', 'default': default_stylesheet_path}), ('Embed the stylesheet in the output HTML file. The stylesheet ' 'file must be accessible during processing (--stylesheet-path is ' 'recommended). This is the default.', ['--embed-stylesheet'], {'default': 1, 'action': 'store_true', 'validator': frontend.validate_boolean}), ('Link to the stylesheet in the output HTML file. Default: ' 'embed the stylesheet, do not link to it.', ['--link-stylesheet'], {'dest': 'embed_stylesheet', 'action': 'store_false', 'validator': frontend.validate_boolean}), ('Specify the initial header level. Default is 1 for "<h1>". ' 'Does not affect document title & subtitle (see --no-doc-title).', ['--initial-header-level'], {'choices': '1 2 3 4 5 6'.split(), 'default': '1', 'metavar': '<level>'}), ('Specify the maximum width (in characters) for one-column field ' 'names. Longer field names will span an entire row of the table ' 'used to render the field list. Default is 14 characters. ' 'Use 0 for "no limit".', ['--field-name-limit'], {'default': 14, 'metavar': '<level>', 'validator': frontend.validate_nonnegative_int}), ('Specify the maximum width (in characters) for options in option ' 'lists. Longer options will span an entire row of the table used ' 'to render the option list. Default is 14 characters. ' 'Use 0 for "no limit".', ['--option-limit'], {'default': 14, 'metavar': '<level>', 'validator': frontend.validate_nonnegative_int}), ('Format for footnote references: one of "superscript" or ' '"brackets". Default is "brackets".', ['--footnote-references'], {'choices': ['superscript', 'brackets'], 'default': 'brackets', 'metavar': '<format>', 'overrides': 'trim_footnote_reference_space'}), ('Format for block quote attributions: one of "dash" (em-dash ' 'prefix), "parentheses"/"parens", or "none". Default is "dash".', ['--attribution'], {'choices': ['dash', 'parentheses', 'parens', 'none'], 'default': 'dash', 'metavar': '<format>'}), ('Remove extra vertical whitespace between items of "simple" bullet ' 'lists and enumerated lists. Default: enabled.', ['--compact-lists'], {'default': 1, 'action': 'store_true', 'validator': frontend.validate_boolean}), ('Disable compact simple bullet and enumerated lists.', ['--no-compact-lists'], {'dest': 'compact_lists', 'action': 'store_false'}), ('Remove extra vertical whitespace between items of simple field ' 'lists. Default: enabled.', ['--compact-field-lists'], {'default': 1, 'action': 'store_true', 'validator': frontend.validate_boolean}), ('Disable compact simple field lists.', ['--no-compact-field-lists'], {'dest': 'compact_field_lists', 'action': 'store_false'}), ('Omit the XML declaration. Use with caution.', ['--no-xml-declaration'], {'dest': 'xml_declaration', 'default': 1, 'action': 'store_false', 'validator': frontend.validate_boolean}), ('Obfuscate email addresses to confuse harvesters while still ' 'keeping email links usable with standards-compliant browsers.', ['--cloak-email-addresses'], {'action': 'store_true', 'validator': frontend.validate_boolean}),)) settings_defaults = {'output_encoding_error_handler': 'xmlcharrefreplace'} relative_path_settings = ('stylesheet_path',) config_section = 'html4css1 writer' config_section_dependencies = ('writers',) def __init__(self): writers.Writer.__init__(self) self.translator_class = HTMLTranslator def translate(self): self.visitor = visitor = self.translator_class(self.document) self.document.walkabout(visitor) self.output = visitor.astext() for attr in ('head_prefix', 'stylesheet', 'head', 'body_prefix', 'body_pre_docinfo', 'docinfo', 'body', 'fragment', 'body_suffix'): setattr(self, attr, getattr(visitor, attr)) def assemble_parts(self): writers.Writer.assemble_parts(self) for part in ('title', 'subtitle', 'docinfo', 'body', 'header', 'footer', 'meta', 'stylesheet', 'fragment', 'html_prolog', 'html_head', 'html_title', 'html_subtitle', 'html_body'): self.parts[part] = ''.join(getattr(self.visitor, part)) class HTMLTranslator(nodes.NodeVisitor): """ This HTML writer has been optimized to produce visually compact lists (less vertical whitespace). HTML's mixed content models allow list items to contain "<li><p>body elements</p></li>" or "<li>just text</li>" or even "<li>text<p>and body elements</p>combined</li>", each with different effects. It would be best to stick with strict body elements in list items, but they affect vertical spacing in browsers (although they really shouldn't). Here is an outline of the optimization: - Check for and omit <p> tags in "simple" lists: list items contain either a single paragraph, a nested simple list, or a paragraph followed by a nested simple list. This means that this list can be compact: - Item 1. - Item 2. But this list cannot be compact: - Item 1. This second paragraph forces space between list items. - Item 2. - In non-list contexts, omit <p> tags on a paragraph if that paragraph is the only child of its parent (footnotes & citations are allowed a label first). - Regardless of the above, in definitions, table cells, field bodies, option descriptions, and list items, mark the first child with 'class="first"' and the last child with 'class="last"'. The stylesheet sets the margins (top & bottom respectively) to 0 for these elements. The ``no_compact_lists`` setting (``--no-compact-lists`` command-line option) disables list whitespace optimization. """ xml_declaration = '<?xml version="1.0" encoding="%s" ?>\n' doctype = ('<!DOCTYPE html' ' PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' ' "http://www.w3.org/TR/xhtml1/DTD/' 'xhtml1-transitional.dtd">\n') head_prefix_template = ('<html xmlns="http://www.w3.org/1999/xhtml"' ' xml:lang="%s" lang="%s">\n<head>\n') content_type = ('<meta http-equiv="Content-Type"' ' content="text/html; charset=%s" />\n') generator = ('<meta name="generator" content="Docutils %s: ' 'http://docutils.sourceforge.net/" />\n') stylesheet_link = '<link rel="stylesheet" href="%s" type="text/css" />\n' embedded_stylesheet = '<style type="text/css">\n\n%s\n</style>\n' named_tags = ['a', 'applet', 'form', 'frame', 'iframe', 'img', 'map'] words_and_spaces = re.compile(r'\S+| +|\n') def __init__(self, document): nodes.NodeVisitor.__init__(self, document) self.settings = settings = document.settings lcode = settings.language_code self.language = languages.get_language(lcode) self.meta = [self.content_type % settings.output_encoding, self.generator % docutils.__version__] self.head_prefix = [] self.html_prolog = [] if settings.xml_declaration: self.head_prefix.append(self.xml_declaration % settings.output_encoding) # encoding not interpolated: self.html_prolog.append(self.xml_declaration) self.head_prefix.extend([self.doctype, self.head_prefix_template % (lcode, lcode)]) self.html_prolog.append(self.doctype) self.head = self.meta[:] stylesheet = utils.get_stylesheet_reference(settings) self.stylesheet = [] if stylesheet: if settings.embed_stylesheet: stylesheet = utils.get_stylesheet_reference( settings, os.path.join(os.getcwd(), 'dummy')) settings.record_dependencies.add(stylesheet) stylesheet_text = open(stylesheet).read() self.stylesheet = [self.embedded_stylesheet % stylesheet_text] else: self.stylesheet = [self.stylesheet_link % self.encode(stylesheet)] self.body_prefix = ['</head>\n<body>\n'] # document title, subtitle display self.body_pre_docinfo = [] # author, date, etc. self.docinfo = [] self.body = [] self.fragment = [] self.body_suffix = ['</body>\n</html>\n'] self.section_level = 0 self.initial_header_level = int(settings.initial_header_level) # A heterogenous stack used in conjunction with the tree traversal. # Make sure that the pops correspond to the pushes: self.context = [] self.topic_classes = [] self.colspecs = [] self.compact_p = 1 self.compact_simple = None self.compact_field_list = None self.in_docinfo = None self.in_sidebar = None self.title = [] self.subtitle = [] self.header = [] self.footer = [] self.html_head = [self.content_type] # charset not interpolated self.html_title = [] self.html_subtitle = [] self.html_body = [] self.in_document_title = 0 self.in_mailto = 0 self.author_in_authors = None def astext(self): return ''.join(self.head_prefix + self.head + self.stylesheet + self.body_prefix + self.body_pre_docinfo + self.docinfo + self.body + self.body_suffix) def encode(self, text): """Encode special characters in `text` & return.""" # @@@ A codec to do these and all other HTML entities would be nice. text = text.replace("&", "&amp;") text = text.replace("<", "&lt;") text = text.replace('"', "&quot;") text = text.replace(">", "&gt;") text = text.replace("@", "&#64;") # may thwart some address harvesters # Replace the non-breaking space character with the HTML entity: text = text.replace(u'\u00a0', "&nbsp;") return text def cloak_mailto(self, uri): """Try to hide a mailto: URL from harvesters.""" # Encode "@" using a URL octet reference (see RFC 1738). # Further cloaking with HTML entities will be done in the # `attval` function. return uri.replace('@', '%40') def cloak_email(self, addr): """Try to hide the link text of a email link from harversters.""" # Surround at-signs and periods with <span> tags. ("@" has # already been encoded to "&#64;" by the `encode` method.) addr = addr.replace('&#64;', '<span>&#64;</span>') addr = addr.replace('.', '<span>&#46;</span>') return addr def attval(self, text, whitespace=re.compile('[\n\r\t\v\f]')): """Cleanse, HTML encode, and return attribute value text.""" encoded = self.encode(whitespace.sub(' ', text)) if self.in_mailto and self.settings.cloak_email_addresses: # Cloak at-signs ("%40") and periods with HTML entities. encoded = encoded.replace('%40', '&#37;&#52;&#48;') encoded = encoded.replace('.', '&#46;') return encoded def starttag(self, node, tagname, suffix='\n', empty=0, **attributes): """ Construct and return a start tag given a node (id & class attributes are extracted), tag name, and optional attributes. """ tagname = tagname.lower() prefix = [] atts = {} ids = [] for (name, value) in attributes.items(): atts[name.lower()] = value classes = node.get('classes', []) if atts.has_key('class'): classes.append(atts['class']) if classes: atts['class'] = ' '.join(classes) assert not atts.has_key('id') ids.extend(node.get('ids', [])) if atts.has_key('ids'): ids.extend(atts['ids']) del atts['ids'] if ids: atts['id'] = ids[0] for id in ids[1:]: # Add empty "span" elements for additional IDs. Note # that we cannot use empty "a" elements because there # may be targets inside of references, but nested "a" # elements aren't allowed in XHTML (even if they do # not all have a "href" attribute). if empty: # Empty tag. Insert target right in front of element. prefix.append('<span id="%s"></span>' % id) else: # Non-empty tag. Place the auxiliary <span> tag # *inside* the element, as the first child. suffix += '<span id="%s"></span>' % id # !!! next 2 lines to be removed in Docutils 0.5: if atts.has_key('id') and tagname in self.named_tags: atts['name'] = atts['id'] # for compatibility with old browsers attlist = atts.items() attlist.sort() parts = [tagname] for name, value in attlist: # value=None was used for boolean attributes without # value, but this isn't supported by XHTML. assert value is not None if isinstance(value, ListType): values = [unicode(v) for v in value] parts.append('%s="%s"' % (name.lower(), self.attval(' '.join(values)))) else: try: uval = unicode(value) except TypeError: # for Python 2.1 compatibility: uval = unicode(str(value)) parts.append('%s="%s"' % (name.lower(), self.attval(uval))) if empty: infix = ' /' else: infix = '' return ''.join(prefix) + '<%s%s>' % (' '.join(parts), infix) + suffix def emptytag(self, node, tagname, suffix='\n', **attributes): """Construct and return an XML-compatible empty tag.""" return self.starttag(node, tagname, suffix, empty=1, **attributes) # !!! to be removed in Docutils 0.5 (change calls to use "starttag"): def start_tag_with_title(self, node, tagname, **atts): """ID and NAME attributes will be handled in the title.""" node = {'classes': node.get('classes', [])} return self.starttag(node, tagname, **atts) def set_class_on_child(self, node, class_, index=0): """ Set class `class_` on the visible child no. index of `node`. Do nothing if node has fewer children than `index`. """ children = [n for n in node if not isinstance(n, nodes.Invisible)] try: child = children[index] except IndexError: return child['classes'].append(class_) def set_first_last(self, node): self.set_class_on_child(node, 'first', 0) self.set_class_on_child(node, 'last', -1) def visit_Text(self, node): text = node.astext() encoded = self.encode(text) if self.in_mailto and self.settings.cloak_email_addresses: encoded = self.cloak_email(encoded) self.body.append(encoded) def depart_Text(self, node): pass def visit_abbreviation(self, node): # @@@ implementation incomplete ("title" attribute) self.body.append(self.starttag(node, 'abbr', '')) def depart_abbreviation(self, node): self.body.append('</abbr>') def visit_acronym(self, node): # @@@ implementation incomplete ("title" attribute) self.body.append(self.starttag(node, 'acronym', '')) def depart_acronym(self, node): self.body.append('</acronym>') def visit_address(self, node): self.visit_docinfo_item(node, 'address', meta=None) self.body.append(self.starttag(node, 'pre', CLASS='address')) def depart_address(self, node): self.body.append('\n</pre>\n') self.depart_docinfo_item() def visit_admonition(self, node, name=''): self.body.append(self.start_tag_with_title( node, 'div', CLASS=(name or 'admonition'))) if name: node.insert(0, nodes.title(name, self.language.labels[name])) self.set_first_last(node) def depart_admonition(self, node=None): self.body.append('</div>\n') def visit_attention(self, node): self.visit_admonition(node, 'attention') def depart_attention(self, node): self.depart_admonition() attribution_formats = {'dash': ('&mdash;', ''), 'parentheses': ('(', ')'), 'parens': ('(', ')'), 'none': ('', '')} def visit_attribution(self, node): prefix, suffix = self.attribution_formats[self.settings.attribution] self.context.append(suffix) self.body.append( self.starttag(node, 'p', prefix, CLASS='attribution')) def depart_attribution(self, node): self.body.append(self.context.pop() + '</p>\n') def visit_author(self, node): if isinstance(node.parent, nodes.authors): if self.author_in_authors: self.body.append('\n<br />') else: self.visit_docinfo_item(node, 'author') def depart_author(self, node): if isinstance(node.parent, nodes.authors): self.author_in_authors += 1 else: self.depart_docinfo_item() def visit_authors(self, node): self.visit_docinfo_item(node, 'authors') self.author_in_authors = 0 # initialize counter def depart_authors(self, node): self.depart_docinfo_item() self.author_in_authors = None def visit_block_quote(self, node): self.body.append(self.starttag(node, 'blockquote')) def depart_block_quote(self, node): self.body.append('</blockquote>\n') def check_simple_list(self, node): """Check for a simple list that can be rendered compactly.""" visitor = SimpleListChecker(self.document) try: node.walk(visitor) except nodes.NodeFound: return None else: return 1 def is_compactable(self, node): return ('compact' in node['classes'] or (self.settings.compact_lists and 'open' not in node['classes'] and (self.compact_simple or self.topic_classes == ['contents'] or self.check_simple_list(node)))) def visit_bullet_list(self, node): atts = {} old_compact_simple = self.compact_simple self.context.append((self.compact_simple, self.compact_p)) self.compact_p = None self.compact_simple = self.is_compactable(node) if self.compact_simple and not old_compact_simple: atts['class'] = 'simple' self.body.append(self.starttag(node, 'ul', **atts)) def depart_bullet_list(self, node): self.compact_simple, self.compact_p = self.context.pop() self.body.append('</ul>\n') def visit_caption(self, node): self.body.append(self.starttag(node, 'p', '', CLASS='caption')) def depart_caption(self, node): self.body.append('</p>\n') def visit_caution(self, node): self.visit_admonition(node, 'caution') def depart_caution(self, node): self.depart_admonition() def visit_citation(self, node): self.body.append(self.starttag(node, 'table', CLASS='docutils citation', frame="void", rules="none")) self.body.append('<colgroup><col class="label" /><col /></colgroup>\n' '<tbody valign="top">\n' '<tr>') self.footnote_backrefs(node) def depart_citation(self, node): self.body.append('</td></tr>\n' '</tbody>\n</table>\n') def visit_citation_reference(self, node): href = '#' + node['refid'] self.body.append(self.starttag( node, 'a', '[', CLASS='citation-reference', href=href)) def depart_citation_reference(self, node): self.body.append(']</a>') def visit_classifier(self, node): self.body.append(' <span class="classifier-delimiter">:</span> ') self.body.append(self.starttag(node, 'span', '', CLASS='classifier')) def depart_classifier(self, node): self.body.append('</span>') def visit_colspec(self, node): self.colspecs.append(node) # "stubs" list is an attribute of the tgroup element: node.parent.stubs.append(node.attributes.get('stub')) def depart_colspec(self, node): pass def write_colspecs(self): width = 0 for node in self.colspecs: width += node['colwidth'] for node in self.colspecs: colwidth = int(node['colwidth'] * 100.0 / width + 0.5) self.body.append(self.emptytag(node, 'col', width='%i%%' % colwidth)) self.colspecs = [] def visit_comment(self, node, sub=re.compile('-(?=-)').sub): """Escape double-dashes in comment text.""" self.body.append('<!-- %s -->\n' % sub('- ', node.astext())) # Content already processed: raise nodes.SkipNode def visit_compound(self, node): self.body.append(self.starttag(node, 'div', CLASS='compound')) if len(node) > 1: node[0]['classes'].append('compound-first') node[-1]['classes'].append('compound-last') for child in node[1:-1]: child['classes'].append('compound-middle') def depart_compound(self, node): self.body.append('</div>\n') def visit_container(self, node): self.body.append(self.starttag(node, 'div', CLASS='container')) def depart_container(self, node): self.body.append('</div>\n') def visit_contact(self, node): self.visit_docinfo_item(node, 'contact', meta=None) def depart_contact(self, node): self.depart_docinfo_item() def visit_copyright(self, node): self.visit_docinfo_item(node, 'copyright') def depart_copyright(self, node): self.depart_docinfo_item() def visit_danger(self, node): self.visit_admonition(node, 'danger') def depart_danger(self, node): self.depart_admonition() def visit_date(self, node): self.visit_docinfo_item(node, 'date') def depart_date(self, node): self.depart_docinfo_item() def visit_decoration(self, node): pass def depart_decoration(self, node): pass def visit_definition(self, node): self.body.append('</dt>\n') self.body.append(self.starttag(node, 'dd', '')) self.set_first_last(node) def depart_definition(self, node): self.body.append('</dd>\n') def visit_definition_list(self, node): self.body.append(self.starttag(node, 'dl', CLASS='docutils')) def depart_definition_list(self, node): self.body.append('</dl>\n') def visit_definition_list_item(self, node): pass def depart_definition_list_item(self, node): pass def visit_description(self, node): self.body.append(self.starttag(node, 'td', '')) self.set_first_last(node) def depart_description(self, node): self.body.append('</td>') def visit_docinfo(self, node): self.context.append(len(self.body)) self.body.append(self.starttag(node, 'table', CLASS='docinfo', frame="void", rules="none")) self.body.append('<col class="docinfo-name" />\n' '<col class="docinfo-content" />\n' '<tbody valign="top">\n') self.in_docinfo = 1 def depart_docinfo(self, node): self.body.append('</tbody>\n</table>\n') self.in_docinfo = None start = self.context.pop() self.docinfo = self.body[start:] self.body = [] def visit_docinfo_item(self, node, name, meta=1): if meta: meta_tag = '<meta name="%s" content="%s" />\n' \ % (name, self.attval(node.astext())) self.add_meta(meta_tag) self.body.append(self.starttag(node, 'tr', '')) self.body.append('<th class="docinfo-name">%s:</th>\n<td>' % self.language.labels[name]) if len(node): if isinstance(node[0], nodes.Element): node[0]['classes'].append('first') if isinstance(node[-1], nodes.Element): node[-1]['classes'].append('last') def depart_docinfo_item(self): self.body.append('</td></tr>\n') def visit_doctest_block(self, node): self.body.append(self.starttag(node, 'pre', CLASS='doctest-block')) def depart_doctest_block(self, node): self.body.append('\n</pre>\n') def visit_document(self, node): self.head.append('<title>%s</title>\n' % self.encode(node.get('title', ''))) def depart_document(self, node): self.fragment.extend(self.body) self.body_prefix.append(self.starttag(node, 'div', CLASS='document')) self.body_suffix.insert(0, '</div>\n') # skip content-type meta tag with interpolated charset value: self.html_head.extend(self.head[1:]) self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo + self.docinfo + self.body + self.body_suffix[:-1]) def visit_emphasis(self, node): self.body.append('<em>') def depart_emphasis(self, node): self.body.append('</em>') def visit_entry(self, node): atts = {'class': []} if isinstance(node.parent.parent, nodes.thead): atts['class'].append('head') if node.parent.parent.parent.stubs[node.parent.column]: # "stubs" list is an attribute of the tgroup element atts['class'].append('stub') if atts['class']: tagname = 'th' atts['class'] = ' '.join(atts['class']) else: tagname = 'td' del atts['class'] node.parent.column += 1 if node.has_key('morerows'): atts['rowspan'] = node['morerows'] + 1 if node.has_key('morecols'): atts['colspan'] = node['morecols'] + 1 node.parent.column += node['morecols'] self.body.append(self.starttag(node, tagname, '', **atts)) self.context.append('</%s>\n' % tagname.lower()) if len(node) == 0: # empty cell self.body.append('&nbsp;') self.set_first_last(node) def depart_entry(self, node): self.body.append(self.context.pop()) def visit_enumerated_list(self, node): """ The 'start' attribute does not conform to HTML 4.01's strict.dtd, but CSS1 doesn't help. CSS2 isn't widely enough supported yet to be usable. """ atts = {} if node.has_key('start'): atts['start'] = node['start'] if node.has_key('enumtype'): atts['class'] = node['enumtype'] # @@@ To do: prefix, suffix. How? Change prefix/suffix to a # single "format" attribute? Use CSS2? old_compact_simple = self.compact_simple self.context.append((self.compact_simple, self.compact_p)) self.compact_p = None self.compact_simple = self.is_compactable(node) if self.compact_simple and not old_compact_simple: atts['class'] = (atts.get('class', '') + ' simple').strip() self.body.append(self.starttag(node, 'ol', **atts)) def depart_enumerated_list(self, node): self.compact_simple, self.compact_p = self.context.pop() self.body.append('</ol>\n') def visit_error(self, node): self.visit_admonition(node, 'error') def depart_error(self, node): self.depart_admonition() def visit_field(self, node): self.body.append(self.starttag(node, 'tr', '', CLASS='field')) def depart_field(self, node): self.body.append('</tr>\n') def visit_field_body(self, node): self.body.append(self.starttag(node, 'td', '', CLASS='field-body')) self.set_class_on_child(node, 'first', 0) field = node.parent if (self.compact_field_list or isinstance(field.parent, nodes.docinfo) or field.parent.index(field) == len(field.parent) - 1): # If we are in a compact list, the docinfo, or if this is # the last field of the field list, do not add vertical # space after last element. self.set_class_on_child(node, 'last', -1) def depart_field_body(self, node): self.body.append('</td>\n') def visit_field_list(self, node): self.context.append((self.compact_field_list, self.compact_p)) self.compact_p = None if 'compact' in node['classes']: self.compact_field_list = 1 elif (self.settings.compact_field_lists and 'open' not in node['classes']): self.compact_field_list = 1 if self.compact_field_list: for field in node: field_body = field[-1] assert isinstance(field_body, nodes.field_body) children = [n for n in field_body if not isinstance(n, nodes.Invisible)] if not (len(children) == 0 or len(children) == 1 and isinstance(children[0], nodes.paragraph)): self.compact_field_list = 0 break self.body.append(self.starttag(node, 'table', frame='void', rules='none', CLASS='docutils field-list')) self.body.append('<col class="field-name" />\n' '<col class="field-body" />\n' '<tbody valign="top">\n') def depart_field_list(self, node): self.body.append('</tbody>\n</table>\n') self.compact_field_list, self.compact_p = self.context.pop() def visit_field_name(self, node): atts = {} if self.in_docinfo: atts['class'] = 'docinfo-name' else: atts['class'] = 'field-name' if ( self.settings.field_name_limit and len(node.astext()) > self.settings.field_name_limit): atts['colspan'] = 2 self.context.append('</tr>\n<tr><td>&nbsp;</td>') else: self.context.append('') self.body.append(self.starttag(node, 'th', '', **atts)) def depart_field_name(self, node): self.body.append(':</th>') self.body.append(self.context.pop()) def visit_figure(self, node): atts = {'class': 'figure'} if node.get('width'): atts['style'] = 'width: %spx' % node['width'] if node.get('align'): atts['align'] = node['align'] self.body.append(self.starttag(node, 'div', **atts)) def depart_figure(self, node): self.body.append('</div>\n') def visit_footer(self, node): self.context.append(len(self.body)) def depart_footer(self, node): start = self.context.pop() footer = [self.starttag(node, 'div', CLASS='footer'), '<hr class="footer" />\n'] footer.extend(self.body[start:]) footer.append('\n</div>\n') self.footer.extend(footer) self.body_suffix[:0] = footer del self.body[start:] def visit_footnote(self, node): self.body.append(self.starttag(node, 'table', CLASS='docutils footnote', frame="void", rules="none")) self.body.append('<colgroup><col class="label" /><col /></colgroup>\n' '<tbody valign="top">\n' '<tr>') self.footnote_backrefs(node) def footnote_backrefs(self, node): backlinks = [] backrefs = node['backrefs'] if self.settings.footnote_backlinks and backrefs: if len(backrefs) == 1: self.context.append('') self.context.append( '<a class="fn-backref" href="#%s" name="%s">' % (backrefs[0], node['ids'][0])) else: i = 1 for backref in backrefs: backlinks.append('<a class="fn-backref" href="#%s">%s</a>' % (backref, i)) i += 1 self.context.append('<em>(%s)</em> ' % ', '.join(backlinks)) self.context.append('<a name="%s">' % node['ids'][0]) else: self.context.append('') self.context.append('<a name="%s">' % node['ids'][0]) # If the node does not only consist of a label. if len(node) > 1: # If there are preceding backlinks, we do not set class # 'first', because we need to retain the top-margin. if not backlinks: node[1]['classes'].append('first') node[-1]['classes'].append('last') def depart_footnote(self, node): self.body.append('</td></tr>\n' '</tbody>\n</table>\n') def visit_footnote_reference(self, node): href = '#' + node['refid'] format = self.settings.footnote_references if format == 'brackets': suffix = '[' self.context.append(']') else: assert format == 'superscript' suffix = '<sup>' self.context.append('</sup>') self.body.append(self.starttag(node, 'a', suffix, CLASS='footnote-reference', href=href)) def depart_footnote_reference(self, node): self.body.append(self.context.pop() + '</a>') def visit_generated(self, node): pass def depart_generated(self, node): pass def visit_header(self, node): self.context.append(len(self.body)) def depart_header(self, node): start = self.context.pop() header = [self.starttag(node, 'div', CLASS='header')] header.extend(self.body[start:]) header.append('\n<hr class="header"/>\n</div>\n') self.body_prefix.extend(header) self.header.extend(header) del self.body[start:] def visit_hint(self, node): self.visit_admonition(node, 'hint') def depart_hint(self, node): self.depart_admonition() def visit_image(self, node): atts = {} atts['src'] = node['uri'] if node.has_key('width'): atts['width'] = node['width'] if node.has_key('height'): atts['height'] = node['height'] if node.has_key('scale'): if Image and not (node.has_key('width') and node.has_key('height')): try: im = Image.open(str(atts['src'])) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. pass else: if not atts.has_key('width'): atts['width'] = str(im.size[0]) if not atts.has_key('height'): atts['height'] = str(im.size[1]) del im for att_name in 'width', 'height': if atts.has_key(att_name): match = re.match(r'([0-9.]+)(\S*)$', atts[att_name]) assert match atts[att_name] = '%s%s' % ( float(match.group(1)) * (float(node['scale']) / 100), match.group(2)) style = [] for att_name in 'width', 'height': if atts.has_key(att_name): if re.match(r'^[0-9.]+$', atts[att_name]): # Interpret unitless values as pixels. atts[att_name] += 'px' style.append('%s: %s;' % (att_name, atts[att_name])) del atts[att_name] if style: atts['style'] = ' '.join(style) atts['alt'] = node.get('alt', atts['src']) if (isinstance(node.parent, nodes.TextElement) or (isinstance(node.parent, nodes.reference) and not isinstance(node.parent.parent, nodes.TextElement))): # Inline context or surrounded by <a>...</a>. suffix = '' else: suffix = '\n' if node.has_key('align'): if node['align'] == 'center': # "align" attribute is set in surrounding "div" element. self.body.append('<div align="center" class="align-center">') self.context.append('</div>\n') suffix = '' else: # "align" attribute is set in "img" element. atts['align'] = node['align'] self.context.append('') atts['class'] = 'align-%s' % node['align'] else: self.context.append('') self.body.append(self.emptytag(node, 'img', suffix, **atts)) def depart_image(self, node): self.body.append(self.context.pop()) def visit_important(self, node): self.visit_admonition(node, 'important') def depart_important(self, node): self.depart_admonition() def visit_inline(self, node): self.body.append(self.starttag(node, 'span', '')) def depart_inline(self, node): self.body.append('</span>') def visit_label(self, node): self.body.append(self.starttag(node, 'td', '%s[' % self.context.pop(), CLASS='label')) def depart_label(self, node): self.body.append(']</a></td><td>%s' % self.context.pop()) def visit_legend(self, node): self.body.append(self.starttag(node, 'div', CLASS='legend')) def depart_legend(self, node): self.body.append('</div>\n') def visit_line(self, node): self.body.append(self.starttag(node, 'div', suffix='', CLASS='line')) if not len(node): self.body.append('<br />') def depart_line(self, node): self.body.append('</div>\n') def visit_line_block(self, node): self.body.append(self.starttag(node, 'div', CLASS='line-block')) def depart_line_block(self, node): self.body.append('</div>\n') def visit_list_item(self, node): self.body.append(self.starttag(node, 'li', '')) if len(node): node[0]['classes'].append('first') def depart_list_item(self, node): self.body.append('</li>\n') def visit_literal(self, node): """Process text to prevent tokens from wrapping.""" self.body.append( self.starttag(node, 'tt', '', CLASS='docutils literal')) text = node.astext() for token in self.words_and_spaces.findall(text): if token.strip(): # Protect text like "--an-option" from bad line wrapping: self.body.append('<span class="pre">%s</span>' % self.encode(token)) elif token in ('\n', ' '): # Allow breaks at whitespace: self.body.append(token) else: # Protect runs of multiple spaces; the last space can wrap: self.body.append('&nbsp;' * (len(token) - 1) + ' ') self.body.append('</tt>') # Content already processed: raise nodes.SkipNode def visit_literal_block(self, node): self.body.append(self.starttag(node, 'pre', CLASS='literal-block')) def depart_literal_block(self, node): self.body.append('\n</pre>\n') def visit_meta(self, node): meta = self.emptytag(node, 'meta', **node.non_default_attributes()) self.add_meta(meta) def depart_meta(self, node): pass def add_meta(self, tag): self.meta.append(tag) self.head.append(tag) def visit_note(self, node): self.visit_admonition(node, 'note') def depart_note(self, node): self.depart_admonition() def visit_option(self, node): if self.context[-1]: self.body.append(', ') self.body.append(self.starttag(node, 'span', '', CLASS='option')) def depart_option(self, node): self.body.append('</span>') self.context[-1] += 1 def visit_option_argument(self, node): self.body.append(node.get('delimiter', ' ')) self.body.append(self.starttag(node, 'var', '')) def depart_option_argument(self, node): self.body.append('</var>') def visit_option_group(self, node): atts = {} if ( self.settings.option_limit and len(node.astext()) > self.settings.option_limit): atts['colspan'] = 2 self.context.append('</tr>\n<tr><td>&nbsp;</td>') else: self.context.append('') self.body.append( self.starttag(node, 'td', CLASS='option-group', **atts)) self.body.append('<kbd>') self.context.append(0) # count number of options def depart_option_group(self, node): self.context.pop() self.body.append('</kbd></td>\n') self.body.append(self.context.pop()) def visit_option_list(self, node): self.body.append( self.starttag(node, 'table', CLASS='docutils option-list', frame="void", rules="none")) self.body.append('<col class="option" />\n' '<col class="description" />\n' '<tbody valign="top">\n') def depart_option_list(self, node): self.body.append('</tbody>\n</table>\n') def visit_option_list_item(self, node): self.body.append(self.starttag(node, 'tr', '')) def depart_option_list_item(self, node): self.body.append('</tr>\n') def visit_option_string(self, node): pass def depart_option_string(self, node): pass def visit_organization(self, node): self.visit_docinfo_item(node, 'organization') def depart_organization(self, node): self.depart_docinfo_item() def should_be_compact_paragraph(self, node): """ Determine if the <p> tags around paragraph ``node`` can be omitted. """ if (isinstance(node.parent, nodes.document) or isinstance(node.parent, nodes.compound)): # Never compact paragraphs in document or compound. return 0 for key, value in node.attlist(): if (node.is_not_default(key) and not (key == 'classes' and value in ([], ['first'], ['last'], ['first', 'last']))): # Attribute which needs to survive. return 0 first = isinstance(node.parent[0], nodes.label) # skip label for child in node.parent.children[first:]: # only first paragraph can be compact if isinstance(child, nodes.Invisible): continue if child is node: break return 0 if ( self.compact_simple or self.compact_field_list or (self.compact_p and (len(node.parent) == 1 or len(node.parent) == 2 and isinstance(node.parent[0], nodes.label)))): return 1 return 0 def visit_paragraph(self, node): if self.should_be_compact_paragraph(node): self.context.append('') else: self.body.append(self.starttag(node, 'p', '')) self.context.append('</p>\n') def depart_paragraph(self, node): self.body.append(self.context.pop()) def visit_problematic(self, node): if node.hasattr('refid'): self.body.append('<a href="#%s" name="%s">' % (node['refid'], node['ids'][0])) self.context.append('</a>') else: self.context.append('') self.body.append(self.starttag(node, 'span', '', CLASS='problematic')) def depart_problematic(self, node): self.body.append('</span>') self.body.append(self.context.pop()) def visit_raw(self, node): if 'html' in node.get('format', '').split(): t = isinstance(node.parent, nodes.TextElement) and 'span' or 'div' if node['classes']: self.body.append(self.starttag(node, t, suffix='')) self.body.append(node.astext()) if node['classes']: self.body.append('</%s>' % t) # Keep non-HTML raw text out of output: raise nodes.SkipNode def visit_reference(self, node): if node.has_key('refuri'): href = node['refuri'] if ( self.settings.cloak_email_addresses and href.startswith('mailto:')): href = self.cloak_mailto(href) self.in_mailto = 1 else: assert node.has_key('refid'), \ 'References must have "refuri" or "refid" attribute.' href = '#' + node['refid'] atts = {'href': href, 'class': 'reference'} if not isinstance(node.parent, nodes.TextElement): assert len(node) == 1 and isinstance(node[0], nodes.image) atts['class'] += ' image-reference' self.body.append(self.starttag(node, 'a', '', **atts)) def depart_reference(self, node): self.body.append('</a>') if not isinstance(node.parent, nodes.TextElement): self.body.append('\n') self.in_mailto = 0 def visit_revision(self, node): self.visit_docinfo_item(node, 'revision', meta=None) def depart_revision(self, node): self.depart_docinfo_item() def visit_row(self, node): self.body.append(self.starttag(node, 'tr', '')) node.column = 0 def depart_row(self, node): self.body.append('</tr>\n') def visit_rubric(self, node): self.body.append(self.starttag(node, 'p', '', CLASS='rubric')) def depart_rubric(self, node): self.body.append('</p>\n') def visit_section(self, node): self.section_level += 1 self.body.append( self.start_tag_with_title(node, 'div', CLASS='section')) def depart_section(self, node): self.section_level -= 1 self.body.append('</div>\n') def visit_sidebar(self, node): self.body.append( self.start_tag_with_title(node, 'div', CLASS='sidebar')) self.set_first_last(node) self.in_sidebar = 1 def depart_sidebar(self, node): self.body.append('</div>\n') self.in_sidebar = None def visit_status(self, node): self.visit_docinfo_item(node, 'status', meta=None) def depart_status(self, node): self.depart_docinfo_item() def visit_strong(self, node): self.body.append('<strong>') def depart_strong(self, node): self.body.append('</strong>') def visit_subscript(self, node): self.body.append(self.starttag(node, 'sub', '')) def depart_subscript(self, node): self.body.append('</sub>') def visit_substitution_definition(self, node): """Internal only.""" raise nodes.SkipNode def visit_substitution_reference(self, node): self.unimplemented_visit(node) def visit_subtitle(self, node): if isinstance(node.parent, nodes.sidebar): self.body.append(self.starttag(node, 'p', '', CLASS='sidebar-subtitle')) self.context.append('</p>\n') elif isinstance(node.parent, nodes.document): self.body.append(self.starttag(node, 'h2', '', CLASS='subtitle')) self.context.append('</h2>\n') self.in_document_title = len(self.body) elif isinstance(node.parent, nodes.section): tag = 'h%s' % (self.section_level + self.initial_header_level - 1) self.body.append( self.starttag(node, tag, '', CLASS='section-subtitle') + self.starttag({}, 'span', '', CLASS='section-subtitle')) self.context.append('</span></%s>\n' % tag) def depart_subtitle(self, node): self.body.append(self.context.pop()) if self.in_document_title: self.subtitle = self.body[self.in_document_title:-1] self.in_document_title = 0 self.body_pre_docinfo.extend(self.body) self.html_subtitle.extend(self.body) del self.body[:] def visit_superscript(self, node): self.body.append(self.starttag(node, 'sup', '')) def depart_superscript(self, node): self.body.append('</sup>') def visit_system_message(self, node): self.body.append(self.starttag(node, 'div', CLASS='system-message')) self.body.append('<p class="system-message-title">') attr = {} backref_text = '' if node['ids']: attr['name'] = node['ids'][0] if len(node['backrefs']): backrefs = node['backrefs'] if len(backrefs) == 1: backref_text = ('; <em><a href="#%s">backlink</a></em>' % backrefs[0]) else: i = 1 backlinks = [] for backref in backrefs: backlinks.append('<a href="#%s">%s</a>' % (backref, i)) i += 1 backref_text = ('; <em>backlinks: %s</em>' % ', '.join(backlinks)) if node.hasattr('line'): line = ', line %s' % node['line'] else: line = '' if attr: a_start = self.starttag({}, 'a', '', **attr) a_end = '</a>' else: a_start = a_end = '' self.body.append('System Message: %s%s/%s%s ' '(<tt class="docutils">%s</tt>%s)%s</p>\n' % (a_start, node['type'], node['level'], a_end, self.encode(node['source']), line, backref_text)) def depart_system_message(self, node): self.body.append('</div>\n') def visit_table(self, node): self.body.append( self.starttag(node, 'table', CLASS='docutils', border="1")) def depart_table(self, node): self.body.append('</table>\n') def visit_target(self, node): if not (node.has_key('refuri') or node.has_key('refid') or node.has_key('refname')): self.body.append(self.starttag(node, 'span', '', CLASS='target')) self.context.append('</span>') else: self.context.append('') def depart_target(self, node): self.body.append(self.context.pop()) def visit_tbody(self, node): self.write_colspecs() self.body.append(self.context.pop()) # '</colgroup>\n' or '' self.body.append(self.starttag(node, 'tbody', valign='top')) def depart_tbody(self, node): self.body.append('</tbody>\n') def visit_term(self, node): self.body.append(self.starttag(node, 'dt', '')) def depart_term(self, node): """ Leave the end tag to `self.visit_definition()`, in case there's a classifier. """ pass def visit_tgroup(self, node): # Mozilla needs <colgroup>: self.body.append(self.starttag(node, 'colgroup')) # Appended by thead or tbody: self.context.append('</colgroup>\n') node.stubs = [] def depart_tgroup(self, node): pass def visit_thead(self, node): self.write_colspecs() self.body.append(self.context.pop()) # '</colgroup>\n' # There may or may not be a <thead>; this is for <tbody> to use: self.context.append('') self.body.append(self.starttag(node, 'thead', valign='bottom')) def depart_thead(self, node): self.body.append('</thead>\n') def visit_tip(self, node): self.visit_admonition(node, 'tip') def depart_tip(self, node): self.depart_admonition() def visit_title(self, node, move_ids=1): """Only 6 section levels are supported by HTML.""" check_id = 0 close_tag = '</p>\n' if isinstance(node.parent, nodes.topic): self.body.append( self.starttag(node, 'p', '', CLASS='topic-title first')) check_id = 1 elif isinstance(node.parent, nodes.sidebar): self.body.append( self.starttag(node, 'p', '', CLASS='sidebar-title')) check_id = 1 elif isinstance(node.parent, nodes.Admonition): self.body.append( self.starttag(node, 'p', '', CLASS='admonition-title')) check_id = 1 elif isinstance(node.parent, nodes.table): self.body.append( self.starttag(node, 'caption', '')) check_id = 1 close_tag = '</caption>\n' elif isinstance(node.parent, nodes.document): self.body.append(self.starttag(node, 'h1', '', CLASS='title')) self.context.append('</h1>\n') self.in_document_title = len(self.body) else: assert isinstance(node.parent, nodes.section) h_level = self.section_level + self.initial_header_level - 1 atts = {} if (len(node.parent) >= 2 and isinstance(node.parent[1], nodes.subtitle)): atts['CLASS'] = 'with-subtitle' self.body.append( self.starttag(node, 'h%s' % h_level, '', **atts)) atts = {} # !!! conditional to be removed in Docutils 0.5: if move_ids: if node.parent['ids']: atts['ids'] = node.parent['ids'] if node.hasattr('refid'): atts['class'] = 'toc-backref' atts['href'] = '#' + node['refid'] if atts: self.body.append(self.starttag({}, 'a', '', **atts)) self.context.append('</a></h%s>\n' % (h_level)) else: self.context.append('</h%s>\n' % (h_level)) # !!! conditional to be removed in Docutils 0.5: if check_id: if node.parent['ids']: atts={'ids': node.parent['ids']} self.body.append( self.starttag({}, 'a', '', **atts)) self.context.append('</a>' + close_tag) else: self.context.append(close_tag) def depart_title(self, node): self.body.append(self.context.pop()) if self.in_document_title: self.title = self.body[self.in_document_title:-1] self.in_document_title = 0 self.body_pre_docinfo.extend(self.body) self.html_title.extend(self.body) del self.body[:] def visit_title_reference(self, node): self.body.append(self.starttag(node, 'cite', '')) def depart_title_reference(self, node): self.body.append('</cite>') def visit_topic(self, node): self.body.append(self.start_tag_with_title(node, 'div', CLASS='topic')) self.topic_classes = node['classes'] def depart_topic(self, node): self.body.append('</div>\n') self.topic_classes = [] def visit_transition(self, node): self.body.append(self.emptytag(node, 'hr', CLASS='docutils')) def depart_transition(self, node): pass def visit_version(self, node): self.visit_docinfo_item(node, 'version', meta=None) def depart_version(self, node): self.depart_docinfo_item() def visit_warning(self, node): self.visit_admonition(node, 'warning') def depart_warning(self, node): self.depart_admonition() def unimplemented_visit(self, node): raise NotImplementedError('visiting unimplemented node type: %s' % node.__class__.__name__) class SimpleListChecker(nodes.GenericNodeVisitor): """ Raise `nodes.NodeFound` if non-simple list item is encountered. Here "simple" means a list item containing nothing other than a single paragraph, a simple list, or a paragraph followed by a simple list. """ def default_visit(self, node): raise nodes.NodeFound def visit_bullet_list(self, node): pass def visit_enumerated_list(self, node): pass def visit_list_item(self, node): children = [] for child in node.children: if not isinstance(child, nodes.Invisible): children.append(child) if (children and isinstance(children[0], nodes.paragraph) and (isinstance(children[-1], nodes.bullet_list) or isinstance(children[-1], nodes.enumerated_list))): children.pop() if len(children) <= 1: return else: raise nodes.NodeFound def visit_paragraph(self, node): raise nodes.SkipNode def invisible_visit(self, node): """Invisible nodes should be ignored.""" raise nodes.SkipNode visit_comment = invisible_visit visit_substitution_definition = invisible_visit visit_target = invisible_visit visit_pending = invisible_visit
{ "repo_name": "santisiri/popego", "path": "envs/ALPHA-POPEGO/lib/python2.5/site-packages/docutils-0.4-py2.5.egg/docutils/writers/html4css1/__init__.py", "copies": "7", "size": "60534", "license": "bsd-3-clause", "hash": -7915463054327902000, "line_mean": 36.8101186758, "line_max": 79, "alpha_frac": 0.5473287739, "autogenerated": false, "ratio": 3.9510475817505384, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7998376355650538, "avg_score": null, "num_lines": null }
""" Directives for figures and simple images. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import directives, states from docutils.nodes import fully_normalize_name, whitespace_normalize_name from docutils.parsers.rst.roles import set_classes try: import Image # PIL except ImportError: Image = None align_h_values = ('left', 'center', 'right') align_v_values = ('top', 'middle', 'bottom') align_values = align_v_values + align_h_values def align(argument): return directives.choice(argument, align_values) def image(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): if options.has_key('align'): # check for align_v values only if isinstance(state, states.SubstitutionDef): if options['align'] not in align_v_values: error = state_machine.reporter.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option within a substitution definition. ' 'Valid values for "align" are: "%s".' % (name, options['align'], '", "'.join(align_v_values)), nodes.literal_block(block_text, block_text), line=lineno) return [error] elif options['align'] not in align_h_values: error = state_machine.reporter.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option. Valid values for "align" are: "%s".' % (name, options['align'], '", "'.join(align_h_values)), nodes.literal_block(block_text, block_text), line=lineno) return [error] messages = [] reference = directives.uri(arguments[0]) options['uri'] = reference reference_node = None if options.has_key('target'): block = states.escape2null(options['target']).splitlines() block = [line for line in block] target_type, data = state.parse_target(block, block_text, lineno) if target_type == 'refuri': reference_node = nodes.reference(refuri=data) elif target_type == 'refname': reference_node = nodes.reference( refname=fully_normalize_name(data), name=whitespace_normalize_name(data)) reference_node.indirect_reference_name = data state.document.note_refname(reference_node) else: # malformed target messages.append(data) # data is a system message del options['target'] set_classes(options) image_node = nodes.image(block_text, **options) if reference_node: reference_node += image_node return messages + [reference_node] else: return messages + [image_node] image.arguments = (1, 0, 1) image.options = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.nonnegative_int, 'align': align, 'target': directives.unchanged_required, 'class': directives.class_option} def figure_align(argument): return directives.choice(argument, align_h_values) def figure(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): figwidth = options.get('figwidth') if figwidth: del options['figwidth'] figclasses = options.get('figclass') if figclasses: del options['figclass'] align = options.get('align') if align: del options['align'] (image_node,) = image(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine) if isinstance(image_node, nodes.system_message): return [image_node] figure_node = nodes.figure('', image_node) if figwidth == 'image': if Image and state.document.settings.file_insertion_enabled: # PIL doesn't like Unicode paths: try: i = Image.open(str(image_node['uri'])) except (IOError, UnicodeError): pass else: state.document.settings.record_dependencies.add(image_node['uri']) figure_node['width'] = i.size[0] elif figwidth is not None: figure_node['width'] = figwidth if figclasses: figure_node['classes'] += figclasses if align: figure_node['align'] = align if content: node = nodes.Element() # anonymous container for parsing state.nested_parse(content, content_offset, node) first_node = node[0] if isinstance(first_node, nodes.paragraph): caption = nodes.caption(first_node.rawsource, '', *first_node.children) figure_node += caption elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0): error = state_machine.reporter.error( 'Figure caption must be a paragraph or empty comment.', nodes.literal_block(block_text, block_text), line=lineno) return [figure_node, error] if len(node) > 1: figure_node += nodes.legend('', *node[1:]) return [figure_node] def figwidth_value(argument): if argument.lower() == 'image': return 'image' else: return directives.nonnegative_int(argument) figure.arguments = (1, 0, 1) figure.options = {'figwidth': figwidth_value, 'figclass': directives.class_option} figure.options.update(image.options) figure.options['align'] = figure_align figure.content = 1
{ "repo_name": "indro/t2c", "path": "libs/external_libs/docutils-0.4/docutils/parsers/rst/directives/images.py", "copies": "6", "size": "6084", "license": "mit", "hash": -7656706128659305000, "line_mean": 39.0263157895, "line_max": 82, "alpha_frac": 0.5987836949, "autogenerated": false, "ratio": 4.075016744809109, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7673800439709109, "avg_score": null, "num_lines": null }
""" Docutils document tree element class library. Classes in CamelCase are abstract base classes or auxiliary classes. The one exception is `Text`, for a text (PCDATA) node; uppercase is used to differentiate from element classes. Classes in lower_case_with_underscores are element classes, matching the XML element generic identifiers in the DTD_. The position of each node (the level at which it can occur) is significant and is represented by abstract base classes (`Root`, `Structural`, `Body`, `Inline`, etc.). Certain transformations will be easier because we can use ``isinstance(node, base_class)`` to determine the position of the node in the hierarchy. .. _DTD: http://docutils.sourceforge.net/docs/ref/docutils.dtd """ __docformat__ = 'reStructuredText' import sys import os import re import warnings from types import IntType, SliceType, StringType, UnicodeType, \ TupleType, ListType, ClassType from UserString import UserString # ============================== # Functional Node Base Classes # ============================== class Node: """Abstract base class of nodes in a document tree.""" parent = None """Back-reference to the Node immediately containing this Node.""" document = None """The `document` node at the root of the tree containing this Node.""" source = None """Path or description of the input source which generated this Node.""" line = None """The line number (1-based) of the beginning of this Node in `source`.""" def __nonzero__(self): """ Node instances are always true, even if they're empty. A node is more than a simple container. Its boolean "truth" does not depend on having one or more subnodes in the doctree. Use `len()` to check node length. Use `None` to represent a boolean false value. """ return 1 def asdom(self, dom=None): """Return a DOM **fragment** representation of this Node.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() return self._dom_node(domroot) def pformat(self, indent=' ', level=0): """ Return an indented pseudo-XML representation, for test purposes. Override in subclasses. """ raise NotImplementedError def copy(self): """Return a copy of self.""" raise NotImplementedError def deepcopy(self): """Return a deep copy of self (also copying children).""" raise NotImplementedError def setup_child(self, child): child.parent = self if self.document: child.document = self.document if child.source is None: child.source = self.document.current_source if child.line is None: child.line = self.document.current_line def walk(self, visitor): """ Traverse a tree of `Node` objects, calling the `dispatch_visit()` method of `visitor` when entering each node. (The `walkabout()` method is similar, except it also calls the `dispatch_departure()` method before exiting each node.) This tree traversal supports limited in-place tree modifications. Replacing one node with one or more nodes is OK, as is removing an element. However, if the node removed or replaced occurs after the current node, the old node will still be traversed, and any new nodes will not. Within ``visit`` methods (and ``depart`` methods for `walkabout()`), `TreePruningException` subclasses may be raised (`SkipChildren`, `SkipSiblings`, `SkipNode`, `SkipDeparture`). Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` implementation for each `Node` subclass encountered. """ visitor.document.reporter.debug( 'docutils.nodes.Node.walk calling dispatch_visit for %s' % self.__class__.__name__) try: visitor.dispatch_visit(self) except (SkipChildren, SkipNode): return except SkipDeparture: # not applicable; ignore pass children = self.children try: for child in children[:]: child.walk(visitor) except SkipSiblings: pass def walkabout(self, visitor): """ Perform a tree traversal similarly to `Node.walk()` (which see), except also call the `dispatch_departure()` method before exiting each node. Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` and ``depart`` implementation for each `Node` subclass encountered. """ call_depart = 1 visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except SkipNode: return except SkipDeparture: call_depart = 0 children = self.children try: for child in children[:]: child.walkabout(visitor) except SkipSiblings: pass except SkipChildren: pass if call_depart: visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_departure ' 'for %s' % self.__class__.__name__) visitor.dispatch_departure(self) def traverse(self, condition=None, include_self=1, descend=1, siblings=0, ascend=0): """ Return an iterable containing * self (if include_self is true) * all descendants in tree traversal order (if descend is true) * all siblings (if siblings is true) and their descendants (if also descend is true) * the siblings of the parent (if ascend is true) and their descendants (if also descend is true), and so on If `condition` is not None, the iterable contains only nodes for which ``condition(node)`` is true. If `condition` is a node class ``cls``, it is equivalent to a function consisting of ``return isinstance(node, cls)``. If ascend is true, assume siblings to be true as well. For example, given the following tree:: <paragraph> <emphasis> <--- emphasis.traverse() and <strong> <--- strong.traverse() are called. Foo Bar <reference name="Baz" refid="baz"> Baz Then list(emphasis.traverse()) equals :: [<emphasis>, <strong>, <#text: Foo>, <#text: Bar>] and list(strong.traverse(ascend=1)) equals :: [<strong>, <#text: Foo>, <#text: Bar>, <reference>, <#text: Baz>] """ r = [] if ascend: siblings=1 if isinstance(condition, ClassType): node_class = condition def condition(node, node_class=node_class): return isinstance(node, node_class) if include_self and (condition is None or condition(self)): r.append(self) if descend and len(self.children): for child in self: r.extend(child.traverse( include_self=1, descend=1, siblings=0, ascend=0, condition=condition)) if siblings or ascend: node = self while node.parent: index = node.parent.index(node) for sibling in node.parent[index+1:]: r.extend(sibling.traverse(include_self=1, descend=descend, siblings=0, ascend=0, condition=condition)) if not ascend: break else: node = node.parent return r def next_node(self, condition=None, include_self=0, descend=1, siblings=0, ascend=0): """ Return the first node in the iterable returned by traverse(), or None if the iterable is empty. Parameter list is the same as of traverse. Note that include_self defaults to 0, though. """ iterable = self.traverse(condition=condition, include_self=include_self, descend=descend, siblings=siblings, ascend=ascend) try: return iterable[0] except IndexError: return None class Text(Node, UserString): """ Instances are terminal nodes (leaves) containing text only; no child nodes or attributes. Initialize by passing a string to the constructor. Access the text itself with the `astext` method. """ tagname = '#text' children = () """Text nodes have no children, and cannot have children.""" def __init__(self, data, rawsource=''): UserString.__init__(self, data) self.rawsource = rawsource """The raw text from which this element was constructed.""" def __repr__(self): data = repr(self.data) if len(data) > 70: data = repr(self.data[:64] + ' ...') return '<%s: %s>' % (self.tagname, data) def __len__(self): return len(self.data) def shortrepr(self): data = repr(self.data) if len(data) > 20: data = repr(self.data[:16] + ' ...') return '<%s: %s>' % (self.tagname, data) def _dom_node(self, domroot): return domroot.createTextNode(self.data) def astext(self): return self.data def copy(self): return self.__class__(self.data) def deepcopy(self): return self.copy() def pformat(self, indent=' ', level=0): result = [] indent = indent * level for line in self.data.splitlines(): result.append(indent + line + '\n') return ''.join(result) class Element(Node): """ `Element` is the superclass to all specific elements. Elements contain attributes and child nodes. Elements emulate dictionaries for attributes, indexing by attribute name (a string). To set the attribute 'att' to 'value', do:: element['att'] = 'value' There are two special attributes: 'ids' and 'names'. Both are lists of unique identifiers, and names serve as human interfaces to IDs. Names are case- and whitespace-normalized (see the fully_normalize_name() function), and IDs conform to the regular expression ``[a-z](-?[a-z0-9]+)*`` (see the make_id() function). Elements also emulate lists for child nodes (element nodes and/or text nodes), indexing by integer. To get the first child node, use:: element[0] Elements may be constructed using the ``+=`` operator. To add one new child node to element, do:: element += node This is equivalent to ``element.append(node)``. To add a list of multiple child nodes at once, use the same ``+=`` operator:: element += [node1, node2] This is equivalent to ``element.extend([node1, node2])``. """ list_attributes = ('ids', 'classes', 'names', 'dupnames', 'backrefs') """List attributes, automatically initialized to empty lists for all nodes.""" tagname = None """The element generic identifier. If None, it is set as an instance attribute to the name of the class.""" child_text_separator = '\n\n' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', *children, **attributes): self.rawsource = rawsource """The raw text from which this element was constructed.""" self.children = [] """List of child nodes (elements and/or `Text`).""" self.extend(children) # maintain parent info self.attributes = {} """Dictionary of attribute {name: value}.""" # Initialize list attributes. for att in self.list_attributes: self.attributes[att] = [] for att, value in attributes.items(): att = att.lower() if att in self.list_attributes: # mutable list; make a copy for this node self.attributes[att] = value[:] else: self.attributes[att] = value if self.tagname is None: self.tagname = self.__class__.__name__ def _dom_node(self, domroot): element = domroot.createElement(self.tagname) for attribute, value in self.attlist(): if isinstance(value, ListType): value = ' '.join([serial_escape('%s' % v) for v in value]) element.setAttribute(attribute, '%s' % value) for child in self.children: element.appendChild(child._dom_node(domroot)) return element def __repr__(self): data = '' for c in self.children: data += c.shortrepr() if len(data) > 60: data = data[:56] + ' ...' break if self['names']: return '<%s "%s": %s>' % (self.__class__.__name__, '; '.join(self['names']), data) else: return '<%s: %s>' % (self.__class__.__name__, data) def shortrepr(self): if self['names']: return '<%s "%s"...>' % (self.__class__.__name__, '; '.join(self['names'])) else: return '<%s...>' % self.tagname def __str__(self): return self.__unicode__().encode('raw_unicode_escape') def __unicode__(self): if self.children: return u'%s%s%s' % (self.starttag(), ''.join([str(c) for c in self.children]), self.endtag()) else: return self.emptytag() def starttag(self): parts = [self.tagname] for name, value in self.attlist(): if value is None: # boolean attribute parts.append(name) elif isinstance(value, ListType): values = [serial_escape('%s' % v) for v in value] parts.append('%s="%s"' % (name, ' '.join(values))) else: parts.append('%s="%s"' % (name, value)) return '<%s>' % ' '.join(parts) def endtag(self): return '</%s>' % self.tagname def emptytag(self): return u'<%s/>' % ' '.join([self.tagname] + ['%s="%s"' % (n, v) for n, v in self.attlist()]) def __len__(self): return len(self.children) def __getitem__(self, key): if isinstance(key, UnicodeType) or isinstance(key, StringType): return self.attributes[key] elif isinstance(key, IntType): return self.children[key] elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' return self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __setitem__(self, key, item): if isinstance(key, UnicodeType) or isinstance(key, StringType): self.attributes[str(key)] = item elif isinstance(key, IntType): self.setup_child(item) self.children[key] = item elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' for node in item: self.setup_child(node) self.children[key.start:key.stop] = item else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __delitem__(self, key): if isinstance(key, UnicodeType) or isinstance(key, StringType): del self.attributes[key] elif isinstance(key, IntType): del self.children[key] elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' del self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a simple ' 'slice, or an attribute name string') def __add__(self, other): return self.children + other def __radd__(self, other): return other + self.children def __iadd__(self, other): """Append a node or a list of nodes to `self.children`.""" if isinstance(other, Node): self.append(other) elif other is not None: self.extend(other) return self def astext(self): return self.child_text_separator.join( [child.astext() for child in self.children]) def non_default_attributes(self): atts = {} for key, value in self.attributes.items(): if self.is_not_default(key): atts[key] = value return atts def attlist(self): attlist = self.non_default_attributes().items() attlist.sort() return attlist def get(self, key, failobj=None): return self.attributes.get(key, failobj) def hasattr(self, attr): return self.attributes.has_key(attr) def delattr(self, attr): if self.attributes.has_key(attr): del self.attributes[attr] def setdefault(self, key, failobj=None): return self.attributes.setdefault(key, failobj) has_key = hasattr def append(self, item): self.setup_child(item) self.children.append(item) def extend(self, item): for node in item: self.append(node) def insert(self, index, item): if isinstance(item, Node): self.setup_child(item) self.children.insert(index, item) elif item is not None: self[index:index] = item def pop(self, i=-1): return self.children.pop(i) def remove(self, item): self.children.remove(item) def index(self, item): return self.children.index(item) def is_not_default(self, key): if self[key] == [] and key in self.list_attributes: return 0 else: return 1 def update_basic_atts(self, dict): """ Update basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') from node or dictionary `dict`. """ if isinstance(dict, Node): dict = dict.attributes for att in ('ids', 'classes', 'names', 'dupnames'): for value in dict.get(att, []): if not value in self[att]: self[att].append(value) def clear(self): self.children = [] def replace(self, old, new): """Replace one child `Node` with another child or children.""" index = self.index(old) if isinstance(new, Node): self.setup_child(new) self[index] = new elif new is not None: self[index:index+1] = new def replace_self(self, new): """ Replace `self` node with `new`, where `new` is a node or a list of nodes. """ update = new if not isinstance(new, Node): # `new` is a list; update first child. try: update = new[0] except IndexError: update = None if isinstance(update, Element): update.update_basic_atts(self) else: # `update` is a Text node or `new` is an empty list. # Assert that we aren't losing any attributes. for att in ('ids', 'names', 'classes', 'dupnames'): assert not self[att], \ 'Losing "%s" attribute: %s' % (att, self[att]) self.parent.replace(self, new) def first_child_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class exactly matches. Parameters: - `childclass`: A `Node` subclass to search for, or a tuple of `Node` classes. If a tuple, any of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, TupleType): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self[index], c): return index return None def first_child_not_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class does *not* match. Parameters: - `childclass`: A `Node` subclass to skip, or a tuple of `Node` classes. If a tuple, none of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, TupleType): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self.children[index], c): break else: return index return None def pformat(self, indent=' ', level=0): return ''.join(['%s%s\n' % (indent * level, self.starttag())] + [child.pformat(indent, level+1) for child in self.children]) def copy(self): return self.__class__(**self.attributes) def deepcopy(self): copy = self.copy() copy.extend([child.deepcopy() for child in self.children]) return copy def set_class(self, name): """Add a new class to the "classes" attribute.""" warnings.warn('docutils.nodes.Element.set_class deprecated; ' "append to Element['classes'] list attribute directly", DeprecationWarning, stacklevel=2) assert ' ' not in name self['classes'].append(name.lower()) def note_referenced_by(self, name=None, id=None): """Note that this Element has been referenced by its name `name` or id `id`.""" self.referenced = 1 # Element.expect_referenced_by_* dictionaries map names or ids # to nodes whose ``referenced`` attribute is set to true as # soon as this node is referenced by the given name or id. # Needed for target propagation. by_name = getattr(self, 'expect_referenced_by_name', {}).get(name) by_id = getattr(self, 'expect_referenced_by_id', {}).get(id) if by_name: assert name is not None by_name.referenced = 1 if by_id: assert id is not None by_id.referenced = 1 class TextElement(Element): """ An element which directly contains text. Its children are all `Text` or `Inline` subclass nodes. You can check whether an element's context is inline simply by checking whether its immediate parent is a `TextElement` instance (including subclasses). This is handy for nodes like `image` that can appear both inline and as standalone body elements. If passing children to `__init__()`, make sure to set `text` to ``''`` or some other suitable value. """ child_text_separator = '' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', text='', *children, **attributes): if text != '': textnode = Text(text) Element.__init__(self, rawsource, textnode, *children, **attributes) else: Element.__init__(self, rawsource, *children, **attributes) class FixedTextElement(TextElement): """An element which directly contains preformatted text.""" def __init__(self, rawsource='', text='', *children, **attributes): TextElement.__init__(self, rawsource, text, *children, **attributes) self.attributes['xml:space'] = 'preserve' # ======== # Mixins # ======== class Resolvable: resolved = 0 class BackLinkable: def add_backref(self, refid): self['backrefs'].append(refid) # ==================== # Element Categories # ==================== class Root: pass class Titular: pass class PreBibliographic: """Category of Node which may occur before Bibliographic Nodes.""" class Bibliographic: pass class Decorative(PreBibliographic): pass class Structural: pass class Body: pass class General(Body): pass class Sequential(Body): """List-like elements.""" class Admonition(Body): pass class Special(Body): """Special internal body elements.""" class Invisible(PreBibliographic): """Internal elements that don't appear in output.""" class Part: pass class Inline: pass class Referential(Resolvable): pass class Targetable(Resolvable): referenced = 0 indirect_reference_name = None """Holds the whitespace_normalized_name (contains mixed case) of a target. Required for MoinMoin/reST compatibility.""" class Labeled: """Contains a `label` as its first element.""" # ============== # Root Element # ============== class document(Root, Structural, Element): """ The document root element. Do not instantiate this class directly; use `docutils.utils.new_document()` instead. """ def __init__(self, settings, reporter, *args, **kwargs): Element.__init__(self, *args, **kwargs) self.current_source = None """Path to or description of the input source being processed.""" self.current_line = None """Line number (1-based) of `current_source`.""" self.settings = settings """Runtime settings data record.""" self.reporter = reporter """System message generator.""" self.indirect_targets = [] """List of indirect target nodes.""" self.substitution_defs = {} """Mapping of substitution names to substitution_definition nodes.""" self.substitution_names = {} """Mapping of case-normalized substitution names to case-sensitive names.""" self.refnames = {} """Mapping of names to lists of referencing nodes.""" self.refids = {} """Mapping of ids to lists of referencing nodes.""" self.nameids = {} """Mapping of names to unique id's.""" self.nametypes = {} """Mapping of names to hyperlink type (boolean: True => explicit, False => implicit.""" self.ids = {} """Mapping of ids to nodes.""" self.footnote_refs = {} """Mapping of footnote labels to lists of footnote_reference nodes.""" self.citation_refs = {} """Mapping of citation labels to lists of citation_reference nodes.""" self.autofootnotes = [] """List of auto-numbered footnote nodes.""" self.autofootnote_refs = [] """List of auto-numbered footnote_reference nodes.""" self.symbol_footnotes = [] """List of symbol footnote nodes.""" self.symbol_footnote_refs = [] """List of symbol footnote_reference nodes.""" self.footnotes = [] """List of manually-numbered footnote nodes.""" self.citations = [] """List of citation nodes.""" self.autofootnote_start = 1 """Initial auto-numbered footnote number.""" self.symbol_footnote_start = 0 """Initial symbol footnote symbol index.""" self.id_start = 1 """Initial ID number.""" self.parse_messages = [] """System messages generated while parsing.""" self.transform_messages = [] """System messages generated while applying transforms.""" import docutils.transforms self.transformer = docutils.transforms.Transformer(self) """Storage for transforms to be applied to this document.""" self.decoration = None """Document's `decoration` node.""" self.document = self def asdom(self, dom=None): """Return a DOM representation of this document.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() domroot.appendChild(self._dom_node(domroot)) return domroot def set_id(self, node, msgnode=None): for id in node['ids']: if self.ids.has_key(id) and self.ids[id] is not node: msg = self.reporter.severe('Duplicate ID: "%s".' % id) if msgnode != None: msgnode += msg if not node['ids']: for name in node['names']: id = self.settings.id_prefix + make_id(name) if id and not self.ids.has_key(id): break else: id = '' while not id or self.ids.has_key(id): id = (self.settings.id_prefix + self.settings.auto_id_prefix + str(self.id_start)) self.id_start += 1 node['ids'].append(id) self.ids[id] = node return id def set_name_id_map(self, node, id, msgnode=None, explicit=None): """ `self.nameids` maps names to IDs, while `self.nametypes` maps names to booleans representing hyperlink type (True==explicit, False==implicit). This method updates the mappings. The following state transition table shows how `self.nameids` ("ids") and `self.nametypes` ("types") change with new input (a call to this method), and what actions are performed ("implicit"-type system messages are INFO/1, and "explicit"-type system messages are ERROR/3): ==== ===== ======== ======== ======= ==== ===== ===== Old State Input Action New State Notes ----------- -------- ----------------- ----------- ----- ids types new type sys.msg. dupname ids types ==== ===== ======== ======== ======= ==== ===== ===== - - explicit - - new True - - implicit - - new False None False explicit - - new True old False explicit implicit old new True None True explicit explicit new None True old True explicit explicit new,old None True [#]_ None False implicit implicit new None False old False implicit implicit new,old None False None True implicit implicit new None True old True implicit implicit new old True ==== ===== ======== ======== ======= ==== ===== ===== .. [#] Do not clear the name-to-id map or invalidate the old target if both old and new targets are external and refer to identical URIs. The new target is invalidated regardless. """ for name in node['names']: if self.nameids.has_key(name): self.set_duplicate_name_id(node, id, name, msgnode, explicit) else: self.nameids[name] = id self.nametypes[name] = explicit def set_duplicate_name_id(self, node, id, name, msgnode, explicit): old_id = self.nameids[name] old_explicit = self.nametypes[name] self.nametypes[name] = old_explicit or explicit if explicit: if old_explicit: level = 2 if old_id is not None: old_node = self.ids[old_id] if node.has_key('refuri'): refuri = node['refuri'] if old_node['names'] \ and old_node.has_key('refuri') \ and old_node['refuri'] == refuri: level = 1 # just inform if refuri's identical if level > 1: dupname(old_node, name) self.nameids[name] = None msg = self.reporter.system_message( level, 'Duplicate explicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg dupname(node, name) else: self.nameids[name] = id if old_id is not None: old_node = self.ids[old_id] dupname(old_node, name) else: if old_id is not None and not old_explicit: self.nameids[name] = None old_node = self.ids[old_id] dupname(old_node, name) dupname(node, name) if not explicit or (not old_explicit and old_id is not None): msg = self.reporter.info( 'Duplicate implicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg def has_name(self, name): return self.nameids.has_key(name) # "note" here is an imperative verb: "take note of". def note_implicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=None) def note_explicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=1) def note_refname(self, node): self.refnames.setdefault(node['refname'], []).append(node) def note_refid(self, node): self.refids.setdefault(node['refid'], []).append(node) def note_indirect_target(self, target): self.indirect_targets.append(target) if target['names']: self.note_refname(target) def note_anonymous_target(self, target): self.set_id(target) def note_autofootnote(self, footnote): self.set_id(footnote) self.autofootnotes.append(footnote) def note_autofootnote_ref(self, ref): self.set_id(ref) self.autofootnote_refs.append(ref) def note_symbol_footnote(self, footnote): self.set_id(footnote) self.symbol_footnotes.append(footnote) def note_symbol_footnote_ref(self, ref): self.set_id(ref) self.symbol_footnote_refs.append(ref) def note_footnote(self, footnote): self.set_id(footnote) self.footnotes.append(footnote) def note_footnote_ref(self, ref): self.set_id(ref) self.footnote_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_citation(self, citation): self.citations.append(citation) def note_citation_ref(self, ref): self.set_id(ref) self.citation_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_substitution_def(self, subdef, def_name, msgnode=None): name = whitespace_normalize_name(def_name) if self.substitution_defs.has_key(name): msg = self.reporter.error( 'Duplicate substitution definition name: "%s".' % name, base_node=subdef) if msgnode != None: msgnode += msg oldnode = self.substitution_defs[name] dupname(oldnode, name) # keep only the last definition: self.substitution_defs[name] = subdef # case-insensitive mapping: self.substitution_names[fully_normalize_name(name)] = name def note_substitution_ref(self, subref, refname): subref['refname'] = whitespace_normalize_name(refname) def note_pending(self, pending, priority=None): self.transformer.add_pending(pending, priority) def note_parse_message(self, message): self.parse_messages.append(message) def note_transform_message(self, message): self.transform_messages.append(message) def note_source(self, source, offset): self.current_source = source if offset is None: self.current_line = offset else: self.current_line = offset + 1 def copy(self): return self.__class__(self.settings, self.reporter, **self.attributes) def get_decoration(self): if not self.decoration: self.decoration = decoration() index = self.first_child_not_matching_class(Titular) if index is None: self.append(self.decoration) else: self.insert(index, self.decoration) return self.decoration # ================ # Title Elements # ================ class title(Titular, PreBibliographic, TextElement): pass class subtitle(Titular, PreBibliographic, TextElement): pass class rubric(Titular, TextElement): pass # ======================== # Bibliographic Elements # ======================== class docinfo(Bibliographic, Element): pass class author(Bibliographic, TextElement): pass class authors(Bibliographic, Element): pass class organization(Bibliographic, TextElement): pass class address(Bibliographic, FixedTextElement): pass class contact(Bibliographic, TextElement): pass class version(Bibliographic, TextElement): pass class revision(Bibliographic, TextElement): pass class status(Bibliographic, TextElement): pass class date(Bibliographic, TextElement): pass class copyright(Bibliographic, TextElement): pass # ===================== # Decorative Elements # ===================== class decoration(Decorative, Element): def get_header(self): if not len(self.children) or not isinstance(self.children[0], header): self.insert(0, header()) return self.children[0] def get_footer(self): if not len(self.children) or not isinstance(self.children[-1], footer): self.append(footer()) return self.children[-1] class header(Decorative, Element): pass class footer(Decorative, Element): pass # ===================== # Structural Elements # ===================== class section(Structural, Element): pass class topic(Structural, Element): """ Topics are terminal, "leaf" mini-sections, like block quotes with titles, or textual figures. A topic is just like a section, except that it has no subsections, and it doesn't have to conform to section placement rules. Topics are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Topics cannot nest inside topics, sidebars, or body elements; you can't have a topic inside a table, list, block quote, etc. """ class sidebar(Structural, Element): """ Sidebars are like miniature, parallel documents that occur inside other documents, providing related or reference material. A sidebar is typically offset by a border and "floats" to the side of the page; the document's main text may flow around it. Sidebars can also be likened to super-footnotes; their content is outside of the flow of the document's main text. Sidebars are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Sidebars cannot nest inside sidebars, topics, or body elements; you can't have a sidebar inside a table, list, block quote, etc. """ class transition(Structural, Element): pass # =============== # Body Elements # =============== class paragraph(General, TextElement): pass class compound(General, Element): pass class container(General, Element): pass class bullet_list(Sequential, Element): pass class enumerated_list(Sequential, Element): pass class list_item(Part, Element): pass class definition_list(Sequential, Element): pass class definition_list_item(Part, Element): pass class term(Part, TextElement): pass class classifier(Part, TextElement): pass class definition(Part, Element): pass class field_list(Sequential, Element): pass class field(Part, Element): pass class field_name(Part, TextElement): pass class field_body(Part, Element): pass class option(Part, Element): child_text_separator = '' class option_argument(Part, TextElement): def astext(self): return self.get('delimiter', ' ') + TextElement.astext(self) class option_group(Part, Element): child_text_separator = ', ' class option_list(Sequential, Element): pass class option_list_item(Part, Element): child_text_separator = ' ' class option_string(Part, TextElement): pass class description(Part, Element): pass class literal_block(General, FixedTextElement): pass class doctest_block(General, FixedTextElement): pass class line_block(General, Element): pass class line(Part, TextElement): indent = None class block_quote(General, Element): pass class attribution(Part, TextElement): pass class attention(Admonition, Element): pass class caution(Admonition, Element): pass class danger(Admonition, Element): pass class error(Admonition, Element): pass class important(Admonition, Element): pass class note(Admonition, Element): pass class tip(Admonition, Element): pass class hint(Admonition, Element): pass class warning(Admonition, Element): pass class admonition(Admonition, Element): pass class comment(Special, Invisible, FixedTextElement): pass class substitution_definition(Special, Invisible, TextElement): pass class target(Special, Invisible, Inline, TextElement, Targetable): pass class footnote(General, BackLinkable, Element, Labeled, Targetable): pass class citation(General, BackLinkable, Element, Labeled, Targetable): pass class label(Part, TextElement): pass class figure(General, Element): pass class caption(Part, TextElement): pass class legend(Part, Element): pass class table(General, Element): pass class tgroup(Part, Element): pass class colspec(Part, Element): pass class thead(Part, Element): pass class tbody(Part, Element): pass class row(Part, Element): pass class entry(Part, Element): pass class system_message(Special, BackLinkable, PreBibliographic, Element): """ System message element. Do not instantiate this class directly; use ``document.reporter.info/warning/error/severe()`` instead. """ def __init__(self, message=None, *children, **attributes): if message: p = paragraph('', message) children = (p,) + children try: Element.__init__(self, '', *children, **attributes) except: print 'system_message: children=%r' % (children,) raise def astext(self): line = self.get('line', '') return u'%s:%s: (%s/%s) %s' % (self['source'], line, self['type'], self['level'], Element.astext(self)) class pending(Special, Invisible, Element): """ The "pending" element is used to encapsulate a pending operation: the operation (transform), the point at which to apply it, and any data it requires. Only the pending operation's location within the document is stored in the public document tree (by the "pending" object itself); the operation and its data are stored in the "pending" object's internal instance attributes. For example, say you want a table of contents in your reStructuredText document. The easiest way to specify where to put it is from within the document, with a directive:: .. contents:: But the "contents" directive can't do its work until the entire document has been parsed and possibly transformed to some extent. So the directive code leaves a placeholder behind that will trigger the second phase of its processing, something like this:: <pending ...public attributes...> + internal attributes Use `document.note_pending()` so that the `docutils.transforms.Transformer` stage of processing can run all pending transforms. """ def __init__(self, transform, details=None, rawsource='', *children, **attributes): Element.__init__(self, rawsource, *children, **attributes) self.transform = transform """The `docutils.transforms.Transform` class implementing the pending operation.""" self.details = details or {} """Detail data (dictionary) required by the pending operation.""" def pformat(self, indent=' ', level=0): internals = [ '.. internal attributes:', ' .transform: %s.%s' % (self.transform.__module__, self.transform.__name__), ' .details:'] details = self.details.items() details.sort() for key, value in details: if isinstance(value, Node): internals.append('%7s%s:' % ('', key)) internals.extend(['%9s%s' % ('', line) for line in value.pformat().splitlines()]) elif value and isinstance(value, ListType) \ and isinstance(value[0], Node): internals.append('%7s%s:' % ('', key)) for v in value: internals.extend(['%9s%s' % ('', line) for line in v.pformat().splitlines()]) else: internals.append('%7s%s: %r' % ('', key, value)) return (Element.pformat(self, indent, level) + ''.join([(' %s%s\n' % (indent * level, line)) for line in internals])) def copy(self): return self.__class__(self.transform, self.details, self.rawsource, **self.attributes) class raw(Special, Inline, PreBibliographic, FixedTextElement): """ Raw data that is to be passed untouched to the Writer. """ pass # ================= # Inline Elements # ================= class emphasis(Inline, TextElement): pass class strong(Inline, TextElement): pass class literal(Inline, TextElement): pass class reference(General, Inline, Referential, TextElement): pass class footnote_reference(Inline, Referential, TextElement): pass class citation_reference(Inline, Referential, TextElement): pass class substitution_reference(Inline, TextElement): pass class title_reference(Inline, TextElement): pass class abbreviation(Inline, TextElement): pass class acronym(Inline, TextElement): pass class superscript(Inline, TextElement): pass class subscript(Inline, TextElement): pass class image(General, Inline, Element): def astext(self): return self.get('alt', '') class inline(Inline, TextElement): pass class problematic(Inline, TextElement): pass class generated(Inline, TextElement): pass # ======================================== # Auxiliary Classes, Functions, and Data # ======================================== node_class_names = """ Text abbreviation acronym address admonition attention attribution author authors block_quote bullet_list caption caution citation citation_reference classifier colspec comment compound contact container copyright danger date decoration definition definition_list definition_list_item description docinfo doctest_block document emphasis entry enumerated_list error field field_body field_list field_name figure footer footnote footnote_reference generated header hint image important inline label legend line line_block list_item literal literal_block note option option_argument option_group option_list option_list_item option_string organization paragraph pending problematic raw reference revision row rubric section sidebar status strong subscript substitution_definition substitution_reference subtitle superscript system_message table target tbody term tgroup thead tip title title_reference topic transition version warning""".split() """A list of names of all concrete Node subclasses.""" class NodeVisitor: """ "Visitor" pattern [GoF95]_ abstract superclass implementation for document tree traversals. Each node class has corresponding methods, doing nothing by default; override individual methods for specific and useful behaviour. The `dispatch_visit()` method is called by `Node.walk()` upon entering a node. `Node.walkabout()` also calls the `dispatch_departure()` method before exiting a node. The dispatch methods call "``visit_`` + node class name" or "``depart_`` + node class name", resp. This is a base class for visitors whose ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types encountered (such as for `docutils.writers.Writer` subclasses). Unimplemented methods will raise exceptions. For sparse traversals, where only certain node types are of interest, subclass `SparseNodeVisitor` instead. When (mostly or entirely) uniform processing is desired, subclass `GenericNodeVisitor`. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA, 1995. """ optional = () """ Tuple containing node class names (as strings). No exception will be raised if writers do not implement visit or departure functions for these node classes. Used to ensure transitional compatibility with existing 3rd-party writers. """ def __init__(self, document): self.document = document def dispatch_visit(self, node): """ Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit. """ node_name = node.__class__.__name__ method = getattr(self, 'visit_' + node_name, self.unknown_visit) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_visit calling %s for %s' % (method.__name__, node_name)) return method(node) def dispatch_departure(self, node): """ Call self."``depart_`` + node class name" with `node` as parameter. If the ``depart_...`` method does not exist, call self.unknown_departure. """ node_name = node.__class__.__name__ method = getattr(self, 'depart_' + node_name, self.unknown_departure) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_departure calling %s for %s' % (method.__name__, node_name)) return method(node) def unknown_visit(self, node): """ Called when entering unknown `Node` types. Raise an exception unless overridden. """ if (node.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s visiting unknown node type: %s' % (self.__class__, node.__class__.__name__)) def unknown_departure(self, node): """ Called before exiting unknown `Node` types. Raise exception unless overridden. """ if (node.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s departing unknown node type: %s' % (self.__class__, node.__class__.__name__)) class SparseNodeVisitor(NodeVisitor): """ Base class for sparse traversals, where only certain node types are of interest. When ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types (such as for `docutils.writers.Writer` subclasses), subclass `NodeVisitor` instead. """ class GenericNodeVisitor(NodeVisitor): """ Generic "Visitor" abstract superclass, for simple traversals. Unless overridden, each ``visit_...`` method calls `default_visit()`, and each ``depart_...`` method (when using `Node.walkabout()`) calls `default_departure()`. `default_visit()` (and `default_departure()`) must be overridden in subclasses. Define fully generic visitors by overriding `default_visit()` (and `default_departure()`) only. Define semi-generic visitors by overriding individual ``visit_...()`` (and ``depart_...()``) methods also. `NodeVisitor.unknown_visit()` (`NodeVisitor.unknown_departure()`) should be overridden for default behavior. """ def default_visit(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def default_departure(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def _call_default_visit(self, node): self.default_visit(node) def _call_default_departure(self, node): self.default_departure(node) def _nop(self, node): pass def _add_node_class_names(names): """Save typing with dynamic assignments:""" for _name in names: setattr(GenericNodeVisitor, "visit_" + _name, _call_default_visit) setattr(GenericNodeVisitor, "depart_" + _name, _call_default_departure) setattr(SparseNodeVisitor, 'visit_' + _name, _nop) setattr(SparseNodeVisitor, 'depart_' + _name, _nop) _add_node_class_names(node_class_names) class TreeCopyVisitor(GenericNodeVisitor): """ Make a complete copy of a tree or branch, including element attributes. """ def __init__(self, document): GenericNodeVisitor.__init__(self, document) self.parent_stack = [] self.parent = [] def get_tree_copy(self): return self.parent[0] def default_visit(self, node): """Copy the current node, and make it the new acting parent.""" newnode = node.copy() self.parent.append(newnode) self.parent_stack.append(self.parent) self.parent = newnode def default_departure(self, node): """Restore the previous acting parent.""" self.parent = self.parent_stack.pop() class TreePruningException(Exception): """ Base class for `NodeVisitor`-related tree pruning exceptions. Raise subclasses from within ``visit_...`` or ``depart_...`` methods called from `Node.walk()` and `Node.walkabout()` tree traversals to prune the tree traversed. """ pass class SkipChildren(TreePruningException): """ Do not visit any children of the current node. The current node's siblings and ``depart_...`` method are not affected. """ pass class SkipSiblings(TreePruningException): """ Do not visit any more siblings (to the right) of the current node. The current node's children and its ``depart_...`` method are not affected. """ pass class SkipNode(TreePruningException): """ Do not visit the current node's children, and do not call the current node's ``depart_...`` method. """ pass class SkipDeparture(TreePruningException): """ Do not call the current node's ``depart_...`` method. The current node's children and siblings are not affected. """ pass class NodeFound(TreePruningException): """ Raise to indicate that the target of a search has been found. This exception must be caught by the client; it is not caught by the traversal code. """ pass def make_id(string): """ Convert `string` into an identifier and return it. Docutils identifiers will conform to the regular expression ``[a-z](-?[a-z0-9]+)*``. For CSS compatibility, identifiers (the "class" and "id" attributes) should have no underscores, colons, or periods. Hyphens may be used. - The `HTML 4.01 spec`_ defines identifiers based on SGML tokens: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). - However the `CSS1 spec`_ defines identifiers based on the "name" token, a tighter interpretation ("flex" tokenizer notation; "latin1" and "escape" 8-bit characters have been replaced with entities):: unicode \\[0-9a-f]{1,4} latin1 [&iexcl;-&yuml;] escape {unicode}|\\[ -~&iexcl;-&yuml;] nmchar [-a-z0-9]|{latin1}|{escape} name {nmchar}+ The CSS1 "nmchar" rule does not include underscores ("_"), colons (":"), or periods ("."), therefore "class" and "id" attributes should not contain these characters. They should be replaced with hyphens ("-"). Combined with HTML's requirements (the first character must be a letter; no "unicode", "latin1", or "escape" characters), this results in the ``[a-z](-?[a-z0-9]+)*`` pattern. .. _HTML 4.01 spec: http://www.w3.org/TR/html401 .. _CSS1 spec: http://www.w3.org/TR/REC-CSS1 """ id = _non_id_chars.sub('-', ' '.join(string.lower().split())) id = _non_id_at_ends.sub('', id) return str(id) _non_id_chars = re.compile('[^a-z0-9]+') _non_id_at_ends = re.compile('^[-0-9]+|-+$') def dupname(node, name): node['dupnames'].append(name) node['names'].remove(name) # Assume that this method is referenced, even though it isn't; we # don't want to throw unnecessary system_messages. node.referenced = 1 def fully_normalize_name(name): """Return a case- and whitespace-normalized name.""" return ' '.join(name.lower().split()) def whitespace_normalize_name(name): """Return a whitespace-normalized name.""" return ' '.join(name.split()) def serial_escape(value): """Escape string values that are elements of a list, for serialization.""" return value.replace('\\', r'\\').replace(' ', r'\ ') # # # Local Variables: # indent-tabs-mode: nil # sentence-end-double-space: t # fill-column: 78 # End:
{ "repo_name": "indro/t2c", "path": "libs/external_libs/docutils-0.4/docutils/nodes.py", "copies": "6", "size": "58874", "license": "mit", "hash": 7586127051076406000, "line_mean": 32.5273348519, "line_max": 79, "alpha_frac": 0.5940822774, "autogenerated": false, "ratio": 4.223385939741751, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7817468217141751, "avg_score": null, "num_lines": null }
""" This is the ``docutils.parsers.restructuredtext.states`` module, the core of the reStructuredText parser. It defines the following: :Classes: - `RSTStateMachine`: reStructuredText parser's entry point. - `NestedStateMachine`: recursive StateMachine. - `RSTState`: reStructuredText State superclass. - `Inliner`: For parsing inline markup. - `Body`: Generic classifier of the first line of a block. - `SpecializedBody`: Superclass for compound element members. - `BulletList`: Second and subsequent bullet_list list_items - `DefinitionList`: Second+ definition_list_items. - `EnumeratedList`: Second+ enumerated_list list_items. - `FieldList`: Second+ fields. - `OptionList`: Second+ option_list_items. - `RFC2822List`: Second+ RFC2822-style fields. - `ExtensionOptions`: Parses directive option fields. - `Explicit`: Second+ explicit markup constructs. - `SubstitutionDef`: For embedded directives in substitution definitions. - `Text`: Classifier of second line of a text block. - `SpecializedText`: Superclass for continuation lines of Text-variants. - `Definition`: Second line of potential definition_list_item. - `Line`: Second line of overlined section title or transition marker. - `Struct`: An auxiliary collection class. :Exception classes: - `MarkupError` - `ParserError` - `MarkupMismatch` :Functions: - `escape2null()`: Return a string, escape-backslashes converted to nulls. - `unescape()`: Return a string, nulls removed or restored to backslashes. :Attributes: - `state_classes`: set of State classes used with `RSTStateMachine`. Parser Overview =============== The reStructuredText parser is implemented as a recursive state machine, examining its input one line at a time. To understand how the parser works, please first become familiar with the `docutils.statemachine` module. In the description below, references are made to classes defined in this module; please see the individual classes for details. Parsing proceeds as follows: 1. The state machine examines each line of input, checking each of the transition patterns of the state `Body`, in order, looking for a match. The implicit transitions (blank lines and indentation) are checked before any others. The 'text' transition is a catch-all (matches anything). 2. The method associated with the matched transition pattern is called. A. Some transition methods are self-contained, appending elements to the document tree (`Body.doctest` parses a doctest block). The parser's current line index is advanced to the end of the element, and parsing continues with step 1. B. Other transition methods trigger the creation of a nested state machine, whose job is to parse a compound construct ('indent' does a block quote, 'bullet' does a bullet list, 'overline' does a section [first checking for a valid section header], etc.). - In the case of lists and explicit markup, a one-off state machine is created and run to parse contents of the first item. - A new state machine is created and its initial state is set to the appropriate specialized state (`BulletList` in the case of the 'bullet' transition; see `SpecializedBody` for more detail). This state machine is run to parse the compound element (or series of explicit markup elements), and returns as soon as a non-member element is encountered. For example, the `BulletList` state machine ends as soon as it encounters an element which is not a list item of that bullet list. The optional omission of inter-element blank lines is enabled by this nested state machine. - The current line index is advanced to the end of the elements parsed, and parsing continues with step 1. C. The result of the 'text' transition depends on the next line of text. The current state is changed to `Text`, under which the second line is examined. If the second line is: - Indented: The element is a definition list item, and parsing proceeds similarly to step 2.B, using the `DefinitionList` state. - A line of uniform punctuation characters: The element is a section header; again, parsing proceeds as in step 2.B, and `Body` is still used. - Anything else: The element is a paragraph, which is examined for inline markup and appended to the parent element. Processing continues with step 1. """ __docformat__ = 'reStructuredText' import sys import re import roman from types import TupleType from docutils import nodes, statemachine, utils, urischemes from docutils import ApplicationError, DataError from docutils.statemachine import StateMachineWS, StateWS from docutils.nodes import fully_normalize_name as normalize_name from docutils.nodes import whitespace_normalize_name from docutils.utils import escape2null, unescape, column_width from docutils.parsers.rst import directives, languages, tableparser, roles from docutils.parsers.rst.languages import en as _fallback_language_module class MarkupError(DataError): pass class UnknownInterpretedRoleError(DataError): pass class InterpretedRoleNotImplementedError(DataError): pass class ParserError(ApplicationError): pass class MarkupMismatch(Exception): pass class Struct: """Stores data attributes for dotted-attribute access.""" def __init__(self, **keywordargs): self.__dict__.update(keywordargs) class RSTStateMachine(StateMachineWS): """ reStructuredText's master StateMachine. The entry point to reStructuredText parsing is the `run()` method. """ def run(self, input_lines, document, input_offset=0, match_titles=1, inliner=None): """ Parse `input_lines` and modify the `document` node in place. Extend `StateMachineWS.run()`: set up parse-global data and run the StateMachine. """ self.language = languages.get_language( document.settings.language_code) self.match_titles = match_titles if inliner is None: inliner = Inliner() inliner.init_customizations(document.settings) self.memo = Struct(document=document, reporter=document.reporter, language=self.language, title_styles=[], section_level=0, section_bubble_up_kludge=0, inliner=inliner) self.document = document self.attach_observer(document.note_source) self.reporter = self.memo.reporter self.node = document results = StateMachineWS.run(self, input_lines, input_offset, input_source=document['source']) assert results == [], 'RSTStateMachine.run() results should be empty!' self.node = self.memo = None # remove unneeded references class NestedStateMachine(StateMachineWS): """ StateMachine run from within other StateMachine runs, to parse nested document structures. """ def run(self, input_lines, input_offset, memo, node, match_titles=1): """ Parse `input_lines` and populate a `docutils.nodes.document` instance. Extend `StateMachineWS.run()`: set up document-wide data. """ self.match_titles = match_titles self.memo = memo self.document = memo.document self.attach_observer(self.document.note_source) self.reporter = memo.reporter self.language = memo.language self.node = node results = StateMachineWS.run(self, input_lines, input_offset) assert results == [], ('NestedStateMachine.run() results should be ' 'empty!') return results class RSTState(StateWS): """ reStructuredText State superclass. Contains methods used by all State subclasses. """ nested_sm = NestedStateMachine def __init__(self, state_machine, debug=0): self.nested_sm_kwargs = {'state_classes': state_classes, 'initial_state': 'Body'} StateWS.__init__(self, state_machine, debug) def runtime_init(self): StateWS.runtime_init(self) memo = self.state_machine.memo self.memo = memo self.reporter = memo.reporter self.inliner = memo.inliner self.document = memo.document self.parent = self.state_machine.node def goto_line(self, abs_line_offset): """ Jump to input line `abs_line_offset`, ignoring jumps past the end. """ try: self.state_machine.goto_line(abs_line_offset) except EOFError: pass def no_match(self, context, transitions): """ Override `StateWS.no_match` to generate a system message. This code should never be run. """ self.reporter.severe( 'Internal error: no transition pattern match. State: "%s"; ' 'transitions: %s; context: %s; current line: %r.' % (self.__class__.__name__, transitions, context, self.state_machine.line), line=self.state_machine.abs_line_number()) return context, None, [] def bof(self, context): """Called at beginning of file.""" return [], [] def nested_parse(self, block, input_offset, node, match_titles=0, state_machine_class=None, state_machine_kwargs=None): """ Create a new StateMachine rooted at `node` and run it over the input `block`. """ if state_machine_class is None: state_machine_class = self.nested_sm if state_machine_kwargs is None: state_machine_kwargs = self.nested_sm_kwargs block_length = len(block) state_machine = state_machine_class(debug=self.debug, **state_machine_kwargs) state_machine.run(block, input_offset, memo=self.memo, node=node, match_titles=match_titles) state_machine.unlink() new_offset = state_machine.abs_line_offset() # No `block.parent` implies disconnected -- lines aren't in sync: if block.parent and (len(block) - block_length) != 0: # Adjustment for block if modified in nested parse: self.state_machine.next_line(len(block) - block_length) return new_offset def nested_list_parse(self, block, input_offset, node, initial_state, blank_finish, blank_finish_state=None, extra_settings={}, match_titles=0, state_machine_class=None, state_machine_kwargs=None): """ Create a new StateMachine rooted at `node` and run it over the input `block`. Also keep track of optional intermediate blank lines and the required final one. """ if state_machine_class is None: state_machine_class = self.nested_sm if state_machine_kwargs is None: state_machine_kwargs = self.nested_sm_kwargs.copy() state_machine_kwargs['initial_state'] = initial_state state_machine = state_machine_class(debug=self.debug, **state_machine_kwargs) if blank_finish_state is None: blank_finish_state = initial_state state_machine.states[blank_finish_state].blank_finish = blank_finish for key, value in extra_settings.items(): setattr(state_machine.states[initial_state], key, value) state_machine.run(block, input_offset, memo=self.memo, node=node, match_titles=match_titles) blank_finish = state_machine.states[blank_finish_state].blank_finish state_machine.unlink() return state_machine.abs_line_offset(), blank_finish def section(self, title, source, style, lineno, messages): """Check for a valid subsection and create one if it checks out.""" if self.check_subsection(source, style, lineno): self.new_subsection(title, lineno, messages) def check_subsection(self, source, style, lineno): """ Check for a valid subsection header. Return 1 (true) or None (false). When a new section is reached that isn't a subsection of the current section, back up the line count (use ``previous_line(-x)``), then ``raise EOFError``. The current StateMachine will finish, then the calling StateMachine can re-examine the title. This will work its way back up the calling chain until the correct section level isreached. @@@ Alternative: Evaluate the title, store the title info & level, and back up the chain until that level is reached. Store in memo? Or return in results? :Exception: `EOFError` when a sibling or supersection encountered. """ memo = self.memo title_styles = memo.title_styles mylevel = memo.section_level try: # check for existing title style level = title_styles.index(style) + 1 except ValueError: # new title style if len(title_styles) == memo.section_level: # new subsection title_styles.append(style) return 1 else: # not at lowest level self.parent += self.title_inconsistent(source, lineno) return None if level <= mylevel: # sibling or supersection memo.section_level = level # bubble up to parent section if len(style) == 2: memo.section_bubble_up_kludge = 1 # back up 2 lines for underline title, 3 for overline title self.state_machine.previous_line(len(style) + 1) raise EOFError # let parent section re-evaluate if level == mylevel + 1: # immediate subsection return 1 else: # invalid subsection self.parent += self.title_inconsistent(source, lineno) return None def title_inconsistent(self, sourcetext, lineno): error = self.reporter.severe( 'Title level inconsistent:', nodes.literal_block('', sourcetext), line=lineno) return error def new_subsection(self, title, lineno, messages): """Append new subsection to document tree. On return, check level.""" memo = self.memo mylevel = memo.section_level memo.section_level += 1 section_node = nodes.section() self.parent += section_node textnodes, title_messages = self.inline_text(title, lineno) titlenode = nodes.title(title, '', *textnodes) name = normalize_name(titlenode.astext()) section_node['names'].append(name) section_node += titlenode section_node += messages section_node += title_messages self.document.note_implicit_target(section_node, section_node) offset = self.state_machine.line_offset + 1 absoffset = self.state_machine.abs_line_offset() + 1 newabsoffset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=absoffset, node=section_node, match_titles=1) self.goto_line(newabsoffset) if memo.section_level <= mylevel: # can't handle next section? raise EOFError # bubble up to supersection # reset section_level; next pass will detect it properly memo.section_level = mylevel def paragraph(self, lines, lineno): """ Return a list (paragraph & messages) & a boolean: literal_block next? """ data = '\n'.join(lines).rstrip() if re.search(r'(?<!\\)(\\\\)*::$', data): if len(data) == 2: return [], 1 elif data[-3] in ' \n': text = data[:-3].rstrip() else: text = data[:-1] literalnext = 1 else: text = data literalnext = 0 textnodes, messages = self.inline_text(text, lineno) p = nodes.paragraph(data, '', *textnodes) p.line = lineno return [p] + messages, literalnext def inline_text(self, text, lineno): """ Return 2 lists: nodes (text and inline elements), and system_messages. """ return self.inliner.parse(text, lineno, self.memo, self.parent) def unindent_warning(self, node_name): return self.reporter.warning( '%s ends without a blank line; unexpected unindent.' % node_name, line=(self.state_machine.abs_line_number() + 1)) def build_regexp(definition, compile=1): """ Build, compile and return a regular expression based on `definition`. :Parameter: `definition`: a 4-tuple (group name, prefix, suffix, parts), where "parts" is a list of regular expressions and/or regular expression definitions to be joined into an or-group. """ name, prefix, suffix, parts = definition part_strings = [] for part in parts: if type(part) is TupleType: part_strings.append(build_regexp(part, None)) else: part_strings.append(part) or_group = '|'.join(part_strings) regexp = '%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s' % locals() if compile: return re.compile(regexp, re.UNICODE) else: return regexp class Inliner: """ Parse inline markup; call the `parse()` method. """ def __init__(self): self.implicit_dispatch = [(self.patterns.uri, self.standalone_uri),] """List of (pattern, bound method) tuples, used by `self.implicit_inline`.""" def init_customizations(self, settings): """Setting-based customizations; run when parsing begins.""" if settings.pep_references: self.implicit_dispatch.append((self.patterns.pep, self.pep_reference)) if settings.rfc_references: self.implicit_dispatch.append((self.patterns.rfc, self.rfc_reference)) def parse(self, text, lineno, memo, parent): # Needs to be refactored for nested inline markup. # Add nested_parse() method? """ Return 2 lists: nodes (text and inline elements), and system_messages. Using `self.patterns.initial`, a pattern which matches start-strings (emphasis, strong, interpreted, phrase reference, literal, substitution reference, and inline target) and complete constructs (simple reference, footnote reference), search for a candidate. When one is found, check for validity (e.g., not a quoted '*' character). If valid, search for the corresponding end string if applicable, and check it for validity. If not found or invalid, generate a warning and ignore the start-string. Implicit inline markup (e.g. standalone URIs) is found last. """ self.reporter = memo.reporter self.document = memo.document self.language = memo.language self.parent = parent pattern_search = self.patterns.initial.search dispatch = self.dispatch remaining = escape2null(text) processed = [] unprocessed = [] messages = [] while remaining: match = pattern_search(remaining) if match: groups = match.groupdict() method = dispatch[groups['start'] or groups['backquote'] or groups['refend'] or groups['fnend']] before, inlines, remaining, sysmessages = method(self, match, lineno) unprocessed.append(before) messages += sysmessages if inlines: processed += self.implicit_inline(''.join(unprocessed), lineno) processed += inlines unprocessed = [] else: break remaining = ''.join(unprocessed) + remaining if remaining: processed += self.implicit_inline(remaining, lineno) return processed, messages openers = '\'"([{<' closers = '\'")]}>' start_string_prefix = (r'((?<=^)|(?<=[-/: \n%s]))' % re.escape(openers)) end_string_suffix = (r'((?=$)|(?=[-/:.,;!? \n\x00%s]))' % re.escape(closers)) non_whitespace_before = r'(?<![ \n])' non_whitespace_escape_before = r'(?<![ \n\x00])' non_whitespace_after = r'(?![ \n])' # Alphanumerics with isolated internal [-._] chars (i.e. not 2 together): simplename = r'(?:(?!_)\w)+(?:[-._](?:(?!_)\w)+)*' # Valid URI characters (see RFC 2396 & RFC 2732); # final \x00 allows backslash escapes in URIs: uric = r"""[-_.!~*'()[\];/:@&=+$,%a-zA-Z0-9\x00]""" # Delimiter indicating the end of a URI (not part of the URI): uri_end_delim = r"""[>]""" # Last URI character; same as uric but no punctuation: urilast = r"""[_~*/=+a-zA-Z0-9]""" # End of a URI (either 'urilast' or 'uric followed by a # uri_end_delim'): uri_end = r"""(?:%(urilast)s|%(uric)s(?=%(uri_end_delim)s))""" % locals() emailc = r"""[-_!~*'{|}/#?^`&=+$%a-zA-Z0-9\x00]""" email_pattern = r""" %(emailc)s+(?:\.%(emailc)s+)* # name (?<!\x00)@ # at %(emailc)s+(?:\.%(emailc)s*)* # host %(uri_end)s # final URI char """ parts = ('initial_inline', start_string_prefix, '', [('start', '', non_whitespace_after, # simple start-strings [r'\*\*', # strong r'\*(?!\*)', # emphasis but not strong r'``', # literal r'_`', # inline internal target r'\|(?!\|)'] # substitution reference ), ('whole', '', end_string_suffix, # whole constructs [# reference name & end-string r'(?P<refname>%s)(?P<refend>__?)' % simplename, ('footnotelabel', r'\[', r'(?P<fnend>\]_)', [r'[0-9]+', # manually numbered r'\#(%s)?' % simplename, # auto-numbered (w/ label?) r'\*', # auto-symbol r'(?P<citationlabel>%s)' % simplename] # citation reference ) ] ), ('backquote', # interpreted text or phrase reference '(?P<role>(:%s:)?)' % simplename, # optional role non_whitespace_after, ['`(?!`)'] # but not literal ) ] ) patterns = Struct( initial=build_regexp(parts), emphasis=re.compile(non_whitespace_escape_before + r'(\*)' + end_string_suffix), strong=re.compile(non_whitespace_escape_before + r'(\*\*)' + end_string_suffix), interpreted_or_phrase_ref=re.compile( r""" %(non_whitespace_escape_before)s ( ` (?P<suffix> (?P<role>:%(simplename)s:)? (?P<refend>__?)? ) ) %(end_string_suffix)s """ % locals(), re.VERBOSE | re.UNICODE), embedded_uri=re.compile( r""" ( (?:[ \n]+|^) # spaces or beginning of line/string < # open bracket %(non_whitespace_after)s ([^<>\x00]+) # anything but angle brackets & nulls %(non_whitespace_before)s > # close bracket w/o whitespace before ) $ # end of string """ % locals(), re.VERBOSE), literal=re.compile(non_whitespace_before + '(``)' + end_string_suffix), target=re.compile(non_whitespace_escape_before + r'(`)' + end_string_suffix), substitution_ref=re.compile(non_whitespace_escape_before + r'(\|_{0,2})' + end_string_suffix), email=re.compile(email_pattern % locals() + '$', re.VERBOSE), uri=re.compile( (r""" %(start_string_prefix)s (?P<whole> (?P<absolute> # absolute URI (?P<scheme> # scheme (http, ftp, mailto) [a-zA-Z][a-zA-Z0-9.+-]* ) : ( ( # either: (//?)? # hierarchical URI %(uric)s* # URI characters %(uri_end)s # final URI char ) ( # optional query \?%(uric)s* %(uri_end)s )? ( # optional fragment \#%(uric)s* %(uri_end)s )? ) ) | # *OR* (?P<email> # email address """ + email_pattern + r""" ) ) %(end_string_suffix)s """) % locals(), re.VERBOSE), pep=re.compile( r""" %(start_string_prefix)s ( (pep-(?P<pepnum1>\d+)(.txt)?) # reference to source file | (PEP\s+(?P<pepnum2>\d+)) # reference by name ) %(end_string_suffix)s""" % locals(), re.VERBOSE), rfc=re.compile( r""" %(start_string_prefix)s (RFC(-|\s+)?(?P<rfcnum>\d+)) %(end_string_suffix)s""" % locals(), re.VERBOSE)) def quoted_start(self, match): """Return 1 if inline markup start-string is 'quoted', 0 if not.""" string = match.string start = match.start() end = match.end() if start == 0: # start-string at beginning of text return 0 prestart = string[start - 1] try: poststart = string[end] if self.openers.index(prestart) \ == self.closers.index(poststart): # quoted return 1 except IndexError: # start-string at end of text return 1 except ValueError: # not quoted pass return 0 def inline_obj(self, match, lineno, end_pattern, nodeclass, restore_backslashes=0): string = match.string matchstart = match.start('start') matchend = match.end('start') if self.quoted_start(match): return (string[:matchend], [], string[matchend:], [], '') endmatch = end_pattern.search(string[matchend:]) if endmatch and endmatch.start(1): # 1 or more chars text = unescape(endmatch.string[:endmatch.start(1)], restore_backslashes) textend = matchend + endmatch.end(1) rawsource = unescape(string[matchstart:textend], 1) return (string[:matchstart], [nodeclass(rawsource, text)], string[textend:], [], endmatch.group(1)) msg = self.reporter.warning( 'Inline %s start-string without end-string.' % nodeclass.__name__, line=lineno) text = unescape(string[matchstart:matchend], 1) rawsource = unescape(string[matchstart:matchend], 1) prb = self.problematic(text, rawsource, msg) return string[:matchstart], [prb], string[matchend:], [msg], '' def problematic(self, text, rawsource, message): msgid = self.document.set_id(message, self.parent) problematic = nodes.problematic(rawsource, text, refid=msgid) prbid = self.document.set_id(problematic) message.add_backref(prbid) return problematic def emphasis(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.emphasis, nodes.emphasis) return before, inlines, remaining, sysmessages def strong(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.strong, nodes.strong) return before, inlines, remaining, sysmessages def interpreted_or_phrase_ref(self, match, lineno): end_pattern = self.patterns.interpreted_or_phrase_ref string = match.string matchstart = match.start('backquote') matchend = match.end('backquote') rolestart = match.start('role') role = match.group('role') position = '' if role: role = role[1:-1] position = 'prefix' elif self.quoted_start(match): return (string[:matchend], [], string[matchend:], []) endmatch = end_pattern.search(string[matchend:]) if endmatch and endmatch.start(1): # 1 or more chars textend = matchend + endmatch.end() if endmatch.group('role'): if role: msg = self.reporter.warning( 'Multiple roles in interpreted text (both ' 'prefix and suffix present; only one allowed).', line=lineno) text = unescape(string[rolestart:textend], 1) prb = self.problematic(text, text, msg) return string[:rolestart], [prb], string[textend:], [msg] role = endmatch.group('suffix')[1:-1] position = 'suffix' escaped = endmatch.string[:endmatch.start(1)] rawsource = unescape(string[matchstart:textend], 1) if rawsource[-1:] == '_': if role: msg = self.reporter.warning( 'Mismatch: both interpreted text role %s and ' 'reference suffix.' % position, line=lineno) text = unescape(string[rolestart:textend], 1) prb = self.problematic(text, text, msg) return string[:rolestart], [prb], string[textend:], [msg] return self.phrase_ref(string[:matchstart], string[textend:], rawsource, escaped, unescape(escaped)) else: rawsource = unescape(string[rolestart:textend], 1) nodelist, messages = self.interpreted(rawsource, escaped, role, lineno) return (string[:rolestart], nodelist, string[textend:], messages) msg = self.reporter.warning( 'Inline interpreted text or phrase reference start-string ' 'without end-string.', line=lineno) text = unescape(string[matchstart:matchend], 1) prb = self.problematic(text, text, msg) return string[:matchstart], [prb], string[matchend:], [msg] def phrase_ref(self, before, after, rawsource, escaped, text): match = self.patterns.embedded_uri.search(escaped) if match: text = unescape(escaped[:match.start(0)]) uri_text = match.group(2) uri = ''.join(uri_text.split()) uri = self.adjust_uri(uri) if uri: target = nodes.target(match.group(1), refuri=uri) else: raise ApplicationError('problem with URI: %r' % uri_text) if not text: text = uri else: target = None refname = normalize_name(text) reference = nodes.reference(rawsource, text, name=whitespace_normalize_name(text)) node_list = [reference] if rawsource[-2:] == '__': if target: reference['refuri'] = uri else: reference['anonymous'] = 1 else: if target: reference['refuri'] = uri target['names'].append(refname) self.document.note_explicit_target(target, self.parent) node_list.append(target) else: reference['refname'] = refname self.document.note_refname(reference) return before, node_list, after, [] def adjust_uri(self, uri): match = self.patterns.email.match(uri) if match: return 'mailto:' + uri else: return uri def interpreted(self, rawsource, text, role, lineno): role_fn, messages = roles.role(role, self.language, lineno, self.reporter) if role_fn: nodes, messages2 = role_fn(role, rawsource, text, lineno, self) return nodes, messages + messages2 else: msg = self.reporter.error( 'Unknown interpreted text role "%s".' % role, line=lineno) return ([self.problematic(rawsource, rawsource, msg)], messages + [msg]) def literal(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.literal, nodes.literal, restore_backslashes=1) return before, inlines, remaining, sysmessages def inline_internal_target(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.target, nodes.target) if inlines and isinstance(inlines[0], nodes.target): assert len(inlines) == 1 target = inlines[0] name = normalize_name(target.astext()) target['names'].append(name) self.document.note_explicit_target(target, self.parent) return before, inlines, remaining, sysmessages def substitution_reference(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.substitution_ref, nodes.substitution_reference) if len(inlines) == 1: subref_node = inlines[0] if isinstance(subref_node, nodes.substitution_reference): subref_text = subref_node.astext() self.document.note_substitution_ref(subref_node, subref_text) if endstring[-1:] == '_': reference_node = nodes.reference( '|%s%s' % (subref_text, endstring), '') if endstring[-2:] == '__': reference_node['anonymous'] = 1 else: reference_node['refname'] = normalize_name(subref_text) self.document.note_refname(reference_node) reference_node += subref_node inlines = [reference_node] return before, inlines, remaining, sysmessages def footnote_reference(self, match, lineno): """ Handles `nodes.footnote_reference` and `nodes.citation_reference` elements. """ label = match.group('footnotelabel') refname = normalize_name(label) string = match.string before = string[:match.start('whole')] remaining = string[match.end('whole'):] if match.group('citationlabel'): refnode = nodes.citation_reference('[%s]_' % label, refname=refname) refnode += nodes.Text(label) self.document.note_citation_ref(refnode) else: refnode = nodes.footnote_reference('[%s]_' % label) if refname[0] == '#': refname = refname[1:] refnode['auto'] = 1 self.document.note_autofootnote_ref(refnode) elif refname == '*': refname = '' refnode['auto'] = '*' self.document.note_symbol_footnote_ref( refnode) else: refnode += nodes.Text(label) if refname: refnode['refname'] = refname self.document.note_footnote_ref(refnode) if utils.get_trim_footnote_ref_space(self.document.settings): before = before.rstrip() return (before, [refnode], remaining, []) def reference(self, match, lineno, anonymous=None): referencename = match.group('refname') refname = normalize_name(referencename) referencenode = nodes.reference( referencename + match.group('refend'), referencename, name=whitespace_normalize_name(referencename)) if anonymous: referencenode['anonymous'] = 1 else: referencenode['refname'] = refname self.document.note_refname(referencenode) string = match.string matchstart = match.start('whole') matchend = match.end('whole') return (string[:matchstart], [referencenode], string[matchend:], []) def anonymous_reference(self, match, lineno): return self.reference(match, lineno, anonymous=1) def standalone_uri(self, match, lineno): if not match.group('scheme') or urischemes.schemes.has_key( match.group('scheme').lower()): if match.group('email'): addscheme = 'mailto:' else: addscheme = '' text = match.group('whole') unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=addscheme + unescaped)] else: # not a valid scheme raise MarkupMismatch pep_url = 'pep-%04d.html' def pep_reference(self, match, lineno): text = match.group(0) if text.startswith('pep-'): pepnum = int(match.group('pepnum1')) elif text.startswith('PEP'): pepnum = int(match.group('pepnum2')) else: raise MarkupMismatch ref = self.document.settings.pep_base_url + self.pep_url % pepnum unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)] rfc_url = 'rfc%d.html' def rfc_reference(self, match, lineno): text = match.group(0) if text.startswith('RFC'): rfcnum = int(match.group('rfcnum')) ref = self.document.settings.rfc_base_url + self.rfc_url % rfcnum else: raise MarkupMismatch unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)] def implicit_inline(self, text, lineno): """ Check each of the patterns in `self.implicit_dispatch` for a match, and dispatch to the stored method for the pattern. Recursively check the text before and after the match. Return a list of `nodes.Text` and inline element nodes. """ if not text: return [] for pattern, method in self.implicit_dispatch: match = pattern.search(text) if match: try: # Must recurse on strings before *and* after the match; # there may be multiple patterns. return (self.implicit_inline(text[:match.start()], lineno) + method(match, lineno) + self.implicit_inline(text[match.end():], lineno)) except MarkupMismatch: pass return [nodes.Text(unescape(text), rawsource=unescape(text, 1))] dispatch = {'*': emphasis, '**': strong, '`': interpreted_or_phrase_ref, '``': literal, '_`': inline_internal_target, ']_': footnote_reference, '|': substitution_reference, '_': reference, '__': anonymous_reference} def _loweralpha_to_int(s, _zero=(ord('a')-1)): return ord(s) - _zero def _upperalpha_to_int(s, _zero=(ord('A')-1)): return ord(s) - _zero def _lowerroman_to_int(s): return roman.fromRoman(s.upper()) class Body(RSTState): """ Generic classifier of the first line of a block. """ double_width_pad_char = tableparser.TableParser.double_width_pad_char """Padding character for East Asian double-width text.""" enum = Struct() """Enumerated list parsing information.""" enum.formatinfo = { 'parens': Struct(prefix='(', suffix=')', start=1, end=-1), 'rparen': Struct(prefix='', suffix=')', start=0, end=-1), 'period': Struct(prefix='', suffix='.', start=0, end=-1)} enum.formats = enum.formatinfo.keys() enum.sequences = ['arabic', 'loweralpha', 'upperalpha', 'lowerroman', 'upperroman'] # ORDERED! enum.sequencepats = {'arabic': '[0-9]+', 'loweralpha': '[a-z]', 'upperalpha': '[A-Z]', 'lowerroman': '[ivxlcdm]+', 'upperroman': '[IVXLCDM]+',} enum.converters = {'arabic': int, 'loweralpha': _loweralpha_to_int, 'upperalpha': _upperalpha_to_int, 'lowerroman': _lowerroman_to_int, 'upperroman': roman.fromRoman} enum.sequenceregexps = {} for sequence in enum.sequences: enum.sequenceregexps[sequence] = re.compile( enum.sequencepats[sequence] + '$') grid_table_top_pat = re.compile(r'\+-[-+]+-\+ *$') """Matches the top (& bottom) of a full table).""" simple_table_top_pat = re.compile('=+( +=+)+ *$') """Matches the top of a simple table.""" simple_table_border_pat = re.compile('=+[ =]*$') """Matches the bottom & header bottom of a simple table.""" pats = {} """Fragments of patterns used by transitions.""" pats['nonalphanum7bit'] = '[!-/:-@[-`{-~]' pats['alpha'] = '[a-zA-Z]' pats['alphanum'] = '[a-zA-Z0-9]' pats['alphanumplus'] = '[a-zA-Z0-9_-]' pats['enum'] = ('(%(arabic)s|%(loweralpha)s|%(upperalpha)s|%(lowerroman)s' '|%(upperroman)s|#)' % enum.sequencepats) pats['optname'] = '%(alphanum)s%(alphanumplus)s*' % pats # @@@ Loosen up the pattern? Allow Unicode? pats['optarg'] = '(%(alpha)s%(alphanumplus)s*|<[^<>]+>)' % pats pats['shortopt'] = r'(-|\+)%(alphanum)s( ?%(optarg)s)?' % pats pats['longopt'] = r'(--|/)%(optname)s([ =]%(optarg)s)?' % pats pats['option'] = r'(%(shortopt)s|%(longopt)s)' % pats for format in enum.formats: pats[format] = '(?P<%s>%s%s%s)' % ( format, re.escape(enum.formatinfo[format].prefix), pats['enum'], re.escape(enum.formatinfo[format].suffix)) patterns = { 'bullet': r'[-+*]( +|$)', 'enumerator': r'(%(parens)s|%(rparen)s|%(period)s)( +|$)' % pats, 'field_marker': r':(?![: ])([^:\\]|\\.)*(?<! ):( +|$)', 'option_marker': r'%(option)s(, %(option)s)*( +| ?$)' % pats, 'doctest': r'>>>( +|$)', 'line_block': r'\|( +|$)', 'grid_table_top': grid_table_top_pat, 'simple_table_top': simple_table_top_pat, 'explicit_markup': r'\.\.( +|$)', 'anonymous': r'__( +|$)', 'line': r'(%(nonalphanum7bit)s)\1* *$' % pats, 'text': r''} initial_transitions = ( 'bullet', 'enumerator', 'field_marker', 'option_marker', 'doctest', 'line_block', 'grid_table_top', 'simple_table_top', 'explicit_markup', 'anonymous', 'line', 'text') def indent(self, match, context, next_state): """Block quote.""" indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() blockquote, messages = self.block_quote(indented, line_offset) self.parent += blockquote self.parent += messages if not blank_finish: self.parent += self.unindent_warning('Block quote') return context, next_state, [] def block_quote(self, indented, line_offset): blockquote_lines, attribution_lines, attribution_offset = \ self.check_attribution(indented, line_offset) blockquote = nodes.block_quote() self.nested_parse(blockquote_lines, line_offset, blockquote) messages = [] if attribution_lines: attribution, messages = self.parse_attribution(attribution_lines, attribution_offset) blockquote += attribution return blockquote, messages # u'\u2014' is an em-dash: attribution_pattern = re.compile(ur'(---?(?!-)|\u2014) *(?=[^ \n])') def check_attribution(self, indented, line_offset): """ Check for an attribution in the last contiguous block of `indented`. * First line after last blank line must begin with "--" (etc.). * Every line after that must have consistent indentation. Return a 3-tuple: (block quote lines, attribution lines, attribution offset). """ #import pdb ; pdb.set_trace() blank = None nonblank_seen = None indent = 0 for i in range(len(indented) - 1, 0, -1): # don't check first line this_line_blank = not indented[i].strip() if nonblank_seen and this_line_blank: match = self.attribution_pattern.match(indented[i + 1]) if match: blank = i break elif not this_line_blank: nonblank_seen = 1 if blank and len(indented) - blank > 2: # multi-line attribution indent = (len(indented[blank + 2]) - len(indented[blank + 2].lstrip())) for j in range(blank + 3, len(indented)): if ( indented[j] # may be blank last line and indent != (len(indented[j]) - len(indented[j].lstrip()))): # bad shape blank = None break if blank: a_lines = indented[blank + 1:] a_lines.trim_left(match.end(), end=1) a_lines.trim_left(indent, start=1) return (indented[:blank], a_lines, line_offset + blank + 1) else: return (indented, None, None) def parse_attribution(self, indented, line_offset): text = '\n'.join(indented).rstrip() lineno = self.state_machine.abs_line_number() + line_offset textnodes, messages = self.inline_text(text, lineno) node = nodes.attribution(text, '', *textnodes) node.line = lineno return node, messages def bullet(self, match, context, next_state): """Bullet list item.""" bulletlist = nodes.bullet_list() self.parent += bulletlist bulletlist['bullet'] = match.string[0] i, blank_finish = self.list_item(match.end()) bulletlist += i offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=bulletlist, initial_state='BulletList', blank_finish=blank_finish) self.goto_line(new_line_offset) if not blank_finish: self.parent += self.unindent_warning('Bullet list') return [], next_state, [] def list_item(self, indent): if self.state_machine.line[indent:]: indented, line_offset, blank_finish = ( self.state_machine.get_known_indented(indent)) else: indented, indent, line_offset, blank_finish = ( self.state_machine.get_first_known_indented(indent)) listitem = nodes.list_item('\n'.join(indented)) if indented: self.nested_parse(indented, input_offset=line_offset, node=listitem) return listitem, blank_finish def enumerator(self, match, context, next_state): """Enumerated List Item""" format, sequence, text, ordinal = self.parse_enumerator(match) if not self.is_enumerated_list_item(ordinal, sequence, format): raise statemachine.TransitionCorrection('text') enumlist = nodes.enumerated_list() self.parent += enumlist if sequence == '#': enumlist['enumtype'] = 'arabic' else: enumlist['enumtype'] = sequence enumlist['prefix'] = self.enum.formatinfo[format].prefix enumlist['suffix'] = self.enum.formatinfo[format].suffix if ordinal != 1: enumlist['start'] = ordinal msg = self.reporter.info( 'Enumerated list start value not ordinal-1: "%s" (ordinal %s)' % (text, ordinal), line=self.state_machine.abs_line_number()) self.parent += msg listitem, blank_finish = self.list_item(match.end()) enumlist += listitem offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=enumlist, initial_state='EnumeratedList', blank_finish=blank_finish, extra_settings={'lastordinal': ordinal, 'format': format, 'auto': sequence == '#'}) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Enumerated list') return [], next_state, [] def parse_enumerator(self, match, expected_sequence=None): """ Analyze an enumerator and return the results. :Return: - the enumerator format ('period', 'parens', or 'rparen'), - the sequence used ('arabic', 'loweralpha', 'upperroman', etc.), - the text of the enumerator, stripped of formatting, and - the ordinal value of the enumerator ('a' -> 1, 'ii' -> 2, etc.; ``None`` is returned for invalid enumerator text). The enumerator format has already been determined by the regular expression match. If `expected_sequence` is given, that sequence is tried first. If not, we check for Roman numeral 1. This way, single-character Roman numerals (which are also alphabetical) can be matched. If no sequence has been matched, all sequences are checked in order. """ groupdict = match.groupdict() sequence = '' for format in self.enum.formats: if groupdict[format]: # was this the format matched? break # yes; keep `format` else: # shouldn't happen raise ParserError('enumerator format not matched') text = groupdict[format][self.enum.formatinfo[format].start :self.enum.formatinfo[format].end] if text == '#': sequence = '#' elif expected_sequence: try: if self.enum.sequenceregexps[expected_sequence].match(text): sequence = expected_sequence except KeyError: # shouldn't happen raise ParserError('unknown enumerator sequence: %s' % sequence) elif text == 'i': sequence = 'lowerroman' elif text == 'I': sequence = 'upperroman' if not sequence: for sequence in self.enum.sequences: if self.enum.sequenceregexps[sequence].match(text): break else: # shouldn't happen raise ParserError('enumerator sequence not matched') if sequence == '#': ordinal = 1 else: try: ordinal = self.enum.converters[sequence](text) except roman.InvalidRomanNumeralError: ordinal = None return format, sequence, text, ordinal def is_enumerated_list_item(self, ordinal, sequence, format): """ Check validity based on the ordinal value and the second line. Return true iff the ordinal is valid and the second line is blank, indented, or starts with the next enumerator or an auto-enumerator. """ if ordinal is None: return None try: next_line = self.state_machine.next_line() except EOFError: # end of input lines self.state_machine.previous_line() return 1 else: self.state_machine.previous_line() if not next_line[:1].strip(): # blank or indented return 1 result = self.make_enumerator(ordinal + 1, sequence, format) if result: next_enumerator, auto_enumerator = result try: if ( next_line.startswith(next_enumerator) or next_line.startswith(auto_enumerator) ): return 1 except TypeError: pass return None def make_enumerator(self, ordinal, sequence, format): """ Construct and return the next enumerated list item marker, and an auto-enumerator ("#" instead of the regular enumerator). Return ``None`` for invalid (out of range) ordinals. """ #" if sequence == '#': enumerator = '#' elif sequence == 'arabic': enumerator = str(ordinal) else: if sequence.endswith('alpha'): if ordinal > 26: return None enumerator = chr(ordinal + ord('a') - 1) elif sequence.endswith('roman'): try: enumerator = roman.toRoman(ordinal) except roman.RomanError: return None else: # shouldn't happen raise ParserError('unknown enumerator sequence: "%s"' % sequence) if sequence.startswith('lower'): enumerator = enumerator.lower() elif sequence.startswith('upper'): enumerator = enumerator.upper() else: # shouldn't happen raise ParserError('unknown enumerator sequence: "%s"' % sequence) formatinfo = self.enum.formatinfo[format] next_enumerator = (formatinfo.prefix + enumerator + formatinfo.suffix + ' ') auto_enumerator = formatinfo.prefix + '#' + formatinfo.suffix + ' ' return next_enumerator, auto_enumerator def field_marker(self, match, context, next_state): """Field list item.""" field_list = nodes.field_list() self.parent += field_list field, blank_finish = self.field(match) field_list += field offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=field_list, initial_state='FieldList', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Field list') return [], next_state, [] def field(self, match): name = self.parse_field_marker(match) lineno = self.state_machine.abs_line_number() indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) field_node = nodes.field() field_node.line = lineno name_nodes, name_messages = self.inline_text(name, lineno) field_node += nodes.field_name(name, '', *name_nodes) field_body = nodes.field_body('\n'.join(indented), *name_messages) field_node += field_body if indented: self.parse_field_body(indented, line_offset, field_body) return field_node, blank_finish def parse_field_marker(self, match): """Extract & return field name from a field marker match.""" field = match.group()[1:] # strip off leading ':' field = field[:field.rfind(':')] # strip off trailing ':' etc. return field def parse_field_body(self, indented, offset, node): self.nested_parse(indented, input_offset=offset, node=node) def option_marker(self, match, context, next_state): """Option list item.""" optionlist = nodes.option_list() try: listitem, blank_finish = self.option_list_item(match) except MarkupError, (message, lineno): # This shouldn't happen; pattern won't match. msg = self.reporter.error( 'Invalid option list marker: %s' % message, line=lineno) self.parent += msg indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) blockquote, messages = self.block_quote(indented, line_offset) self.parent += blockquote self.parent += messages if not blank_finish: self.parent += self.unindent_warning('Option list') return [], next_state, [] self.parent += optionlist optionlist += listitem offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=optionlist, initial_state='OptionList', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Option list') return [], next_state, [] def option_list_item(self, match): offset = self.state_machine.abs_line_offset() options = self.parse_option_marker(match) indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) if not indented: # not an option list item self.goto_line(offset) raise statemachine.TransitionCorrection('text') option_group = nodes.option_group('', *options) description = nodes.description('\n'.join(indented)) option_list_item = nodes.option_list_item('', option_group, description) if indented: self.nested_parse(indented, input_offset=line_offset, node=description) return option_list_item, blank_finish def parse_option_marker(self, match): """ Return a list of `node.option` and `node.option_argument` objects, parsed from an option marker match. :Exception: `MarkupError` for invalid option markers. """ optlist = [] optionstrings = match.group().rstrip().split(', ') for optionstring in optionstrings: tokens = optionstring.split() delimiter = ' ' firstopt = tokens[0].split('=') if len(firstopt) > 1: # "--opt=value" form tokens[:1] = firstopt delimiter = '=' elif (len(tokens[0]) > 2 and ((tokens[0].startswith('-') and not tokens[0].startswith('--')) or tokens[0].startswith('+'))): # "-ovalue" form tokens[:1] = [tokens[0][:2], tokens[0][2:]] delimiter = '' if len(tokens) > 1 and (tokens[1].startswith('<') and tokens[-1].endswith('>')): # "-o <value1 value2>" form; join all values into one token tokens[1:] = [' '.join(tokens[1:])] if 0 < len(tokens) <= 2: option = nodes.option(optionstring) option += nodes.option_string(tokens[0], tokens[0]) if len(tokens) > 1: option += nodes.option_argument(tokens[1], tokens[1], delimiter=delimiter) optlist.append(option) else: raise MarkupError( 'wrong number of option tokens (=%s), should be 1 or 2: ' '"%s"' % (len(tokens), optionstring), self.state_machine.abs_line_number() + 1) return optlist def doctest(self, match, context, next_state): data = '\n'.join(self.state_machine.get_text_block()) self.parent += nodes.doctest_block(data, data) return [], next_state, [] def line_block(self, match, context, next_state): """First line of a line block.""" block = nodes.line_block() self.parent += block lineno = self.state_machine.abs_line_number() line, messages, blank_finish = self.line_block_line(match, lineno) block += line self.parent += messages if not blank_finish: offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=block, initial_state='LineBlock', blank_finish=0) self.goto_line(new_line_offset) if not blank_finish: self.parent += self.reporter.warning( 'Line block ends without a blank line.', line=(self.state_machine.abs_line_number() + 1)) if len(block): if block[0].indent is None: block[0].indent = 0 self.nest_line_block_lines(block) return [], next_state, [] def line_block_line(self, match, lineno): """Return one line element of a line_block.""" indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), until_blank=1) text = u'\n'.join(indented) text_nodes, messages = self.inline_text(text, lineno) line = nodes.line(text, '', *text_nodes) if match.string.rstrip() != '|': # not empty line.indent = len(match.group(1)) - 1 return line, messages, blank_finish def nest_line_block_lines(self, block): for index in range(1, len(block)): if block[index].indent is None: block[index].indent = block[index - 1].indent self.nest_line_block_segment(block) def nest_line_block_segment(self, block): indents = [item.indent for item in block] least = min(indents) new_items = [] new_block = nodes.line_block() for item in block: if item.indent > least: new_block.append(item) else: if len(new_block): self.nest_line_block_segment(new_block) new_items.append(new_block) new_block = nodes.line_block() new_items.append(item) if len(new_block): self.nest_line_block_segment(new_block) new_items.append(new_block) block[:] = new_items def grid_table_top(self, match, context, next_state): """Top border of a full table.""" return self.table_top(match, context, next_state, self.isolate_grid_table, tableparser.GridTableParser) def simple_table_top(self, match, context, next_state): """Top border of a simple table.""" return self.table_top(match, context, next_state, self.isolate_simple_table, tableparser.SimpleTableParser) def table_top(self, match, context, next_state, isolate_function, parser_class): """Top border of a generic table.""" nodelist, blank_finish = self.table(isolate_function, parser_class) self.parent += nodelist if not blank_finish: msg = self.reporter.warning( 'Blank line required after table.', line=self.state_machine.abs_line_number() + 1) self.parent += msg return [], next_state, [] def table(self, isolate_function, parser_class): """Parse a table.""" block, messages, blank_finish = isolate_function() if block: try: parser = parser_class() tabledata = parser.parse(block) tableline = (self.state_machine.abs_line_number() - len(block) + 1) table = self.build_table(tabledata, tableline) nodelist = [table] + messages except tableparser.TableMarkupError, detail: nodelist = self.malformed_table( block, ' '.join(detail.args)) + messages else: nodelist = messages return nodelist, blank_finish def isolate_grid_table(self): messages = [] blank_finish = 1 try: block = self.state_machine.get_text_block(flush_left=1) except statemachine.UnexpectedIndentationError, instance: block, source, lineno = instance.args messages.append(self.reporter.error('Unexpected indentation.', source=source, line=lineno)) blank_finish = 0 block.disconnect() # for East Asian chars: block.pad_double_width(self.double_width_pad_char) width = len(block[0].strip()) for i in range(len(block)): block[i] = block[i].strip() if block[i][0] not in '+|': # check left edge blank_finish = 0 self.state_machine.previous_line(len(block) - i) del block[i:] break if not self.grid_table_top_pat.match(block[-1]): # find bottom blank_finish = 0 # from second-last to third line of table: for i in range(len(block) - 2, 1, -1): if self.grid_table_top_pat.match(block[i]): self.state_machine.previous_line(len(block) - i + 1) del block[i+1:] break else: messages.extend(self.malformed_table(block)) return [], messages, blank_finish for i in range(len(block)): # check right edge if len(block[i]) != width or block[i][-1] not in '+|': messages.extend(self.malformed_table(block)) return [], messages, blank_finish return block, messages, blank_finish def isolate_simple_table(self): start = self.state_machine.line_offset lines = self.state_machine.input_lines limit = len(lines) - 1 toplen = len(lines[start].strip()) pattern_match = self.simple_table_border_pat.match found = 0 found_at = None i = start + 1 while i <= limit: line = lines[i] match = pattern_match(line) if match: if len(line.strip()) != toplen: self.state_machine.next_line(i - start) messages = self.malformed_table( lines[start:i+1], 'Bottom/header table border does ' 'not match top border.') return [], messages, i == limit or not lines[i+1].strip() found += 1 found_at = i if found == 2 or i == limit or not lines[i+1].strip(): end = i break i += 1 else: # reached end of input_lines if found: extra = ' or no blank line after table bottom' self.state_machine.next_line(found_at - start) block = lines[start:found_at+1] else: extra = '' self.state_machine.next_line(i - start - 1) block = lines[start:] messages = self.malformed_table( block, 'No bottom table border found%s.' % extra) return [], messages, not extra self.state_machine.next_line(end - start) block = lines[start:end+1] # for East Asian chars: block.pad_double_width(self.double_width_pad_char) return block, [], end == limit or not lines[end+1].strip() def malformed_table(self, block, detail=''): block.replace(self.double_width_pad_char, '') data = '\n'.join(block) message = 'Malformed table.' lineno = self.state_machine.abs_line_number() - len(block) + 1 if detail: message += '\n' + detail error = self.reporter.error(message, nodes.literal_block(data, data), line=lineno) return [error] def build_table(self, tabledata, tableline, stub_columns=0): colwidths, headrows, bodyrows = tabledata table = nodes.table() tgroup = nodes.tgroup(cols=len(colwidths)) table += tgroup for colwidth in colwidths: colspec = nodes.colspec(colwidth=colwidth) if stub_columns: colspec.attributes['stub'] = 1 stub_columns -= 1 tgroup += colspec if headrows: thead = nodes.thead() tgroup += thead for row in headrows: thead += self.build_table_row(row, tableline) tbody = nodes.tbody() tgroup += tbody for row in bodyrows: tbody += self.build_table_row(row, tableline) return table def build_table_row(self, rowdata, tableline): row = nodes.row() for cell in rowdata: if cell is None: continue morerows, morecols, offset, cellblock = cell attributes = {} if morerows: attributes['morerows'] = morerows if morecols: attributes['morecols'] = morecols entry = nodes.entry(**attributes) row += entry if ''.join(cellblock): self.nested_parse(cellblock, input_offset=tableline+offset, node=entry) return row explicit = Struct() """Patterns and constants used for explicit markup recognition.""" explicit.patterns = Struct( target=re.compile(r""" ( _ # anonymous target | # *OR* (?P<quote>`?) # optional open quote (?![ `]) # first char. not space or # backquote (?P<name> # reference name .+? ) %(non_whitespace_escape_before)s (?P=quote) # close quote if open quote used ) (?<!(?<!\x00):) # no unescaped colon at end %(non_whitespace_escape_before)s [ ]? # optional space : # end of reference name ([ ]+|$) # followed by whitespace """ % vars(Inliner), re.VERBOSE), reference=re.compile(r""" ( (?P<simple>%(simplename)s)_ | # *OR* ` # open backquote (?![ ]) # not space (?P<phrase>.+?) # hyperlink phrase %(non_whitespace_escape_before)s `_ # close backquote, # reference mark ) $ # end of string """ % vars(Inliner), re.VERBOSE | re.UNICODE), substitution=re.compile(r""" ( (?![ ]) # first char. not space (?P<name>.+?) # substitution text %(non_whitespace_escape_before)s \| # close delimiter ) ([ ]+|$) # followed by whitespace """ % vars(Inliner), re.VERBOSE),) def footnote(self, match): lineno = self.state_machine.abs_line_number() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) label = match.group(1) name = normalize_name(label) footnote = nodes.footnote('\n'.join(indented)) footnote.line = lineno if name[0] == '#': # auto-numbered name = name[1:] # autonumber label footnote['auto'] = 1 if name: footnote['names'].append(name) self.document.note_autofootnote(footnote) elif name == '*': # auto-symbol name = '' footnote['auto'] = '*' self.document.note_symbol_footnote(footnote) else: # manually numbered footnote += nodes.label('', label) footnote['names'].append(name) self.document.note_footnote(footnote) if name: self.document.note_explicit_target(footnote, footnote) else: self.document.set_id(footnote, footnote) if indented: self.nested_parse(indented, input_offset=offset, node=footnote) return [footnote], blank_finish def citation(self, match): lineno = self.state_machine.abs_line_number() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) label = match.group(1) name = normalize_name(label) citation = nodes.citation('\n'.join(indented)) citation.line = lineno citation += nodes.label('', label) citation['names'].append(name) self.document.note_citation(citation) self.document.note_explicit_target(citation, citation) if indented: self.nested_parse(indented, input_offset=offset, node=citation) return [citation], blank_finish def hyperlink_target(self, match): pattern = self.explicit.patterns.target lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented( match.end(), until_blank=1, strip_indent=0) blocktext = match.string[:match.end()] + '\n'.join(block) block = [escape2null(line) for line in block] escaped = block[0] blockindex = 0 while 1: targetmatch = pattern.match(escaped) if targetmatch: break blockindex += 1 try: escaped += block[blockindex] except IndexError: raise MarkupError('malformed hyperlink target.', lineno) del block[:blockindex] block[0] = (block[0] + ' ')[targetmatch.end()-len(escaped)-1:].strip() target = self.make_target(block, blocktext, lineno, targetmatch.group('name')) return [target], blank_finish def make_target(self, block, block_text, lineno, target_name): target_type, data = self.parse_target(block, block_text, lineno) if target_type == 'refname': target = nodes.target(block_text, '', refname=normalize_name(data)) target.indirect_reference_name = data self.add_target(target_name, '', target, lineno) self.document.note_indirect_target(target) return target elif target_type == 'refuri': target = nodes.target(block_text, '') self.add_target(target_name, data, target, lineno) return target else: return data def parse_target(self, block, block_text, lineno): """ Determine the type of reference of a target. :Return: A 2-tuple, one of: - 'refname' and the indirect reference name - 'refuri' and the URI - 'malformed' and a system_message node """ if block and block[-1].strip()[-1:] == '_': # possible indirect target reference = ' '.join([line.strip() for line in block]) refname = self.is_reference(reference) if refname: return 'refname', refname reference = ''.join([''.join(line.split()) for line in block]) return 'refuri', unescape(reference) def is_reference(self, reference): match = self.explicit.patterns.reference.match( whitespace_normalize_name(reference)) if not match: return None return unescape(match.group('simple') or match.group('phrase')) def add_target(self, targetname, refuri, target, lineno): target.line = lineno if targetname: name = normalize_name(unescape(targetname)) target['names'].append(name) if refuri: uri = self.inliner.adjust_uri(refuri) if uri: target['refuri'] = uri else: raise ApplicationError('problem with URI: %r' % refuri) self.document.note_explicit_target(target, self.parent) else: # anonymous target if refuri: target['refuri'] = refuri target['anonymous'] = 1 self.document.note_anonymous_target(target) def substitution_def(self, match): pattern = self.explicit.patterns.substitution lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), strip_indent=0) blocktext = (match.string[:match.end()] + '\n'.join(block)) block.disconnect() escaped = escape2null(block[0].rstrip()) blockindex = 0 while 1: subdefmatch = pattern.match(escaped) if subdefmatch: break blockindex += 1 try: escaped = escaped + ' ' + escape2null(block[blockindex].strip()) except IndexError: raise MarkupError('malformed substitution definition.', lineno) del block[:blockindex] # strip out the substitution marker block[0] = (block[0].strip() + ' ')[subdefmatch.end()-len(escaped)-1:-1] if not block[0]: del block[0] offset += 1 while block and not block[-1].strip(): block.pop() subname = subdefmatch.group('name') substitution_node = nodes.substitution_definition(blocktext) substitution_node.line = lineno if not block: msg = self.reporter.warning( 'Substitution definition "%s" missing contents.' % subname, nodes.literal_block(blocktext, blocktext), line=lineno) return [msg], blank_finish block[0] = block[0].strip() substitution_node['names'].append( nodes.whitespace_normalize_name(subname)) new_abs_offset, blank_finish = self.nested_list_parse( block, input_offset=offset, node=substitution_node, initial_state='SubstitutionDef', blank_finish=blank_finish) i = 0 for node in substitution_node[:]: if not (isinstance(node, nodes.Inline) or isinstance(node, nodes.Text)): self.parent += substitution_node[i] del substitution_node[i] else: i += 1 for node in substitution_node.traverse(nodes.Element): if self.disallowed_inside_substitution_definitions(node): pformat = nodes.literal_block('', node.pformat().rstrip()) msg = self.reporter.error( 'Substitution definition contains illegal element:', pformat, nodes.literal_block(blocktext, blocktext), line=lineno) return [msg], blank_finish if len(substitution_node) == 0: msg = self.reporter.warning( 'Substitution definition "%s" empty or invalid.' % subname, nodes.literal_block(blocktext, blocktext), line=lineno) return [msg], blank_finish self.document.note_substitution_def( substitution_node, subname, self.parent) return [substitution_node], blank_finish def disallowed_inside_substitution_definitions(self, node): if (node['ids'] or isinstance(node, nodes.reference) and node.get('anonymous') or isinstance(node, nodes.footnote_reference) and node.get('auto')): return 1 else: return 0 def directive(self, match, **option_presets): """Returns a 2-tuple: list of nodes, and a "blank finish" boolean.""" type_name = match.group(1) directive_function, messages = directives.directive( type_name, self.memo.language, self.document) self.parent += messages if directive_function: return self.run_directive( directive_function, match, type_name, option_presets) else: return self.unknown_directive(type_name) def run_directive(self, directive_fn, match, type_name, option_presets): """ Parse a directive then run its directive function. Parameters: - `directive_fn`: The function implementing the directive. Uses function attributes ``arguments``, ``options``, and/or ``content`` if present. - `match`: A regular expression match object which matched the first line of the directive. - `type_name`: The directive name, as used in the source text. - `option_presets`: A dictionary of preset options, defaults for the directive options. Currently, only an "alt" option is passed by substitution definitions (value: the substitution name), which may be used by an embedded image directive. Returns a 2-tuple: list of nodes, and a "blank finish" boolean. """ lineno = self.state_machine.abs_line_number() initial_line_offset = self.state_machine.line_offset indented, indent, line_offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), strip_top=0) block_text = '\n'.join(self.state_machine.input_lines[ initial_line_offset : self.state_machine.line_offset + 1]) try: arguments, options, content, content_offset = ( self.parse_directive_block(indented, line_offset, directive_fn, option_presets)) except MarkupError, detail: error = self.reporter.error( 'Error in "%s" directive:\n%s.' % (type_name, ' '.join(detail.args)), nodes.literal_block(block_text, block_text), line=lineno) return [error], blank_finish result = directive_fn(type_name, arguments, options, content, lineno, content_offset, block_text, self, self.state_machine) return (result, blank_finish or self.state_machine.is_next_line_blank()) def parse_directive_block(self, indented, line_offset, directive_fn, option_presets): arguments = [] options = {} argument_spec = getattr(directive_fn, 'arguments', None) if argument_spec and argument_spec[:2] == (0, 0): argument_spec = None option_spec = getattr(directive_fn, 'options', None) content_spec = getattr(directive_fn, 'content', None) if indented and not indented[0].strip(): indented.trim_start() line_offset += 1 while indented and not indented[-1].strip(): indented.trim_end() if indented and (argument_spec or option_spec): for i in range(len(indented)): if not indented[i].strip(): break else: i += 1 arg_block = indented[:i] content = indented[i+1:] content_offset = line_offset + i + 1 else: content = indented content_offset = line_offset arg_block = [] while content and not content[0].strip(): content.trim_start() content_offset += 1 if option_spec: options, arg_block = self.parse_directive_options( option_presets, option_spec, arg_block) if arg_block and not argument_spec: raise MarkupError('no arguments permitted; blank line ' 'required before content block') if argument_spec: arguments = self.parse_directive_arguments( argument_spec, arg_block) if content and not content_spec: raise MarkupError('no content permitted') return (arguments, options, content, content_offset) def parse_directive_options(self, option_presets, option_spec, arg_block): options = option_presets.copy() for i in range(len(arg_block)): if arg_block[i][:1] == ':': opt_block = arg_block[i:] arg_block = arg_block[:i] break else: opt_block = [] if opt_block: success, data = self.parse_extension_options(option_spec, opt_block) if success: # data is a dict of options options.update(data) else: # data is an error string raise MarkupError(data) return options, arg_block def parse_directive_arguments(self, argument_spec, arg_block): required, optional, last_whitespace = argument_spec arg_text = '\n'.join(arg_block) arguments = arg_text.split() if len(arguments) < required: raise MarkupError('%s argument(s) required, %s supplied' % (required, len(arguments))) elif len(arguments) > required + optional: if last_whitespace: arguments = arg_text.split(None, required + optional - 1) else: raise MarkupError( 'maximum %s argument(s) allowed, %s supplied' % (required + optional, len(arguments))) return arguments def parse_extension_options(self, option_spec, datalines): """ Parse `datalines` for a field list containing extension options matching `option_spec`. :Parameters: - `option_spec`: a mapping of option name to conversion function, which should raise an exception on bad input. - `datalines`: a list of input strings. :Return: - Success value, 1 or 0. - An option dictionary on success, an error string on failure. """ node = nodes.field_list() newline_offset, blank_finish = self.nested_list_parse( datalines, 0, node, initial_state='ExtensionOptions', blank_finish=1) if newline_offset != len(datalines): # incomplete parse of block return 0, 'invalid option block' try: options = utils.extract_extension_options(node, option_spec) except KeyError, detail: return 0, ('unknown option: "%s"' % detail.args[0]) except (ValueError, TypeError), detail: return 0, ('invalid option value: %s' % ' '.join(detail.args)) except utils.ExtensionOptionError, detail: return 0, ('invalid option data: %s' % ' '.join(detail.args)) if blank_finish: return 1, options else: return 0, 'option data incompletely parsed' def unknown_directive(self, type_name): lineno = self.state_machine.abs_line_number() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(0, strip_indent=0) text = '\n'.join(indented) error = self.reporter.error( 'Unknown directive type "%s".' % type_name, nodes.literal_block(text, text), line=lineno) return [error], blank_finish def comment(self, match): if not match.string[match.end():].strip() \ and self.state_machine.is_next_line_blank(): # an empty comment? return [nodes.comment()], 1 # "A tiny but practical wart." indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) while indented and not indented[-1].strip(): indented.trim_end() text = '\n'.join(indented) return [nodes.comment(text, text)], blank_finish explicit.constructs = [ (footnote, re.compile(r""" \.\.[ ]+ # explicit markup start \[ ( # footnote label: [0-9]+ # manually numbered footnote | # *OR* \# # anonymous auto-numbered footnote | # *OR* \#%s # auto-number ed?) footnote label | # *OR* \* # auto-symbol footnote ) \] ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE)), (citation, re.compile(r""" \.\.[ ]+ # explicit markup start \[(%s)\] # citation label ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE)), (hyperlink_target, re.compile(r""" \.\.[ ]+ # explicit markup start _ # target indicator (?![ ]|$) # first char. not space or EOL """, re.VERBOSE)), (substitution_def, re.compile(r""" \.\.[ ]+ # explicit markup start \| # substitution indicator (?![ ]|$) # first char. not space or EOL """, re.VERBOSE)), (directive, re.compile(r""" \.\.[ ]+ # explicit markup start (%s) # directive name [ ]? # optional space :: # directive delimiter ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE))] def explicit_markup(self, match, context, next_state): """Footnotes, hyperlink targets, directives, comments.""" nodelist, blank_finish = self.explicit_construct(match) self.parent += nodelist self.explicit_list(blank_finish) return [], next_state, [] def explicit_construct(self, match): """Determine which explicit construct this is, parse & return it.""" errors = [] for method, pattern in self.explicit.constructs: expmatch = pattern.match(match.string) if expmatch: try: return method(self, expmatch) except MarkupError, (message, lineno): # never reached? errors.append(self.reporter.warning(message, line=lineno)) break nodelist, blank_finish = self.comment(match) return nodelist + errors, blank_finish def explicit_list(self, blank_finish): """ Create a nested state machine for a series of explicit markup constructs (including anonymous hyperlink targets). """ offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=self.parent, initial_state='Explicit', blank_finish=blank_finish, match_titles=self.state_machine.match_titles) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Explicit markup') def anonymous(self, match, context, next_state): """Anonymous hyperlink targets.""" nodelist, blank_finish = self.anonymous_target(match) self.parent += nodelist self.explicit_list(blank_finish) return [], next_state, [] def anonymous_target(self, match): lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), until_blank=1) blocktext = match.string[:match.end()] + '\n'.join(block) block = [escape2null(line) for line in block] target = self.make_target(block, blocktext, lineno, '') return [target], blank_finish def line(self, match, context, next_state): """Section title overline or transition marker.""" if self.state_machine.match_titles: return [match.string], 'Line', [] elif match.string.strip() == '::': raise statemachine.TransitionCorrection('text') elif len(match.string.strip()) < 4: msg = self.reporter.info( 'Unexpected possible title overline or transition.\n' "Treating it as ordinary text because it's so short.", line=self.state_machine.abs_line_number()) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = self.state_machine.line msg = self.reporter.severe( 'Unexpected section title or transition.', nodes.literal_block(blocktext, blocktext), line=self.state_machine.abs_line_number()) self.parent += msg return [], next_state, [] def text(self, match, context, next_state): """Titles, definition lists, paragraphs.""" return [match.string], 'Text', [] class RFC2822Body(Body): """ RFC2822 headers are only valid as the first constructs in documents. As soon as anything else appears, the `Body` state should take over. """ patterns = Body.patterns.copy() # can't modify the original patterns['rfc2822'] = r'[!-9;-~]+:( +|$)' initial_transitions = [(name, 'Body') for name in Body.initial_transitions] initial_transitions.insert(-1, ('rfc2822', 'Body')) # just before 'text' def rfc2822(self, match, context, next_state): """RFC2822-style field list item.""" fieldlist = nodes.field_list(classes=['rfc2822']) self.parent += fieldlist field, blank_finish = self.rfc2822_field(match) fieldlist += field offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=fieldlist, initial_state='RFC2822List', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning( 'RFC2822-style field list') return [], next_state, [] def rfc2822_field(self, match): name = match.string[:match.string.find(':')] indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), until_blank=1) fieldnode = nodes.field() fieldnode += nodes.field_name(name, name) fieldbody = nodes.field_body('\n'.join(indented)) fieldnode += fieldbody if indented: self.nested_parse(indented, input_offset=line_offset, node=fieldbody) return fieldnode, blank_finish class SpecializedBody(Body): """ Superclass for second and subsequent compound element members. Compound elements are lists and list-like constructs. All transition methods are disabled (redefined as `invalid_input`). Override individual methods in subclasses to re-enable. For example, once an initial bullet list item, say, is recognized, the `BulletList` subclass takes over, with a "bullet_list" node as its container. Upon encountering the initial bullet list item, `Body.bullet` calls its ``self.nested_list_parse`` (`RSTState.nested_list_parse`), which starts up a nested parsing session with `BulletList` as the initial state. Only the ``bullet`` transition method is enabled in `BulletList`; as long as only bullet list items are encountered, they are parsed and inserted into the container. The first construct which is *not* a bullet list item triggers the `invalid_input` method, which ends the nested parse and closes the container. `BulletList` needs to recognize input that is invalid in the context of a bullet list, which means everything *other than* bullet list items, so it inherits the transition list created in `Body`. """ def invalid_input(self, match=None, context=None, next_state=None): """Not a compound element member. Abort this state machine.""" self.state_machine.previous_line() # back up so parent SM can reassess raise EOFError indent = invalid_input bullet = invalid_input enumerator = invalid_input field_marker = invalid_input option_marker = invalid_input doctest = invalid_input line_block = invalid_input grid_table_top = invalid_input simple_table_top = invalid_input explicit_markup = invalid_input anonymous = invalid_input line = invalid_input text = invalid_input class BulletList(SpecializedBody): """Second and subsequent bullet_list list_items.""" def bullet(self, match, context, next_state): """Bullet list item.""" if match.string[0] != self.parent['bullet']: # different bullet: new list self.invalid_input() listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish return [], next_state, [] class DefinitionList(SpecializedBody): """Second and subsequent definition_list_items.""" def text(self, match, context, next_state): """Definition lists.""" return [match.string], 'Definition', [] class EnumeratedList(SpecializedBody): """Second and subsequent enumerated_list list_items.""" def enumerator(self, match, context, next_state): """Enumerated list item.""" format, sequence, text, ordinal = self.parse_enumerator( match, self.parent['enumtype']) if ( format != self.format or (sequence != '#' and (sequence != self.parent['enumtype'] or self.auto or ordinal != (self.lastordinal + 1))) or not self.is_enumerated_list_item(ordinal, sequence, format)): # different enumeration: new list self.invalid_input() if sequence == '#': self.auto = 1 listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish self.lastordinal = ordinal return [], next_state, [] class FieldList(SpecializedBody): """Second and subsequent field_list fields.""" def field_marker(self, match, context, next_state): """Field list field.""" field, blank_finish = self.field(match) self.parent += field self.blank_finish = blank_finish return [], next_state, [] class OptionList(SpecializedBody): """Second and subsequent option_list option_list_items.""" def option_marker(self, match, context, next_state): """Option list item.""" try: option_list_item, blank_finish = self.option_list_item(match) except MarkupError, (message, lineno): self.invalid_input() self.parent += option_list_item self.blank_finish = blank_finish return [], next_state, [] class RFC2822List(SpecializedBody, RFC2822Body): """Second and subsequent RFC2822-style field_list fields.""" patterns = RFC2822Body.patterns initial_transitions = RFC2822Body.initial_transitions def rfc2822(self, match, context, next_state): """RFC2822-style field list item.""" field, blank_finish = self.rfc2822_field(match) self.parent += field self.blank_finish = blank_finish return [], 'RFC2822List', [] blank = SpecializedBody.invalid_input class ExtensionOptions(FieldList): """ Parse field_list fields for extension options. No nested parsing is done (including inline markup parsing). """ def parse_field_body(self, indented, offset, node): """Override `Body.parse_field_body` for simpler parsing.""" lines = [] for line in list(indented) + ['']: if line.strip(): lines.append(line) elif lines: text = '\n'.join(lines) node += nodes.paragraph(text, text) lines = [] class LineBlock(SpecializedBody): """Second and subsequent lines of a line_block.""" blank = SpecializedBody.invalid_input def line_block(self, match, context, next_state): """New line of line block.""" lineno = self.state_machine.abs_line_number() line, messages, blank_finish = self.line_block_line(match, lineno) self.parent += line self.parent.parent += messages self.blank_finish = blank_finish return [], next_state, [] class Explicit(SpecializedBody): """Second and subsequent explicit markup construct.""" def explicit_markup(self, match, context, next_state): """Footnotes, hyperlink targets, directives, comments.""" nodelist, blank_finish = self.explicit_construct(match) self.parent += nodelist self.blank_finish = blank_finish return [], next_state, [] def anonymous(self, match, context, next_state): """Anonymous hyperlink targets.""" nodelist, blank_finish = self.anonymous_target(match) self.parent += nodelist self.blank_finish = blank_finish return [], next_state, [] blank = SpecializedBody.invalid_input class SubstitutionDef(Body): """ Parser for the contents of a substitution_definition element. """ patterns = { 'embedded_directive': re.compile(r'(%s)::( +|$)' % Inliner.simplename, re.UNICODE), 'text': r''} initial_transitions = ['embedded_directive', 'text'] def embedded_directive(self, match, context, next_state): nodelist, blank_finish = self.directive(match, alt=self.parent['names'][0]) self.parent += nodelist if not self.state_machine.at_eof(): self.blank_finish = blank_finish raise EOFError def text(self, match, context, next_state): if not self.state_machine.at_eof(): self.blank_finish = self.state_machine.is_next_line_blank() raise EOFError class Text(RSTState): """ Classifier of second line of a text block. Could be a paragraph, a definition list item, or a title. """ patterns = {'underline': Body.patterns['line'], 'text': r''} initial_transitions = [('underline', 'Body'), ('text', 'Body')] def blank(self, match, context, next_state): """End of paragraph.""" paragraph, literalnext = self.paragraph( context, self.state_machine.abs_line_number() - 1) self.parent += paragraph if literalnext: self.parent += self.literal_block() return [], 'Body', [] def eof(self, context): if context: self.blank(None, context, None) return [] def indent(self, match, context, next_state): """Definition list item.""" definitionlist = nodes.definition_list() definitionlistitem, blank_finish = self.definition_list_item(context) definitionlist += definitionlistitem self.parent += definitionlist offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=definitionlist, initial_state='DefinitionList', blank_finish=blank_finish, blank_finish_state='Definition') self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Definition list') return [], 'Body', [] def underline(self, match, context, next_state): """Section title.""" lineno = self.state_machine.abs_line_number() title = context[0].rstrip() underline = match.string.rstrip() source = title + '\n' + underline messages = [] if column_width(title) > len(underline): if len(underline) < 4: if self.state_machine.match_titles: msg = self.reporter.info( 'Possible title underline, too short for the title.\n' "Treating it as ordinary text because it's so short.", line=lineno) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = context[0] + '\n' + self.state_machine.line msg = self.reporter.warning( 'Title underline too short.', nodes.literal_block(blocktext, blocktext), line=lineno) messages.append(msg) if not self.state_machine.match_titles: blocktext = context[0] + '\n' + self.state_machine.line msg = self.reporter.severe( 'Unexpected section title.', nodes.literal_block(blocktext, blocktext), line=lineno) self.parent += messages self.parent += msg return [], next_state, [] style = underline[0] context[:] = [] self.section(title, source, style, lineno - 1, messages) return [], next_state, [] def text(self, match, context, next_state): """Paragraph.""" startline = self.state_machine.abs_line_number() - 1 msg = None try: block = self.state_machine.get_text_block(flush_left=1) except statemachine.UnexpectedIndentationError, instance: block, source, lineno = instance.args msg = self.reporter.error('Unexpected indentation.', source=source, line=lineno) lines = context + list(block) paragraph, literalnext = self.paragraph(lines, startline) self.parent += paragraph self.parent += msg if literalnext: try: self.state_machine.next_line() except EOFError: pass self.parent += self.literal_block() return [], next_state, [] def literal_block(self): """Return a list of nodes.""" indented, indent, offset, blank_finish = \ self.state_machine.get_indented() while indented and not indented[-1].strip(): indented.trim_end() if not indented: return self.quoted_literal_block() data = '\n'.join(indented) literal_block = nodes.literal_block(data, data) literal_block.line = offset + 1 nodelist = [literal_block] if not blank_finish: nodelist.append(self.unindent_warning('Literal block')) return nodelist def quoted_literal_block(self): abs_line_offset = self.state_machine.abs_line_offset() offset = self.state_machine.line_offset parent_node = nodes.Element() new_abs_offset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=abs_line_offset, node=parent_node, match_titles=0, state_machine_kwargs={'state_classes': (QuotedLiteralBlock,), 'initial_state': 'QuotedLiteralBlock'}) self.goto_line(new_abs_offset) return parent_node.children def definition_list_item(self, termline): indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() definitionlistitem = nodes.definition_list_item( '\n'.join(termline + list(indented))) lineno = self.state_machine.abs_line_number() - 1 definitionlistitem.line = lineno termlist, messages = self.term(termline, lineno) definitionlistitem += termlist definition = nodes.definition('', *messages) definitionlistitem += definition if termline[0][-2:] == '::': definition += self.reporter.info( 'Blank line missing before literal block (after the "::")? ' 'Interpreted as a definition list item.', line=line_offset+1) self.nested_parse(indented, input_offset=line_offset, node=definition) return definitionlistitem, blank_finish classifier_delimiter = re.compile(' +: +') def term(self, lines, lineno): """Return a definition_list's term and optional classifiers.""" assert len(lines) == 1 text_nodes, messages = self.inline_text(lines[0], lineno) term_node = nodes.term() node_list = [term_node] for i in range(len(text_nodes)): node = text_nodes[i] if isinstance(node, nodes.Text): parts = self.classifier_delimiter.split(node.rawsource) if len(parts) == 1: node_list[-1] += node else: node_list[-1] += nodes.Text(parts[0].rstrip()) for part in parts[1:]: classifier_node = nodes.classifier('', part) node_list.append(classifier_node) else: node_list[-1] += node return node_list, messages class SpecializedText(Text): """ Superclass for second and subsequent lines of Text-variants. All transition methods are disabled. Override individual methods in subclasses to re-enable. """ def eof(self, context): """Incomplete construct.""" return [] def invalid_input(self, match=None, context=None, next_state=None): """Not a compound element member. Abort this state machine.""" raise EOFError blank = invalid_input indent = invalid_input underline = invalid_input text = invalid_input class Definition(SpecializedText): """Second line of potential definition_list_item.""" def eof(self, context): """Not a definition.""" self.state_machine.previous_line(2) # so parent SM can reassess return [] def indent(self, match, context, next_state): """Definition list item.""" definitionlistitem, blank_finish = self.definition_list_item(context) self.parent += definitionlistitem self.blank_finish = blank_finish return [], 'DefinitionList', [] class Line(SpecializedText): """ Second line of over- & underlined section title or transition marker. """ eofcheck = 1 # @@@ ??? """Set to 0 while parsing sections, so that we don't catch the EOF.""" def eof(self, context): """Transition marker at end of section or document.""" marker = context[0].strip() if self.memo.section_bubble_up_kludge: self.memo.section_bubble_up_kludge = 0 elif len(marker) < 4: self.state_correction(context) if self.eofcheck: # ignore EOFError with sections lineno = self.state_machine.abs_line_number() - 1 transition = nodes.transition(rawsource=context[0]) transition.line = lineno self.parent += transition self.eofcheck = 1 return [] def blank(self, match, context, next_state): """Transition marker.""" lineno = self.state_machine.abs_line_number() - 1 marker = context[0].strip() if len(marker) < 4: self.state_correction(context) transition = nodes.transition(rawsource=marker) transition.line = lineno self.parent += transition return [], 'Body', [] def text(self, match, context, next_state): """Potential over- & underlined title.""" lineno = self.state_machine.abs_line_number() - 1 overline = context[0] title = match.string underline = '' try: underline = self.state_machine.next_line() except EOFError: blocktext = overline + '\n' + title if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Incomplete section title.', nodes.literal_block(blocktext, blocktext), line=lineno) self.parent += msg return [], 'Body', [] source = '%s\n%s\n%s' % (overline, title, underline) overline = overline.rstrip() underline = underline.rstrip() if not self.transitions['underline'][0].match(underline): blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Missing matching underline for section title overline.', nodes.literal_block(source, source), line=lineno) self.parent += msg return [], 'Body', [] elif overline != underline: blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Title overline & underline mismatch.', nodes.literal_block(source, source), line=lineno) self.parent += msg return [], 'Body', [] title = title.rstrip() messages = [] if column_width(title) > len(overline): blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.warning( 'Title overline too short.', nodes.literal_block(source, source), line=lineno) messages.append(msg) style = (overline[0], underline[0]) self.eofcheck = 0 # @@@ not sure this is correct self.section(title.lstrip(), source, style, lineno + 1, messages) self.eofcheck = 1 return [], 'Body', [] indent = text # indented title def underline(self, match, context, next_state): overline = context[0] blocktext = overline + '\n' + self.state_machine.line lineno = self.state_machine.abs_line_number() - 1 if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 1) msg = self.reporter.error( 'Invalid section title or transition marker.', nodes.literal_block(blocktext, blocktext), line=lineno) self.parent += msg return [], 'Body', [] def short_overline(self, context, blocktext, lineno, lines=1): msg = self.reporter.info( 'Possible incomplete section title.\nTreating the overline as ' "ordinary text because it's so short.", line=lineno) self.parent += msg self.state_correction(context, lines) def state_correction(self, context, lines=1): self.state_machine.previous_line(lines) context[:] = [] raise statemachine.StateCorrection('Body', 'text') class QuotedLiteralBlock(RSTState): """ Nested parse handler for quoted (unindented) literal blocks. Special-purpose. Not for inclusion in `state_classes`. """ patterns = {'initial_quoted': r'(%(nonalphanum7bit)s)' % Body.pats, 'text': r''} initial_transitions = ('initial_quoted', 'text') def __init__(self, state_machine, debug=0): RSTState.__init__(self, state_machine, debug) self.messages = [] self.initial_lineno = None def blank(self, match, context, next_state): if context: raise EOFError else: return context, next_state, [] def eof(self, context): if context: text = '\n'.join(context) literal_block = nodes.literal_block(text, text) literal_block.line = self.initial_lineno self.parent += literal_block else: self.parent += self.reporter.warning( 'Literal block expected; none found.', line=self.state_machine.abs_line_number()) self.state_machine.previous_line() self.parent += self.messages return [] def indent(self, match, context, next_state): assert context, ('QuotedLiteralBlock.indent: context should not ' 'be empty!') self.messages.append( self.reporter.error('Unexpected indentation.', line=self.state_machine.abs_line_number())) self.state_machine.previous_line() raise EOFError def initial_quoted(self, match, context, next_state): """Match arbitrary quote character on the first line only.""" self.remove_transition('initial_quoted') quote = match.string[0] pattern = re.compile(re.escape(quote)) # New transition matches consistent quotes only: self.add_transition('quoted', (pattern, self.quoted, self.__class__.__name__)) self.initial_lineno = self.state_machine.abs_line_number() return [match.string], next_state, [] def quoted(self, match, context, next_state): """Match consistent quotes on subsequent lines.""" context.append(match.string) return context, next_state, [] def text(self, match, context, next_state): if context: self.messages.append( self.reporter.error('Inconsistent literal block quoting.', line=self.state_machine.abs_line_number())) self.state_machine.previous_line() raise EOFError state_classes = (Body, BulletList, DefinitionList, EnumeratedList, FieldList, OptionList, LineBlock, ExtensionOptions, Explicit, Text, Definition, Line, SubstitutionDef, RFC2822Body, RFC2822List) """Standard set of State classes used to start `RSTStateMachine`."""
{ "repo_name": "google-code-export/django-hotclub", "path": "libs/external_libs/docutils-0.4/docutils/parsers/rst/states.py", "copies": "6", "size": "123983", "license": "mit", "hash": -721569077677909100, "line_mean": 41.0566485753, "line_max": 80, "alpha_frac": 0.5470427397, "autogenerated": false, "ratio": 4.385673859214715, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7932716598914714, "avg_score": null, "num_lines": null }
""" Docutils component-related transforms. """ __docformat__ = 'reStructuredText' import sys import os import re import time from docutils import nodes, utils from docutils import ApplicationError, DataError from docutils.transforms import Transform, TransformError class Filter(Transform): """ Include or exclude elements which depend on a specific Docutils component. For use with `nodes.pending` elements. A "pending" element's dictionary attribute ``details`` must contain the keys "component" and "format". The value of ``details['component']`` must match the type name of the component the elements depend on (e.g. "writer"). The value of ``details['format']`` is the name of a specific format or context of that component (e.g. "html"). If the matching Docutils component supports that format or context, the "pending" element is replaced by the contents of ``details['nodes']`` (a list of nodes); otherwise, the "pending" element is removed. For example, the reStructuredText "meta" directive creates a "pending" element containing a "meta" element (in ``pending.details['nodes']``). Only writers (``pending.details['component'] == 'writer'``) supporting the "html" format (``pending.details['format'] == 'html'``) will include the "meta" element; it will be deleted from the output of all other writers. """ default_priority = 780 def apply(self): pending = self.startnode component_type = pending.details['component'] # 'reader' or 'writer' format = pending.details['format'] component = self.document.transformer.components[component_type] if component.supports(format): pending.parent.replace(pending, pending.details['nodes']) else: pending.parent.remove(pending)
{ "repo_name": "jmchilton/galaxy-central", "path": "modules/docutils/transforms/components.py", "copies": "1", "size": "2058", "license": "mit", "hash": -1050033501474873500, "line_mean": 37.1111111111, "line_max": 78, "alpha_frac": 0.6967930029, "autogenerated": false, "ratio": 4.140845070422535, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5337638073322535, "avg_score": null, "num_lines": null }
""" Directives for additional body elements. See `docutils.parsers.rst.directives` for API details. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes from docutils.parsers.rst import directives from docutils.parsers.rst.roles import set_classes def topic(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine, node_class=nodes.topic): if not (state_machine.match_titles or isinstance(state_machine.node, nodes.sidebar)): error = state_machine.reporter.error( 'The "%s" directive may not be used within topics ' 'or body elements.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [error] if not content: warning = state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [warning] title_text = arguments[0] textnodes, messages = state.inline_text(title_text, lineno) titles = [nodes.title(title_text, '', *textnodes)] # sidebar uses this code if options.has_key('subtitle'): textnodes, more_messages = state.inline_text(options['subtitle'], lineno) titles.append(nodes.subtitle(options['subtitle'], '', *textnodes)) messages.extend(more_messages) text = '\n'.join(content) node = node_class(text, *(titles + messages)) node['classes'] += options.get('class', []) if text: state.nested_parse(content, content_offset, node) return [node] topic.arguments = (1, 0, 1) topic.options = {'class': directives.class_option} topic.content = 1 def sidebar(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): if isinstance(state_machine.node, nodes.sidebar): error = state_machine.reporter.error( 'The "%s" directive may not be used within a sidebar element.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [error] return topic(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine, node_class=nodes.sidebar) sidebar.arguments = (1, 0, 1) sidebar.options = {'subtitle': directives.unchanged_required, 'class': directives.class_option} sidebar.content = 1 def line_block(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): if not content: warning = state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [warning] block = nodes.line_block(classes=options.get('class', [])) node_list = [block] for line_text in content: text_nodes, messages = state.inline_text(line_text.strip(), lineno + content_offset) line = nodes.line(line_text, '', *text_nodes) if line_text.strip(): line.indent = len(line_text) - len(line_text.lstrip()) block += line node_list.extend(messages) content_offset += 1 state.nest_line_block_lines(block) return node_list line_block.options = {'class': directives.class_option} line_block.content = 1 def parsed_literal(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): set_classes(options) return block(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine, node_class=nodes.literal_block) parsed_literal.options = {'class': directives.class_option} parsed_literal.content = 1 def block(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine, node_class): if not content: warning = state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [warning] text = '\n'.join(content) text_nodes, messages = state.inline_text(text, lineno) node = node_class(text, '', *text_nodes, **options) node.line = content_offset + 1 return [node] + messages def rubric(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): rubric_text = arguments[0] textnodes, messages = state.inline_text(rubric_text, lineno) rubric = nodes.rubric(rubric_text, '', *textnodes, **options) return [rubric] + messages rubric.arguments = (1, 0, 1) rubric.options = {'class': directives.class_option} def epigraph(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): block_quote, messages = state.block_quote(content, content_offset) block_quote['classes'].append('epigraph') return [block_quote] + messages epigraph.content = 1 def highlights(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): block_quote, messages = state.block_quote(content, content_offset) block_quote['classes'].append('highlights') return [block_quote] + messages highlights.content = 1 def pull_quote(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): block_quote, messages = state.block_quote(content, content_offset) block_quote['classes'].append('pull-quote') return [block_quote] + messages pull_quote.content = 1 def compound(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): text = '\n'.join(content) if not text: error = state_machine.reporter.error( 'The "%s" directive is empty; content required.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [error] node = nodes.compound(text) node['classes'] += options.get('class', []) state.nested_parse(content, content_offset, node) return [node] compound.options = {'class': directives.class_option} compound.content = 1 def container(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): text = '\n'.join(content) if not text: error = state_machine.reporter.error( 'The "%s" directive is empty; content required.' % name, nodes.literal_block(block_text, block_text), line=lineno) return [error] try: if arguments: classes = directives.class_option(arguments[0]) else: classes = [] except ValueError: error = state_machine.reporter.error( 'Invalid class attribute value for "%s" directive: "%s".' % (name, arguments[0]), nodes.literal_block(block_text, block_text), line=lineno) return [error] node = nodes.container(text) node['classes'].extend(classes) state.nested_parse(content, content_offset, node) return [node] container.arguments = (0, 1, 1) container.content = 1
{ "repo_name": "mogotest/selenium", "path": "selenium/src/py/lib/docutils/parsers/rst/directives/body.py", "copies": "5", "size": "7848", "license": "apache-2.0", "hash": -5455777502211972000, "line_mean": 38.0408163265, "line_max": 79, "alpha_frac": 0.624235474, "autogenerated": false, "ratio": 3.9279279279279278, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0031661842390919926, "num_lines": 196 }
""" This package contains directive implementation modules. The interface for directive functions is as follows:: def directive_fn(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): code... # Set function attributes: directive_fn.arguments = ... directive_fn.options = ... direcitve_fn.content = ... Parameters: - ``name`` is the directive type or name (string). - ``arguments`` is a list of positional arguments (strings). - ``options`` is a dictionary mapping option names (strings) to values (type depends on option conversion functions; see below). - ``content`` is a list of strings, the directive content. - ``lineno`` is the line number of the first line of the directive. - ``content_offset`` is the line offset of the first line of the content from the beginning of the current input. Used when initiating a nested parse. - ``block_text`` is a string containing the entire directive. Include it as the content of a literal block in a system message if there is a problem. - ``state`` is the state which called the directive function. - ``state_machine`` is the state machine which controls the state which called the directive function. Function attributes, interpreted by the directive parser (which calls the directive function): - ``arguments``: A 3-tuple specifying the expected positional arguments, or ``None`` if the directive has no arguments. The 3 items in the tuple are ``(required, optional, whitespace OK in last argument)``: 1. The number of required arguments. 2. The number of optional arguments. 3. A boolean, indicating if the final argument may contain whitespace. Arguments are normally single whitespace-separated words. The final argument may contain whitespace if the third item in the argument spec tuple is 1/True. If the form of the arguments is more complex, specify only one argument (either required or optional) and indicate that final whitespace is OK; the client code must do any context-sensitive parsing. - ``options``: A dictionary, mapping known option names to conversion functions such as `int` or `float`. ``None`` or an empty dict implies no options to parse. Several directive option conversion functions are defined in this module. Option conversion functions take a single parameter, the option argument (a string or ``None``), validate it and/or convert it to the appropriate form. Conversion functions may raise ``ValueError`` and ``TypeError`` exceptions. - ``content``: A boolean; true if content is allowed. Client code must handle the case where content is required but not supplied (an empty content list will be supplied). Directive functions return a list of nodes which will be inserted into the document tree at the point where the directive was encountered (can be an empty list). See `Creating reStructuredText Directives`_ for more information. .. _Creating reStructuredText Directives: http://docutils.sourceforge.net/docs/howto/rst-directives.html """ __docformat__ = 'reStructuredText' import re import codecs from docutils import nodes from docutils.parsers.rst.languages import en as _fallback_language_module _directive_registry = { 'attention': ('admonitions', 'attention'), 'caution': ('admonitions', 'caution'), 'danger': ('admonitions', 'danger'), 'error': ('admonitions', 'error'), 'important': ('admonitions', 'important'), 'note': ('admonitions', 'note'), 'tip': ('admonitions', 'tip'), 'hint': ('admonitions', 'hint'), 'warning': ('admonitions', 'warning'), 'admonition': ('admonitions', 'admonition'), 'sidebar': ('body', 'sidebar'), 'topic': ('body', 'topic'), 'line-block': ('body', 'line_block'), 'parsed-literal': ('body', 'parsed_literal'), 'rubric': ('body', 'rubric'), 'epigraph': ('body', 'epigraph'), 'highlights': ('body', 'highlights'), 'pull-quote': ('body', 'pull_quote'), 'compound': ('body', 'compound'), 'container': ('body', 'container'), #'questions': ('body', 'question_list'), 'table': ('tables', 'table'), 'csv-table': ('tables', 'csv_table'), 'list-table': ('tables', 'list_table'), 'image': ('images', 'image'), 'figure': ('images', 'figure'), 'contents': ('parts', 'contents'), 'sectnum': ('parts', 'sectnum'), 'header': ('parts', 'header'), 'footer': ('parts', 'footer'), #'footnotes': ('parts', 'footnotes'), #'citations': ('parts', 'citations'), 'target-notes': ('references', 'target_notes'), 'meta': ('html', 'meta'), #'imagemap': ('html', 'imagemap'), 'raw': ('misc', 'raw'), 'include': ('misc', 'include'), 'replace': ('misc', 'replace'), 'unicode': ('misc', 'unicode_directive'), 'class': ('misc', 'class_directive'), 'role': ('misc', 'role'), 'default-role': ('misc', 'default_role'), 'title': ('misc', 'title'), 'date': ('misc', 'date'), 'restructuredtext-test-directive': ('misc', 'directive_test_function'),} """Mapping of directive name to (module name, function name). The directive name is canonical & must be lowercase. Language-dependent names are defined in the ``language`` subpackage.""" _modules = {} """Cache of imported directive modules.""" _directives = {} """Cache of imported directive functions.""" def directive(directive_name, language_module, document): """ Locate and return a directive function from its language-dependent name. If not found in the current language, check English. Return None if the named directive cannot be found. """ normname = directive_name.lower() messages = [] msg_text = [] if _directives.has_key(normname): return _directives[normname], messages canonicalname = None try: canonicalname = language_module.directives[normname] except AttributeError, error: msg_text.append('Problem retrieving directive entry from language ' 'module %r: %s.' % (language_module, error)) except KeyError: msg_text.append('No directive entry for "%s" in module "%s".' % (directive_name, language_module.__name__)) if not canonicalname: try: canonicalname = _fallback_language_module.directives[normname] msg_text.append('Using English fallback for directive "%s".' % directive_name) except KeyError: msg_text.append('Trying "%s" as canonical directive name.' % directive_name) # The canonical name should be an English name, but just in case: canonicalname = normname if msg_text: message = document.reporter.info( '\n'.join(msg_text), line=document.current_line) messages.append(message) try: modulename, functionname = _directive_registry[canonicalname] except KeyError: # Error handling done by caller. return None, messages if _modules.has_key(modulename): module = _modules[modulename] else: try: module = __import__(modulename, globals(), locals()) except ImportError, detail: messages.append(document.reporter.error( 'Error importing directive module "%s" (directive "%s"):\n%s' % (modulename, directive_name, detail), line=document.current_line)) return None, messages try: function = getattr(module, functionname) _directives[normname] = function except AttributeError: messages.append(document.reporter.error( 'No function "%s" in module "%s" (directive "%s").' % (functionname, modulename, directive_name), line=document.current_line)) return None, messages return function, messages def register_directive(name, directive_function): """ Register a nonstandard application-defined directive function. Language lookups are not needed for such functions. """ _directives[name] = directive_function def flag(argument): """ Check for a valid flag option (no argument) and return ``None``. (Directive option conversion function.) Raise ``ValueError`` if an argument is found. """ if argument and argument.strip(): raise ValueError('no argument is allowed; "%s" supplied' % argument) else: return None def unchanged_required(argument): """ Return the argument text, unchanged. (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') else: return argument # unchanged! def unchanged(argument): """ Return the argument text, unchanged. (Directive option conversion function.) No argument implies empty string (""). """ if argument is None: return u'' else: return argument # unchanged! def path(argument): """ Return the path argument unwrapped (with newlines removed). (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') else: path = ''.join([s.strip() for s in argument.splitlines()]) return path def uri(argument): """ Return the URI argument with whitespace removed. (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') else: uri = ''.join(argument.split()) return uri def nonnegative_int(argument): """ Check for a nonnegative integer argument; raise ``ValueError`` if not. (Directive option conversion function.) """ value = int(argument) if value < 0: raise ValueError('negative value; must be positive or zero') return value length_units = ['em', 'ex', 'px', 'in', 'cm', 'mm', 'pt', 'pc'] def get_measure(argument, units): """ Check for a positive argument of one of the units and return a normalized string of the form "<value><unit>" (without space in between). To be called from directive option conversion functions. """ match = re.match(r'^([0-9.]+) *(%s)$' % '|'.join(units), argument) try: assert match is not None float(match.group(1)) except (AssertionError, ValueError): raise ValueError( 'not a positive measure of one of the following units:\n%s' % ' '.join(['"%s"' % i for i in units])) return match.group(1) + match.group(2) def length_or_unitless(argument): return get_measure(argument, length_units + ['']) def length_or_percentage_or_unitless(argument): return get_measure(argument, length_units + ['%', '']) def class_option(argument): """ Convert the argument into a list of ID-compatible strings and return it. (Directive option conversion function.) Raise ``ValueError`` if no argument is found. """ if argument is None: raise ValueError('argument required but none supplied') names = argument.split() class_names = [] for name in names: class_name = nodes.make_id(name) if not class_name: raise ValueError('cannot make "%s" into a class name' % name) class_names.append(class_name) return class_names unicode_pattern = re.compile( r'(?:0x|x|\\x|U\+?|\\u)([0-9a-f]+)$|&#x([0-9a-f]+);$', re.IGNORECASE) def unicode_code(code): r""" Convert a Unicode character code to a Unicode character. (Directive option conversion function.) Codes may be decimal numbers, hexadecimal numbers (prefixed by ``0x``, ``x``, ``\x``, ``U+``, ``u``, or ``\u``; e.g. ``U+262E``), or XML-style numeric character entities (e.g. ``&#x262E;``). Other text remains as-is. Raise ValueError for illegal Unicode code values. """ try: if code.isdigit(): # decimal number return unichr(int(code)) else: match = unicode_pattern.match(code) if match: # hex number value = match.group(1) or match.group(2) return unichr(int(value, 16)) else: # other text return code except OverflowError, detail: raise ValueError('code too large (%s)' % detail) def single_char_or_unicode(argument): """ A single character is returned as-is. Unicode characters codes are converted as in `unicode_code`. (Directive option conversion function.) """ char = unicode_code(argument) if len(char) > 1: raise ValueError('%r invalid; must be a single character or ' 'a Unicode code' % char) return char def single_char_or_whitespace_or_unicode(argument): """ As with `single_char_or_unicode`, but "tab" and "space" are also supported. (Directive option conversion function.) """ if argument == 'tab': char = '\t' elif argument == 'space': char = ' ' else: char = single_char_or_unicode(argument) return char def positive_int(argument): """ Converts the argument into an integer. Raises ValueError for negative, zero, or non-integer values. (Directive option conversion function.) """ value = int(argument) if value < 1: raise ValueError('negative or zero value; must be positive') return value def positive_int_list(argument): """ Converts a space- or comma-separated list of values into a Python list of integers. (Directive option conversion function.) Raises ValueError for non-positive-integer values. """ if ',' in argument: entries = argument.split(',') else: entries = argument.split() return [positive_int(entry) for entry in entries] def encoding(argument): """ Verfies the encoding argument by lookup. (Directive option conversion function.) Raises ValueError for unknown encodings. """ try: codecs.lookup(argument) except LookupError: raise ValueError('unknown encoding: "%s"' % argument) return argument def choice(argument, values): """ Directive option utility function, supplied to enable options whose argument must be a member of a finite set of possible values (must be lower case). A custom conversion function must be written to use it. For example:: from docutils.parsers.rst import directives def yesno(argument): return directives.choice(argument, ('yes', 'no')) Raise ``ValueError`` if no argument is found or if the argument's value is not valid (not an entry in the supplied list). """ try: value = argument.lower().strip() except AttributeError: raise ValueError('must supply an argument; choose from %s' % format_values(values)) if value in values: return value else: raise ValueError('"%s" unknown; choose from %s' % (argument, format_values(values))) def format_values(values): return '%s, or "%s"' % (', '.join(['"%s"' % s for s in values[:-1]]), values[-1])
{ "repo_name": "brownman/selenium-webdriver", "path": "selenium/src/py/lib/docutils/parsers/rst/directives/__init__.py", "copies": "5", "size": "16275", "license": "apache-2.0", "hash": -7285068301638758000, "line_mean": 34.2472160356, "line_max": 79, "alpha_frac": 0.6151766513, "autogenerated": false, "ratio": 4.336530775379696, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7451707426679697, "avg_score": null, "num_lines": null }
""" This package contains Docutils parser modules. """ __docformat__ = 'reStructuredText' from docutils import Component class Parser(Component): component_type = 'parser' config_section = 'parsers' def parse(self, inputstring, document): """Override to parse `inputstring` into document tree `document`.""" raise NotImplementedError('subclass must override this method') def setup_parse(self, inputstring, document): """Initial parse setup. Call at start of `self.parse()`.""" self.inputstring = inputstring self.document = document document.reporter.attach_observer(document.note_parse_message) def finish_parse(self): """Finalize parse details. Call at end of `self.parse()`.""" self.document.reporter.detach_observer( self.document.note_parse_message) _parser_aliases = { 'restructuredtext': 'rst', 'rest': 'rst', 'restx': 'rst', 'rtxt': 'rst',} def get_parser_class(parser_name): """Return the Parser class from the `parser_name` module.""" parser_name = parser_name.lower() if _parser_aliases.has_key(parser_name): parser_name = _parser_aliases[parser_name] module = __import__(parser_name, globals(), locals()) return module.Parser
{ "repo_name": "mfazekas/safaridriver", "path": "selenium/src/py/lib/docutils/parsers/__init__.py", "copies": "5", "size": "1570", "license": "apache-2.0", "hash": 1041036096915285800, "line_mean": 30.0408163265, "line_max": 76, "alpha_frac": 0.6401273885, "autogenerated": false, "ratio": 3.9054726368159205, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7045600025315921, "avg_score": null, "num_lines": null }
""" Directives for typically HTML-specific constructs. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import states from docutils.transforms import components def meta(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): node = nodes.Element() if content: new_line_offset, blank_finish = state.nested_list_parse( content, content_offset, node, initial_state='MetaBody', blank_finish=1, state_machine_kwargs=metaSMkwargs) if (new_line_offset - content_offset) != len(content): # incomplete parse of block? error = state_machine.reporter.error( 'Invalid meta directive.', nodes.literal_block(block_text, block_text), line=lineno) node += error else: error = state_machine.reporter.error( 'Empty meta directive.', nodes.literal_block(block_text, block_text), line=lineno) node += error return node.children meta.content = 1 def imagemap(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return [] class MetaBody(states.SpecializedBody): class meta(nodes.Special, nodes.PreBibliographic, nodes.Element): """HTML-specific "meta" element.""" pass def field_marker(self, match, context, next_state): """Meta element.""" node, blank_finish = self.parsemeta(match) self.parent += node return [], next_state, [] def parsemeta(self, match): name = self.parse_field_marker(match) indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) node = self.meta() pending = nodes.pending(components.Filter, {'component': 'writer', 'format': 'html', 'nodes': [node]}) node['content'] = ' '.join(indented) if not indented: line = self.state_machine.line msg = self.reporter.info( 'No content for meta tag "%s".' % name, nodes.literal_block(line, line), line=self.state_machine.abs_line_number()) return msg, blank_finish tokens = name.split() try: attname, val = utils.extract_name_value(tokens[0])[0] node[attname.lower()] = val except utils.NameValueError: node['name'] = tokens[0] for token in tokens[1:]: try: attname, val = utils.extract_name_value(token)[0] node[attname.lower()] = val except utils.NameValueError, detail: line = self.state_machine.line msg = self.reporter.error( 'Error parsing meta tag attribute "%s": %s.' % (token, detail), nodes.literal_block(line, line), line=self.state_machine.abs_line_number()) return msg, blank_finish self.document.note_pending(pending) return pending, blank_finish metaSMkwargs = {'state_classes': (MetaBody,)}
{ "repo_name": "epall/selenium", "path": "selenium/src/py/lib/docutils/parsers/rst/directives/html.py", "copies": "5", "size": "3625", "license": "apache-2.0", "hash": 265128556201435550, "line_mean": 35.7604166667, "line_max": 73, "alpha_frac": 0.5655172414, "autogenerated": false, "ratio": 4.220023282887078, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009061281676413256, "num_lines": 96 }
""" This package contains the Python Source Reader modules. It requires Python 2.2 or higher (`moduleparser` depends on the `compiler` and `tokenize` modules). """ __docformat__ = 'reStructuredText' import sys import docutils.readers from docutils.readers.python import moduleparser from docutils import parsers from docutils import nodes from docutils.readers.python import pynodes from docutils import readers class Reader(docutils.readers.Reader): config_section = 'python reader' config_section_dependencies = ('readers',) default_parser = 'restructuredtext' def parse(self): """Parse `self.input` into a document tree.""" self.document = document = self.new_document() module_section = moduleparser.parse_module(self.input, self.source.source_path) module_section.walk(DocformatVisitor(self.document)) visitor = DocstringFormattingVisitor( document=document, default_parser=self.default_parser) module_section.walk(visitor) self.document.append(module_section) class DocformatVisitor(nodes.SparseNodeVisitor): """ This sets docformat attributes in a module. Wherever an assignment to __docformat__ is found, we look for the enclosing scope -- a class, a module, or a function -- and set the docformat attribute there. We can't do this during the DocstringFormattingVisitor walking, because __docformat__ may appear below a docstring in that format (typically below the module docstring). """ def visit_attribute(self, node): assert isinstance(node[0], pynodes.object_name) name = node[0][0].data if name != '__docformat__': return value = None for child in children: if isinstance(child, pynodes.expression_value): value = child[0].data break assert value.startswith("'") or value.startswith('"'), "__docformat__ must be assigned a string literal (not %s); line: %s" % (value, node['lineno']) name = name[1:-1] looking_in = node.parent while not isinstance(looking_in, (pynodes.module_section, pynodes.function_section, pynodes.class_section)): looking_in = looking_in.parent looking_in['docformat'] = name class DocstringFormattingVisitor(nodes.SparseNodeVisitor): def __init__(self, document, default_parser): self.document = document self.default_parser = default_parser self.parsers = {} def visit_docstring(self, node): text = node[0].data docformat = self.find_docformat(node) del node[0] node['docformat'] = docformat parser = self.get_parser(docformat) parser.parse(text, self.document) for child in self.document.children: node.append(child) self.document.current_source = self.document.current_line = None del self.document[:] def get_parser(self, parser_name): """ Get a parser based on its name. We reuse parsers during this visitation, so parser instances are cached. """ parser_name = parsers._parser_aliases.get(parser_name, parser_name) if not self.parsers.has_key(parser_name): cls = parsers.get_parser_class(parser_name) self.parsers[parser_name] = cls() return self.parsers[parser_name] def find_docformat(self, node): """ Find the __docformat__ closest to this node (i.e., look in the class or module) """ while node: if node.get('docformat'): return node['docformat'] node = node.parent return self.default_parser if __name__ == '__main__': try: import locale locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates pseudo-XML from Python modules ' '(for testing purposes). ' + default_description) publish_cmdline(description=description, reader=Reader())
{ "repo_name": "mogotest/selenium", "path": "selenium/src/py/lib/docutils/readers/python/__init__.py", "copies": "5", "size": "4635", "license": "apache-2.0", "hash": -90454939465709740, "line_mean": 33.1136363636, "line_max": 157, "alpha_frac": 0.6069039914, "autogenerated": false, "ratio": 4.405893536121673, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0009683350623972156, "num_lines": 132 }
""" Admonition directives. """ __docformat__ = 'reStructuredText' from docutils.parsers.rst import states, directives from docutils import nodes def make_admonition(node_class, name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): if not content: error = state_machine.reporter.error( 'The "%s" admonition is empty; content required.' % (name), nodes.literal_block(block_text, block_text), line=lineno) return [error] text = '\n'.join(content) admonition_node = node_class(text) if arguments: title_text = arguments[0] textnodes, messages = state.inline_text(title_text, lineno) admonition_node += nodes.title(title_text, '', *textnodes) admonition_node += messages if options.has_key('class'): classes = options['class'] else: classes = ['admonition-' + nodes.make_id(title_text)] admonition_node['classes'] += classes state.nested_parse(content, content_offset, admonition_node) return [admonition_node] def admonition(*args): return make_admonition(nodes.admonition, *args) admonition.arguments = (1, 0, 1) admonition.options = {'class': directives.class_option} admonition.content = 1 def attention(*args): return make_admonition(nodes.attention, *args) attention.content = 1 def caution(*args): return make_admonition(nodes.caution, *args) caution.content = 1 def danger(*args): return make_admonition(nodes.danger, *args) danger.content = 1 def error(*args): return make_admonition(nodes.error, *args) error.content = 1 def hint(*args): return make_admonition(nodes.hint, *args) hint.content = 1 def important(*args): return make_admonition(nodes.important, *args) important.content = 1 def note(*args): return make_admonition(nodes.note, *args) note.content = 1 def tip(*args): return make_admonition(nodes.tip, *args) tip.content = 1 def warning(*args): return make_admonition(nodes.warning, *args) warning.content = 1
{ "repo_name": "epall/selenium", "path": "selenium/src/py/lib/docutils/parsers/rst/directives/admonitions.py", "copies": "5", "size": "2410", "license": "apache-2.0", "hash": 7710547089451044000, "line_mean": 24.7777777778, "line_max": 74, "alpha_frac": 0.6493775934, "autogenerated": false, "ratio": 3.5233918128654973, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6672769406265497, "avg_score": null, "num_lines": null }
""" Python Enhancement Proposal (PEP) Reader. """ __docformat__ = 'reStructuredText' from docutils.readers import standalone from docutils.transforms import peps, references, misc, frontmatter from docutils.parsers import rst class Reader(standalone.Reader): supported = ('pep',) """Contexts this reader supports.""" settings_spec = ( 'PEP Reader Option Defaults', 'The --pep-references and --rfc-references options (for the ' 'reStructuredText parser) are on by default.', ()) config_section = 'pep reader' config_section_dependencies = ('readers', 'standalone reader') def get_transforms(self): transforms = standalone.Reader.get_transforms(self) # We have PEP-specific frontmatter handling. transforms.remove(frontmatter.DocTitle) transforms.remove(frontmatter.SectionSubTitle) transforms.remove(frontmatter.DocInfo) transforms.extend([peps.Headers, peps.Contents, peps.TargetNotes]) return transforms settings_default_overrides = {'pep_references': 1, 'rfc_references': 1} inliner_class = rst.states.Inliner def __init__(self, parser=None, parser_name=None): """`parser` should be ``None``.""" if parser is None: parser = rst.Parser(rfc2822=1, inliner=self.inliner_class()) standalone.Reader.__init__(self, parser, '')
{ "repo_name": "mogotest/selenium", "path": "selenium/src/py/lib/docutils/readers/pep.py", "copies": "5", "size": "1666", "license": "apache-2.0", "hash": -8956217481703280000, "line_mean": 31.32, "line_max": 75, "alpha_frac": 0.6548619448, "autogenerated": false, "ratio": 3.9292452830188678, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7084107227818868, "avg_score": null, "num_lines": null }
""" Standalone file Reader for the reStructuredText markup syntax. """ __docformat__ = 'reStructuredText' import sys from docutils import frontend, readers from docutils.transforms import frontmatter, references, misc class Reader(readers.Reader): supported = ('standalone',) """Contexts this reader supports.""" document = None """A single document tree.""" settings_spec = ( 'Standalone Reader', None, (('Disable the promotion of a lone top-level section title to ' 'document title (and subsequent section title to document ' 'subtitle promotion; enabled by default).', ['--no-doc-title'], {'dest': 'doctitle_xform', 'action': 'store_false', 'default': 1, 'validator': frontend.validate_boolean}), ('Disable the bibliographic field list transform (enabled by ' 'default).', ['--no-doc-info'], {'dest': 'docinfo_xform', 'action': 'store_false', 'default': 1, 'validator': frontend.validate_boolean}), ('Activate the promotion of lone subsection titles to ' 'section subtitles (disabled by default).', ['--section-subtitles'], {'dest': 'sectsubtitle_xform', 'action': 'store_true', 'default': 0, 'validator': frontend.validate_boolean}), ('Deactivate the promotion of lone subsection titles.', ['--no-section-subtitles'], {'dest': 'sectsubtitle_xform', 'action': 'store_false', 'validator': frontend.validate_boolean}), )) config_section = 'standalone reader' config_section_dependencies = ('readers',) def get_transforms(self): return readers.Reader.get_transforms(self) + [ references.Substitutions, references.PropagateTargets, frontmatter.DocTitle, frontmatter.SectionSubTitle, frontmatter.DocInfo, references.AnonymousHyperlinks, references.IndirectHyperlinks, references.Footnotes, references.ExternalTargets, references.InternalTargets, references.DanglingReferences, misc.Transitions, ]
{ "repo_name": "mogotest/selenium", "path": "selenium/src/py/lib/docutils/readers/standalone.py", "copies": "5", "size": "2515", "license": "apache-2.0", "hash": -5458604138221138000, "line_mean": 34.4492753623, "line_max": 78, "alpha_frac": 0.6011928429, "autogenerated": false, "ratio": 4.451327433628318, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7552520276528318, "avg_score": null, "num_lines": null }
""" Docutils component-related transforms. """ __docformat__ = 'reStructuredText' import sys import os import re import time from docutils import nodes, utils from docutils import ApplicationError, DataError from docutils.transforms import Transform, TransformError class Filter(Transform): """ Include or exclude elements which depend on a specific Docutils component. For use with `nodes.pending` elements. A "pending" element's dictionary attribute ``details`` must contain the keys "component" and "format". The value of ``details['component']`` must match the type name of the component the elements depend on (e.g. "writer"). The value of ``details['format']`` is the name of a specific format or context of that component (e.g. "html"). If the matching Docutils component supports that format or context, the "pending" element is replaced by the contents of ``details['nodes']`` (a list of nodes); otherwise, the "pending" element is removed. For example, the reStructuredText "meta" directive creates a "pending" element containing a "meta" element (in ``pending.details['nodes']``). Only writers (``pending.details['component'] == 'writer'``) supporting the "html" format (``pending.details['format'] == 'html'``) will include the "meta" element; it will be deleted from the output of all other writers. """ default_priority = 780 def apply(self): pending = self.startnode component_type = pending.details['component'] # 'reader' or 'writer' format = pending.details['format'] component = self.document.transformer.components[component_type] if component.supports(format): pending.replace_self(pending.details['nodes']) else: pending.parent.remove(pending)
{ "repo_name": "epall/selenium", "path": "selenium/src/py/lib/docutils/transforms/components.py", "copies": "5", "size": "2102", "license": "apache-2.0", "hash": -271973202732318460, "line_mean": 36.9259259259, "line_max": 78, "alpha_frac": 0.6784015224, "autogenerated": false, "ratio": 4.145956607495069, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00023741690408357073, "num_lines": 54 }
""" Miscellaneous transforms. """ __docformat__ = 'reStructuredText' from docutils import nodes from docutils.transforms import Transform, TransformError class CallBack(Transform): """ Inserts a callback into a document. The callback is called when the transform is applied, which is determined by its priority. For use with `nodes.pending` elements. Requires a ``details['callback']`` entry, a bound method or function which takes one parameter: the pending node. Other data can be stored in the ``details`` attribute or in the object hosting the callback method. """ default_priority = 990 def apply(self): pending = self.startnode pending.details['callback'](pending) pending.parent.remove(pending) class ClassAttribute(Transform): """ Move the "class" attribute specified in the "pending" node into the immediately following non-comment element. """ default_priority = 210 def apply(self): pending = self.startnode parent = pending.parent child = pending while parent: # Check for appropriate following siblings: for index in range(parent.index(child) + 1, len(parent)): element = parent[index] if (isinstance(element, nodes.Invisible) or isinstance(element, nodes.system_message)): continue element['classes'] += pending.details['class'] pending.parent.remove(pending) return else: # At end of section or container; apply to sibling child = parent parent = parent.parent error = self.document.reporter.error( 'No suitable element following "%s" directive' % pending.details['directive'], nodes.literal_block(pending.rawsource, pending.rawsource), line=pending.line) pending.replace_self(error) class Transitions(Transform): """ Move transitions at the end of sections up the tree. Complain on transitions after a title, at the beginning or end of the document, and after another transition. For example, transform this:: <section> ... <transition> <section> ... into this:: <section> ... <transition> <section> ... """ default_priority = 830 def apply(self): for node in self.document.traverse(nodes.transition): self.visit_transition(node) def visit_transition(self, node): index = node.parent.index(node) error = None if (index == 0 or isinstance(node.parent[0], nodes.title) and (index == 1 or isinstance(node.parent[1], nodes.subtitle) and index == 2)): assert (isinstance(node.parent, nodes.document) or isinstance(node.parent, nodes.section)) error = self.document.reporter.error( 'Document or section may not begin with a transition.', line=node.line) elif isinstance(node.parent[index - 1], nodes.transition): error = self.document.reporter.error( 'At least one body element must separate transitions; ' 'adjacent transitions are not allowed.', line=node.line) if error: # Insert before node and update index. node.parent.insert(index, error) index += 1 assert index < len(node.parent) if index != len(node.parent) - 1: # No need to move the node. return # Node behind which the transition is to be moved. sibling = node # While sibling is the last node of its parent. while index == len(sibling.parent) - 1: sibling = sibling.parent # If sibling is the whole document (i.e. it has no parent). if sibling.parent is None: # Transition at the end of document. Do not move the # transition up, and place an error behind. error = self.document.reporter.error( 'Document may not end with a transition.', line=node.line) node.parent.insert(node.parent.index(node) + 1, error) return index = sibling.parent.index(sibling) # Remove the original transition node. node.parent.remove(node) # Insert the transition after the sibling. sibling.parent.insert(index + 1, node)
{ "repo_name": "mogotest/selenium", "path": "selenium/src/py/lib/docutils/transforms/misc.py", "copies": "5", "size": "5034", "license": "apache-2.0", "hash": -3677136511702662700, "line_mean": 32.7172413793, "line_max": 78, "alpha_frac": 0.5723083035, "autogenerated": false, "ratio": 4.740112994350283, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00010610079575596818, "num_lines": 145 }
""" A finite state machine specialized for regular-expression-based text filters, this module defines the following classes: - `StateMachine`, a state machine - `State`, a state superclass - `StateMachineWS`, a whitespace-sensitive version of `StateMachine` - `StateWS`, a state superclass for use with `StateMachineWS` - `SearchStateMachine`, uses `re.search()` instead of `re.match()` - `SearchStateMachineWS`, uses `re.search()` instead of `re.match()` - `ViewList`, extends standard Python lists. - `StringList`, string-specific ViewList. Exception classes: - `StateMachineError` - `UnknownStateError` - `DuplicateStateError` - `UnknownTransitionError` - `DuplicateTransitionError` - `TransitionPatternNotFound` - `TransitionMethodNotFound` - `UnexpectedIndentationError` - `TransitionCorrection`: Raised to switch to another transition. - `StateCorrection`: Raised to switch to another state & transition. Functions: - `string2lines()`: split a multi-line string into a list of one-line strings How To Use This Module ====================== (See the individual classes, methods, and attributes for details.) 1. Import it: ``import statemachine`` or ``from statemachine import ...``. You will also need to ``import re``. 2. Derive a subclass of `State` (or `StateWS`) for each state in your state machine:: class MyState(statemachine.State): Within the state's class definition: a) Include a pattern for each transition, in `State.patterns`:: patterns = {'atransition': r'pattern', ...} b) Include a list of initial transitions to be set up automatically, in `State.initial_transitions`:: initial_transitions = ['atransition', ...] c) Define a method for each transition, with the same name as the transition pattern:: def atransition(self, match, context, next_state): # do something result = [...] # a list return context, next_state, result # context, next_state may be altered Transition methods may raise an `EOFError` to cut processing short. d) You may wish to override the `State.bof()` and/or `State.eof()` implicit transition methods, which handle the beginning- and end-of-file. e) In order to handle nested processing, you may wish to override the attributes `State.nested_sm` and/or `State.nested_sm_kwargs`. If you are using `StateWS` as a base class, in order to handle nested indented blocks, you may wish to: - override the attributes `StateWS.indent_sm`, `StateWS.indent_sm_kwargs`, `StateWS.known_indent_sm`, and/or `StateWS.known_indent_sm_kwargs`; - override the `StateWS.blank()` method; and/or - override or extend the `StateWS.indent()`, `StateWS.known_indent()`, and/or `StateWS.firstknown_indent()` methods. 3. Create a state machine object:: sm = StateMachine(state_classes=[MyState, ...], initial_state='MyState') 4. Obtain the input text, which needs to be converted into a tab-free list of one-line strings. For example, to read text from a file called 'inputfile':: input_string = open('inputfile').read() input_lines = statemachine.string2lines(input_string) 5. Run the state machine on the input text and collect the results, a list:: results = sm.run(input_lines) 6. Remove any lingering circular references:: sm.unlink() """ __docformat__ = 'restructuredtext' import sys import re import types import unicodedata class StateMachine: """ A finite state machine for text filters using regular expressions. The input is provided in the form of a list of one-line strings (no newlines). States are subclasses of the `State` class. Transitions consist of regular expression patterns and transition methods, and are defined in each state. The state machine is started with the `run()` method, which returns the results of processing in a list. """ def __init__(self, state_classes, initial_state, debug=0): """ Initialize a `StateMachine` object; add state objects. Parameters: - `state_classes`: a list of `State` (sub)classes. - `initial_state`: a string, the class name of the initial state. - `debug`: a boolean; produce verbose output if true (nonzero). """ self.input_lines = None """`StringList` of input lines (without newlines). Filled by `self.run()`.""" self.input_offset = 0 """Offset of `self.input_lines` from the beginning of the file.""" self.line = None """Current input line.""" self.line_offset = -1 """Current input line offset from beginning of `self.input_lines`.""" self.debug = debug """Debugging mode on/off.""" self.initial_state = initial_state """The name of the initial state (key to `self.states`).""" self.current_state = initial_state """The name of the current state (key to `self.states`).""" self.states = {} """Mapping of {state_name: State_object}.""" self.add_states(state_classes) self.observers = [] """List of bound methods or functions to call whenever the current line changes. Observers are called with one argument, ``self``. Cleared at the end of `run()`.""" def unlink(self): """Remove circular references to objects no longer required.""" for state in self.states.values(): state.unlink() self.states = None def run(self, input_lines, input_offset=0, context=None, input_source=None): """ Run the state machine on `input_lines`. Return results (a list). Reset `self.line_offset` and `self.current_state`. Run the beginning-of-file transition. Input one line at a time and check for a matching transition. If a match is found, call the transition method and possibly change the state. Store the context returned by the transition method to be passed on to the next transition matched. Accumulate the results returned by the transition methods in a list. Run the end-of-file transition. Finally, return the accumulated results. Parameters: - `input_lines`: a list of strings without newlines, or `StringList`. - `input_offset`: the line offset of `input_lines` from the beginning of the file. - `context`: application-specific storage. - `input_source`: name or path of source of `input_lines`. """ self.runtime_init() if isinstance(input_lines, StringList): self.input_lines = input_lines else: self.input_lines = StringList(input_lines, source=input_source) self.input_offset = input_offset self.line_offset = -1 self.current_state = self.initial_state if self.debug: print >>sys.stderr, ( '\nStateMachine.run: input_lines (line_offset=%s):\n| %s' % (self.line_offset, '\n| '.join(self.input_lines))) transitions = None results = [] state = self.get_state() try: if self.debug: print >>sys.stderr, ('\nStateMachine.run: bof transition') context, result = state.bof(context) results.extend(result) while 1: try: try: self.next_line() if self.debug: source, offset = self.input_lines.info( self.line_offset) print >>sys.stderr, ( '\nStateMachine.run: line (source=%r, ' 'offset=%r):\n| %s' % (source, offset, self.line)) context, next_state, result = self.check_line( context, state, transitions) except EOFError: if self.debug: print >>sys.stderr, ( '\nStateMachine.run: %s.eof transition' % state.__class__.__name__) result = state.eof(context) results.extend(result) break else: results.extend(result) except TransitionCorrection, exception: self.previous_line() # back up for another try transitions = (exception.args[0],) if self.debug: print >>sys.stderr, ( '\nStateMachine.run: TransitionCorrection to ' 'state "%s", transition %s.' % (state.__class__.__name__, transitions[0])) continue except StateCorrection, exception: self.previous_line() # back up for another try next_state = exception.args[0] if len(exception.args) == 1: transitions = None else: transitions = (exception.args[1],) if self.debug: print >>sys.stderr, ( '\nStateMachine.run: StateCorrection to state ' '"%s", transition %s.' % (next_state, transitions[0])) else: transitions = None state = self.get_state(next_state) except: if self.debug: self.error() raise self.observers = [] return results def get_state(self, next_state=None): """ Return current state object; set it first if `next_state` given. Parameter `next_state`: a string, the name of the next state. Exception: `UnknownStateError` raised if `next_state` unknown. """ if next_state: if self.debug and next_state != self.current_state: print >>sys.stderr, \ ('\nStateMachine.get_state: Changing state from ' '"%s" to "%s" (input line %s).' % (self.current_state, next_state, self.abs_line_number())) self.current_state = next_state try: return self.states[self.current_state] except KeyError: raise UnknownStateError(self.current_state) def next_line(self, n=1): """Load `self.line` with the `n`'th next line and return it.""" try: try: self.line_offset += n self.line = self.input_lines[self.line_offset] except IndexError: self.line = None raise EOFError return self.line finally: self.notify_observers() def is_next_line_blank(self): """Return 1 if the next line is blank or non-existant.""" try: return not self.input_lines[self.line_offset + 1].strip() except IndexError: return 1 def at_eof(self): """Return 1 if the input is at or past end-of-file.""" return self.line_offset >= len(self.input_lines) - 1 def at_bof(self): """Return 1 if the input is at or before beginning-of-file.""" return self.line_offset <= 0 def previous_line(self, n=1): """Load `self.line` with the `n`'th previous line and return it.""" self.line_offset -= n if self.line_offset < 0: self.line = None else: self.line = self.input_lines[self.line_offset] self.notify_observers() return self.line def goto_line(self, line_offset): """Jump to absolute line offset `line_offset`, load and return it.""" try: try: self.line_offset = line_offset - self.input_offset self.line = self.input_lines[self.line_offset] except IndexError: self.line = None raise EOFError return self.line finally: self.notify_observers() def get_source(self, line_offset): """Return source of line at absolute line offset `line_offset`.""" return self.input_lines.source(line_offset - self.input_offset) def abs_line_offset(self): """Return line offset of current line, from beginning of file.""" return self.line_offset + self.input_offset def abs_line_number(self): """Return line number of current line (counting from 1).""" return self.line_offset + self.input_offset + 1 def insert_input(self, input_lines, source): self.input_lines.insert(self.line_offset + 1, '', source='internal padding') self.input_lines.insert(self.line_offset + 1, '', source='internal padding') self.input_lines.insert(self.line_offset + 2, StringList(input_lines, source)) def get_text_block(self, flush_left=0): """ Return a contiguous block of text. If `flush_left` is true, raise `UnexpectedIndentationError` if an indented line is encountered before the text block ends (with a blank line). """ try: block = self.input_lines.get_text_block(self.line_offset, flush_left) self.next_line(len(block) - 1) return block except UnexpectedIndentationError, error: block, source, lineno = error self.next_line(len(block) - 1) # advance to last line of block raise def check_line(self, context, state, transitions=None): """ Examine one line of input for a transition match & execute its method. Parameters: - `context`: application-dependent storage. - `state`: a `State` object, the current state. - `transitions`: an optional ordered list of transition names to try, instead of ``state.transition_order``. Return the values returned by the transition method: - context: possibly modified from the parameter `context`; - next state name (`State` subclass name); - the result output of the transition, a list. When there is no match, ``state.no_match()`` is called and its return value is returned. """ if transitions is None: transitions = state.transition_order state_correction = None if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: state="%s", transitions=%r.' % (state.__class__.__name__, transitions)) for name in transitions: pattern, method, next_state = state.transitions[name] match = self.match(pattern) if match: if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: Matched transition ' '"%s" in state "%s".' % (name, state.__class__.__name__)) return method(match, context, next_state) else: if self.debug: print >>sys.stderr, ( '\nStateMachine.check_line: No match in state "%s".' % state.__class__.__name__) return state.no_match(context, transitions) def match(self, pattern): """ Return the result of a regular expression match. Parameter `pattern`: an `re` compiled regular expression. """ return pattern.match(self.line) def add_state(self, state_class): """ Initialize & add a `state_class` (`State` subclass) object. Exception: `DuplicateStateError` raised if `state_class` was already added. """ statename = state_class.__name__ if self.states.has_key(statename): raise DuplicateStateError(statename) self.states[statename] = state_class(self, self.debug) def add_states(self, state_classes): """ Add `state_classes` (a list of `State` subclasses). """ for state_class in state_classes: self.add_state(state_class) def runtime_init(self): """ Initialize `self.states`. """ for state in self.states.values(): state.runtime_init() def error(self): """Report error details.""" type, value, module, line, function = _exception_data() print >>sys.stderr, '%s: %s' % (type, value) print >>sys.stderr, 'input line %s' % (self.abs_line_number()) print >>sys.stderr, ('module %s, line %s, function %s' % (module, line, function)) def attach_observer(self, observer): """ The `observer` parameter is a function or bound method which takes two arguments, the source and offset of the current line. """ self.observers.append(observer) def detach_observer(self, observer): self.observers.remove(observer) def notify_observers(self): for observer in self.observers: try: info = self.input_lines.info(self.line_offset) except IndexError: info = (None, None) observer(*info) class State: """ State superclass. Contains a list of transitions, and transition methods. Transition methods all have the same signature. They take 3 parameters: - An `re` match object. ``match.string`` contains the matched input line, ``match.start()`` gives the start index of the match, and ``match.end()`` gives the end index. - A context object, whose meaning is application-defined (initial value ``None``). It can be used to store any information required by the state machine, and the retured context is passed on to the next transition method unchanged. - The name of the next state, a string, taken from the transitions list; normally it is returned unchanged, but it may be altered by the transition method if necessary. Transition methods all return a 3-tuple: - A context object, as (potentially) modified by the transition method. - The next state name (a return value of ``None`` means no state change). - The processing result, a list, which is accumulated by the state machine. Transition methods may raise an `EOFError` to cut processing short. There are two implicit transitions, and corresponding transition methods are defined: `bof()` handles the beginning-of-file, and `eof()` handles the end-of-file. These methods have non-standard signatures and return values. `bof()` returns the initial context and results, and may be used to return a header string, or do any other processing needed. `eof()` should handle any remaining context and wrap things up; it returns the final processing result. Typical applications need only subclass `State` (or a subclass), set the `patterns` and `initial_transitions` class attributes, and provide corresponding transition methods. The default object initialization will take care of constructing the list of transitions. """ patterns = None """ {Name: pattern} mapping, used by `make_transition()`. Each pattern may be a string or a compiled `re` pattern. Override in subclasses. """ initial_transitions = None """ A list of transitions to initialize when a `State` is instantiated. Each entry is either a transition name string, or a (transition name, next state name) pair. See `make_transitions()`. Override in subclasses. """ nested_sm = None """ The `StateMachine` class for handling nested processing. If left as ``None``, `nested_sm` defaults to the class of the state's controlling state machine. Override it in subclasses to avoid the default. """ nested_sm_kwargs = None """ Keyword arguments dictionary, passed to the `nested_sm` constructor. Two keys must have entries in the dictionary: - Key 'state_classes' must be set to a list of `State` classes. - Key 'initial_state' must be set to the name of the initial state class. If `nested_sm_kwargs` is left as ``None``, 'state_classes' defaults to the class of the current state, and 'initial_state' defaults to the name of the class of the current state. Override in subclasses to avoid the defaults. """ def __init__(self, state_machine, debug=0): """ Initialize a `State` object; make & add initial transitions. Parameters: - `statemachine`: the controlling `StateMachine` object. - `debug`: a boolean; produce verbose output if true (nonzero). """ self.transition_order = [] """A list of transition names in search order.""" self.transitions = {} """ A mapping of transition names to 3-tuples containing (compiled_pattern, transition_method, next_state_name). Initialized as an instance attribute dynamically (instead of as a class attribute) because it may make forward references to patterns and methods in this or other classes. """ self.add_initial_transitions() self.state_machine = state_machine """A reference to the controlling `StateMachine` object.""" self.debug = debug """Debugging mode on/off.""" if self.nested_sm is None: self.nested_sm = self.state_machine.__class__ if self.nested_sm_kwargs is None: self.nested_sm_kwargs = {'state_classes': [self.__class__], 'initial_state': self.__class__.__name__} def runtime_init(self): """ Initialize this `State` before running the state machine; called from `self.state_machine.run()`. """ pass def unlink(self): """Remove circular references to objects no longer required.""" self.state_machine = None def add_initial_transitions(self): """Make and add transitions listed in `self.initial_transitions`.""" if self.initial_transitions: names, transitions = self.make_transitions( self.initial_transitions) self.add_transitions(names, transitions) def add_transitions(self, names, transitions): """ Add a list of transitions to the start of the transition list. Parameters: - `names`: a list of transition names. - `transitions`: a mapping of names to transition tuples. Exceptions: `DuplicateTransitionError`, `UnknownTransitionError`. """ for name in names: if self.transitions.has_key(name): raise DuplicateTransitionError(name) if not transitions.has_key(name): raise UnknownTransitionError(name) self.transition_order[:0] = names self.transitions.update(transitions) def add_transition(self, name, transition): """ Add a transition to the start of the transition list. Parameter `transition`: a ready-made transition 3-tuple. Exception: `DuplicateTransitionError`. """ if self.transitions.has_key(name): raise DuplicateTransitionError(name) self.transition_order[:0] = [name] self.transitions[name] = transition def remove_transition(self, name): """ Remove a transition by `name`. Exception: `UnknownTransitionError`. """ try: del self.transitions[name] self.transition_order.remove(name) except: raise UnknownTransitionError(name) def make_transition(self, name, next_state=None): """ Make & return a transition tuple based on `name`. This is a convenience function to simplify transition creation. Parameters: - `name`: a string, the name of the transition pattern & method. This `State` object must have a method called '`name`', and a dictionary `self.patterns` containing a key '`name`'. - `next_state`: a string, the name of the next `State` object for this transition. A value of ``None`` (or absent) implies no state change (i.e., continue with the same state). Exceptions: `TransitionPatternNotFound`, `TransitionMethodNotFound`. """ if next_state is None: next_state = self.__class__.__name__ try: pattern = self.patterns[name] if not hasattr(pattern, 'match'): pattern = re.compile(pattern) except KeyError: raise TransitionPatternNotFound( '%s.patterns[%r]' % (self.__class__.__name__, name)) try: method = getattr(self, name) except AttributeError: raise TransitionMethodNotFound( '%s.%s' % (self.__class__.__name__, name)) return (pattern, method, next_state) def make_transitions(self, name_list): """ Return a list of transition names and a transition mapping. Parameter `name_list`: a list, where each entry is either a transition name string, or a 1- or 2-tuple (transition name, optional next state name). """ stringtype = type('') names = [] transitions = {} for namestate in name_list: if type(namestate) is stringtype: transitions[namestate] = self.make_transition(namestate) names.append(namestate) else: transitions[namestate[0]] = self.make_transition(*namestate) names.append(namestate[0]) return names, transitions def no_match(self, context, transitions): """ Called when there is no match from `StateMachine.check_line()`. Return the same values returned by transition methods: - context: unchanged; - next state name: ``None``; - empty result list. Override in subclasses to catch this event. """ return context, None, [] def bof(self, context): """ Handle beginning-of-file. Return unchanged `context`, empty result. Override in subclasses. Parameter `context`: application-defined storage. """ return context, [] def eof(self, context): """ Handle end-of-file. Return empty result. Override in subclasses. Parameter `context`: application-defined storage. """ return [] def nop(self, match, context, next_state): """ A "do nothing" transition method. Return unchanged `context` & `next_state`, empty result. Useful for simple state changes (actionless transitions). """ return context, next_state, [] class StateMachineWS(StateMachine): """ `StateMachine` subclass specialized for whitespace recognition. There are three methods provided for extracting indented text blocks: - `get_indented()`: use when the indent is unknown. - `get_known_indented()`: use when the indent is known for all lines. - `get_first_known_indented()`: use when only the first line's indent is known. """ def get_indented(self, until_blank=0, strip_indent=1): """ Return a block of indented lines of text, and info. Extract an indented block where the indent is unknown for all lines. :Parameters: - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip common leading indent if true (1, default). :Return: - the indented block (a list of lines of text), - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent) if indented: self.next_line(len(indented) - 1) # advance to last indented line while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, indent, offset, blank_finish def get_known_indented(self, indent, until_blank=0, strip_indent=1): """ Return an indented block and info. Extract an indented block where the indent is known for all lines. Starting with the current line, extract the entire text block with at least `indent` indentation (which must be whitespace, except for the first line). :Parameters: - `indent`: The number of indent columns/characters. - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip `indent` characters of indentation if true (1, default). :Return: - the indented block, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent, block_indent=indent) self.next_line(len(indented) - 1) # advance to last indented line while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, offset, blank_finish def get_first_known_indented(self, indent, until_blank=0, strip_indent=1, strip_top=1): """ Return an indented block and info. Extract an indented block where the indent is known for the first line and unknown for all other lines. :Parameters: - `indent`: The first line's indent (# of columns/characters). - `until_blank`: Stop collecting at the first blank line if true (1). - `strip_indent`: Strip `indent` characters of indentation if true (1, default). - `strip_top`: Strip blank lines from the beginning of the block. :Return: - the indented block, - its indent, - its first line offset from BOF, and - whether or not it finished with a blank line. """ offset = self.abs_line_offset() indented, indent, blank_finish = self.input_lines.get_indented( self.line_offset, until_blank, strip_indent, first_indent=indent) self.next_line(len(indented) - 1) # advance to last indented line if strip_top: while indented and not indented[0].strip(): indented.trim_start() offset += 1 return indented, indent, offset, blank_finish class StateWS(State): """ State superclass specialized for whitespace (blank lines & indents). Use this class with `StateMachineWS`. The transitions 'blank' (for blank lines) and 'indent' (for indented text blocks) are added automatically, before any other transitions. The transition method `blank()` handles blank lines and `indent()` handles nested indented blocks. Indented blocks trigger a new state machine to be created by `indent()` and run. The class of the state machine to be created is in `indent_sm`, and the constructor keyword arguments are in the dictionary `indent_sm_kwargs`. The methods `known_indent()` and `firstknown_indent()` are provided for indented blocks where the indent (all lines' and first line's only, respectively) is known to the transition method, along with the attributes `known_indent_sm` and `known_indent_sm_kwargs`. Neither transition method is triggered automatically. """ indent_sm = None """ The `StateMachine` class handling indented text blocks. If left as ``None``, `indent_sm` defaults to the value of `State.nested_sm`. Override it in subclasses to avoid the default. """ indent_sm_kwargs = None """ Keyword arguments dictionary, passed to the `indent_sm` constructor. If left as ``None``, `indent_sm_kwargs` defaults to the value of `State.nested_sm_kwargs`. Override it in subclasses to avoid the default. """ known_indent_sm = None """ The `StateMachine` class handling known-indented text blocks. If left as ``None``, `known_indent_sm` defaults to the value of `indent_sm`. Override it in subclasses to avoid the default. """ known_indent_sm_kwargs = None """ Keyword arguments dictionary, passed to the `known_indent_sm` constructor. If left as ``None``, `known_indent_sm_kwargs` defaults to the value of `indent_sm_kwargs`. Override it in subclasses to avoid the default. """ ws_patterns = {'blank': ' *$', 'indent': ' +'} """Patterns for default whitespace transitions. May be overridden in subclasses.""" ws_initial_transitions = ('blank', 'indent') """Default initial whitespace transitions, added before those listed in `State.initial_transitions`. May be overridden in subclasses.""" def __init__(self, state_machine, debug=0): """ Initialize a `StateSM` object; extends `State.__init__()`. Check for indent state machine attributes, set defaults if not set. """ State.__init__(self, state_machine, debug) if self.indent_sm is None: self.indent_sm = self.nested_sm if self.indent_sm_kwargs is None: self.indent_sm_kwargs = self.nested_sm_kwargs if self.known_indent_sm is None: self.known_indent_sm = self.indent_sm if self.known_indent_sm_kwargs is None: self.known_indent_sm_kwargs = self.indent_sm_kwargs def add_initial_transitions(self): """ Add whitespace-specific transitions before those defined in subclass. Extends `State.add_initial_transitions()`. """ State.add_initial_transitions(self) if self.patterns is None: self.patterns = {} self.patterns.update(self.ws_patterns) names, transitions = self.make_transitions( self.ws_initial_transitions) self.add_transitions(names, transitions) def blank(self, match, context, next_state): """Handle blank lines. Does nothing. Override in subclasses.""" return self.nop(match, context, next_state) def indent(self, match, context, next_state): """ Handle an indented text block. Extend or override in subclasses. Recursively run the registered state machine for indented blocks (`self.indent_sm`). """ indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() sm = self.indent_sm(debug=self.debug, **self.indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results def known_indent(self, match, context, next_state): """ Handle a known-indent text block. Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. """ indented, line_offset, blank_finish = \ self.state_machine.get_known_indented(match.end()) sm = self.known_indent_sm(debug=self.debug, **self.known_indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results def first_known_indent(self, match, context, next_state): """ Handle an indented text block (first line's indent known). Extend or override in subclasses. Recursively run the registered state machine for known-indent indented blocks (`self.known_indent_sm`). The indent is the length of the match, ``match.end()``. """ indented, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) sm = self.known_indent_sm(debug=self.debug, **self.known_indent_sm_kwargs) results = sm.run(indented, input_offset=line_offset) return context, next_state, results class _SearchOverride: """ Mix-in class to override `StateMachine` regular expression behavior. Changes regular expression matching, from the default `re.match()` (succeeds only if the pattern matches at the start of `self.line`) to `re.search()` (succeeds if the pattern matches anywhere in `self.line`). When subclassing a `StateMachine`, list this class **first** in the inheritance list of the class definition. """ def match(self, pattern): """ Return the result of a regular expression search. Overrides `StateMachine.match()`. Parameter `pattern`: `re` compiled regular expression. """ return pattern.search(self.line) class SearchStateMachine(_SearchOverride, StateMachine): """`StateMachine` which uses `re.search()` instead of `re.match()`.""" pass class SearchStateMachineWS(_SearchOverride, StateMachineWS): """`StateMachineWS` which uses `re.search()` instead of `re.match()`.""" pass class ViewList: """ List with extended functionality: slices of ViewList objects are child lists, linked to their parents. Changes made to a child list also affect the parent list. A child list is effectively a "view" (in the SQL sense) of the parent list. Changes to parent lists, however, do *not* affect active child lists. If a parent list is changed, any active child lists should be recreated. The start and end of the slice can be trimmed using the `trim_start()` and `trim_end()` methods, without affecting the parent list. The link between child and parent lists can be broken by calling `disconnect()` on the child list. Also, ViewList objects keep track of the source & offset of each item. This information is accessible via the `source()`, `offset()`, and `info()` methods. """ def __init__(self, initlist=None, source=None, items=None, parent=None, parent_offset=None): self.data = [] """The actual list of data, flattened from various sources.""" self.items = [] """A list of (source, offset) pairs, same length as `self.data`: the source of each line and the offset of each line from the beginning of its source.""" self.parent = parent """The parent list.""" self.parent_offset = parent_offset """Offset of this list from the beginning of the parent list.""" if isinstance(initlist, ViewList): self.data = initlist.data[:] self.items = initlist.items[:] elif initlist is not None: self.data = list(initlist) if items: self.items = items else: self.items = [(source, i) for i in range(len(initlist))] assert len(self.data) == len(self.items), 'data mismatch' def __str__(self): return str(self.data) def __repr__(self): return '%s(%s, items=%s)' % (self.__class__.__name__, self.data, self.items) def __lt__(self, other): return self.data < self.__cast(other) def __le__(self, other): return self.data <= self.__cast(other) def __eq__(self, other): return self.data == self.__cast(other) def __ne__(self, other): return self.data != self.__cast(other) def __gt__(self, other): return self.data > self.__cast(other) def __ge__(self, other): return self.data >= self.__cast(other) def __cmp__(self, other): return cmp(self.data, self.__cast(other)) def __cast(self, other): if isinstance(other, ViewList): return other.data else: return other def __contains__(self, item): return item in self.data def __len__(self): return len(self.data) # The __getitem__()/__setitem__() methods check whether the index # is a slice first, since native list objects start supporting # them directly in Python 2.3 (no exception is raised when # indexing a list with a slice object; they just work). def __getitem__(self, i): if isinstance(i, types.SliceType): assert i.step in (None, 1), 'cannot handle slice with stride' return self.__class__(self.data[i.start:i.stop], items=self.items[i.start:i.stop], parent=self, parent_offset=i.start) else: return self.data[i] def __setitem__(self, i, item): if isinstance(i, types.SliceType): assert i.step in (None, 1), 'cannot handle slice with stride' if not isinstance(item, ViewList): raise TypeError('assigning non-ViewList to ViewList slice') self.data[i.start:i.stop] = item.data self.items[i.start:i.stop] = item.items assert len(self.data) == len(self.items), 'data mismatch' if self.parent: self.parent[i.start + self.parent_offset : i.stop + self.parent_offset] = item else: self.data[i] = item if self.parent: self.parent[i + self.parent_offset] = item def __delitem__(self, i): try: del self.data[i] del self.items[i] if self.parent: del self.parent[i + self.parent_offset] except TypeError: assert i.step is None, 'cannot handle slice with stride' del self.data[i.start:i.stop] del self.items[i.start:i.stop] if self.parent: del self.parent[i.start + self.parent_offset : i.stop + self.parent_offset] def __add__(self, other): if isinstance(other, ViewList): return self.__class__(self.data + other.data, items=(self.items + other.items)) else: raise TypeError('adding non-ViewList to a ViewList') def __radd__(self, other): if isinstance(other, ViewList): return self.__class__(other.data + self.data, items=(other.items + self.items)) else: raise TypeError('adding ViewList to a non-ViewList') def __iadd__(self, other): if isinstance(other, ViewList): self.data += other.data else: raise TypeError('argument to += must be a ViewList') return self def __mul__(self, n): return self.__class__(self.data * n, items=(self.items * n)) __rmul__ = __mul__ def __imul__(self, n): self.data *= n self.items *= n return self def extend(self, other): if not isinstance(other, ViewList): raise TypeError('extending a ViewList with a non-ViewList') if self.parent: self.parent.insert(len(self.data) + self.parent_offset, other) self.data.extend(other.data) self.items.extend(other.items) def append(self, item, source=None, offset=0): if source is None: self.extend(item) else: if self.parent: self.parent.insert(len(self.data) + self.parent_offset, item, source, offset) self.data.append(item) self.items.append((source, offset)) def insert(self, i, item, source=None, offset=0): if source is None: if not isinstance(item, ViewList): raise TypeError('inserting non-ViewList with no source given') self.data[i:i] = item.data self.items[i:i] = item.items if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.insert(index + self.parent_offset, item) else: self.data.insert(i, item) self.items.insert(i, (source, offset)) if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.insert(index + self.parent_offset, item, source, offset) def pop(self, i=-1): if self.parent: index = (len(self.data) + i) % len(self.data) self.parent.pop(index + self.parent_offset) self.items.pop(i) return self.data.pop(i) def trim_start(self, n=1): """ Remove items from the start of the list, without touching the parent. """ if n > len(self.data): raise IndexError("Size of trim too large; can't trim %s items " "from a list of size %s." % (n, len(self.data))) elif n < 0: raise IndexError('Trim size must be >= 0.') del self.data[:n] del self.items[:n] if self.parent: self.parent_offset += n def trim_end(self, n=1): """ Remove items from the end of the list, without touching the parent. """ if n > len(self.data): raise IndexError("Size of trim too large; can't trim %s items " "from a list of size %s." % (n, len(self.data))) elif n < 0: raise IndexError('Trim size must be >= 0.') del self.data[-n:] del self.items[-n:] def remove(self, item): index = self.index(item) del self[index] def count(self, item): return self.data.count(item) def index(self, item): return self.data.index(item) def reverse(self): self.data.reverse() self.items.reverse() self.parent = None def sort(self, *args): tmp = zip(self.data, self.items) tmp.sort(*args) self.data = [entry[0] for entry in tmp] self.items = [entry[1] for entry in tmp] self.parent = None def info(self, i): """Return source & offset for index `i`.""" try: return self.items[i] except IndexError: if i == len(self.data): # Just past the end return self.items[i - 1][0], None else: raise def source(self, i): """Return source for index `i`.""" return self.info(i)[0] def offset(self, i): """Return offset for index `i`.""" return self.info(i)[1] def disconnect(self): """Break link between this list and parent list.""" self.parent = None class StringList(ViewList): """A `ViewList` with string-specific methods.""" def trim_left(self, length, start=0, end=sys.maxint): """ Trim `length` characters off the beginning of each item, in-place, from index `start` to `end`. No whitespace-checking is done on the trimmed text. Does not affect slice parent. """ self.data[start:end] = [line[length:] for line in self.data[start:end]] def get_text_block(self, start, flush_left=0): """ Return a contiguous block of text. If `flush_left` is true, raise `UnexpectedIndentationError` if an indented line is encountered before the text block ends (with a blank line). """ end = start last = len(self.data) while end < last: line = self.data[end] if not line.strip(): break if flush_left and (line[0] == ' '): source, offset = self.info(end) raise UnexpectedIndentationError(self[start:end], source, offset + 1) end += 1 return self[start:end] def get_indented(self, start=0, until_blank=0, strip_indent=1, block_indent=None, first_indent=None): """ Extract and return a StringList of indented lines of text. Collect all lines with indentation, determine the minimum indentation, remove the minimum indentation from all indented lines (unless `strip_indent` is false), and return them. All lines up to but not including the first unindented line will be returned. :Parameters: - `start`: The index of the first line to examine. - `until_blank`: Stop collecting at the first blank line if true. - `strip_indent`: Strip common leading indent if true (default). - `block_indent`: The indent of the entire block, if known. - `first_indent`: The indent of the first line, if known. :Return: - a StringList of indented lines with mininum indent removed; - the amount of the indent; - a boolean: did the indented block finish with a blank line or EOF? """ indent = block_indent # start with None if unknown end = start if block_indent is not None and first_indent is None: first_indent = block_indent if first_indent is not None: end += 1 last = len(self.data) while end < last: line = self.data[end] if line and (line[0] != ' ' or (block_indent is not None and line[:block_indent].strip())): # Line not indented or insufficiently indented. # Block finished properly iff the last indented line blank: blank_finish = ((end > start) and not self.data[end - 1].strip()) break stripped = line.lstrip() if not stripped: # blank line if until_blank: blank_finish = 1 break elif block_indent is None: line_indent = len(line) - len(stripped) if indent is None: indent = line_indent else: indent = min(indent, line_indent) end += 1 else: blank_finish = 1 # block ends at end of lines block = self[start:end] if first_indent is not None and block: block.data[0] = block.data[0][first_indent:] if indent and strip_indent: block.trim_left(indent, start=(first_indent is not None)) return block, indent or 0, blank_finish def get_2D_block(self, top, left, bottom, right, strip_indent=1): block = self[top:bottom] indent = right for i in range(len(block.data)): block.data[i] = line = block.data[i][left:right].rstrip() if line: indent = min(indent, len(line) - len(line.lstrip())) if strip_indent and 0 < indent < right: block.data = [line[indent:] for line in block.data] return block def pad_double_width(self, pad_char): """ Pad all double-width characters in self by appending `pad_char` to each. For East Asian language support. """ if hasattr(unicodedata, 'east_asian_width'): east_asian_width = unicodedata.east_asian_width else: return # new in Python 2.4 for i in range(len(self.data)): line = self.data[i] if isinstance(line, types.UnicodeType): new = [] for char in line: new.append(char) if east_asian_width(char) in 'WF': # 'W'ide & 'F'ull-width new.append(pad_char) self.data[i] = ''.join(new) def replace(self, old, new): """Replace all occurrences of substring `old` with `new`.""" for i in range(len(self.data)): self.data[i] = self.data[i].replace(old, new) class StateMachineError(Exception): pass class UnknownStateError(StateMachineError): pass class DuplicateStateError(StateMachineError): pass class UnknownTransitionError(StateMachineError): pass class DuplicateTransitionError(StateMachineError): pass class TransitionPatternNotFound(StateMachineError): pass class TransitionMethodNotFound(StateMachineError): pass class UnexpectedIndentationError(StateMachineError): pass class TransitionCorrection(Exception): """ Raise from within a transition method to switch to another transition. Raise with one argument, the new transition name. """ class StateCorrection(Exception): """ Raise from within a transition method to switch to another state. Raise with one or two arguments: new state name, and an optional new transition name. """ def string2lines(astring, tab_width=8, convert_whitespace=0, whitespace=re.compile('[\v\f]')): """ Return a list of one-line strings with tabs expanded, no newlines, and trailing whitespace stripped. Each tab is expanded with between 1 and `tab_width` spaces, so that the next character's index becomes a multiple of `tab_width` (8 by default). Parameters: - `astring`: a multi-line string. - `tab_width`: the number of columns between tab stops. - `convert_whitespace`: convert form feeds and vertical tabs to spaces? """ if convert_whitespace: astring = whitespace.sub(' ', astring) return [s.expandtabs(tab_width).rstrip() for s in astring.splitlines()] def _exception_data(): """ Return exception information: - the exception's class name; - the exception object; - the name of the file containing the offending code; - the line number of the offending code; - the function name of the offending code. """ type, value, traceback = sys.exc_info() while traceback.tb_next: traceback = traceback.tb_next code = traceback.tb_frame.f_code return (type.__name__, value, code.co_filename, traceback.tb_lineno, code.co_name)
{ "repo_name": "epall/selenium", "path": "selenium/src/py/lib/docutils/statemachine.py", "copies": "5", "size": "56869", "license": "apache-2.0", "hash": -7583321879857108000, "line_mean": 36.1159517426, "line_max": 80, "alpha_frac": 0.5717174559, "autogenerated": false, "ratio": 4.48246236304879, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7554179818948791, "avg_score": null, "num_lines": null }
""" Miscellaneous utilities for the documentation utilities. """ __docformat__ = 'reStructuredText' import sys import os import os.path import types import warnings import unicodedata from types import StringType, UnicodeType from docutils import ApplicationError, DataError from docutils import frontend, nodes class SystemMessage(ApplicationError): def __init__(self, system_message, level): Exception.__init__(self, system_message.astext()) self.level = level class SystemMessagePropagation(ApplicationError): pass class Reporter: """ Info/warning/error reporter and ``system_message`` element generator. Five levels of system messages are defined, along with corresponding methods: `debug()`, `info()`, `warning()`, `error()`, and `severe()`. There is typically one Reporter object per process. A Reporter object is instantiated with thresholds for reporting (generating warnings) and halting processing (raising exceptions), a switch to turn debug output on or off, and an I/O stream for warnings. These are stored as instance attributes. When a system message is generated, its level is compared to the stored thresholds, and a warning or error is generated as appropriate. Debug messages are produced iff the stored debug switch is on, independently of other thresholds. Message output is sent to the stored warning stream if not set to ''. The Reporter class also employs a modified form of the "Observer" pattern [GoF95]_ to track system messages generated. The `attach_observer` method should be called before parsing, with a bound method or function which accepts system messages. The observer can be removed with `detach_observer`, and another added in its place. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA, 1995. """ levels = 'DEBUG INFO WARNING ERROR SEVERE'.split() """List of names for system message levels, indexed by level.""" def __init__(self, source, report_level, halt_level, stream=None, debug=0, encoding='ascii', error_handler='replace'): """ :Parameters: - `source`: The path to or description of the source data. - `report_level`: The level at or above which warning output will be sent to `stream`. - `halt_level`: The level at or above which `SystemMessage` exceptions will be raised, halting execution. - `debug`: Show debug (level=0) system messages? - `stream`: Where warning output is sent. Can be file-like (has a ``.write`` method), a string (file name, opened for writing), '' (empty string, for discarding all stream messages) or `None` (implies `sys.stderr`; default). - `encoding`: The encoding for stderr output. - `error_handler`: The error handler for stderr output encoding. """ self.source = source """The path to or description of the source data.""" self.encoding = encoding """The character encoding for the stderr output.""" self.error_handler = error_handler """The character encoding error handler.""" self.debug_flag = debug """Show debug (level=0) system messages?""" self.report_level = report_level """The level at or above which warning output will be sent to `self.stream`.""" self.halt_level = halt_level """The level at or above which `SystemMessage` exceptions will be raised, halting execution.""" if stream is None: stream = sys.stderr elif type(stream) in (StringType, UnicodeType): # Leave stream untouched if it's ''. if stream != '': if type(stream) == StringType: stream = open(stream, 'w') elif type(stream) == UnicodeType: stream = open(stream.encode(), 'w') self.stream = stream """Where warning output is sent.""" self.observers = [] """List of bound methods or functions to call with each system_message created.""" self.max_level = -1 """The highest level system message generated so far.""" def set_conditions(self, category, report_level, halt_level, stream=None, debug=0): warnings.warn('docutils.utils.Reporter.set_conditions deprecated; ' 'set attributes via configuration settings or directly', DeprecationWarning, stacklevel=2) self.report_level = report_level self.halt_level = halt_level if stream is None: stream = sys.stderr self.stream = stream self.debug_flag = debug def attach_observer(self, observer): """ The `observer` parameter is a function or bound method which takes one argument, a `nodes.system_message` instance. """ self.observers.append(observer) def detach_observer(self, observer): self.observers.remove(observer) def notify_observers(self, message): for observer in self.observers: observer(message) def system_message(self, level, message, *children, **kwargs): """ Return a system_message object. Raise an exception or generate a warning if appropriate. """ attributes = kwargs.copy() if kwargs.has_key('base_node'): source, line = get_source_line(kwargs['base_node']) del attributes['base_node'] if source is not None: attributes.setdefault('source', source) if line is not None: attributes.setdefault('line', line) attributes.setdefault('source', self.source) msg = nodes.system_message(message, level=level, type=self.levels[level], *children, **attributes) if self.stream and (level >= self.report_level or self.debug_flag and level == 0): msgtext = msg.astext().encode(self.encoding, self.error_handler) print >>self.stream, msgtext if level >= self.halt_level: raise SystemMessage(msg, level) if level > 0 or self.debug_flag: self.notify_observers(msg) self.max_level = max(level, self.max_level) return msg def debug(self, *args, **kwargs): """ Level-0, "DEBUG": an internal reporting issue. Typically, there is no effect on the processing. Level-0 system messages are handled separately from the others. """ if self.debug_flag: return self.system_message(0, *args, **kwargs) def info(self, *args, **kwargs): """ Level-1, "INFO": a minor issue that can be ignored. Typically there is no effect on processing, and level-1 system messages are not reported. """ return self.system_message(1, *args, **kwargs) def warning(self, *args, **kwargs): """ Level-2, "WARNING": an issue that should be addressed. If ignored, there may be unpredictable problems with the output. """ return self.system_message(2, *args, **kwargs) def error(self, *args, **kwargs): """ Level-3, "ERROR": an error that should be addressed. If ignored, the output will contain errors. """ return self.system_message(3, *args, **kwargs) def severe(self, *args, **kwargs): """ Level-4, "SEVERE": a severe error that must be addressed. If ignored, the output will contain severe errors. Typically level-4 system messages are turned into exceptions which halt processing. """ return self.system_message(4, *args, **kwargs) class ExtensionOptionError(DataError): pass class BadOptionError(ExtensionOptionError): pass class BadOptionDataError(ExtensionOptionError): pass class DuplicateOptionError(ExtensionOptionError): pass def extract_extension_options(field_list, options_spec): """ Return a dictionary mapping extension option names to converted values. :Parameters: - `field_list`: A flat field list without field arguments, where each field body consists of a single paragraph only. - `options_spec`: Dictionary mapping known option names to a conversion function such as `int` or `float`. :Exceptions: - `KeyError` for unknown option names. - `ValueError` for invalid option values (raised by the conversion function). - `TypeError` for invalid option value types (raised by conversion function). - `DuplicateOptionError` for duplicate options. - `BadOptionError` for invalid fields. - `BadOptionDataError` for invalid option data (missing name, missing data, bad quotes, etc.). """ option_list = extract_options(field_list) option_dict = assemble_option_dict(option_list, options_spec) return option_dict def extract_options(field_list): """ Return a list of option (name, value) pairs from field names & bodies. :Parameter: `field_list`: A flat field list, where each field name is a single word and each field body consists of a single paragraph only. :Exceptions: - `BadOptionError` for invalid fields. - `BadOptionDataError` for invalid option data (missing name, missing data, bad quotes, etc.). """ option_list = [] for field in field_list: if len(field[0].astext().split()) != 1: raise BadOptionError( 'extension option field name may not contain multiple words') name = str(field[0].astext().lower()) body = field[1] if len(body) == 0: data = None elif len(body) > 1 or not isinstance(body[0], nodes.paragraph) \ or len(body[0]) != 1 or not isinstance(body[0][0], nodes.Text): raise BadOptionDataError( 'extension option field body may contain\n' 'a single paragraph only (option "%s")' % name) else: data = body[0][0].astext() option_list.append((name, data)) return option_list def assemble_option_dict(option_list, options_spec): """ Return a mapping of option names to values. :Parameters: - `option_list`: A list of (name, value) pairs (the output of `extract_options()`). - `options_spec`: Dictionary mapping known option names to a conversion function such as `int` or `float`. :Exceptions: - `KeyError` for unknown option names. - `DuplicateOptionError` for duplicate options. - `ValueError` for invalid option values (raised by conversion function). - `TypeError` for invalid option value types (raised by conversion function). """ options = {} for name, value in option_list: convertor = options_spec[name] # raises KeyError if unknown if convertor is None: raise KeyError(name) # or if explicitly disabled if options.has_key(name): raise DuplicateOptionError('duplicate option "%s"' % name) try: options[name] = convertor(value) except (ValueError, TypeError), detail: raise detail.__class__('(option: "%s"; value: %r)\n%s' % (name, value, ' '.join(detail.args))) return options class NameValueError(DataError): pass def extract_name_value(line): """ Return a list of (name, value) from a line of the form "name=value ...". :Exception: `NameValueError` for invalid input (missing name, missing data, bad quotes, etc.). """ attlist = [] while line: equals = line.find('=') if equals == -1: raise NameValueError('missing "="') attname = line[:equals].strip() if equals == 0 or not attname: raise NameValueError( 'missing attribute name before "="') line = line[equals+1:].lstrip() if not line: raise NameValueError( 'missing value after "%s="' % attname) if line[0] in '\'"': endquote = line.find(line[0], 1) if endquote == -1: raise NameValueError( 'attribute "%s" missing end quote (%s)' % (attname, line[0])) if len(line) > endquote + 1 and line[endquote + 1].strip(): raise NameValueError( 'attribute "%s" end quote (%s) not followed by ' 'whitespace' % (attname, line[0])) data = line[1:endquote] line = line[endquote+1:].lstrip() else: space = line.find(' ') if space == -1: data = line line = '' else: data = line[:space] line = line[space+1:].lstrip() attlist.append((attname.lower(), data)) return attlist def new_reporter(source_path, settings): """ Return a new Reporter object. :Parameters: `source` : string The path to or description of the source text of the document. `settings` : optparse.Values object Runtime settings. """ reporter = Reporter( source_path, settings.report_level, settings.halt_level, stream=settings.warning_stream, debug=settings.debug, encoding=settings.error_encoding, error_handler=settings.error_encoding_error_handler) return reporter def new_document(source_path, settings=None): """ Return a new empty document object. :Parameters: `source` : string The path to or description of the source text of the document. `settings` : optparse.Values object Runtime settings. If none provided, a default set will be used. """ if settings is None: settings = frontend.OptionParser().get_default_values() reporter = new_reporter(source_path, settings) document = nodes.document(settings, reporter, source=source_path) document.note_source(source_path, -1) return document def clean_rcs_keywords(paragraph, keyword_substitutions): if len(paragraph) == 1 and isinstance(paragraph[0], nodes.Text): textnode = paragraph[0] for pattern, substitution in keyword_substitutions: match = pattern.search(textnode.data) if match: textnode.data = pattern.sub(substitution, textnode.data) return def relative_path(source, target): """ Build and return a path to `target`, relative to `source` (both files). If there is no common prefix, return the absolute path to `target`. """ source_parts = os.path.abspath(source or 'dummy_file').split(os.sep) target_parts = os.path.abspath(target).split(os.sep) # Check first 2 parts because '/dir'.split('/') == ['', 'dir']: if source_parts[:2] != target_parts[:2]: # Nothing in common between paths. # Return absolute path, using '/' for URLs: return '/'.join(target_parts) source_parts.reverse() target_parts.reverse() while (source_parts and target_parts and source_parts[-1] == target_parts[-1]): # Remove path components in common: source_parts.pop() target_parts.pop() target_parts.reverse() parts = ['..'] * (len(source_parts) - 1) + target_parts return '/'.join(parts) def get_stylesheet_reference(settings, relative_to=None): """ Retrieve a stylesheet reference from the settings object. """ if settings.stylesheet_path: assert not settings.stylesheet, \ 'stylesheet and stylesheet_path are mutually exclusive.' if relative_to == None: relative_to = settings._destination return relative_path(relative_to, settings.stylesheet_path) else: return settings.stylesheet def get_trim_footnote_ref_space(settings): """ Return whether or not to trim footnote space. If trim_footnote_reference_space is not None, return it. If trim_footnote_reference_space is None, return False unless the footnote reference style is 'superscript'. """ if settings.trim_footnote_reference_space is None: return hasattr(settings, 'footnote_references') and \ settings.footnote_references == 'superscript' else: return settings.trim_footnote_reference_space def get_source_line(node): """ Return the "source" and "line" attributes from the `node` given or from its closest ancestor. """ while node: if node.source or node.line: return node.source, node.line node = node.parent return None, None def escape2null(text): """Return a string with escape-backslashes converted to nulls.""" parts = [] start = 0 while 1: found = text.find('\\', start) if found == -1: parts.append(text[start:]) return ''.join(parts) parts.append(text[start:found]) parts.append('\x00' + text[found+1:found+2]) start = found + 2 # skip character after escape def unescape(text, restore_backslashes=0): """ Return a string with nulls removed or restored to backslashes. Backslash-escaped spaces are also removed. """ if restore_backslashes: return text.replace('\x00', '\\') else: for sep in ['\x00 ', '\x00\n', '\x00']: text = ''.join(text.split(sep)) return text east_asian_widths = {'W': 2, # Wide 'F': 2, # Full-width (wide) 'Na': 1, # Narrow 'H': 1, # Half-width (narrow) 'N': 1, # Neutral (not East Asian, treated as narrow) 'A': 1} # Ambiguous (s/b wide in East Asian context, # narrow otherwise, but that doesn't work) """Mapping of result codes from `unicodedata.east_asian_width()` to character column widths.""" def east_asian_column_width(text): if isinstance(text, types.UnicodeType): total = 0 for c in text: total += east_asian_widths[unicodedata.east_asian_width(c)] return total else: return len(text) if hasattr(unicodedata, 'east_asian_width'): column_width = east_asian_column_width else: column_width = len class DependencyList: """ List of dependencies, with file recording support. Note that the output file is not automatically closed. You have to explicitly call the close() method. """ def __init__(self, output_file=None, dependencies=[]): """ Initialize the dependency list, automatically setting the output file to `output_file` (see `set_output()`) and adding all supplied dependencies. """ self.set_output(output_file) for i in dependencies: self.add(i) def set_output(self, output_file): """ Set the output file and clear the list of already added dependencies. `output_file` must be a string. The specified file is immediately overwritten. If output_file is '-', the output will be written to stdout. If it is None, no file output is done when calling add(). """ self.list = [] if output_file == '-': self.file = sys.stdout elif output_file: self.file = open(output_file, 'w') else: self.file = None def add(self, filename): """ If the dependency `filename` has not already been added, append it to self.list and print it to self.file if self.file is not None. """ if not filename in self.list: self.list.append(filename) if self.file is not None: print >>self.file, filename def close(self): """ Close the output file. """ self.file.close() self.file = None def __repr__(self): if self.file: output_file = self.file.name else: output_file = None return '%s(%r, %s)' % (self.__class__.__name__, output_file, self.list)
{ "repo_name": "hugs/selenium", "path": "selenium/src/py/lib/docutils/utils.py", "copies": "5", "size": "21527", "license": "apache-2.0", "hash": -4607713165947366000, "line_mean": 35.1155172414, "line_max": 79, "alpha_frac": 0.5861011753, "autogenerated": false, "ratio": 4.414889253486464, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0010741596419982008, "num_lines": 580 }
""" This module defines table parser classes,which parse plaintext-graphic tables and produce a well-formed data structure suitable for building a CALS table. :Classes: - `GridTableParser`: Parse fully-formed tables represented with a grid. - `SimpleTableParser`: Parse simple tables, delimited by top & bottom borders. :Exception class: `TableMarkupError` :Function: `update_dict_of_lists()`: Merge two dictionaries containing list values. """ __docformat__ = 'reStructuredText' import re import sys from docutils import DataError class TableMarkupError(DataError): pass class TableParser: """ Abstract superclass for the common parts of the syntax-specific parsers. """ head_body_separator_pat = None """Matches the row separator between head rows and body rows.""" double_width_pad_char = '\x00' """Padding character for East Asian double-width text.""" def parse(self, block): """ Analyze the text `block` and return a table data structure. Given a plaintext-graphic table in `block` (list of lines of text; no whitespace padding), parse the table, construct and return the data necessary to construct a CALS table or equivalent. Raise `TableMarkupError` if there is any problem with the markup. """ self.setup(block) self.find_head_body_sep() self.parse_table() structure = self.structure_from_cells() return structure def find_head_body_sep(self): """Look for a head/body row separator line; store the line index.""" for i in range(len(self.block)): line = self.block[i] if self.head_body_separator_pat.match(line): if self.head_body_sep: raise TableMarkupError( 'Multiple head/body row separators in table (at line ' 'offset %s and %s); only one allowed.' % (self.head_body_sep, i)) else: self.head_body_sep = i self.block[i] = line.replace('=', '-') if self.head_body_sep == 0 or self.head_body_sep == (len(self.block) - 1): raise TableMarkupError('The head/body row separator may not be ' 'the first or last line of the table.') class GridTableParser(TableParser): """ Parse a grid table using `parse()`. Here's an example of a grid table:: +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | Cells may span columns. | +------------------------+------------+---------------------+ | body row 3 | Cells may | - Table cells | +------------------------+ span rows. | - contain | | body row 4 | | - body elements. | +------------------------+------------+---------------------+ Intersections use '+', row separators use '-' (except for one optional head/body row separator, which uses '='), and column separators use '|'. Passing the above table to the `parse()` method will result in the following data structure:: ([24, 12, 10, 10], [[(0, 0, 1, ['Header row, column 1']), (0, 0, 1, ['Header 2']), (0, 0, 1, ['Header 3']), (0, 0, 1, ['Header 4'])]], [[(0, 0, 3, ['body row 1, column 1']), (0, 0, 3, ['column 2']), (0, 0, 3, ['column 3']), (0, 0, 3, ['column 4'])], [(0, 0, 5, ['body row 2']), (0, 2, 5, ['Cells may span columns.']), None, None], [(0, 0, 7, ['body row 3']), (1, 0, 7, ['Cells may', 'span rows.', '']), (1, 1, 7, ['- Table cells', '- contain', '- body elements.']), None], [(0, 0, 9, ['body row 4']), None, None, None]]) The first item is a list containing column widths (colspecs). The second item is a list of head rows, and the third is a list of body rows. Each row contains a list of cells. Each cell is either None (for a cell unused because of another cell's span), or a tuple. A cell tuple contains four items: the number of extra rows used by the cell in a vertical span (morerows); the number of extra columns used by the cell in a horizontal span (morecols); the line offset of the first line of the cell contents; and the cell contents, a list of lines of text. """ head_body_separator_pat = re.compile(r'\+=[=+]+=\+ *$') def setup(self, block): self.block = block[:] # make a copy; it may be modified self.block.disconnect() # don't propagate changes to parent self.bottom = len(block) - 1 self.right = len(block[0]) - 1 self.head_body_sep = None self.done = [-1] * len(block[0]) self.cells = [] self.rowseps = {0: [0]} self.colseps = {0: [0]} def parse_table(self): """ Start with a queue of upper-left corners, containing the upper-left corner of the table itself. Trace out one rectangular cell, remember it, and add its upper-right and lower-left corners to the queue of potential upper-left corners of further cells. Process the queue in top-to-bottom order, keeping track of how much of each text column has been seen. We'll end up knowing all the row and column boundaries, cell positions and their dimensions. """ corners = [(0, 0)] while corners: top, left = corners.pop(0) if top == self.bottom or left == self.right \ or top <= self.done[left]: continue result = self.scan_cell(top, left) if not result: continue bottom, right, rowseps, colseps = result update_dict_of_lists(self.rowseps, rowseps) update_dict_of_lists(self.colseps, colseps) self.mark_done(top, left, bottom, right) cellblock = self.block.get_2D_block(top + 1, left + 1, bottom, right) cellblock.disconnect() # lines in cell can't sync with parent cellblock.replace(self.double_width_pad_char, '') self.cells.append((top, left, bottom, right, cellblock)) corners.extend([(top, right), (bottom, left)]) corners.sort() if not self.check_parse_complete(): raise TableMarkupError('Malformed table; parse incomplete.') def mark_done(self, top, left, bottom, right): """For keeping track of how much of each text column has been seen.""" before = top - 1 after = bottom - 1 for col in range(left, right): assert self.done[col] == before self.done[col] = after def check_parse_complete(self): """Each text column should have been completely seen.""" last = self.bottom - 1 for col in range(self.right): if self.done[col] != last: return None return 1 def scan_cell(self, top, left): """Starting at the top-left corner, start tracing out a cell.""" assert self.block[top][left] == '+' result = self.scan_right(top, left) return result def scan_right(self, top, left): """ Look for the top-right corner of the cell, and make note of all column boundaries ('+'). """ colseps = {} line = self.block[top] for i in range(left + 1, self.right + 1): if line[i] == '+': colseps[i] = [top] result = self.scan_down(top, left, i) if result: bottom, rowseps, newcolseps = result update_dict_of_lists(colseps, newcolseps) return bottom, i, rowseps, colseps elif line[i] != '-': return None return None def scan_down(self, top, left, right): """ Look for the bottom-right corner of the cell, making note of all row boundaries. """ rowseps = {} for i in range(top + 1, self.bottom + 1): if self.block[i][right] == '+': rowseps[i] = [right] result = self.scan_left(top, left, i, right) if result: newrowseps, colseps = result update_dict_of_lists(rowseps, newrowseps) return i, rowseps, colseps elif self.block[i][right] != '|': return None return None def scan_left(self, top, left, bottom, right): """ Noting column boundaries, look for the bottom-left corner of the cell. It must line up with the starting point. """ colseps = {} line = self.block[bottom] for i in range(right - 1, left, -1): if line[i] == '+': colseps[i] = [bottom] elif line[i] != '-': return None if line[left] != '+': return None result = self.scan_up(top, left, bottom, right) if result is not None: rowseps = result return rowseps, colseps return None def scan_up(self, top, left, bottom, right): """ Noting row boundaries, see if we can return to the starting point. """ rowseps = {} for i in range(bottom - 1, top, -1): if self.block[i][left] == '+': rowseps[i] = [left] elif self.block[i][left] != '|': return None return rowseps def structure_from_cells(self): """ From the data collected by `scan_cell()`, convert to the final data structure. """ rowseps = self.rowseps.keys() # list of row boundaries rowseps.sort() rowindex = {} for i in range(len(rowseps)): rowindex[rowseps[i]] = i # row boundary -> row number mapping colseps = self.colseps.keys() # list of column boundaries colseps.sort() colindex = {} for i in range(len(colseps)): colindex[colseps[i]] = i # column boundary -> col number map colspecs = [(colseps[i] - colseps[i - 1] - 1) for i in range(1, len(colseps))] # list of column widths # prepare an empty table with the correct number of rows & columns onerow = [None for i in range(len(colseps) - 1)] rows = [onerow[:] for i in range(len(rowseps) - 1)] # keep track of # of cells remaining; should reduce to zero remaining = (len(rowseps) - 1) * (len(colseps) - 1) for top, left, bottom, right, block in self.cells: rownum = rowindex[top] colnum = colindex[left] assert rows[rownum][colnum] is None, ( 'Cell (row %s, column %s) already used.' % (rownum + 1, colnum + 1)) morerows = rowindex[bottom] - rownum - 1 morecols = colindex[right] - colnum - 1 remaining -= (morerows + 1) * (morecols + 1) # write the cell into the table rows[rownum][colnum] = (morerows, morecols, top + 1, block) assert remaining == 0, 'Unused cells remaining.' if self.head_body_sep: # separate head rows from body rows numheadrows = rowindex[self.head_body_sep] headrows = rows[:numheadrows] bodyrows = rows[numheadrows:] else: headrows = [] bodyrows = rows return (colspecs, headrows, bodyrows) class SimpleTableParser(TableParser): """ Parse a simple table using `parse()`. Here's an example of a simple table:: ===== ===== col 1 col 2 ===== ===== 1 Second column of row 1. 2 Second column of row 2. Second line of paragraph. 3 - Second column of row 3. - Second item in bullet list (row 3, column 2). 4 is a span ------------ 5 ===== ===== Top and bottom borders use '=', column span underlines use '-', column separation is indicated with spaces. Passing the above table to the `parse()` method will result in the following data structure, whose interpretation is the same as for `GridTableParser`:: ([5, 25], [[(0, 0, 1, ['col 1']), (0, 0, 1, ['col 2'])]], [[(0, 0, 3, ['1']), (0, 0, 3, ['Second column of row 1.'])], [(0, 0, 4, ['2']), (0, 0, 4, ['Second column of row 2.', 'Second line of paragraph.'])], [(0, 0, 6, ['3']), (0, 0, 6, ['- Second column of row 3.', '', '- Second item in bullet', ' list (row 3, column 2).'])], [(0, 1, 10, ['4 is a span'])], [(0, 0, 12, ['5']), (0, 0, 12, [''])]]) """ head_body_separator_pat = re.compile('=[ =]*$') span_pat = re.compile('-[ -]*$') def setup(self, block): self.block = block[:] # make a copy; it will be modified self.block.disconnect() # don't propagate changes to parent # Convert top & bottom borders to column span underlines: self.block[0] = self.block[0].replace('=', '-') self.block[-1] = self.block[-1].replace('=', '-') self.head_body_sep = None self.columns = [] self.border_end = None self.table = [] self.done = [-1] * len(block[0]) self.rowseps = {0: [0]} self.colseps = {0: [0]} def parse_table(self): """ First determine the column boundaries from the top border, then process rows. Each row may consist of multiple lines; accumulate lines until a row is complete. Call `self.parse_row` to finish the job. """ # Top border must fully describe all table columns. self.columns = self.parse_columns(self.block[0], 0) self.border_end = self.columns[-1][1] firststart, firstend = self.columns[0] offset = 1 # skip top border start = 1 text_found = None while offset < len(self.block): line = self.block[offset] if self.span_pat.match(line): # Column span underline or border; row is complete. self.parse_row(self.block[start:offset], start, (line.rstrip(), offset)) start = offset + 1 text_found = None elif line[firststart:firstend].strip(): # First column not blank, therefore it's a new row. if text_found and offset != start: self.parse_row(self.block[start:offset], start) start = offset text_found = 1 elif not text_found: start = offset + 1 offset += 1 def parse_columns(self, line, offset): """ Given a column span underline, return a list of (begin, end) pairs. """ cols = [] end = 0 while 1: begin = line.find('-', end) end = line.find(' ', begin) if begin < 0: break if end < 0: end = len(line) cols.append((begin, end)) if self.columns: if cols[-1][1] != self.border_end: raise TableMarkupError('Column span incomplete at line ' 'offset %s.' % offset) # Allow for an unbounded rightmost column: cols[-1] = (cols[-1][0], self.columns[-1][1]) return cols def init_row(self, colspec, offset): i = 0 cells = [] for start, end in colspec: morecols = 0 try: assert start == self.columns[i][0] while end != self.columns[i][1]: i += 1 morecols += 1 except (AssertionError, IndexError): raise TableMarkupError('Column span alignment problem at ' 'line offset %s.' % (offset + 1)) cells.append([0, morecols, offset, []]) i += 1 return cells def parse_row(self, lines, start, spanline=None): """ Given the text `lines` of a row, parse it and append to `self.table`. The row is parsed according to the current column spec (either `spanline` if provided or `self.columns`). For each column, extract text from each line, and check for text in column margins. Finally, adjust for insigificant whitespace. """ if not (lines or spanline): # No new row, just blank lines. return if spanline: columns = self.parse_columns(*spanline) span_offset = spanline[1] else: columns = self.columns[:] span_offset = start self.check_columns(lines, start, columns) row = self.init_row(columns, start) for i in range(len(columns)): start, end = columns[i] cellblock = lines.get_2D_block(0, start, len(lines), end) cellblock.disconnect() # lines in cell can't sync with parent cellblock.replace(self.double_width_pad_char, '') row[i][3] = cellblock self.table.append(row) def check_columns(self, lines, first_line, columns): """ Check for text in column margins and text overflow in the last column. Raise TableMarkupError if anything but whitespace is in column margins. Adjust the end value for the last column if there is text overflow. """ # "Infinite" value for a dummy last column's beginning, used to # check for text overflow: columns.append((sys.maxint, None)) lastcol = len(columns) - 2 for i in range(len(columns) - 1): start, end = columns[i] nextstart = columns[i+1][0] offset = 0 for line in lines: if i == lastcol and line[end:].strip(): text = line[start:].rstrip() new_end = start + len(text) columns[i] = (start, new_end) main_start, main_end = self.columns[-1] if new_end > main_end: self.columns[-1] = (main_start, new_end) elif line[end:nextstart].strip(): raise TableMarkupError('Text in column margin at line ' 'offset %s.' % (first_line + offset)) offset += 1 columns.pop() def structure_from_cells(self): colspecs = [end - start for start, end in self.columns] first_body_row = 0 if self.head_body_sep: for i in range(len(self.table)): if self.table[i][0][2] > self.head_body_sep: first_body_row = i break return (colspecs, self.table[:first_body_row], self.table[first_body_row:]) def update_dict_of_lists(master, newdata): """ Extend the list values of `master` with those from `newdata`. Both parameters must be dictionaries containing list values. """ for key, values in newdata.items(): master.setdefault(key, []).extend(values)
{ "repo_name": "epall/selenium", "path": "selenium/src/py/lib/docutils/parsers/rst/tableparser.py", "copies": "5", "size": "20909", "license": "apache-2.0", "hash": -6516695136960645000, "line_mean": 37.6755218216, "line_max": 80, "alpha_frac": 0.5033239275, "autogenerated": false, "ratio": 4.224893917963225, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00013500001728454264, "num_lines": 527 }
""" Transforms for resolving references. """ __docformat__ = 'reStructuredText' import sys import re from docutils import nodes, utils from docutils.transforms import TransformError, Transform class PropagateTargets(Transform): """ Propagate empty internal targets to the next element. Given the following nodes:: <target ids="internal1" names="internal1"> <target anonymous="1" ids="id1"> <target ids="internal2" names="internal2"> <paragraph> This is a test. PropagateTargets propagates the ids and names of the internal targets preceding the paragraph to the paragraph itself:: <target refid="internal1"> <target anonymous="1" refid="id1"> <target refid="internal2"> <paragraph ids="internal2 id1 internal1" names="internal2 internal1"> This is a test. """ default_priority = 260 def apply(self): for target in self.document.traverse(nodes.target): # Only block-level targets without reference (like ".. target:"): if (isinstance(target.parent, nodes.TextElement) or (target.hasattr('refid') or target.hasattr('refuri') or target.hasattr('refname'))): continue assert len(target) == 0, 'error: block-level target has children' next_node = target.next_node(ascend=1) # Do not move names and ids into Invisibles (we'd lose the # attributes) or different Targetables (e.g. footnotes). if (next_node is not None and ((not isinstance(next_node, nodes.Invisible) and not isinstance(next_node, nodes.Targetable)) or isinstance(next_node, nodes.target))): next_node['ids'].extend(target['ids']) next_node['names'].extend(target['names']) # Set defaults for next_node.expect_referenced_by_name/id. if not hasattr(next_node, 'expect_referenced_by_name'): next_node.expect_referenced_by_name = {} if not hasattr(next_node, 'expect_referenced_by_id'): next_node.expect_referenced_by_id = {} for id in target['ids']: # Update IDs to node mapping. self.document.ids[id] = next_node # If next_node is referenced by id ``id``, this # target shall be marked as referenced. next_node.expect_referenced_by_id[id] = target for name in target['names']: next_node.expect_referenced_by_name[name] = target # If there are any expect_referenced_by_... attributes # in target set, copy them to next_node. next_node.expect_referenced_by_name.update( getattr(target, 'expect_referenced_by_name', {})) next_node.expect_referenced_by_id.update( getattr(target, 'expect_referenced_by_id', {})) # Set refid to point to the first former ID of target # which is now an ID of next_node. target['refid'] = target['ids'][0] # Clear ids and names; they have been moved to # next_node. target['ids'] = [] target['names'] = [] self.document.note_refid(target) class AnonymousHyperlinks(Transform): """ Link anonymous references to targets. Given:: <paragraph> <reference anonymous="1"> internal <reference anonymous="1"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> Corresponding references are linked via "refid" or resolved via "refuri":: <paragraph> <reference anonymous="1" refid="id1"> text <reference anonymous="1" refuri="http://external"> external <target anonymous="1" ids="id1"> <target anonymous="1" ids="id2" refuri="http://external"> """ default_priority = 440 def apply(self): anonymous_refs = [] anonymous_targets = [] for node in self.document.traverse(nodes.reference): if node.get('anonymous'): anonymous_refs.append(node) for node in self.document.traverse(nodes.target): if node.get('anonymous'): anonymous_targets.append(node) if len(anonymous_refs) \ != len(anonymous_targets): msg = self.document.reporter.error( 'Anonymous hyperlink mismatch: %s references but %s ' 'targets.\nSee "backrefs" attribute for IDs.' % (len(anonymous_refs), len(anonymous_targets))) msgid = self.document.set_id(msg) for ref in anonymous_refs: prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) return for ref, target in zip(anonymous_refs, anonymous_targets): target.referenced = 1 while 1: if target.hasattr('refuri'): ref['refuri'] = target['refuri'] ref.resolved = 1 break else: if not target['ids']: # Propagated target. target = self.document.ids[target['refid']] continue ref['refid'] = target['ids'][0] self.document.note_refid(ref) break class IndirectHyperlinks(Transform): """ a) Indirect external references:: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refname="direct external"> The "refuri" attribute is migrated back to all indirect targets from the final direct target (i.e. a target not referring to another indirect target):: <paragraph> <reference refname="indirect external"> indirect external <target id="id1" name="direct external" refuri="http://indirect"> <target id="id2" name="indirect external" refuri="http://indirect"> Once the attribute is migrated, the preexisting "refname" attribute is dropped. b) Indirect internal references:: <target id="id1" name="final target"> <paragraph> <reference refname="indirect internal"> indirect internal <target id="id2" name="indirect internal 2" refname="final target"> <target id="id3" name="indirect internal" refname="indirect internal 2"> Targets which indirectly refer to an internal target become one-hop indirect (their "refid" attributes are directly set to the internal target's "id"). References which indirectly refer to an internal target become direct internal references:: <target id="id1" name="final target"> <paragraph> <reference refid="id1"> indirect internal <target id="id2" name="indirect internal 2" refid="id1"> <target id="id3" name="indirect internal" refid="id1"> """ default_priority = 460 def apply(self): for target in self.document.indirect_targets: if not target.resolved: self.resolve_indirect_target(target) self.resolve_indirect_references(target) def resolve_indirect_target(self, target): refname = target.get('refname') if refname is None: reftarget_id = target['refid'] else: reftarget_id = self.document.nameids.get(refname) if not reftarget_id: # Check the unknown_reference_resolvers for resolver_function in \ self.document.transformer.unknown_reference_resolvers: if resolver_function(target): break else: self.nonexistent_indirect_target(target) return reftarget = self.document.ids[reftarget_id] reftarget.note_referenced_by(id=reftarget_id) if isinstance(reftarget, nodes.target) \ and not reftarget.resolved and reftarget.hasattr('refname'): if hasattr(target, 'multiply_indirect'): #and target.multiply_indirect): #del target.multiply_indirect self.circular_indirect_reference(target) return target.multiply_indirect = 1 self.resolve_indirect_target(reftarget) # multiply indirect del target.multiply_indirect if reftarget.hasattr('refuri'): target['refuri'] = reftarget['refuri'] if target.has_key('refid'): del target['refid'] elif reftarget.hasattr('refid'): target['refid'] = reftarget['refid'] self.document.note_refid(target) else: if reftarget['ids']: target['refid'] = reftarget_id self.document.note_refid(target) else: self.nonexistent_indirect_target(target) return if refname is not None: del target['refname'] target.resolved = 1 def nonexistent_indirect_target(self, target): if self.document.nameids.has_key(target['refname']): self.indirect_target_error(target, 'which is a duplicate, and ' 'cannot be used as a unique reference') else: self.indirect_target_error(target, 'which does not exist') def circular_indirect_reference(self, target): self.indirect_target_error(target, 'forming a circular reference') def indirect_target_error(self, target, explanation): naming = '' reflist = [] if target['names']: naming = '"%s" ' % target['names'][0] for name in target['names']: reflist.extend(self.document.refnames.get(name, [])) for id in target['ids']: reflist.extend(self.document.refids.get(id, [])) naming += '(id="%s")' % target['ids'][0] msg = self.document.reporter.error( 'Indirect hyperlink target %s refers to target "%s", %s.' % (naming, target['refname'], explanation), base_node=target) msgid = self.document.set_id(msg) for ref in uniq(reflist): prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) target.resolved = 1 def resolve_indirect_references(self, target): if target.hasattr('refid'): attname = 'refid' call_method = self.document.note_refid elif target.hasattr('refuri'): attname = 'refuri' call_method = None else: return attval = target[attname] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) for id in target['ids']: reflist = self.document.refids.get(id, []) if reflist: target.note_referenced_by(id=id) for ref in reflist: if ref.resolved: continue del ref['refid'] ref[attname] = attval if call_method: call_method(ref) ref.resolved = 1 if isinstance(ref, nodes.target): self.resolve_indirect_references(ref) class ExternalTargets(Transform): """ Given:: <paragraph> <reference refname="direct external"> direct external <target id="id1" name="direct external" refuri="http://direct"> The "refname" attribute is replaced by the direct "refuri" attribute:: <paragraph> <reference refuri="http://direct"> direct external <target id="id1" name="direct external" refuri="http://direct"> """ default_priority = 640 def apply(self): for target in self.document.traverse(nodes.target): if target.hasattr('refuri'): refuri = target['refuri'] for name in target['names']: reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refuri'] = refuri ref.resolved = 1 class InternalTargets(Transform): default_priority = 660 def apply(self): for target in self.document.traverse(nodes.target): if not target.hasattr('refuri') and not target.hasattr('refid'): self.resolve_reference_ids(target) def resolve_reference_ids(self, target): """ Given:: <paragraph> <reference refname="direct internal"> direct internal <target id="id1" name="direct internal"> The "refname" attribute is replaced by "refid" linking to the target's "id":: <paragraph> <reference refid="id1"> direct internal <target id="id1" name="direct internal"> """ for name in target['names']: refid = self.document.nameids[name] reflist = self.document.refnames.get(name, []) if reflist: target.note_referenced_by(name=name) for ref in reflist: if ref.resolved: continue del ref['refname'] ref['refid'] = refid ref.resolved = 1 class Footnotes(Transform): """ Assign numbers to autonumbered footnotes, and resolve links to footnotes, citations, and their references. Given the following ``document`` as input:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refname="footnote"> <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2"> <footnote auto="1" id="id3"> <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote"> <paragraph> Labeled autonumbered footnote. Auto-numbered footnotes have attribute ``auto="1"`` and no label. Auto-numbered footnote_references have no reference text (they're empty elements). When resolving the numbering, a ``label`` element is added to the beginning of the ``footnote``, and reference text to the ``footnote_reference``. The transformed result will be:: <document> <paragraph> A labeled autonumbered footnote referece: <footnote_reference auto="1" id="id1" refid="footnote"> 2 <paragraph> An unlabeled autonumbered footnote referece: <footnote_reference auto="1" id="id2" refid="id3"> 1 <footnote auto="1" id="id3" backrefs="id2"> <label> 1 <paragraph> Unlabeled autonumbered footnote. <footnote auto="1" id="footnote" name="footnote" backrefs="id1"> <label> 2 <paragraph> Labeled autonumbered footnote. Note that the footnotes are not in the same order as the references. The labels and reference text are added to the auto-numbered ``footnote`` and ``footnote_reference`` elements. Footnote elements are backlinked to their references via "refids" attributes. References are assigned "id" and "refid" attributes. After adding labels and reference text, the "auto" attributes can be ignored. """ default_priority = 620 autofootnote_labels = None """Keep track of unlabeled autonumbered footnotes.""" symbols = [ # Entries 1-4 and 6 below are from section 12.51 of # The Chicago Manual of Style, 14th edition. '*', # asterisk/star u'\u2020', # dagger &dagger; u'\u2021', # double dagger &Dagger; u'\u00A7', # section mark &sect; u'\u00B6', # paragraph mark (pilcrow) &para; # (parallels ['||'] in CMoS) '#', # number sign # The entries below were chosen arbitrarily. u'\u2660', # spade suit &spades; u'\u2665', # heart suit &hearts; u'\u2666', # diamond suit &diams; u'\u2663', # club suit &clubs; ] def apply(self): self.autofootnote_labels = [] startnum = self.document.autofootnote_start self.document.autofootnote_start = self.number_footnotes(startnum) self.number_footnote_references(startnum) self.symbolize_footnotes() self.resolve_footnotes_and_citations() def number_footnotes(self, startnum): """ Assign numbers to autonumbered footnotes. For labeled autonumbered footnotes, copy the number over to corresponding footnote references. """ for footnote in self.document.autofootnotes: while 1: label = str(startnum) startnum += 1 if not self.document.nameids.has_key(label): break footnote.insert(0, nodes.label('', label)) for name in footnote['names']: for ref in self.document.footnote_refs.get(name, []): ref += nodes.Text(label) ref.delattr('refname') assert len(footnote['ids']) == len(ref['ids']) == 1 ref['refid'] = footnote['ids'][0] footnote.add_backref(ref['ids'][0]) self.document.note_refid(ref) ref.resolved = 1 if not footnote['names'] and not footnote['dupnames']: footnote['names'].append(label) self.document.note_explicit_target(footnote, footnote) self.autofootnote_labels.append(label) return startnum def number_footnote_references(self, startnum): """Assign numbers to autonumbered footnote references.""" i = 0 for ref in self.document.autofootnote_refs: if ref.resolved or ref.hasattr('refid'): continue try: label = self.autofootnote_labels[i] except IndexError: msg = self.document.reporter.error( 'Too many autonumbered footnote references: only %s ' 'corresponding footnotes available.' % len(self.autofootnote_labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.autofootnote_refs[i:]: if ref.resolved or ref.hasattr('refname'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break ref += nodes.Text(label) id = self.document.nameids[label] footnote = self.document.ids[id] ref['refid'] = id self.document.note_refid(ref) assert len(ref['ids']) == 1 footnote.add_backref(ref['ids'][0]) ref.resolved = 1 i += 1 def symbolize_footnotes(self): """Add symbols indexes to "[*]"-style footnotes and references.""" labels = [] for footnote in self.document.symbol_footnotes: reps, index = divmod(self.document.symbol_footnote_start, len(self.symbols)) labeltext = self.symbols[index] * (reps + 1) labels.append(labeltext) footnote.insert(0, nodes.label('', labeltext)) self.document.symbol_footnote_start += 1 self.document.set_id(footnote) i = 0 for ref in self.document.symbol_footnote_refs: try: ref += nodes.Text(labels[i]) except IndexError: msg = self.document.reporter.error( 'Too many symbol footnote references: only %s ' 'corresponding footnotes available.' % len(labels), base_node=ref) msgid = self.document.set_id(msg) for ref in self.document.symbol_footnote_refs[i:]: if ref.resolved or ref.hasattr('refid'): continue prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) break footnote = self.document.symbol_footnotes[i] assert len(footnote['ids']) == 1 ref['refid'] = footnote['ids'][0] self.document.note_refid(ref) footnote.add_backref(ref['ids'][0]) i += 1 def resolve_footnotes_and_citations(self): """ Link manually-labeled footnotes and citations to/from their references. """ for footnote in self.document.footnotes: for label in footnote['names']: if self.document.footnote_refs.has_key(label): reflist = self.document.footnote_refs[label] self.resolve_references(footnote, reflist) for citation in self.document.citations: for label in citation['names']: if self.document.citation_refs.has_key(label): reflist = self.document.citation_refs[label] self.resolve_references(citation, reflist) def resolve_references(self, note, reflist): assert len(note['ids']) == 1 id = note['ids'][0] for ref in reflist: if ref.resolved: continue ref.delattr('refname') ref['refid'] = id assert len(ref['ids']) == 1 note.add_backref(ref['ids'][0]) ref.resolved = 1 note.resolved = 1 class CircularSubstitutionDefinitionError(Exception): pass class Substitutions(Transform): """ Given the following ``document`` as input:: <document> <paragraph> The <substitution_reference refname="biohazard"> biohazard symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> The ``substitution_reference`` will simply be replaced by the contents of the corresponding ``substitution_definition``. The transformed result will be:: <document> <paragraph> The <image alt="biohazard" uri="biohazard.png"> symbol is deservedly scary-looking. <substitution_definition name="biohazard"> <image alt="biohazard" uri="biohazard.png"> """ default_priority = 220 """The Substitutions transform has to be applied very early, before `docutils.tranforms.frontmatter.DocTitle` and others.""" def apply(self): defs = self.document.substitution_defs normed = self.document.substitution_names subreflist = self.document.traverse(nodes.substitution_reference) nested = {} for ref in subreflist: refname = ref['refname'] key = None if defs.has_key(refname): key = refname else: normed_name = refname.lower() if normed.has_key(normed_name): key = normed[normed_name] if key is None: msg = self.document.reporter.error( 'Undefined substitution referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: subdef = defs[key] parent = ref.parent index = parent.index(ref) if (subdef.attributes.has_key('ltrim') or subdef.attributes.has_key('trim')): if index > 0 and isinstance(parent[index - 1], nodes.Text): parent.replace(parent[index - 1], parent[index - 1].rstrip()) if (subdef.attributes.has_key('rtrim') or subdef.attributes.has_key('trim')): if (len(parent) > index + 1 and isinstance(parent[index + 1], nodes.Text)): parent.replace(parent[index + 1], parent[index + 1].lstrip()) subdef_copy = subdef.deepcopy() try: # Take care of nested substitution references: for nested_ref in subdef_copy.traverse( nodes.substitution_reference): nested_name = normed[nested_ref['refname'].lower()] if nested_name in nested.setdefault(nested_name, []): raise CircularSubstitutionDefinitionError else: nested[nested_name].append(key) subreflist.append(nested_ref) except CircularSubstitutionDefinitionError: parent = ref.parent if isinstance(parent, nodes.substitution_definition): msg = self.document.reporter.error( 'Circular substitution definition detected:', nodes.literal_block(parent.rawsource, parent.rawsource), line=parent.line, base_node=parent) parent.replace_self(msg) else: msg = self.document.reporter.error( 'Circular substitution definition referenced: "%s".' % refname, base_node=ref) msgid = self.document.set_id(msg) prb = nodes.problematic( ref.rawsource, ref.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) ref.replace_self(prb) else: ref.replace_self(subdef_copy.children) class TargetNotes(Transform): """ Creates a footnote for each external target in the text, and corresponding footnote references after each reference. """ default_priority = 540 """The TargetNotes transform has to be applied after `IndirectHyperlinks` but before `Footnotes`.""" def __init__(self, document, startnode): Transform.__init__(self, document, startnode=startnode) self.classes = startnode.details.get('class', []) def apply(self): notes = {} nodelist = [] for target in self.document.traverse(nodes.target): # Only external targets. if not target.hasattr('refuri'): continue names = target['names'] refs = [] for name in names: refs.extend(self.document.refnames.get(name, [])) if not refs: continue footnote = self.make_target_footnote(target['refuri'], refs, notes) if not notes.has_key(target['refuri']): notes[target['refuri']] = footnote nodelist.append(footnote) # Take care of anonymous references. for ref in self.document.traverse(nodes.reference): if not ref.get('anonymous'): continue if ref.hasattr('refuri'): footnote = self.make_target_footnote(ref['refuri'], [ref], notes) if not notes.has_key(ref['refuri']): notes[ref['refuri']] = footnote nodelist.append(footnote) self.startnode.replace_self(nodelist) def make_target_footnote(self, refuri, refs, notes): if notes.has_key(refuri): # duplicate? footnote = notes[refuri] assert len(footnote['names']) == 1 footnote_name = footnote['names'][0] else: # original footnote = nodes.footnote() footnote_id = self.document.set_id(footnote) # Use uppercase letters and a colon; they can't be # produced inside names by the parser. footnote_name = 'TARGET_NOTE: ' + footnote_id footnote['auto'] = 1 footnote['names'] = [footnote_name] footnote_paragraph = nodes.paragraph() footnote_paragraph += nodes.reference('', refuri, refuri=refuri) footnote += footnote_paragraph self.document.note_autofootnote(footnote) self.document.note_explicit_target(footnote, footnote) for ref in refs: if isinstance(ref, nodes.target): continue refnode = nodes.footnote_reference( refname=footnote_name, auto=1) refnode['classes'] += self.classes self.document.note_autofootnote_ref(refnode) self.document.note_footnote_ref(refnode) index = ref.parent.index(ref) + 1 reflist = [refnode] if not utils.get_trim_footnote_ref_space(self.document.settings): if self.classes: reflist.insert(0, nodes.inline(text=' ', Classes=self.classes)) else: reflist.insert(0, nodes.Text(' ')) ref.parent.insert(index, reflist) return footnote class DanglingReferences(Transform): """ Check for dangling references (incl. footnote & citation) and for unreferenced targets. """ default_priority = 850 def apply(self): visitor = DanglingReferencesVisitor( self.document, self.document.transformer.unknown_reference_resolvers) self.document.walk(visitor) # *After* resolving all references, check for unreferenced # targets: for target in self.document.traverse(nodes.target): if not target.referenced: if target.get('anonymous'): # If we have unreferenced anonymous targets, there # is already an error message about anonymous # hyperlink mismatch; no need to generate another # message. continue if target['names']: naming = target['names'][0] elif target['ids']: naming = target['ids'][0] else: # Hack: Propagated targets always have their refid # attribute set. naming = target['refid'] self.document.reporter.info( 'Hyperlink target "%s" is not referenced.' % naming, base_node=target) class DanglingReferencesVisitor(nodes.SparseNodeVisitor): def __init__(self, document, unknown_reference_resolvers): nodes.SparseNodeVisitor.__init__(self, document) self.document = document self.unknown_reference_resolvers = unknown_reference_resolvers def unknown_visit(self, node): pass def visit_reference(self, node): if node.resolved or not node.hasattr('refname'): return refname = node['refname'] id = self.document.nameids.get(refname) if id is None: for resolver_function in self.unknown_reference_resolvers: if resolver_function(node): break else: if self.document.nameids.has_key(refname): msg = self.document.reporter.error( 'Duplicate target name, cannot be used as a unique ' 'reference: "%s".' % (node['refname']), base_node=node) else: msg = self.document.reporter.error( 'Unknown target name: "%s".' % (node['refname']), base_node=node) msgid = self.document.set_id(msg) prb = nodes.problematic( node.rawsource, node.rawsource, refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) node.replace_self(prb) else: del node['refname'] node['refid'] = id self.document.ids[id].note_referenced_by(id=id) node.resolved = 1 visit_footnote_reference = visit_citation_reference = visit_reference def uniq(L): r = [] for item in L: if not item in r: r.append(item) return r
{ "repo_name": "mogotest/selenium", "path": "selenium/src/py/lib/docutils/transforms/references.py", "copies": "5", "size": "36764", "license": "apache-2.0", "hash": 32911645642263690, "line_mean": 38.5783664459, "line_max": 83, "alpha_frac": 0.5167283212, "autogenerated": false, "ratio": 4.693476318141197, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7710204639341197, "avg_score": null, "num_lines": null }
""" Directives for figures and simple images. """ __docformat__ = 'reStructuredText' import sys from docutils import nodes, utils from docutils.parsers.rst import directives, states from docutils.nodes import fully_normalize_name, whitespace_normalize_name from docutils.parsers.rst.roles import set_classes try: import Image # PIL except ImportError: Image = None align_h_values = ('left', 'center', 'right') align_v_values = ('top', 'middle', 'bottom') align_values = align_v_values + align_h_values def align(argument): return directives.choice(argument, align_values) def image(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): if options.has_key('align'): # check for align_v values only if isinstance(state, states.SubstitutionDef): if options['align'] not in align_v_values: error = state_machine.reporter.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option within a substitution definition. ' 'Valid values for "align" are: "%s".' % (name, options['align'], '", "'.join(align_v_values)), nodes.literal_block(block_text, block_text), line=lineno) return [error] elif options['align'] not in align_h_values: error = state_machine.reporter.error( 'Error in "%s" directive: "%s" is not a valid value for ' 'the "align" option. Valid values for "align" are: "%s".' % (name, options['align'], '", "'.join(align_h_values)), nodes.literal_block(block_text, block_text), line=lineno) return [error] messages = [] reference = directives.uri(arguments[0]) options['uri'] = reference reference_node = None if options.has_key('target'): block = states.escape2null(options['target']).splitlines() block = [line for line in block] target_type, data = state.parse_target(block, block_text, lineno) if target_type == 'refuri': reference_node = nodes.reference(refuri=data) elif target_type == 'refname': reference_node = nodes.reference( refname=fully_normalize_name(data), name=whitespace_normalize_name(data)) reference_node.indirect_reference_name = data state.document.note_refname(reference_node) else: # malformed target messages.append(data) # data is a system message del options['target'] set_classes(options) image_node = nodes.image(block_text, **options) if reference_node: reference_node += image_node return messages + [reference_node] else: return messages + [image_node] image.arguments = (1, 0, 1) image.options = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.nonnegative_int, 'align': align, 'target': directives.unchanged_required, 'class': directives.class_option} def figure_align(argument): return directives.choice(argument, align_h_values) def figure(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): figwidth = options.get('figwidth') if figwidth: del options['figwidth'] figclasses = options.get('figclass') if figclasses: del options['figclass'] align = options.get('align') if align: del options['align'] (image_node,) = image(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine) if isinstance(image_node, nodes.system_message): return [image_node] figure_node = nodes.figure('', image_node) if figwidth == 'image': if Image and state.document.settings.file_insertion_enabled: # PIL doesn't like Unicode paths: try: i = Image.open(str(image_node['uri'])) except (IOError, UnicodeError): pass else: state.document.settings.record_dependencies.add(image_node['uri']) figure_node['width'] = i.size[0] elif figwidth is not None: figure_node['width'] = figwidth if figclasses: figure_node['classes'] += figclasses if align: figure_node['align'] = align if content: node = nodes.Element() # anonymous container for parsing state.nested_parse(content, content_offset, node) first_node = node[0] if isinstance(first_node, nodes.paragraph): caption = nodes.caption(first_node.rawsource, '', *first_node.children) figure_node += caption elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0): error = state_machine.reporter.error( 'Figure caption must be a paragraph or empty comment.', nodes.literal_block(block_text, block_text), line=lineno) return [figure_node, error] if len(node) > 1: figure_node += nodes.legend('', *node[1:]) return [figure_node] def figwidth_value(argument): if argument.lower() == 'image': return 'image' else: return directives.nonnegative_int(argument) figure.arguments = (1, 0, 1) figure.options = {'figwidth': figwidth_value, 'figclass': directives.class_option} figure.options.update(image.options) figure.options['align'] = figure_align figure.content = 1
{ "repo_name": "mogotest/selenium", "path": "selenium/src/py/lib/docutils/parsers/rst/directives/images.py", "copies": "5", "size": "6236", "license": "apache-2.0", "hash": 7405224582999723000, "line_mean": 39.0263157895, "line_max": 82, "alpha_frac": 0.5841885824, "autogenerated": false, "ratio": 4.121612690019828, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7205801272419828, "avg_score": null, "num_lines": null }
""" Parser for Python modules. Requires Python 2.2 or higher. The `parse_module()` function takes a module's text and file name, runs it through the module parser (using compiler.py and tokenize.py) and produces a parse tree of the source code, using the nodes as found in pynodes.py. For example, given this module (x.py):: # comment '''Docstring''' '''Additional docstring''' __docformat__ = 'reStructuredText' a = 1 '''Attribute docstring''' class C(Super): '''C's docstring''' class_attribute = 1 '''class_attribute's docstring''' def __init__(self, text=None): '''__init__'s docstring''' self.instance_attribute = (text * 7 + ' whaddyaknow') '''instance_attribute's docstring''' def f(x, # parameter x y=a*5, # parameter y *args): # parameter args '''f's docstring''' return [x + item for item in args] f.function_attribute = 1 '''f.function_attribute's docstring''' The module parser will produce this module documentation tree:: <module_section filename="test data"> <docstring> Docstring <docstring lineno="5"> Additional docstring <attribute lineno="7"> <object_name> __docformat__ <expression_value lineno="7"> 'reStructuredText' <attribute lineno="9"> <object_name> a <expression_value lineno="9"> 1 <docstring lineno="10"> Attribute docstring <class_section lineno="12"> <object_name> C <class_base> Super <docstring lineno="12"> C's docstring <attribute lineno="16"> <object_name> class_attribute <expression_value lineno="16"> 1 <docstring lineno="17"> class_attribute's docstring <method_section lineno="19"> <object_name> __init__ <docstring lineno="19"> __init__'s docstring <parameter_list lineno="19"> <parameter lineno="19"> <object_name> self <parameter lineno="19"> <object_name> text <parameter_default lineno="19"> None <attribute lineno="22"> <object_name> self.instance_attribute <expression_value lineno="22"> (text * 7 + ' whaddyaknow') <docstring lineno="24"> instance_attribute's docstring <function_section lineno="27"> <object_name> f <docstring lineno="27"> f's docstring <parameter_list lineno="27"> <parameter lineno="27"> <object_name> x <comment> # parameter x <parameter lineno="27"> <object_name> y <parameter_default lineno="27"> a * 5 <comment> # parameter y <parameter excess_positional="1" lineno="27"> <object_name> args <comment> # parameter args <attribute lineno="33"> <object_name> f.function_attribute <expression_value lineno="33"> 1 <docstring lineno="34"> f.function_attribute's docstring (Comments are not implemented yet.) compiler.parse() provides most of what's needed for this doctree, and "tokenize" can be used to get the rest. We can determine the line number from the compiler.parse() AST, and the TokenParser.rhs(lineno) method provides the rest. The Docutils Python reader component will transform this module doctree into a Python-specific Docutils doctree, and then a "stylist transform" will further transform it into a generic doctree. Namespaces will have to be compiled for each of the scopes, but I'm not certain at what stage of processing. It's very important to keep all docstring processing out of this, so that it's a completely generic and not tool-specific. :: > Why perform all of those transformations? Why not go from the AST to a > generic doctree? Or, even from the AST to the final output? I want the docutils.readers.python.moduleparser.parse_module() function to produce a standard documentation-oriented tree that can be used by any tool. We can develop it together without having to compromise on the rest of our design (i.e., HappyDoc doesn't have to be made to work like Docutils, and vice-versa). It would be a higher-level version of what compiler.py provides. The Python reader component transforms this generic AST into a Python-specific doctree (it knows about modules, classes, functions, etc.), but this is specific to Docutils and cannot be used by HappyDoc or others. The stylist transform does the final layout, converting Python-specific structures ("class" sections, etc.) into a generic doctree using primitives (tables, sections, lists, etc.). This generic doctree does *not* know about Python structures any more. The advantage is that this doctree can be handed off to any of the output writers to create any output format we like. The latter two transforms are separate because I want to be able to have multiple independent layout styles (multiple runtime-selectable "stylist transforms"). Each of the existing tools (HappyDoc, pydoc, epydoc, Crystal, etc.) has its own fixed format. I personally don't like the tables-based format produced by these tools, and I'd like to be able to customize the format easily. That's the goal of stylist transforms, which are independent from the Reader component itself. One stylist transform could produce HappyDoc-like output, another could produce output similar to module docs in the Python library reference manual, and so on. It's for exactly this reason:: >> It's very important to keep all docstring processing out of this, so that >> it's a completely generic and not tool-specific. ... but it goes past docstring processing. It's also important to keep style decisions and tool-specific data transforms out of this module parser. Issues ====== * At what point should namespaces be computed? Should they be part of the basic AST produced by the ASTVisitor walk, or generated by another tree traversal? * At what point should a distinction be made between local variables & instance attributes in __init__ methods? * Docstrings are getting their lineno from their parents. Should the TokenParser find the real line no's? * Comments: include them? How and when? Only full-line comments, or parameter comments too? (See function "f" above for an example.) * Module could use more docstrings & refactoring in places. """ __docformat__ = 'reStructuredText' import sys import compiler import compiler.ast import tokenize import token from compiler.consts import OP_ASSIGN from compiler.visitor import ASTVisitor from types import StringType, UnicodeType, TupleType from docutils.readers.python import pynodes from docutils.nodes import Text def parse_module(module_text, filename): """Return a module documentation tree from `module_text`.""" ast = compiler.parse(module_text) token_parser = TokenParser(module_text) visitor = ModuleVisitor(filename, token_parser) compiler.walk(ast, visitor, walker=visitor) return visitor.module class BaseVisitor(ASTVisitor): def __init__(self, token_parser): ASTVisitor.__init__(self) self.token_parser = token_parser self.context = [] self.documentable = None def default(self, node, *args): self.documentable = None #print 'in default (%s)' % node.__class__.__name__ #ASTVisitor.default(self, node, *args) def default_visit(self, node, *args): #print 'in default_visit (%s)' % node.__class__.__name__ ASTVisitor.default(self, node, *args) class DocstringVisitor(BaseVisitor): def visitDiscard(self, node): if self.documentable: self.visit(node.expr) def visitConst(self, node): if self.documentable: if type(node.value) in (StringType, UnicodeType): self.documentable.append(make_docstring(node.value, node.lineno)) else: self.documentable = None def visitStmt(self, node): self.default_visit(node) class AssignmentVisitor(DocstringVisitor): def visitAssign(self, node): visitor = AttributeVisitor(self.token_parser) compiler.walk(node, visitor, walker=visitor) if visitor.attributes: self.context[-1].extend(visitor.attributes) if len(visitor.attributes) == 1: self.documentable = visitor.attributes[0] else: self.documentable = None class ModuleVisitor(AssignmentVisitor): def __init__(self, filename, token_parser): AssignmentVisitor.__init__(self, token_parser) self.filename = filename self.module = None def visitModule(self, node): self.module = module = pynodes.module_section() module['filename'] = self.filename append_docstring(module, node.doc, node.lineno) self.context.append(module) self.documentable = module self.visit(node.node) self.context.pop() def visitImport(self, node): self.context[-1] += make_import_group(names=node.names, lineno=node.lineno) self.documentable = None def visitFrom(self, node): self.context[-1].append( make_import_group(names=node.names, from_name=node.modname, lineno=node.lineno)) self.documentable = None def visitFunction(self, node): visitor = FunctionVisitor(self.token_parser, function_class=pynodes.function_section) compiler.walk(node, visitor, walker=visitor) self.context[-1].append(visitor.function) def visitClass(self, node): visitor = ClassVisitor(self.token_parser) compiler.walk(node, visitor, walker=visitor) self.context[-1].append(visitor.klass) class AttributeVisitor(BaseVisitor): def __init__(self, token_parser): BaseVisitor.__init__(self, token_parser) self.attributes = pynodes.class_attribute_section() def visitAssign(self, node): # Don't visit the expression itself, just the attribute nodes: for child in node.nodes: self.dispatch(child) expression_text = self.token_parser.rhs(node.lineno) expression = pynodes.expression_value() expression.append(Text(expression_text)) for attribute in self.attributes: attribute.append(expression) def visitAssName(self, node): self.attributes.append(make_attribute(node.name, lineno=node.lineno)) def visitAssTuple(self, node): attributes = self.attributes self.attributes = [] self.default_visit(node) n = pynodes.attribute_tuple() n.extend(self.attributes) n['lineno'] = self.attributes[0]['lineno'] attributes.append(n) self.attributes = attributes #self.attributes.append(att_tuple) def visitAssAttr(self, node): self.default_visit(node, node.attrname) def visitGetattr(self, node, suffix): self.default_visit(node, node.attrname + '.' + suffix) def visitName(self, node, suffix): self.attributes.append(make_attribute(node.name + '.' + suffix, lineno=node.lineno)) class FunctionVisitor(DocstringVisitor): in_function = 0 def __init__(self, token_parser, function_class): DocstringVisitor.__init__(self, token_parser) self.function_class = function_class def visitFunction(self, node): if self.in_function: self.documentable = None # Don't bother with nested function definitions. return self.in_function = 1 self.function = function = make_function_like_section( name=node.name, lineno=node.lineno, doc=node.doc, function_class=self.function_class) self.context.append(function) self.documentable = function self.parse_parameter_list(node) self.visit(node.code) self.context.pop() def parse_parameter_list(self, node): parameters = [] special = [] argnames = list(node.argnames) if node.kwargs: special.append(make_parameter(argnames[-1], excess_keyword=1)) argnames.pop() if node.varargs: special.append(make_parameter(argnames[-1], excess_positional=1)) argnames.pop() defaults = list(node.defaults) defaults = [None] * (len(argnames) - len(defaults)) + defaults function_parameters = self.token_parser.function_parameters( node.lineno) #print >>sys.stderr, function_parameters for argname, default in zip(argnames, defaults): if type(argname) is TupleType: parameter = pynodes.parameter_tuple() for tuplearg in argname: parameter.append(make_parameter(tuplearg)) argname = normalize_parameter_name(argname) else: parameter = make_parameter(argname) if default: n_default = pynodes.parameter_default() n_default.append(Text(function_parameters[argname])) parameter.append(n_default) parameters.append(parameter) if parameters or special: special.reverse() parameters.extend(special) parameter_list = pynodes.parameter_list() parameter_list.extend(parameters) self.function.append(parameter_list) class ClassVisitor(AssignmentVisitor): in_class = 0 def __init__(self, token_parser): AssignmentVisitor.__init__(self, token_parser) self.bases = [] def visitClass(self, node): if self.in_class: self.documentable = None # Don't bother with nested class definitions. return self.in_class = 1 #import mypdb as pdb #pdb.set_trace() for base in node.bases: self.visit(base) self.klass = klass = make_class_section(node.name, self.bases, doc=node.doc, lineno=node.lineno) self.context.append(klass) self.documentable = klass self.visit(node.code) self.context.pop() def visitGetattr(self, node, suffix=None): if suffix: name = node.attrname + '.' + suffix else: name = node.attrname self.default_visit(node, name) def visitName(self, node, suffix=None): if suffix: name = node.name + '.' + suffix else: name = node.name self.bases.append(name) def visitFunction(self, node): if node.name == '__init__': visitor = InitMethodVisitor(self.token_parser, function_class=pynodes.method_section) compiler.walk(node, visitor, walker=visitor) else: visitor = FunctionVisitor(self.token_parser, function_class=pynodes.method_section) compiler.walk(node, visitor, walker=visitor) self.context[-1].append(visitor.function) class InitMethodVisitor(FunctionVisitor, AssignmentVisitor): pass class TokenParser: def __init__(self, text): self.text = text + '\n\n' self.lines = self.text.splitlines(1) self.generator = tokenize.generate_tokens(iter(self.lines).next) self.next() def __iter__(self): return self def next(self): self.token = self.generator.next() self.type, self.string, self.start, self.end, self.line = self.token return self.token def goto_line(self, lineno): while self.start[0] < lineno: self.next() return token def rhs(self, lineno): """ Return a whitespace-normalized expression string from the right-hand side of an assignment at line `lineno`. """ self.goto_line(lineno) while self.string != '=': self.next() self.stack = None while self.type != token.NEWLINE and self.string != ';': if self.string == '=' and not self.stack: self.tokens = [] self.stack = [] self._type = None self._string = None self._backquote = 0 else: self.note_token() self.next() self.next() text = ''.join(self.tokens) return text.strip() closers = {')': '(', ']': '[', '}': '{'} openers = {'(': 1, '[': 1, '{': 1} del_ws_prefix = {'.': 1, '=': 1, ')': 1, ']': 1, '}': 1, ':': 1, ',': 1} no_ws_suffix = {'.': 1, '=': 1, '(': 1, '[': 1, '{': 1} def note_token(self): if self.type == tokenize.NL: return del_ws = self.del_ws_prefix.has_key(self.string) append_ws = not self.no_ws_suffix.has_key(self.string) if self.openers.has_key(self.string): self.stack.append(self.string) if (self._type == token.NAME or self.closers.has_key(self._string)): del_ws = 1 elif self.closers.has_key(self.string): assert self.stack[-1] == self.closers[self.string] self.stack.pop() elif self.string == '`': if self._backquote: del_ws = 1 assert self.stack[-1] == '`' self.stack.pop() else: append_ws = 0 self.stack.append('`') self._backquote = not self._backquote if del_ws and self.tokens and self.tokens[-1] == ' ': del self.tokens[-1] self.tokens.append(self.string) self._type = self.type self._string = self.string if append_ws: self.tokens.append(' ') def function_parameters(self, lineno): """ Return a dictionary mapping parameters to defaults (whitespace-normalized strings). """ self.goto_line(lineno) while self.string != 'def': self.next() while self.string != '(': self.next() name = None default = None parameter_tuple = None self.tokens = [] parameters = {} self.stack = [self.string] self.next() while 1: if len(self.stack) == 1: if parameter_tuple: # Just encountered ")". #print >>sys.stderr, 'parameter_tuple: %r' % self.tokens name = ''.join(self.tokens).strip() self.tokens = [] parameter_tuple = None if self.string in (')', ','): if name: if self.tokens: default_text = ''.join(self.tokens).strip() else: default_text = None parameters[name] = default_text self.tokens = [] name = None default = None if self.string == ')': break elif self.type == token.NAME: if name and default: self.note_token() else: assert name is None, ( 'token=%r name=%r parameters=%r stack=%r' % (self.token, name, parameters, self.stack)) name = self.string #print >>sys.stderr, 'name=%r' % name elif self.string == '=': assert name is not None, 'token=%r' % (self.token,) assert default is None, 'token=%r' % (self.token,) assert self.tokens == [], 'token=%r' % (self.token,) default = 1 self._type = None self._string = None self._backquote = 0 elif name: self.note_token() elif self.string == '(': parameter_tuple = 1 self._type = None self._string = None self._backquote = 0 self.note_token() else: # ignore these tokens: assert (self.string in ('*', '**', '\n') or self.type == tokenize.COMMENT), ( 'token=%r' % (self.token,)) else: self.note_token() self.next() return parameters def make_docstring(doc, lineno): n = pynodes.docstring() if lineno: # Really, only module docstrings don't have a line # (@@: but maybe they should) n['lineno'] = lineno n.append(Text(doc)) return n def append_docstring(node, doc, lineno): if doc: node.append(make_docstring(doc, lineno)) def make_class_section(name, bases, lineno, doc): n = pynodes.class_section() n['lineno'] = lineno n.append(make_object_name(name)) for base in bases: b = pynodes.class_base() b.append(make_object_name(base)) n.append(b) append_docstring(n, doc, lineno) return n def make_object_name(name): n = pynodes.object_name() n.append(Text(name)) return n def make_function_like_section(name, lineno, doc, function_class): n = function_class() n['lineno'] = lineno n.append(make_object_name(name)) append_docstring(n, doc, lineno) return n def make_import_group(names, lineno, from_name=None): n = pynodes.import_group() n['lineno'] = lineno if from_name: n_from = pynodes.import_from() n_from.append(Text(from_name)) n.append(n_from) for name, alias in names: n_name = pynodes.import_name() n_name.append(Text(name)) if alias: n_alias = pynodes.import_alias() n_alias.append(Text(alias)) n_name.append(n_alias) n.append(n_name) return n def make_class_attribute(name, lineno): n = pynodes.class_attribute() n['lineno'] = lineno n.append(Text(name)) return n def make_attribute(name, lineno): n = pynodes.attribute() n['lineno'] = lineno n.append(make_object_name(name)) return n def make_parameter(name, excess_keyword=0, excess_positional=0): """ excess_keyword and excess_positional must be either 1 or 0, and not both of them can be 1. """ n = pynodes.parameter() n.append(make_object_name(name)) assert not excess_keyword or not excess_positional if excess_keyword: n['excess_keyword'] = 1 if excess_positional: n['excess_positional'] = 1 return n def trim_docstring(text): """ Trim indentation and blank lines from docstring text & return it. See PEP 257. """ if not text: return text # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = text.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = sys.maxint for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxint: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed) def normalize_parameter_name(name): """ Converts a tuple like ``('a', ('b', 'c'), 'd')`` into ``'(a, (b, c), d)'`` """ if type(name) is TupleType: return '(%s)' % ', '.join([normalize_parameter_name(n) for n in name]) else: return name if __name__ == '__main__': import sys args = sys.argv[1:] if args[0] == '-v': filename = args[1] module_text = open(filename).read() ast = compiler.parse(module_text) visitor = compiler.visitor.ExampleASTVisitor() compiler.walk(ast, visitor, walker=visitor, verbose=1) else: filename = args[0] content = open(filename).read() print parse_module(content, filename).pformat()
{ "repo_name": "epall/selenium", "path": "selenium/src/py/lib/docutils/readers/python/moduleparser.py", "copies": "5", "size": "26602", "license": "apache-2.0", "hash": -8905408654349880000, "line_mean": 33.0026315789, "line_max": 81, "alpha_frac": 0.5531914894, "autogenerated": false, "ratio": 4.3136046700178365, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7366796159417837, "avg_score": null, "num_lines": null }
""" Transforms for PEP processing. - `Headers`: Used to transform a PEP's initial RFC-2822 header. It remains a field list, but some entries get processed. - `Contents`: Auto-inserts a table of contents. - `PEPZero`: Special processing for PEP 0. """ __docformat__ = 'reStructuredText' import sys import os import re import time from docutils import nodes, utils, languages from docutils import ApplicationError, DataError from docutils.transforms import Transform, TransformError from docutils.transforms import parts, references, misc class Headers(Transform): """ Process fields in a PEP's initial RFC-2822 header. """ default_priority = 360 pep_url = 'pep-%04d' pep_cvs_url = ('http://svn.python.org/view/*checkout*' '/peps/trunk/pep-%04d.txt') rcs_keyword_substitutions = ( (re.compile(r'\$' r'RCSfile: (.+),v \$$', re.IGNORECASE), r'\1'), (re.compile(r'\$[a-zA-Z]+: (.+) \$$'), r'\1'),) def apply(self): if not len(self.document): # @@@ replace these DataErrors with proper system messages raise DataError('Document tree is empty.') header = self.document[0] if not isinstance(header, nodes.field_list) or \ 'rfc2822' not in header['classes']: raise DataError('Document does not begin with an RFC-2822 ' 'header; it is not a PEP.') pep = None for field in header: if field[0].astext().lower() == 'pep': # should be the first field value = field[1].astext() try: pep = int(value) cvs_url = self.pep_cvs_url % pep except ValueError: pep = value cvs_url = None msg = self.document.reporter.warning( '"PEP" header must contain an integer; "%s" is an ' 'invalid value.' % pep, base_node=field) msgid = self.document.set_id(msg) prb = nodes.problematic(value, value or '(none)', refid=msgid) prbid = self.document.set_id(prb) msg.add_backref(prbid) if len(field[1]): field[1][0][:] = [prb] else: field[1] += nodes.paragraph('', '', prb) break if pep is None: raise DataError('Document does not contain an RFC-2822 "PEP" ' 'header.') if pep == 0: # Special processing for PEP 0. pending = nodes.pending(PEPZero) self.document.insert(1, pending) self.document.note_pending(pending) if len(header) < 2 or header[1][0].astext().lower() != 'title': raise DataError('No title!') for field in header: name = field[0].astext().lower() body = field[1] if len(body) > 1: raise DataError('PEP header field body contains multiple ' 'elements:\n%s' % field.pformat(level=1)) elif len(body) == 1: if not isinstance(body[0], nodes.paragraph): raise DataError('PEP header field body may only contain ' 'a single paragraph:\n%s' % field.pformat(level=1)) elif name == 'last-modified': date = time.strftime( '%d-%b-%Y', time.localtime(os.stat(self.document['source'])[8])) if cvs_url: body += nodes.paragraph( '', '', nodes.reference('', date, refuri=cvs_url)) else: # empty continue para = body[0] if name == 'author': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node)) elif name == 'discussions-to': for node in para: if isinstance(node, nodes.reference): node.replace_self(mask_email(node, pep)) elif name in ('replaces', 'replaced-by', 'requires'): newbody = [] space = nodes.Text(' ') for refpep in re.split(',?\s+', body.astext()): pepno = int(refpep) newbody.append(nodes.reference( refpep, refpep, refuri=(self.document.settings.pep_base_url + self.pep_url % pepno))) newbody.append(space) para[:] = newbody[:-1] # drop trailing space elif name == 'last-modified': utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) if cvs_url: date = para.astext() para[:] = [nodes.reference('', date, refuri=cvs_url)] elif name == 'content-type': pep_type = para.astext() uri = self.document.settings.pep_base_url + self.pep_url % 12 para[:] = [nodes.reference('', pep_type, refuri=uri)] elif name == 'version' and len(body): utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions) class Contents(Transform): """ Insert an empty table of contents topic and a transform placeholder into the document after the RFC 2822 header. """ default_priority = 380 def apply(self): language = languages.get_language(self.document.settings.language_code) name = language.labels['contents'] title = nodes.title('', name) topic = nodes.topic('', title, classes=['contents']) name = nodes.fully_normalize_name(name) if not self.document.has_name(name): topic['names'].append(name) self.document.note_implicit_target(topic) pending = nodes.pending(parts.Contents) topic += pending self.document.insert(1, topic) self.document.note_pending(pending) class TargetNotes(Transform): """ Locate the "References" section, insert a placeholder for an external target footnote insertion transform at the end, and schedule the transform to run immediately. """ default_priority = 520 def apply(self): doc = self.document i = len(doc) - 1 refsect = copyright = None while i >= 0 and isinstance(doc[i], nodes.section): title_words = doc[i][0].astext().lower().split() if 'references' in title_words: refsect = doc[i] break elif 'copyright' in title_words: copyright = i i -= 1 if not refsect: refsect = nodes.section() refsect += nodes.title('', 'References') doc.set_id(refsect) if copyright: # Put the new "References" section before "Copyright": doc.insert(copyright, refsect) else: # Put the new "References" section at end of doc: doc.append(refsect) pending = nodes.pending(references.TargetNotes) refsect.append(pending) self.document.note_pending(pending, 0) pending = nodes.pending(misc.CallBack, details={'callback': self.cleanup_callback}) refsect.append(pending) self.document.note_pending(pending, 1) def cleanup_callback(self, pending): """ Remove an empty "References" section. Called after the `references.TargetNotes` transform is complete. """ if len(pending.parent) == 2: # <title> and <pending> pending.parent.parent.remove(pending.parent) class PEPZero(Transform): """ Special processing for PEP 0. """ default_priority =760 def apply(self): visitor = PEPZeroSpecial(self.document) self.document.walk(visitor) self.startnode.parent.remove(self.startnode) class PEPZeroSpecial(nodes.SparseNodeVisitor): """ Perform the special processing needed by PEP 0: - Mask email addresses. - Link PEP numbers in the second column of 4-column tables to the PEPs themselves. """ pep_url = Headers.pep_url def unknown_visit(self, node): pass def visit_reference(self, node): node.replace_self(mask_email(node)) def visit_field_list(self, node): if 'rfc2822' in node['classes']: raise nodes.SkipNode def visit_tgroup(self, node): self.pep_table = node['cols'] == 4 self.entry = 0 def visit_colspec(self, node): self.entry += 1 if self.pep_table and self.entry == 2: node['classes'].append('num') def visit_row(self, node): self.entry = 0 def visit_entry(self, node): self.entry += 1 if self.pep_table and self.entry == 2 and len(node) == 1: node['classes'].append('num') p = node[0] if isinstance(p, nodes.paragraph) and len(p) == 1: text = p.astext() try: pep = int(text) ref = (self.document.settings.pep_base_url + self.pep_url % pep) p[0] = nodes.reference(text, text, refuri=ref) except ValueError: pass non_masked_addresses = ('peps@python.org', 'python-list@python.org', 'python-dev@python.org') def mask_email(ref, pepno=None): """ Mask the email address in `ref` and return a replacement node. `ref` is returned unchanged if it contains no email address. For email addresses such as "user@host", mask the address as "user at host" (text) to thwart simple email address harvesters (except for those listed in `non_masked_addresses`). If a PEP number (`pepno`) is given, return a reference including a default email subject. """ if ref.hasattr('refuri') and ref['refuri'].startswith('mailto:'): if ref['refuri'][8:] in non_masked_addresses: replacement = ref[0] else: replacement_text = ref.astext().replace('@', '&#32;&#97;t&#32;') replacement = nodes.raw('', replacement_text, format='html') if pepno is None: return replacement else: ref['refuri'] += '?subject=PEP%%20%s' % pepno ref[:] = [replacement] return ref else: return ref
{ "repo_name": "epall/selenium", "path": "selenium/src/py/lib/docutils/transforms/peps.py", "copies": "5", "size": "11368", "license": "apache-2.0", "hash": -98548824707364510, "line_mean": 35.1503267974, "line_max": 79, "alpha_frac": 0.5199683322, "autogenerated": false, "ratio": 4.330666666666667, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7350634998866667, "avg_score": null, "num_lines": null }
""" This is ``docutils.parsers.rst`` package. It exports a single class, `Parser`, the reStructuredText parser. Usage ===== 1. Create a parser:: parser = docutils.parsers.rst.Parser() Several optional arguments may be passed to modify the parser's behavior. Please see `Customizing the Parser`_ below for details. 2. Gather input (a multi-line string), by reading a file or the standard input:: input = sys.stdin.read() 3. Create a new empty `docutils.nodes.document` tree:: document = docutils.utils.new_document(source, settings) See `docutils.utils.new_document()` for parameter details. 4. Run the parser, populating the document tree:: parser.parse(input, document) Parser Overview =============== The reStructuredText parser is implemented as a state machine, examining its input one line at a time. To understand how the parser works, please first become familiar with the `docutils.statemachine` module, then see the `states` module. Customizing the Parser ---------------------- Anything that isn't already customizable is that way simply because that type of customizability hasn't been implemented yet. Patches welcome! When instantiating an object of the `Parser` class, two parameters may be passed: ``rfc2822`` and ``inliner``. Pass ``rfc2822=1`` to enable an initial RFC-2822 style header block, parsed as a "field_list" element (with "class" attribute set to "rfc2822"). Currently this is the only body-level element which is customizable without subclassing. (Tip: subclass `Parser` and change its "state_classes" and "initial_state" attributes to refer to new classes. Contact the author if you need more details.) The ``inliner`` parameter takes an instance of `states.Inliner` or a subclass. It handles inline markup recognition. A common extension is the addition of further implicit hyperlinks, like "RFC 2822". This can be done by subclassing `states.Inliner`, adding a new method for the implicit markup, and adding a ``(pattern, method)`` pair to the "implicit_dispatch" attribute of the subclass. See `states.Inliner.implicit_inline()` for details. Explicit inline markup can be customized in a `states.Inliner` subclass via the ``patterns.initial`` and ``dispatch`` attributes (and new methods as appropriate). """ __docformat__ = 'reStructuredText' import docutils.parsers import docutils.statemachine from docutils.parsers.rst import states from docutils import frontend class Parser(docutils.parsers.Parser): """The reStructuredText parser.""" supported = ('restructuredtext', 'rst', 'rest', 'restx', 'rtxt', 'rstx') """Aliases this parser supports.""" settings_spec = ( 'reStructuredText Parser Options', None, (('Recognize and link to standalone PEP references (like "PEP 258").', ['--pep-references'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Base URL for PEP references ' '(default "http://www.python.org/dev/peps/").', ['--pep-base-url'], {'metavar': '<URL>', 'default': 'http://www.python.org/dev/peps/', 'validator': frontend.validate_url_trailing_slash}), ('Template for PEP file part of URL. (default "pep-%04d")', ['--pep-file-url-template'], {'metavar': '<URL>', 'default': 'pep-%04d'}), ('Recognize and link to standalone RFC references (like "RFC 822").', ['--rfc-references'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Base URL for RFC references (default "http://www.faqs.org/rfcs/").', ['--rfc-base-url'], {'metavar': '<URL>', 'default': 'http://www.faqs.org/rfcs/', 'validator': frontend.validate_url_trailing_slash}), ('Set number of spaces for tab expansion (default 8).', ['--tab-width'], {'metavar': '<width>', 'type': 'int', 'default': 8, 'validator': frontend.validate_nonnegative_int}), ('Remove spaces before footnote references.', ['--trim-footnote-reference-space'], {'action': 'store_true', 'validator': frontend.validate_boolean}), ('Leave spaces before footnote references.', ['--leave-footnote-reference-space'], {'action': 'store_false', 'dest': 'trim_footnote_reference_space', 'validator': frontend.validate_boolean}), ('Disable directives that insert the contents of external file ' '("include" & "raw"); replaced with a "warning" system message.', ['--no-file-insertion'], {'action': 'store_false', 'default': 1, 'dest': 'file_insertion_enabled'}), ('Enable directives that insert the contents of external file ' '("include" & "raw"). Enabled by default.', ['--file-insertion-enabled'], {'action': 'store_true', 'dest': 'file_insertion_enabled'}), ('Disable the "raw" directives; replaced with a "warning" ' 'system message.', ['--no-raw'], {'action': 'store_false', 'default': 1, 'dest': 'raw_enabled'}), ('Enable the "raw" directive. Enabled by default.', ['--raw-enabled'], {'action': 'store_true', 'dest': 'raw_enabled'}),)) config_section = 'restructuredtext parser' config_section_dependencies = ('parsers',) def __init__(self, rfc2822=None, inliner=None): if rfc2822: self.initial_state = 'RFC2822Body' else: self.initial_state = 'Body' self.state_classes = states.state_classes self.inliner = inliner def parse(self, inputstring, document): """Parse `inputstring` and populate `document`, a document tree.""" self.setup_parse(inputstring, document) self.statemachine = states.RSTStateMachine( state_classes=self.state_classes, initial_state=self.initial_state, debug=document.reporter.debug_flag) inputlines = docutils.statemachine.string2lines( inputstring, tab_width=document.settings.tab_width, convert_whitespace=1) self.statemachine.run(inputlines, document, inliner=self.inliner) self.finish_parse()
{ "repo_name": "hugs/selenium", "path": "selenium/src/py/lib/docutils/parsers/rst/__init__.py", "copies": "5", "size": "6660", "license": "apache-2.0", "hash": -6469652439552409000, "line_mean": 39.8867924528, "line_max": 79, "alpha_frac": 0.6315315315, "autogenerated": false, "ratio": 4.068417837507636, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 159 }
""" PEP HTML Writer. """ __docformat__ = 'reStructuredText' import sys import os import os.path import codecs import docutils from docutils import frontend, nodes, utils, writers from docutils.writers import html4css1 class Writer(html4css1.Writer): default_stylesheet = 'pep.css' default_stylesheet_path = utils.relative_path( os.path.join(os.getcwd(), 'dummy'), os.path.join(os.path.dirname(__file__), default_stylesheet)) default_template = 'template.txt' default_template_path = utils.relative_path( os.path.join(os.getcwd(), 'dummy'), os.path.join(os.path.dirname(__file__), default_template)) settings_spec = html4css1.Writer.settings_spec + ( 'PEP/HTML-Specific Options', 'For the PEP/HTML writer, the default value for the --stylesheet-path ' 'option is "%s", and the default value for --template is "%s". ' 'See HTML-Specific Options above.' % (default_stylesheet_path, default_template_path), (('Python\'s home URL. Default is "http://www.python.org".', ['--python-home'], {'default': 'http://www.python.org', 'metavar': '<URL>'}), ('Home URL prefix for PEPs. Default is "." (current directory).', ['--pep-home'], {'default': '.', 'metavar': '<URL>'}), # For testing. (frontend.SUPPRESS_HELP, ['--no-random'], {'action': 'store_true', 'validator': frontend.validate_boolean}),)) settings_default_overrides = {'stylesheet_path': default_stylesheet_path, 'template': default_template_path,} relative_path_settings = (html4css1.Writer.relative_path_settings + ('template',)) config_section = 'pep_html writer' config_section_dependencies = ('writers', 'html4css1 writer') def __init__(self): html4css1.Writer.__init__(self) self.translator_class = HTMLTranslator def interpolation_dict(self): subs = html4css1.Writer.interpolation_dict(self) settings = self.document.settings pyhome = settings.python_home subs['pyhome'] = pyhome subs['pephome'] = settings.pep_home if pyhome == '..': subs['pepindex'] = '.' else: subs['pepindex'] = pyhome + '/dev/peps' index = self.document.first_child_matching_class(nodes.field_list) header = self.document[index] self.pepnum = header[0][1].astext() subs['pep'] = self.pepnum if settings.no_random: subs['banner'] = 0 else: import random subs['banner'] = random.randrange(64) try: subs['pepnum'] = '%04i' % int(self.pepnum) except ValueError: subs['pepnum'] = pepnum self.title = header[1][1].astext() subs['title'] = self.title subs['body'] = ''.join( self.body_pre_docinfo + self.docinfo + self.body) return subs def assemble_parts(self): html4css1.Writer.assemble_parts(self) self.parts['title'] = [self.title] self.parts['pepnum'] = self.pepnum class HTMLTranslator(html4css1.HTMLTranslator): def depart_field_list(self, node): html4css1.HTMLTranslator.depart_field_list(self, node) if 'rfc2822' in node['classes']: self.body.append('<hr />\n')
{ "repo_name": "mogotest/selenium", "path": "selenium/src/py/lib/docutils/writers/pep_html/__init__.py", "copies": "5", "size": "3742", "license": "apache-2.0", "hash": -4406159805577134000, "line_mean": 32.9719626168, "line_max": 79, "alpha_frac": 0.5793693212, "autogenerated": false, "ratio": 3.845837615621788, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6925206936821787, "avg_score": null, "num_lines": null }
""" Simple HyperText Markup Language document tree Writer. The output conforms to the XHTML version 1.0 Transitional DTD (*almost* strict). The output contains a minimum of formatting information. The cascading style sheet "html4css1.css" is required for proper viewing with a modern graphical browser. """ __docformat__ = 'reStructuredText' import sys import os import os.path import codecs import time import re from types import ListType try: import Image # check for the Python Imaging Library except ImportError: Image = None import docutils from docutils import frontend, nodes, utils, writers, languages class Writer(writers.Writer): supported = ('html', 'html4css1', 'xhtml') """Formats this writer supports.""" default_stylesheet = 'html4css1.css' default_stylesheet_path = utils.relative_path( os.path.join(os.getcwd(), 'dummy'), os.path.join(os.path.dirname(__file__), default_stylesheet)) default_template = 'template.txt' default_template_path = utils.relative_path( os.path.join(os.getcwd(), 'dummy'), os.path.join(os.path.dirname(__file__), default_template)) settings_spec = ( 'HTML-Specific Options', None, (('Specify the template file (UTF-8 encoded). Default is "%s".' % default_template_path, ['--template'], {'default': default_template_path, 'metavar': '<file>'}), ('Specify a stylesheet URL, used verbatim. Overrides ' '--stylesheet-path.', ['--stylesheet'], {'metavar': '<URL>', 'overrides': 'stylesheet_path'}), ('Specify a stylesheet file, relative to the current working ' 'directory. The path is adjusted relative to the output HTML ' 'file. Overrides --stylesheet. Default: "%s"' % default_stylesheet_path, ['--stylesheet-path'], {'metavar': '<file>', 'overrides': 'stylesheet', 'default': default_stylesheet_path}), ('Embed the stylesheet in the output HTML file. The stylesheet ' 'file must be accessible during processing (--stylesheet-path is ' 'recommended). This is the default.', ['--embed-stylesheet'], {'default': 1, 'action': 'store_true', 'validator': frontend.validate_boolean}), ('Link to the stylesheet in the output HTML file. Default: ' 'embed the stylesheet, do not link to it.', ['--link-stylesheet'], {'dest': 'embed_stylesheet', 'action': 'store_false', 'validator': frontend.validate_boolean}), ('Specify the initial header level. Default is 1 for "<h1>". ' 'Does not affect document title & subtitle (see --no-doc-title).', ['--initial-header-level'], {'choices': '1 2 3 4 5 6'.split(), 'default': '1', 'metavar': '<level>'}), ('Specify the maximum width (in characters) for one-column field ' 'names. Longer field names will span an entire row of the table ' 'used to render the field list. Default is 14 characters. ' 'Use 0 for "no limit".', ['--field-name-limit'], {'default': 14, 'metavar': '<level>', 'validator': frontend.validate_nonnegative_int}), ('Specify the maximum width (in characters) for options in option ' 'lists. Longer options will span an entire row of the table used ' 'to render the option list. Default is 14 characters. ' 'Use 0 for "no limit".', ['--option-limit'], {'default': 14, 'metavar': '<level>', 'validator': frontend.validate_nonnegative_int}), ('Format for footnote references: one of "superscript" or ' '"brackets". Default is "brackets".', ['--footnote-references'], {'choices': ['superscript', 'brackets'], 'default': 'brackets', 'metavar': '<format>', 'overrides': 'trim_footnote_reference_space'}), ('Format for block quote attributions: one of "dash" (em-dash ' 'prefix), "parentheses"/"parens", or "none". Default is "dash".', ['--attribution'], {'choices': ['dash', 'parentheses', 'parens', 'none'], 'default': 'dash', 'metavar': '<format>'}), ('Remove extra vertical whitespace between items of "simple" bullet ' 'lists and enumerated lists. Default: enabled.', ['--compact-lists'], {'default': 1, 'action': 'store_true', 'validator': frontend.validate_boolean}), ('Disable compact simple bullet and enumerated lists.', ['--no-compact-lists'], {'dest': 'compact_lists', 'action': 'store_false'}), ('Remove extra vertical whitespace between items of simple field ' 'lists. Default: enabled.', ['--compact-field-lists'], {'default': 1, 'action': 'store_true', 'validator': frontend.validate_boolean}), ('Disable compact simple field lists.', ['--no-compact-field-lists'], {'dest': 'compact_field_lists', 'action': 'store_false'}), ('Omit the XML declaration. Use with caution.', ['--no-xml-declaration'], {'dest': 'xml_declaration', 'default': 1, 'action': 'store_false', 'validator': frontend.validate_boolean}), ('Obfuscate email addresses to confuse harvesters while still ' 'keeping email links usable with standards-compliant browsers.', ['--cloak-email-addresses'], {'action': 'store_true', 'validator': frontend.validate_boolean}),)) settings_defaults = {'output_encoding_error_handler': 'xmlcharrefreplace'} relative_path_settings = ('stylesheet_path',) config_section = 'html4css1 writer' config_section_dependencies = ('writers',) visitor_attributes = ( 'head_prefix', 'head', 'stylesheet', 'body_prefix', 'body_pre_docinfo', 'docinfo', 'body', 'body_suffix', 'title', 'subtitle', 'header', 'footer', 'meta', 'fragment', 'html_prolog', 'html_head', 'html_title', 'html_subtitle', 'html_body') def __init__(self): writers.Writer.__init__(self) self.translator_class = HTMLTranslator def translate(self): self.visitor = visitor = self.translator_class(self.document) self.document.walkabout(visitor) for attr in self.visitor_attributes: setattr(self, attr, getattr(visitor, attr)) self.output = self.apply_template() def apply_template(self): template_file = codecs.open( self.document.settings.template, 'r', 'utf-8') template = template_file.read() template_file.close() subs = self.interpolation_dict() return template % subs def interpolation_dict(self): subs = {} settings = self.document.settings for attr in self.visitor_attributes: subs[attr] = ''.join(getattr(self, attr)).rstrip('\n') subs['encoding'] = settings.output_encoding subs['version'] = docutils.__version__ return subs def assemble_parts(self): writers.Writer.assemble_parts(self) for part in self.visitor_attributes: self.parts[part] = ''.join(getattr(self, part)) class HTMLTranslator(nodes.NodeVisitor): """ This HTML writer has been optimized to produce visually compact lists (less vertical whitespace). HTML's mixed content models allow list items to contain "<li><p>body elements</p></li>" or "<li>just text</li>" or even "<li>text<p>and body elements</p>combined</li>", each with different effects. It would be best to stick with strict body elements in list items, but they affect vertical spacing in browsers (although they really shouldn't). Here is an outline of the optimization: - Check for and omit <p> tags in "simple" lists: list items contain either a single paragraph, a nested simple list, or a paragraph followed by a nested simple list. This means that this list can be compact: - Item 1. - Item 2. But this list cannot be compact: - Item 1. This second paragraph forces space between list items. - Item 2. - In non-list contexts, omit <p> tags on a paragraph if that paragraph is the only child of its parent (footnotes & citations are allowed a label first). - Regardless of the above, in definitions, table cells, field bodies, option descriptions, and list items, mark the first child with 'class="first"' and the last child with 'class="last"'. The stylesheet sets the margins (top & bottom respectively) to 0 for these elements. The ``no_compact_lists`` setting (``--no-compact-lists`` command-line option) disables list whitespace optimization. """ xml_declaration = '<?xml version="1.0" encoding="%s" ?>\n' doctype = ( '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n') head_prefix_template = ('<html xmlns="http://www.w3.org/1999/xhtml"' ' xml:lang="%s" lang="%s">\n<head>\n') content_type = ('<meta http-equiv="Content-Type"' ' content="text/html; charset=%s" />\n') generator = ('<meta name="generator" content="Docutils %s: ' 'http://docutils.sourceforge.net/" />\n') stylesheet_link = '<link rel="stylesheet" href="%s" type="text/css" />\n' embedded_stylesheet = '<style type="text/css">\n\n%s\n</style>\n' named_tags = ['a', 'applet', 'form', 'frame', 'iframe', 'img', 'map'] words_and_spaces = re.compile(r'\S+| +|\n') def __init__(self, document): nodes.NodeVisitor.__init__(self, document) self.settings = settings = document.settings lcode = settings.language_code self.language = languages.get_language(lcode) self.meta = [self.content_type % settings.output_encoding, self.generator % docutils.__version__] self.head_prefix = [] self.html_prolog = [] if settings.xml_declaration: self.head_prefix.append(self.xml_declaration % settings.output_encoding) # encoding not interpolated: self.html_prolog.append(self.xml_declaration) self.head_prefix.extend([self.doctype, self.head_prefix_template % (lcode, lcode)]) self.html_prolog.append(self.doctype) self.head = self.meta[:] stylesheet = utils.get_stylesheet_reference(settings) self.stylesheet = [] if stylesheet: if settings.embed_stylesheet: stylesheet = utils.get_stylesheet_reference( settings, os.path.join(os.getcwd(), 'dummy')) settings.record_dependencies.add(stylesheet) stylesheet_text = open(stylesheet).read() self.stylesheet = [self.embedded_stylesheet % stylesheet_text] else: self.stylesheet = [self.stylesheet_link % self.encode(stylesheet)] self.body_prefix = ['</head>\n<body>\n'] # document title, subtitle display self.body_pre_docinfo = [] # author, date, etc. self.docinfo = [] self.body = [] self.fragment = [] self.body_suffix = ['</body>\n</html>\n'] self.section_level = 0 self.initial_header_level = int(settings.initial_header_level) # A heterogenous stack used in conjunction with the tree traversal. # Make sure that the pops correspond to the pushes: self.context = [] self.topic_classes = [] self.colspecs = [] self.compact_p = 1 self.compact_simple = None self.compact_field_list = None self.in_docinfo = None self.in_sidebar = None self.title = [] self.subtitle = [] self.header = [] self.footer = [] self.html_head = [self.content_type] # charset not interpolated self.html_title = [] self.html_subtitle = [] self.html_body = [] self.in_document_title = 0 self.in_mailto = 0 self.author_in_authors = None def astext(self): return ''.join(self.head_prefix + self.head + self.stylesheet + self.body_prefix + self.body_pre_docinfo + self.docinfo + self.body + self.body_suffix) def encode(self, text): """Encode special characters in `text` & return.""" # @@@ A codec to do these and all other HTML entities would be nice. text = text.replace("&", "&amp;") text = text.replace("<", "&lt;") text = text.replace('"', "&quot;") text = text.replace(">", "&gt;") text = text.replace("@", "&#64;") # may thwart some address harvesters # Replace the non-breaking space character with the HTML entity: text = text.replace(u'\u00a0', "&nbsp;") return text def cloak_mailto(self, uri): """Try to hide a mailto: URL from harvesters.""" # Encode "@" using a URL octet reference (see RFC 1738). # Further cloaking with HTML entities will be done in the # `attval` function. return uri.replace('@', '%40') def cloak_email(self, addr): """Try to hide the link text of a email link from harversters.""" # Surround at-signs and periods with <span> tags. ("@" has # already been encoded to "&#64;" by the `encode` method.) addr = addr.replace('&#64;', '<span>&#64;</span>') addr = addr.replace('.', '<span>&#46;</span>') return addr def attval(self, text, whitespace=re.compile('[\n\r\t\v\f]')): """Cleanse, HTML encode, and return attribute value text.""" encoded = self.encode(whitespace.sub(' ', text)) if self.in_mailto and self.settings.cloak_email_addresses: # Cloak at-signs ("%40") and periods with HTML entities. encoded = encoded.replace('%40', '&#37;&#52;&#48;') encoded = encoded.replace('.', '&#46;') return encoded def starttag(self, node, tagname, suffix='\n', empty=0, **attributes): """ Construct and return a start tag given a node (id & class attributes are extracted), tag name, and optional attributes. """ tagname = tagname.lower() prefix = [] atts = {} ids = [] for (name, value) in attributes.items(): atts[name.lower()] = value classes = node.get('classes', []) if atts.has_key('class'): classes.append(atts['class']) if classes: atts['class'] = ' '.join(classes) assert not atts.has_key('id') ids.extend(node.get('ids', [])) if atts.has_key('ids'): ids.extend(atts['ids']) del atts['ids'] if ids: atts['id'] = ids[0] for id in ids[1:]: # Add empty "span" elements for additional IDs. Note # that we cannot use empty "a" elements because there # may be targets inside of references, but nested "a" # elements aren't allowed in XHTML (even if they do # not all have a "href" attribute). if empty: # Empty tag. Insert target right in front of element. prefix.append('<span id="%s"></span>' % id) else: # Non-empty tag. Place the auxiliary <span> tag # *inside* the element, as the first child. suffix += '<span id="%s"></span>' % id # !!! next 2 lines to be removed in Docutils 0.5: if atts.has_key('id') and tagname in self.named_tags: atts['name'] = atts['id'] # for compatibility with old browsers attlist = atts.items() attlist.sort() parts = [tagname] for name, value in attlist: # value=None was used for boolean attributes without # value, but this isn't supported by XHTML. assert value is not None if isinstance(value, ListType): values = [unicode(v) for v in value] parts.append('%s="%s"' % (name.lower(), self.attval(' '.join(values)))) else: try: uval = unicode(value) except TypeError: # for Python 2.1 compatibility: uval = unicode(str(value)) parts.append('%s="%s"' % (name.lower(), self.attval(uval))) if empty: infix = ' /' else: infix = '' return ''.join(prefix) + '<%s%s>' % (' '.join(parts), infix) + suffix def emptytag(self, node, tagname, suffix='\n', **attributes): """Construct and return an XML-compatible empty tag.""" return self.starttag(node, tagname, suffix, empty=1, **attributes) # !!! to be removed in Docutils 0.5 (change calls to use "starttag"): def start_tag_with_title(self, node, tagname, **atts): """ID and NAME attributes will be handled in the title.""" node = {'classes': node.get('classes', [])} return self.starttag(node, tagname, **atts) def set_class_on_child(self, node, class_, index=0): """ Set class `class_` on the visible child no. index of `node`. Do nothing if node has fewer children than `index`. """ children = [n for n in node if not isinstance(n, nodes.Invisible)] try: child = children[index] except IndexError: return child['classes'].append(class_) def set_first_last(self, node): self.set_class_on_child(node, 'first', 0) self.set_class_on_child(node, 'last', -1) def visit_Text(self, node): text = node.astext() encoded = self.encode(text) if self.in_mailto and self.settings.cloak_email_addresses: encoded = self.cloak_email(encoded) self.body.append(encoded) def depart_Text(self, node): pass def visit_abbreviation(self, node): # @@@ implementation incomplete ("title" attribute) self.body.append(self.starttag(node, 'abbr', '')) def depart_abbreviation(self, node): self.body.append('</abbr>') def visit_acronym(self, node): # @@@ implementation incomplete ("title" attribute) self.body.append(self.starttag(node, 'acronym', '')) def depart_acronym(self, node): self.body.append('</acronym>') def visit_address(self, node): self.visit_docinfo_item(node, 'address', meta=None) self.body.append(self.starttag(node, 'pre', CLASS='address')) def depart_address(self, node): self.body.append('\n</pre>\n') self.depart_docinfo_item() def visit_admonition(self, node, name=''): self.body.append(self.start_tag_with_title( node, 'div', CLASS=(name or 'admonition'))) if name: node.insert(0, nodes.title(name, self.language.labels[name])) self.set_first_last(node) def depart_admonition(self, node=None): self.body.append('</div>\n') def visit_attention(self, node): self.visit_admonition(node, 'attention') def depart_attention(self, node): self.depart_admonition() attribution_formats = {'dash': ('&mdash;', ''), 'parentheses': ('(', ')'), 'parens': ('(', ')'), 'none': ('', '')} def visit_attribution(self, node): prefix, suffix = self.attribution_formats[self.settings.attribution] self.context.append(suffix) self.body.append( self.starttag(node, 'p', prefix, CLASS='attribution')) def depart_attribution(self, node): self.body.append(self.context.pop() + '</p>\n') def visit_author(self, node): if isinstance(node.parent, nodes.authors): if self.author_in_authors: self.body.append('\n<br />') else: self.visit_docinfo_item(node, 'author') def depart_author(self, node): if isinstance(node.parent, nodes.authors): self.author_in_authors += 1 else: self.depart_docinfo_item() def visit_authors(self, node): self.visit_docinfo_item(node, 'authors') self.author_in_authors = 0 # initialize counter def depart_authors(self, node): self.depart_docinfo_item() self.author_in_authors = None def visit_block_quote(self, node): self.body.append(self.starttag(node, 'blockquote')) def depart_block_quote(self, node): self.body.append('</blockquote>\n') def check_simple_list(self, node): """Check for a simple list that can be rendered compactly.""" visitor = SimpleListChecker(self.document) try: node.walk(visitor) except nodes.NodeFound: return None else: return 1 def is_compactable(self, node): return ('compact' in node['classes'] or (self.settings.compact_lists and 'open' not in node['classes'] and (self.compact_simple or self.topic_classes == ['contents'] or self.check_simple_list(node)))) def visit_bullet_list(self, node): atts = {} old_compact_simple = self.compact_simple self.context.append((self.compact_simple, self.compact_p)) self.compact_p = None self.compact_simple = self.is_compactable(node) if self.compact_simple and not old_compact_simple: atts['class'] = 'simple' self.body.append(self.starttag(node, 'ul', **atts)) def depart_bullet_list(self, node): self.compact_simple, self.compact_p = self.context.pop() self.body.append('</ul>\n') def visit_caption(self, node): self.body.append(self.starttag(node, 'p', '', CLASS='caption')) def depart_caption(self, node): self.body.append('</p>\n') def visit_caution(self, node): self.visit_admonition(node, 'caution') def depart_caution(self, node): self.depart_admonition() def visit_citation(self, node): self.body.append(self.starttag(node, 'table', CLASS='docutils citation', frame="void", rules="none")) self.body.append('<colgroup><col class="label" /><col /></colgroup>\n' '<tbody valign="top">\n' '<tr>') self.footnote_backrefs(node) def depart_citation(self, node): self.body.append('</td></tr>\n' '</tbody>\n</table>\n') def visit_citation_reference(self, node): href = '#' + node['refid'] self.body.append(self.starttag( node, 'a', '[', CLASS='citation-reference', href=href)) def depart_citation_reference(self, node): self.body.append(']</a>') def visit_classifier(self, node): self.body.append(' <span class="classifier-delimiter">:</span> ') self.body.append(self.starttag(node, 'span', '', CLASS='classifier')) def depart_classifier(self, node): self.body.append('</span>') def visit_colspec(self, node): self.colspecs.append(node) # "stubs" list is an attribute of the tgroup element: node.parent.stubs.append(node.attributes.get('stub')) def depart_colspec(self, node): pass def write_colspecs(self): width = 0 for node in self.colspecs: width += node['colwidth'] for node in self.colspecs: colwidth = int(node['colwidth'] * 100.0 / width + 0.5) self.body.append(self.emptytag(node, 'col', width='%i%%' % colwidth)) self.colspecs = [] def visit_comment(self, node, sub=re.compile('-(?=-)').sub): """Escape double-dashes in comment text.""" self.body.append('<!-- %s -->\n' % sub('- ', node.astext())) # Content already processed: raise nodes.SkipNode def visit_compound(self, node): self.body.append(self.starttag(node, 'div', CLASS='compound')) if len(node) > 1: node[0]['classes'].append('compound-first') node[-1]['classes'].append('compound-last') for child in node[1:-1]: child['classes'].append('compound-middle') def depart_compound(self, node): self.body.append('</div>\n') def visit_container(self, node): self.body.append(self.starttag(node, 'div', CLASS='container')) def depart_container(self, node): self.body.append('</div>\n') def visit_contact(self, node): self.visit_docinfo_item(node, 'contact', meta=None) def depart_contact(self, node): self.depart_docinfo_item() def visit_copyright(self, node): self.visit_docinfo_item(node, 'copyright') def depart_copyright(self, node): self.depart_docinfo_item() def visit_danger(self, node): self.visit_admonition(node, 'danger') def depart_danger(self, node): self.depart_admonition() def visit_date(self, node): self.visit_docinfo_item(node, 'date') def depart_date(self, node): self.depart_docinfo_item() def visit_decoration(self, node): pass def depart_decoration(self, node): pass def visit_definition(self, node): self.body.append('</dt>\n') self.body.append(self.starttag(node, 'dd', '')) self.set_first_last(node) def depart_definition(self, node): self.body.append('</dd>\n') def visit_definition_list(self, node): self.body.append(self.starttag(node, 'dl', CLASS='docutils')) def depart_definition_list(self, node): self.body.append('</dl>\n') def visit_definition_list_item(self, node): pass def depart_definition_list_item(self, node): pass def visit_description(self, node): self.body.append(self.starttag(node, 'td', '')) self.set_first_last(node) def depart_description(self, node): self.body.append('</td>') def visit_docinfo(self, node): self.context.append(len(self.body)) self.body.append(self.starttag(node, 'table', CLASS='docinfo', frame="void", rules="none")) self.body.append('<col class="docinfo-name" />\n' '<col class="docinfo-content" />\n' '<tbody valign="top">\n') self.in_docinfo = 1 def depart_docinfo(self, node): self.body.append('</tbody>\n</table>\n') self.in_docinfo = None start = self.context.pop() self.docinfo = self.body[start:] self.body = [] def visit_docinfo_item(self, node, name, meta=1): if meta: meta_tag = '<meta name="%s" content="%s" />\n' \ % (name, self.attval(node.astext())) self.add_meta(meta_tag) self.body.append(self.starttag(node, 'tr', '')) self.body.append('<th class="docinfo-name">%s:</th>\n<td>' % self.language.labels[name]) if len(node): if isinstance(node[0], nodes.Element): node[0]['classes'].append('first') if isinstance(node[-1], nodes.Element): node[-1]['classes'].append('last') def depart_docinfo_item(self): self.body.append('</td></tr>\n') def visit_doctest_block(self, node): self.body.append(self.starttag(node, 'pre', CLASS='doctest-block')) def depart_doctest_block(self, node): self.body.append('\n</pre>\n') def visit_document(self, node): self.head.append('<title>%s</title>\n' % self.encode(node.get('title', ''))) def depart_document(self, node): self.fragment.extend(self.body) self.body_prefix.append(self.starttag(node, 'div', CLASS='document')) self.body_suffix.insert(0, '</div>\n') # skip content-type meta tag with interpolated charset value: self.html_head.extend(self.head[1:]) self.html_body.extend(self.body_prefix[1:] + self.body_pre_docinfo + self.docinfo + self.body + self.body_suffix[:-1]) def visit_emphasis(self, node): self.body.append('<em>') def depart_emphasis(self, node): self.body.append('</em>') def visit_entry(self, node): atts = {'class': []} if isinstance(node.parent.parent, nodes.thead): atts['class'].append('head') if node.parent.parent.parent.stubs[node.parent.column]: # "stubs" list is an attribute of the tgroup element atts['class'].append('stub') if atts['class']: tagname = 'th' atts['class'] = ' '.join(atts['class']) else: tagname = 'td' del atts['class'] node.parent.column += 1 if node.has_key('morerows'): atts['rowspan'] = node['morerows'] + 1 if node.has_key('morecols'): atts['colspan'] = node['morecols'] + 1 node.parent.column += node['morecols'] self.body.append(self.starttag(node, tagname, '', **atts)) self.context.append('</%s>\n' % tagname.lower()) if len(node) == 0: # empty cell self.body.append('&nbsp;') self.set_first_last(node) def depart_entry(self, node): self.body.append(self.context.pop()) def visit_enumerated_list(self, node): """ The 'start' attribute does not conform to HTML 4.01's strict.dtd, but CSS1 doesn't help. CSS2 isn't widely enough supported yet to be usable. """ atts = {} if node.has_key('start'): atts['start'] = node['start'] if node.has_key('enumtype'): atts['class'] = node['enumtype'] # @@@ To do: prefix, suffix. How? Change prefix/suffix to a # single "format" attribute? Use CSS2? old_compact_simple = self.compact_simple self.context.append((self.compact_simple, self.compact_p)) self.compact_p = None self.compact_simple = self.is_compactable(node) if self.compact_simple and not old_compact_simple: atts['class'] = (atts.get('class', '') + ' simple').strip() self.body.append(self.starttag(node, 'ol', **atts)) def depart_enumerated_list(self, node): self.compact_simple, self.compact_p = self.context.pop() self.body.append('</ol>\n') def visit_error(self, node): self.visit_admonition(node, 'error') def depart_error(self, node): self.depart_admonition() def visit_field(self, node): self.body.append(self.starttag(node, 'tr', '', CLASS='field')) def depart_field(self, node): self.body.append('</tr>\n') def visit_field_body(self, node): self.body.append(self.starttag(node, 'td', '', CLASS='field-body')) self.set_class_on_child(node, 'first', 0) field = node.parent if (self.compact_field_list or isinstance(field.parent, nodes.docinfo) or field.parent.index(field) == len(field.parent) - 1): # If we are in a compact list, the docinfo, or if this is # the last field of the field list, do not add vertical # space after last element. self.set_class_on_child(node, 'last', -1) def depart_field_body(self, node): self.body.append('</td>\n') def visit_field_list(self, node): self.context.append((self.compact_field_list, self.compact_p)) self.compact_p = None if 'compact' in node['classes']: self.compact_field_list = 1 elif (self.settings.compact_field_lists and 'open' not in node['classes']): self.compact_field_list = 1 if self.compact_field_list: for field in node: field_body = field[-1] assert isinstance(field_body, nodes.field_body) children = [n for n in field_body if not isinstance(n, nodes.Invisible)] if not (len(children) == 0 or len(children) == 1 and isinstance(children[0], nodes.paragraph)): self.compact_field_list = 0 break self.body.append(self.starttag(node, 'table', frame='void', rules='none', CLASS='docutils field-list')) self.body.append('<col class="field-name" />\n' '<col class="field-body" />\n' '<tbody valign="top">\n') def depart_field_list(self, node): self.body.append('</tbody>\n</table>\n') self.compact_field_list, self.compact_p = self.context.pop() def visit_field_name(self, node): atts = {} if self.in_docinfo: atts['class'] = 'docinfo-name' else: atts['class'] = 'field-name' if ( self.settings.field_name_limit and len(node.astext()) > self.settings.field_name_limit): atts['colspan'] = 2 self.context.append('</tr>\n<tr><td>&nbsp;</td>') else: self.context.append('') self.body.append(self.starttag(node, 'th', '', **atts)) def depart_field_name(self, node): self.body.append(':</th>') self.body.append(self.context.pop()) def visit_figure(self, node): atts = {'class': 'figure'} if node.get('width'): atts['style'] = 'width: %spx' % node['width'] if node.get('align'): atts['align'] = node['align'] self.body.append(self.starttag(node, 'div', **atts)) def depart_figure(self, node): self.body.append('</div>\n') def visit_footer(self, node): self.context.append(len(self.body)) def depart_footer(self, node): start = self.context.pop() footer = [self.starttag(node, 'div', CLASS='footer'), '<hr class="footer" />\n'] footer.extend(self.body[start:]) footer.append('\n</div>\n') self.footer.extend(footer) self.body_suffix[:0] = footer del self.body[start:] def visit_footnote(self, node): self.body.append(self.starttag(node, 'table', CLASS='docutils footnote', frame="void", rules="none")) self.body.append('<colgroup><col class="label" /><col /></colgroup>\n' '<tbody valign="top">\n' '<tr>') self.footnote_backrefs(node) def footnote_backrefs(self, node): backlinks = [] backrefs = node['backrefs'] if self.settings.footnote_backlinks and backrefs: if len(backrefs) == 1: self.context.append('') self.context.append( '<a class="fn-backref" href="#%s" name="%s">' % (backrefs[0], node['ids'][0])) else: i = 1 for backref in backrefs: backlinks.append('<a class="fn-backref" href="#%s">%s</a>' % (backref, i)) i += 1 self.context.append('<em>(%s)</em> ' % ', '.join(backlinks)) self.context.append('<a name="%s">' % node['ids'][0]) else: self.context.append('') self.context.append('<a name="%s">' % node['ids'][0]) # If the node does not only consist of a label. if len(node) > 1: # If there are preceding backlinks, we do not set class # 'first', because we need to retain the top-margin. if not backlinks: node[1]['classes'].append('first') node[-1]['classes'].append('last') def depart_footnote(self, node): self.body.append('</td></tr>\n' '</tbody>\n</table>\n') def visit_footnote_reference(self, node): href = '#' + node['refid'] format = self.settings.footnote_references if format == 'brackets': suffix = '[' self.context.append(']') else: assert format == 'superscript' suffix = '<sup>' self.context.append('</sup>') self.body.append(self.starttag(node, 'a', suffix, CLASS='footnote-reference', href=href)) def depart_footnote_reference(self, node): self.body.append(self.context.pop() + '</a>') def visit_generated(self, node): pass def depart_generated(self, node): pass def visit_header(self, node): self.context.append(len(self.body)) def depart_header(self, node): start = self.context.pop() header = [self.starttag(node, 'div', CLASS='header')] header.extend(self.body[start:]) header.append('\n<hr class="header"/>\n</div>\n') self.body_prefix.extend(header) self.header.extend(header) del self.body[start:] def visit_hint(self, node): self.visit_admonition(node, 'hint') def depart_hint(self, node): self.depart_admonition() def visit_image(self, node): atts = {} atts['src'] = node['uri'] if node.has_key('width'): atts['width'] = node['width'] if node.has_key('height'): atts['height'] = node['height'] if node.has_key('scale'): if Image and not (node.has_key('width') and node.has_key('height')): try: im = Image.open(str(atts['src'])) except (IOError, # Source image can't be found or opened UnicodeError): # PIL doesn't like Unicode paths. pass else: if not atts.has_key('width'): atts['width'] = str(im.size[0]) if not atts.has_key('height'): atts['height'] = str(im.size[1]) del im for att_name in 'width', 'height': if atts.has_key(att_name): match = re.match(r'([0-9.]+)(\S*)$', atts[att_name]) assert match atts[att_name] = '%s%s' % ( float(match.group(1)) * (float(node['scale']) / 100), match.group(2)) style = [] for att_name in 'width', 'height': if atts.has_key(att_name): if re.match(r'^[0-9.]+$', atts[att_name]): # Interpret unitless values as pixels. atts[att_name] += 'px' style.append('%s: %s;' % (att_name, atts[att_name])) del atts[att_name] if style: atts['style'] = ' '.join(style) atts['alt'] = node.get('alt', atts['src']) if (isinstance(node.parent, nodes.TextElement) or (isinstance(node.parent, nodes.reference) and not isinstance(node.parent.parent, nodes.TextElement))): # Inline context or surrounded by <a>...</a>. suffix = '' else: suffix = '\n' if node.has_key('align'): if node['align'] == 'center': # "align" attribute is set in surrounding "div" element. self.body.append('<div align="center" class="align-center">') self.context.append('</div>\n') suffix = '' else: # "align" attribute is set in "img" element. atts['align'] = node['align'] self.context.append('') atts['class'] = 'align-%s' % node['align'] else: self.context.append('') self.body.append(self.emptytag(node, 'img', suffix, **atts)) def depart_image(self, node): self.body.append(self.context.pop()) def visit_important(self, node): self.visit_admonition(node, 'important') def depart_important(self, node): self.depart_admonition() def visit_inline(self, node): self.body.append(self.starttag(node, 'span', '')) def depart_inline(self, node): self.body.append('</span>') def visit_label(self, node): self.body.append(self.starttag(node, 'td', '%s[' % self.context.pop(), CLASS='label')) def depart_label(self, node): self.body.append(']</a></td><td>%s' % self.context.pop()) def visit_legend(self, node): self.body.append(self.starttag(node, 'div', CLASS='legend')) def depart_legend(self, node): self.body.append('</div>\n') def visit_line(self, node): self.body.append(self.starttag(node, 'div', suffix='', CLASS='line')) if not len(node): self.body.append('<br />') def depart_line(self, node): self.body.append('</div>\n') def visit_line_block(self, node): self.body.append(self.starttag(node, 'div', CLASS='line-block')) def depart_line_block(self, node): self.body.append('</div>\n') def visit_list_item(self, node): self.body.append(self.starttag(node, 'li', '')) if len(node): node[0]['classes'].append('first') def depart_list_item(self, node): self.body.append('</li>\n') def visit_literal(self, node): """Process text to prevent tokens from wrapping.""" self.body.append( self.starttag(node, 'tt', '', CLASS='docutils literal')) text = node.astext() for token in self.words_and_spaces.findall(text): if token.strip(): # Protect text like "--an-option" from bad line wrapping: self.body.append('<span class="pre">%s</span>' % self.encode(token)) elif token in ('\n', ' '): # Allow breaks at whitespace: self.body.append(token) else: # Protect runs of multiple spaces; the last space can wrap: self.body.append('&nbsp;' * (len(token) - 1) + ' ') self.body.append('</tt>') # Content already processed: raise nodes.SkipNode def visit_literal_block(self, node): self.body.append(self.starttag(node, 'pre', CLASS='literal-block')) def depart_literal_block(self, node): self.body.append('\n</pre>\n') def visit_meta(self, node): meta = self.emptytag(node, 'meta', **node.non_default_attributes()) self.add_meta(meta) def depart_meta(self, node): pass def add_meta(self, tag): self.meta.append(tag) self.head.append(tag) def visit_note(self, node): self.visit_admonition(node, 'note') def depart_note(self, node): self.depart_admonition() def visit_option(self, node): if self.context[-1]: self.body.append(', ') self.body.append(self.starttag(node, 'span', '', CLASS='option')) def depart_option(self, node): self.body.append('</span>') self.context[-1] += 1 def visit_option_argument(self, node): self.body.append(node.get('delimiter', ' ')) self.body.append(self.starttag(node, 'var', '')) def depart_option_argument(self, node): self.body.append('</var>') def visit_option_group(self, node): atts = {} if ( self.settings.option_limit and len(node.astext()) > self.settings.option_limit): atts['colspan'] = 2 self.context.append('</tr>\n<tr><td>&nbsp;</td>') else: self.context.append('') self.body.append( self.starttag(node, 'td', CLASS='option-group', **atts)) self.body.append('<kbd>') self.context.append(0) # count number of options def depart_option_group(self, node): self.context.pop() self.body.append('</kbd></td>\n') self.body.append(self.context.pop()) def visit_option_list(self, node): self.body.append( self.starttag(node, 'table', CLASS='docutils option-list', frame="void", rules="none")) self.body.append('<col class="option" />\n' '<col class="description" />\n' '<tbody valign="top">\n') def depart_option_list(self, node): self.body.append('</tbody>\n</table>\n') def visit_option_list_item(self, node): self.body.append(self.starttag(node, 'tr', '')) def depart_option_list_item(self, node): self.body.append('</tr>\n') def visit_option_string(self, node): pass def depart_option_string(self, node): pass def visit_organization(self, node): self.visit_docinfo_item(node, 'organization') def depart_organization(self, node): self.depart_docinfo_item() def should_be_compact_paragraph(self, node): """ Determine if the <p> tags around paragraph ``node`` can be omitted. """ if (isinstance(node.parent, nodes.document) or isinstance(node.parent, nodes.compound)): # Never compact paragraphs in document or compound. return 0 for key, value in node.attlist(): if (node.is_not_default(key) and not (key == 'classes' and value in ([], ['first'], ['last'], ['first', 'last']))): # Attribute which needs to survive. return 0 first = isinstance(node.parent[0], nodes.label) # skip label for child in node.parent.children[first:]: # only first paragraph can be compact if isinstance(child, nodes.Invisible): continue if child is node: break return 0 if ( self.compact_simple or self.compact_field_list or (self.compact_p and (len(node.parent) == 1 or len(node.parent) == 2 and isinstance(node.parent[0], nodes.label)))): return 1 return 0 def visit_paragraph(self, node): if self.should_be_compact_paragraph(node): self.context.append('') else: self.body.append(self.starttag(node, 'p', '')) self.context.append('</p>\n') def depart_paragraph(self, node): self.body.append(self.context.pop()) def visit_problematic(self, node): if node.hasattr('refid'): self.body.append('<a href="#%s" name="%s">' % (node['refid'], node['ids'][0])) self.context.append('</a>') else: self.context.append('') self.body.append(self.starttag(node, 'span', '', CLASS='problematic')) def depart_problematic(self, node): self.body.append('</span>') self.body.append(self.context.pop()) def visit_raw(self, node): if 'html' in node.get('format', '').split(): t = isinstance(node.parent, nodes.TextElement) and 'span' or 'div' if node['classes']: self.body.append(self.starttag(node, t, suffix='')) self.body.append(node.astext()) if node['classes']: self.body.append('</%s>' % t) # Keep non-HTML raw text out of output: raise nodes.SkipNode def visit_reference(self, node): if node.has_key('refuri'): href = node['refuri'] if ( self.settings.cloak_email_addresses and href.startswith('mailto:')): href = self.cloak_mailto(href) self.in_mailto = 1 else: assert node.has_key('refid'), \ 'References must have "refuri" or "refid" attribute.' href = '#' + node['refid'] atts = {'href': href, 'class': 'reference'} if not isinstance(node.parent, nodes.TextElement): assert len(node) == 1 and isinstance(node[0], nodes.image) atts['class'] += ' image-reference' self.body.append(self.starttag(node, 'a', '', **atts)) def depart_reference(self, node): self.body.append('</a>') if not isinstance(node.parent, nodes.TextElement): self.body.append('\n') self.in_mailto = 0 def visit_revision(self, node): self.visit_docinfo_item(node, 'revision', meta=None) def depart_revision(self, node): self.depart_docinfo_item() def visit_row(self, node): self.body.append(self.starttag(node, 'tr', '')) node.column = 0 def depart_row(self, node): self.body.append('</tr>\n') def visit_rubric(self, node): self.body.append(self.starttag(node, 'p', '', CLASS='rubric')) def depart_rubric(self, node): self.body.append('</p>\n') def visit_section(self, node): self.section_level += 1 self.body.append( self.start_tag_with_title(node, 'div', CLASS='section')) def depart_section(self, node): self.section_level -= 1 self.body.append('</div>\n') def visit_sidebar(self, node): self.body.append( self.start_tag_with_title(node, 'div', CLASS='sidebar')) self.set_first_last(node) self.in_sidebar = 1 def depart_sidebar(self, node): self.body.append('</div>\n') self.in_sidebar = None def visit_status(self, node): self.visit_docinfo_item(node, 'status', meta=None) def depart_status(self, node): self.depart_docinfo_item() def visit_strong(self, node): self.body.append('<strong>') def depart_strong(self, node): self.body.append('</strong>') def visit_subscript(self, node): self.body.append(self.starttag(node, 'sub', '')) def depart_subscript(self, node): self.body.append('</sub>') def visit_substitution_definition(self, node): """Internal only.""" raise nodes.SkipNode def visit_substitution_reference(self, node): self.unimplemented_visit(node) def visit_subtitle(self, node): if isinstance(node.parent, nodes.sidebar): self.body.append(self.starttag(node, 'p', '', CLASS='sidebar-subtitle')) self.context.append('</p>\n') elif isinstance(node.parent, nodes.document): self.body.append(self.starttag(node, 'h2', '', CLASS='subtitle')) self.context.append('</h2>\n') self.in_document_title = len(self.body) elif isinstance(node.parent, nodes.section): tag = 'h%s' % (self.section_level + self.initial_header_level - 1) self.body.append( self.starttag(node, tag, '', CLASS='section-subtitle') + self.starttag({}, 'span', '', CLASS='section-subtitle')) self.context.append('</span></%s>\n' % tag) def depart_subtitle(self, node): self.body.append(self.context.pop()) if self.in_document_title: self.subtitle = self.body[self.in_document_title:-1] self.in_document_title = 0 self.body_pre_docinfo.extend(self.body) self.html_subtitle.extend(self.body) del self.body[:] def visit_superscript(self, node): self.body.append(self.starttag(node, 'sup', '')) def depart_superscript(self, node): self.body.append('</sup>') def visit_system_message(self, node): self.body.append(self.starttag(node, 'div', CLASS='system-message')) self.body.append('<p class="system-message-title">') attr = {} backref_text = '' if node['ids']: attr['name'] = node['ids'][0] if len(node['backrefs']): backrefs = node['backrefs'] if len(backrefs) == 1: backref_text = ('; <em><a href="#%s">backlink</a></em>' % backrefs[0]) else: i = 1 backlinks = [] for backref in backrefs: backlinks.append('<a href="#%s">%s</a>' % (backref, i)) i += 1 backref_text = ('; <em>backlinks: %s</em>' % ', '.join(backlinks)) if node.hasattr('line'): line = ', line %s' % node['line'] else: line = '' if attr: a_start = self.starttag({}, 'a', '', **attr) a_end = '</a>' else: a_start = a_end = '' self.body.append('System Message: %s%s/%s%s ' '(<tt class="docutils">%s</tt>%s)%s</p>\n' % (a_start, node['type'], node['level'], a_end, self.encode(node['source']), line, backref_text)) def depart_system_message(self, node): self.body.append('</div>\n') def visit_table(self, node): self.body.append( self.starttag(node, 'table', CLASS='docutils', border="1")) def depart_table(self, node): self.body.append('</table>\n') def visit_target(self, node): if not (node.has_key('refuri') or node.has_key('refid') or node.has_key('refname')): self.body.append(self.starttag(node, 'span', '', CLASS='target')) self.context.append('</span>') else: self.context.append('') def depart_target(self, node): self.body.append(self.context.pop()) def visit_tbody(self, node): self.write_colspecs() self.body.append(self.context.pop()) # '</colgroup>\n' or '' self.body.append(self.starttag(node, 'tbody', valign='top')) def depart_tbody(self, node): self.body.append('</tbody>\n') def visit_term(self, node): self.body.append(self.starttag(node, 'dt', '')) def depart_term(self, node): """ Leave the end tag to `self.visit_definition()`, in case there's a classifier. """ pass def visit_tgroup(self, node): # Mozilla needs <colgroup>: self.body.append(self.starttag(node, 'colgroup')) # Appended by thead or tbody: self.context.append('</colgroup>\n') node.stubs = [] def depart_tgroup(self, node): pass def visit_thead(self, node): self.write_colspecs() self.body.append(self.context.pop()) # '</colgroup>\n' # There may or may not be a <thead>; this is for <tbody> to use: self.context.append('') self.body.append(self.starttag(node, 'thead', valign='bottom')) def depart_thead(self, node): self.body.append('</thead>\n') def visit_tip(self, node): self.visit_admonition(node, 'tip') def depart_tip(self, node): self.depart_admonition() def visit_title(self, node, move_ids=1): """Only 6 section levels are supported by HTML.""" check_id = 0 close_tag = '</p>\n' if isinstance(node.parent, nodes.topic): self.body.append( self.starttag(node, 'p', '', CLASS='topic-title first')) check_id = 1 elif isinstance(node.parent, nodes.sidebar): self.body.append( self.starttag(node, 'p', '', CLASS='sidebar-title')) check_id = 1 elif isinstance(node.parent, nodes.Admonition): self.body.append( self.starttag(node, 'p', '', CLASS='admonition-title')) check_id = 1 elif isinstance(node.parent, nodes.table): self.body.append( self.starttag(node, 'caption', '')) check_id = 1 close_tag = '</caption>\n' elif isinstance(node.parent, nodes.document): self.body.append(self.starttag(node, 'h1', '', CLASS='title')) self.context.append('</h1>\n') self.in_document_title = len(self.body) else: assert isinstance(node.parent, nodes.section) h_level = self.section_level + self.initial_header_level - 1 atts = {} if (len(node.parent) >= 2 and isinstance(node.parent[1], nodes.subtitle)): atts['CLASS'] = 'with-subtitle' self.body.append( self.starttag(node, 'h%s' % h_level, '', **atts)) atts = {} # !!! conditional to be removed in Docutils 0.5: if move_ids: if node.parent['ids']: atts['ids'] = node.parent['ids'] if node.hasattr('refid'): atts['class'] = 'toc-backref' atts['href'] = '#' + node['refid'] if atts: self.body.append(self.starttag({}, 'a', '', **atts)) self.context.append('</a></h%s>\n' % (h_level)) else: self.context.append('</h%s>\n' % (h_level)) # !!! conditional to be removed in Docutils 0.5: if check_id: if node.parent['ids']: atts={'ids': node.parent['ids']} self.body.append( self.starttag({}, 'a', '', **atts)) self.context.append('</a>' + close_tag) else: self.context.append(close_tag) def depart_title(self, node): self.body.append(self.context.pop()) if self.in_document_title: self.title = self.body[self.in_document_title:-1] self.in_document_title = 0 self.body_pre_docinfo.extend(self.body) self.html_title.extend(self.body) del self.body[:] def visit_title_reference(self, node): self.body.append(self.starttag(node, 'cite', '')) def depart_title_reference(self, node): self.body.append('</cite>') def visit_topic(self, node): self.body.append(self.start_tag_with_title(node, 'div', CLASS='topic')) self.topic_classes = node['classes'] def depart_topic(self, node): self.body.append('</div>\n') self.topic_classes = [] def visit_transition(self, node): self.body.append(self.emptytag(node, 'hr', CLASS='docutils')) def depart_transition(self, node): pass def visit_version(self, node): self.visit_docinfo_item(node, 'version', meta=None) def depart_version(self, node): self.depart_docinfo_item() def visit_warning(self, node): self.visit_admonition(node, 'warning') def depart_warning(self, node): self.depart_admonition() def unimplemented_visit(self, node): raise NotImplementedError('visiting unimplemented node type: %s' % node.__class__.__name__) class SimpleListChecker(nodes.GenericNodeVisitor): """ Raise `nodes.NodeFound` if non-simple list item is encountered. Here "simple" means a list item containing nothing other than a single paragraph, a simple list, or a paragraph followed by a simple list. """ def default_visit(self, node): raise nodes.NodeFound def visit_bullet_list(self, node): pass def visit_enumerated_list(self, node): pass def visit_list_item(self, node): children = [] for child in node.children: if not isinstance(child, nodes.Invisible): children.append(child) if (children and isinstance(children[0], nodes.paragraph) and (isinstance(children[-1], nodes.bullet_list) or isinstance(children[-1], nodes.enumerated_list))): children.pop() if len(children) <= 1: return else: raise nodes.NodeFound def visit_paragraph(self, node): raise nodes.SkipNode def invisible_visit(self, node): """Invisible nodes should be ignored.""" raise nodes.SkipNode visit_comment = invisible_visit visit_substitution_definition = invisible_visit visit_target = invisible_visit visit_pending = invisible_visit
{ "repo_name": "epall/selenium", "path": "selenium/src/py/lib/docutils/writers/html4css1/__init__.py", "copies": "5", "size": "63101", "license": "apache-2.0", "hash": -1355694280750258700, "line_mean": 36.7122699387, "line_max": 79, "alpha_frac": 0.5349202073, "autogenerated": false, "ratio": 4.034590792838875, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7069511000138875, "avg_score": null, "num_lines": null }
""" Docutils document tree element class library. Classes in CamelCase are abstract base classes or auxiliary classes. The one exception is `Text`, for a text (PCDATA) node; uppercase is used to differentiate from element classes. Classes in lower_case_with_underscores are element classes, matching the XML element generic identifiers in the DTD_. The position of each node (the level at which it can occur) is significant and is represented by abstract base classes (`Root`, `Structural`, `Body`, `Inline`, etc.). Certain transformations will be easier because we can use ``isinstance(node, base_class)`` to determine the position of the node in the hierarchy. .. _DTD: http://docutils.sourceforge.net/docs/ref/docutils.dtd """ __docformat__ = 'reStructuredText' import sys import os import re import warnings from types import IntType, SliceType, StringType, UnicodeType, \ TupleType, ListType, ClassType from UserString import UserString # ============================== # Functional Node Base Classes # ============================== class Node: """Abstract base class of nodes in a document tree.""" parent = None """Back-reference to the Node immediately containing this Node.""" document = None """The `document` node at the root of the tree containing this Node.""" source = None """Path or description of the input source which generated this Node.""" line = None """The line number (1-based) of the beginning of this Node in `source`.""" def __nonzero__(self): """ Node instances are always true, even if they're empty. A node is more than a simple container. Its boolean "truth" does not depend on having one or more subnodes in the doctree. Use `len()` to check node length. Use `None` to represent a boolean false value. """ return 1 def asdom(self, dom=None): """Return a DOM **fragment** representation of this Node.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() return self._dom_node(domroot) def pformat(self, indent=' ', level=0): """ Return an indented pseudo-XML representation, for test purposes. Override in subclasses. """ raise NotImplementedError def copy(self): """Return a copy of self.""" raise NotImplementedError def deepcopy(self): """Return a deep copy of self (also copying children).""" raise NotImplementedError def setup_child(self, child): child.parent = self if self.document: child.document = self.document if child.source is None: child.source = self.document.current_source if child.line is None: child.line = self.document.current_line def walk(self, visitor): """ Traverse a tree of `Node` objects, calling the `dispatch_visit()` method of `visitor` when entering each node. (The `walkabout()` method is similar, except it also calls the `dispatch_departure()` method before exiting each node.) This tree traversal supports limited in-place tree modifications. Replacing one node with one or more nodes is OK, as is removing an element. However, if the node removed or replaced occurs after the current node, the old node will still be traversed, and any new nodes will not. Within ``visit`` methods (and ``depart`` methods for `walkabout()`), `TreePruningException` subclasses may be raised (`SkipChildren`, `SkipSiblings`, `SkipNode`, `SkipDeparture`). Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` implementation for each `Node` subclass encountered. """ visitor.document.reporter.debug( 'docutils.nodes.Node.walk calling dispatch_visit for %s' % self.__class__.__name__) try: visitor.dispatch_visit(self) except (SkipChildren, SkipNode): return except SkipDeparture: # not applicable; ignore pass children = self.children try: for child in children[:]: child.walk(visitor) except SkipSiblings: pass def walkabout(self, visitor): """ Perform a tree traversal similarly to `Node.walk()` (which see), except also call the `dispatch_departure()` method before exiting each node. Parameter `visitor`: A `NodeVisitor` object, containing a ``visit`` and ``depart`` implementation for each `Node` subclass encountered. """ call_depart = 1 visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_visit for %s' % self.__class__.__name__) try: try: visitor.dispatch_visit(self) except SkipNode: return except SkipDeparture: call_depart = 0 children = self.children try: for child in children[:]: child.walkabout(visitor) except SkipSiblings: pass except SkipChildren: pass if call_depart: visitor.document.reporter.debug( 'docutils.nodes.Node.walkabout calling dispatch_departure ' 'for %s' % self.__class__.__name__) visitor.dispatch_departure(self) def traverse(self, condition=None, include_self=1, descend=1, siblings=0, ascend=0): """ Return an iterable containing * self (if include_self is true) * all descendants in tree traversal order (if descend is true) * all siblings (if siblings is true) and their descendants (if also descend is true) * the siblings of the parent (if ascend is true) and their descendants (if also descend is true), and so on If `condition` is not None, the iterable contains only nodes for which ``condition(node)`` is true. If `condition` is a node class ``cls``, it is equivalent to a function consisting of ``return isinstance(node, cls)``. If ascend is true, assume siblings to be true as well. For example, given the following tree:: <paragraph> <emphasis> <--- emphasis.traverse() and <strong> <--- strong.traverse() are called. Foo Bar <reference name="Baz" refid="baz"> Baz Then list(emphasis.traverse()) equals :: [<emphasis>, <strong>, <#text: Foo>, <#text: Bar>] and list(strong.traverse(ascend=1)) equals :: [<strong>, <#text: Foo>, <#text: Bar>, <reference>, <#text: Baz>] """ r = [] if ascend: siblings=1 if isinstance(condition, ClassType): node_class = condition def condition(node, node_class=node_class): return isinstance(node, node_class) if include_self and (condition is None or condition(self)): r.append(self) if descend and len(self.children): for child in self: r.extend(child.traverse( include_self=1, descend=1, siblings=0, ascend=0, condition=condition)) if siblings or ascend: node = self while node.parent: index = node.parent.index(node) for sibling in node.parent[index+1:]: r.extend(sibling.traverse(include_self=1, descend=descend, siblings=0, ascend=0, condition=condition)) if not ascend: break else: node = node.parent return r def next_node(self, condition=None, include_self=0, descend=1, siblings=0, ascend=0): """ Return the first node in the iterable returned by traverse(), or None if the iterable is empty. Parameter list is the same as of traverse. Note that include_self defaults to 0, though. """ iterable = self.traverse(condition=condition, include_self=include_self, descend=descend, siblings=siblings, ascend=ascend) try: return iterable[0] except IndexError: return None class Text(Node, UserString): """ Instances are terminal nodes (leaves) containing text only; no child nodes or attributes. Initialize by passing a string to the constructor. Access the text itself with the `astext` method. """ tagname = '#text' children = () """Text nodes have no children, and cannot have children.""" def __init__(self, data, rawsource=''): UserString.__init__(self, data) self.rawsource = rawsource """The raw text from which this element was constructed.""" def __repr__(self): data = repr(self.data) if len(data) > 70: data = repr(self.data[:64] + ' ...') return '<%s: %s>' % (self.tagname, data) def __len__(self): return len(self.data) def shortrepr(self): data = repr(self.data) if len(data) > 20: data = repr(self.data[:16] + ' ...') return '<%s: %s>' % (self.tagname, data) def _dom_node(self, domroot): return domroot.createTextNode(self.data) def astext(self): return self.data def copy(self): return self.__class__(self.data) def deepcopy(self): return self.copy() def pformat(self, indent=' ', level=0): result = [] indent = indent * level for line in self.data.splitlines(): result.append(indent + line + '\n') return ''.join(result) class Element(Node): """ `Element` is the superclass to all specific elements. Elements contain attributes and child nodes. Elements emulate dictionaries for attributes, indexing by attribute name (a string). To set the attribute 'att' to 'value', do:: element['att'] = 'value' There are two special attributes: 'ids' and 'names'. Both are lists of unique identifiers, and names serve as human interfaces to IDs. Names are case- and whitespace-normalized (see the fully_normalize_name() function), and IDs conform to the regular expression ``[a-z](-?[a-z0-9]+)*`` (see the make_id() function). Elements also emulate lists for child nodes (element nodes and/or text nodes), indexing by integer. To get the first child node, use:: element[0] Elements may be constructed using the ``+=`` operator. To add one new child node to element, do:: element += node This is equivalent to ``element.append(node)``. To add a list of multiple child nodes at once, use the same ``+=`` operator:: element += [node1, node2] This is equivalent to ``element.extend([node1, node2])``. """ list_attributes = ('ids', 'classes', 'names', 'dupnames', 'backrefs') """List attributes, automatically initialized to empty lists for all nodes.""" tagname = None """The element generic identifier. If None, it is set as an instance attribute to the name of the class.""" child_text_separator = '\n\n' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', *children, **attributes): self.rawsource = rawsource """The raw text from which this element was constructed.""" self.children = [] """List of child nodes (elements and/or `Text`).""" self.extend(children) # maintain parent info self.attributes = {} """Dictionary of attribute {name: value}.""" # Initialize list attributes. for att in self.list_attributes: self.attributes[att] = [] for att, value in attributes.items(): att = att.lower() if att in self.list_attributes: # mutable list; make a copy for this node self.attributes[att] = value[:] else: self.attributes[att] = value if self.tagname is None: self.tagname = self.__class__.__name__ def _dom_node(self, domroot): element = domroot.createElement(self.tagname) for attribute, value in self.attlist(): if isinstance(value, ListType): value = ' '.join([serial_escape('%s' % v) for v in value]) element.setAttribute(attribute, '%s' % value) for child in self.children: element.appendChild(child._dom_node(domroot)) return element def __repr__(self): data = '' for c in self.children: data += c.shortrepr() if len(data) > 60: data = data[:56] + ' ...' break if self['names']: return '<%s "%s": %s>' % (self.__class__.__name__, '; '.join(self['names']), data) else: return '<%s: %s>' % (self.__class__.__name__, data) def shortrepr(self): if self['names']: return '<%s "%s"...>' % (self.__class__.__name__, '; '.join(self['names'])) else: return '<%s...>' % self.tagname def __str__(self): return self.__unicode__().encode('raw_unicode_escape') def __unicode__(self): if self.children: return u'%s%s%s' % (self.starttag(), ''.join([str(c) for c in self.children]), self.endtag()) else: return self.emptytag() def starttag(self): parts = [self.tagname] for name, value in self.attlist(): if value is None: # boolean attribute parts.append(name) elif isinstance(value, ListType): values = [serial_escape('%s' % v) for v in value] parts.append('%s="%s"' % (name, ' '.join(values))) else: parts.append('%s="%s"' % (name, value)) return '<%s>' % ' '.join(parts) def endtag(self): return '</%s>' % self.tagname def emptytag(self): return u'<%s/>' % ' '.join([self.tagname] + ['%s="%s"' % (n, v) for n, v in self.attlist()]) def __len__(self): return len(self.children) def __getitem__(self, key): if isinstance(key, UnicodeType) or isinstance(key, StringType): return self.attributes[key] elif isinstance(key, IntType): return self.children[key] elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' return self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __setitem__(self, key, item): if isinstance(key, UnicodeType) or isinstance(key, StringType): self.attributes[str(key)] = item elif isinstance(key, IntType): self.setup_child(item) self.children[key] = item elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' for node in item: self.setup_child(node) self.children[key.start:key.stop] = item else: raise TypeError, ('element index must be an integer, a slice, or ' 'an attribute name string') def __delitem__(self, key): if isinstance(key, UnicodeType) or isinstance(key, StringType): del self.attributes[key] elif isinstance(key, IntType): del self.children[key] elif isinstance(key, SliceType): assert key.step in (None, 1), 'cannot handle slice with stride' del self.children[key.start:key.stop] else: raise TypeError, ('element index must be an integer, a simple ' 'slice, or an attribute name string') def __add__(self, other): return self.children + other def __radd__(self, other): return other + self.children def __iadd__(self, other): """Append a node or a list of nodes to `self.children`.""" if isinstance(other, Node): self.append(other) elif other is not None: self.extend(other) return self def astext(self): return self.child_text_separator.join( [child.astext() for child in self.children]) def non_default_attributes(self): atts = {} for key, value in self.attributes.items(): if self.is_not_default(key): atts[key] = value return atts def attlist(self): attlist = self.non_default_attributes().items() attlist.sort() return attlist def get(self, key, failobj=None): return self.attributes.get(key, failobj) def hasattr(self, attr): return self.attributes.has_key(attr) def delattr(self, attr): if self.attributes.has_key(attr): del self.attributes[attr] def setdefault(self, key, failobj=None): return self.attributes.setdefault(key, failobj) has_key = hasattr def append(self, item): self.setup_child(item) self.children.append(item) def extend(self, item): for node in item: self.append(node) def insert(self, index, item): if isinstance(item, Node): self.setup_child(item) self.children.insert(index, item) elif item is not None: self[index:index] = item def pop(self, i=-1): return self.children.pop(i) def remove(self, item): self.children.remove(item) def index(self, item): return self.children.index(item) def is_not_default(self, key): if self[key] == [] and key in self.list_attributes: return 0 else: return 1 def update_basic_atts(self, dict): """ Update basic attributes ('ids', 'names', 'classes', 'dupnames', but not 'source') from node or dictionary `dict`. """ if isinstance(dict, Node): dict = dict.attributes for att in ('ids', 'classes', 'names', 'dupnames'): for value in dict.get(att, []): if not value in self[att]: self[att].append(value) def clear(self): self.children = [] def replace(self, old, new): """Replace one child `Node` with another child or children.""" index = self.index(old) if isinstance(new, Node): self.setup_child(new) self[index] = new elif new is not None: self[index:index+1] = new def replace_self(self, new): """ Replace `self` node with `new`, where `new` is a node or a list of nodes. """ update = new if not isinstance(new, Node): # `new` is a list; update first child. try: update = new[0] except IndexError: update = None if isinstance(update, Element): update.update_basic_atts(self) else: # `update` is a Text node or `new` is an empty list. # Assert that we aren't losing any attributes. for att in ('ids', 'names', 'classes', 'dupnames'): assert not self[att], \ 'Losing "%s" attribute: %s' % (att, self[att]) self.parent.replace(self, new) def first_child_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class exactly matches. Parameters: - `childclass`: A `Node` subclass to search for, or a tuple of `Node` classes. If a tuple, any of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, TupleType): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self[index], c): return index return None def first_child_not_matching_class(self, childclass, start=0, end=sys.maxint): """ Return the index of the first child whose class does *not* match. Parameters: - `childclass`: A `Node` subclass to skip, or a tuple of `Node` classes. If a tuple, none of the classes may match. - `start`: Initial index to check. - `end`: Initial index to *not* check. """ if not isinstance(childclass, TupleType): childclass = (childclass,) for index in range(start, min(len(self), end)): for c in childclass: if isinstance(self.children[index], c): break else: return index return None def pformat(self, indent=' ', level=0): return ''.join(['%s%s\n' % (indent * level, self.starttag())] + [child.pformat(indent, level+1) for child in self.children]) def copy(self): return self.__class__(**self.attributes) def deepcopy(self): copy = self.copy() copy.extend([child.deepcopy() for child in self.children]) return copy def set_class(self, name): """Add a new class to the "classes" attribute.""" warnings.warn('docutils.nodes.Element.set_class deprecated; ' "append to Element['classes'] list attribute directly", DeprecationWarning, stacklevel=2) assert ' ' not in name self['classes'].append(name.lower()) def note_referenced_by(self, name=None, id=None): """Note that this Element has been referenced by its name `name` or id `id`.""" self.referenced = 1 # Element.expect_referenced_by_* dictionaries map names or ids # to nodes whose ``referenced`` attribute is set to true as # soon as this node is referenced by the given name or id. # Needed for target propagation. by_name = getattr(self, 'expect_referenced_by_name', {}).get(name) by_id = getattr(self, 'expect_referenced_by_id', {}).get(id) if by_name: assert name is not None by_name.referenced = 1 if by_id: assert id is not None by_id.referenced = 1 class TextElement(Element): """ An element which directly contains text. Its children are all `Text` or `Inline` subclass nodes. You can check whether an element's context is inline simply by checking whether its immediate parent is a `TextElement` instance (including subclasses). This is handy for nodes like `image` that can appear both inline and as standalone body elements. If passing children to `__init__()`, make sure to set `text` to ``''`` or some other suitable value. """ child_text_separator = '' """Separator for child nodes, used by `astext()` method.""" def __init__(self, rawsource='', text='', *children, **attributes): if text != '': textnode = Text(text) Element.__init__(self, rawsource, textnode, *children, **attributes) else: Element.__init__(self, rawsource, *children, **attributes) class FixedTextElement(TextElement): """An element which directly contains preformatted text.""" def __init__(self, rawsource='', text='', *children, **attributes): TextElement.__init__(self, rawsource, text, *children, **attributes) self.attributes['xml:space'] = 'preserve' # ======== # Mixins # ======== class Resolvable: resolved = 0 class BackLinkable: def add_backref(self, refid): self['backrefs'].append(refid) # ==================== # Element Categories # ==================== class Root: pass class Titular: pass class PreBibliographic: """Category of Node which may occur before Bibliographic Nodes.""" class Bibliographic: pass class Decorative(PreBibliographic): pass class Structural: pass class Body: pass class General(Body): pass class Sequential(Body): """List-like elements.""" class Admonition(Body): pass class Special(Body): """Special internal body elements.""" class Invisible(PreBibliographic): """Internal elements that don't appear in output.""" class Part: pass class Inline: pass class Referential(Resolvable): pass class Targetable(Resolvable): referenced = 0 indirect_reference_name = None """Holds the whitespace_normalized_name (contains mixed case) of a target. Required for MoinMoin/reST compatibility.""" class Labeled: """Contains a `label` as its first element.""" # ============== # Root Element # ============== class document(Root, Structural, Element): """ The document root element. Do not instantiate this class directly; use `docutils.utils.new_document()` instead. """ def __init__(self, settings, reporter, *args, **kwargs): Element.__init__(self, *args, **kwargs) self.current_source = None """Path to or description of the input source being processed.""" self.current_line = None """Line number (1-based) of `current_source`.""" self.settings = settings """Runtime settings data record.""" self.reporter = reporter """System message generator.""" self.indirect_targets = [] """List of indirect target nodes.""" self.substitution_defs = {} """Mapping of substitution names to substitution_definition nodes.""" self.substitution_names = {} """Mapping of case-normalized substitution names to case-sensitive names.""" self.refnames = {} """Mapping of names to lists of referencing nodes.""" self.refids = {} """Mapping of ids to lists of referencing nodes.""" self.nameids = {} """Mapping of names to unique id's.""" self.nametypes = {} """Mapping of names to hyperlink type (boolean: True => explicit, False => implicit.""" self.ids = {} """Mapping of ids to nodes.""" self.footnote_refs = {} """Mapping of footnote labels to lists of footnote_reference nodes.""" self.citation_refs = {} """Mapping of citation labels to lists of citation_reference nodes.""" self.autofootnotes = [] """List of auto-numbered footnote nodes.""" self.autofootnote_refs = [] """List of auto-numbered footnote_reference nodes.""" self.symbol_footnotes = [] """List of symbol footnote nodes.""" self.symbol_footnote_refs = [] """List of symbol footnote_reference nodes.""" self.footnotes = [] """List of manually-numbered footnote nodes.""" self.citations = [] """List of citation nodes.""" self.autofootnote_start = 1 """Initial auto-numbered footnote number.""" self.symbol_footnote_start = 0 """Initial symbol footnote symbol index.""" self.id_start = 1 """Initial ID number.""" self.parse_messages = [] """System messages generated while parsing.""" self.transform_messages = [] """System messages generated while applying transforms.""" import docutils.transforms self.transformer = docutils.transforms.Transformer(self) """Storage for transforms to be applied to this document.""" self.decoration = None """Document's `decoration` node.""" self.document = self def __getstate__(self): """ Return dict with unpicklable references removed. """ state = self.__dict__.copy() state['reporter'] = None state['transformer'] = None return state def asdom(self, dom=None): """Return a DOM representation of this document.""" if dom is None: import xml.dom.minidom as dom domroot = dom.Document() domroot.appendChild(self._dom_node(domroot)) return domroot def set_id(self, node, msgnode=None): for id in node['ids']: if self.ids.has_key(id) and self.ids[id] is not node: msg = self.reporter.severe('Duplicate ID: "%s".' % id) if msgnode != None: msgnode += msg if not node['ids']: for name in node['names']: id = self.settings.id_prefix + make_id(name) if id and not self.ids.has_key(id): break else: id = '' while not id or self.ids.has_key(id): id = (self.settings.id_prefix + self.settings.auto_id_prefix + str(self.id_start)) self.id_start += 1 node['ids'].append(id) self.ids[id] = node return id def set_name_id_map(self, node, id, msgnode=None, explicit=None): """ `self.nameids` maps names to IDs, while `self.nametypes` maps names to booleans representing hyperlink type (True==explicit, False==implicit). This method updates the mappings. The following state transition table shows how `self.nameids` ("ids") and `self.nametypes` ("types") change with new input (a call to this method), and what actions are performed ("implicit"-type system messages are INFO/1, and "explicit"-type system messages are ERROR/3): ==== ===== ======== ======== ======= ==== ===== ===== Old State Input Action New State Notes ----------- -------- ----------------- ----------- ----- ids types new type sys.msg. dupname ids types ==== ===== ======== ======== ======= ==== ===== ===== - - explicit - - new True - - implicit - - new False None False explicit - - new True old False explicit implicit old new True None True explicit explicit new None True old True explicit explicit new,old None True [#]_ None False implicit implicit new None False old False implicit implicit new,old None False None True implicit implicit new None True old True implicit implicit new old True ==== ===== ======== ======== ======= ==== ===== ===== .. [#] Do not clear the name-to-id map or invalidate the old target if both old and new targets are external and refer to identical URIs. The new target is invalidated regardless. """ for name in node['names']: if self.nameids.has_key(name): self.set_duplicate_name_id(node, id, name, msgnode, explicit) else: self.nameids[name] = id self.nametypes[name] = explicit def set_duplicate_name_id(self, node, id, name, msgnode, explicit): old_id = self.nameids[name] old_explicit = self.nametypes[name] self.nametypes[name] = old_explicit or explicit if explicit: if old_explicit: level = 2 if old_id is not None: old_node = self.ids[old_id] if node.has_key('refuri'): refuri = node['refuri'] if old_node['names'] \ and old_node.has_key('refuri') \ and old_node['refuri'] == refuri: level = 1 # just inform if refuri's identical if level > 1: dupname(old_node, name) self.nameids[name] = None msg = self.reporter.system_message( level, 'Duplicate explicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg dupname(node, name) else: self.nameids[name] = id if old_id is not None: old_node = self.ids[old_id] dupname(old_node, name) else: if old_id is not None and not old_explicit: self.nameids[name] = None old_node = self.ids[old_id] dupname(old_node, name) dupname(node, name) if not explicit or (not old_explicit and old_id is not None): msg = self.reporter.info( 'Duplicate implicit target name: "%s".' % name, backrefs=[id], base_node=node) if msgnode != None: msgnode += msg def has_name(self, name): return self.nameids.has_key(name) # "note" here is an imperative verb: "take note of". def note_implicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=None) def note_explicit_target(self, target, msgnode=None): id = self.set_id(target, msgnode) self.set_name_id_map(target, id, msgnode, explicit=1) def note_refname(self, node): self.refnames.setdefault(node['refname'], []).append(node) def note_refid(self, node): self.refids.setdefault(node['refid'], []).append(node) def note_indirect_target(self, target): self.indirect_targets.append(target) if target['names']: self.note_refname(target) def note_anonymous_target(self, target): self.set_id(target) def note_autofootnote(self, footnote): self.set_id(footnote) self.autofootnotes.append(footnote) def note_autofootnote_ref(self, ref): self.set_id(ref) self.autofootnote_refs.append(ref) def note_symbol_footnote(self, footnote): self.set_id(footnote) self.symbol_footnotes.append(footnote) def note_symbol_footnote_ref(self, ref): self.set_id(ref) self.symbol_footnote_refs.append(ref) def note_footnote(self, footnote): self.set_id(footnote) self.footnotes.append(footnote) def note_footnote_ref(self, ref): self.set_id(ref) self.footnote_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_citation(self, citation): self.citations.append(citation) def note_citation_ref(self, ref): self.set_id(ref) self.citation_refs.setdefault(ref['refname'], []).append(ref) self.note_refname(ref) def note_substitution_def(self, subdef, def_name, msgnode=None): name = whitespace_normalize_name(def_name) if self.substitution_defs.has_key(name): msg = self.reporter.error( 'Duplicate substitution definition name: "%s".' % name, base_node=subdef) if msgnode != None: msgnode += msg oldnode = self.substitution_defs[name] dupname(oldnode, name) # keep only the last definition: self.substitution_defs[name] = subdef # case-insensitive mapping: self.substitution_names[fully_normalize_name(name)] = name def note_substitution_ref(self, subref, refname): subref['refname'] = whitespace_normalize_name(refname) def note_pending(self, pending, priority=None): self.transformer.add_pending(pending, priority) def note_parse_message(self, message): self.parse_messages.append(message) def note_transform_message(self, message): self.transform_messages.append(message) def note_source(self, source, offset): self.current_source = source if offset is None: self.current_line = offset else: self.current_line = offset + 1 def copy(self): return self.__class__(self.settings, self.reporter, **self.attributes) def get_decoration(self): if not self.decoration: self.decoration = decoration() index = self.first_child_not_matching_class(Titular) if index is None: self.append(self.decoration) else: self.insert(index, self.decoration) return self.decoration # ================ # Title Elements # ================ class title(Titular, PreBibliographic, TextElement): pass class subtitle(Titular, PreBibliographic, TextElement): pass class rubric(Titular, TextElement): pass # ======================== # Bibliographic Elements # ======================== class docinfo(Bibliographic, Element): pass class author(Bibliographic, TextElement): pass class authors(Bibliographic, Element): pass class organization(Bibliographic, TextElement): pass class address(Bibliographic, FixedTextElement): pass class contact(Bibliographic, TextElement): pass class version(Bibliographic, TextElement): pass class revision(Bibliographic, TextElement): pass class status(Bibliographic, TextElement): pass class date(Bibliographic, TextElement): pass class copyright(Bibliographic, TextElement): pass # ===================== # Decorative Elements # ===================== class decoration(Decorative, Element): def get_header(self): if not len(self.children) or not isinstance(self.children[0], header): self.insert(0, header()) return self.children[0] def get_footer(self): if not len(self.children) or not isinstance(self.children[-1], footer): self.append(footer()) return self.children[-1] class header(Decorative, Element): pass class footer(Decorative, Element): pass # ===================== # Structural Elements # ===================== class section(Structural, Element): pass class topic(Structural, Element): """ Topics are terminal, "leaf" mini-sections, like block quotes with titles, or textual figures. A topic is just like a section, except that it has no subsections, and it doesn't have to conform to section placement rules. Topics are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Topics cannot nest inside topics, sidebars, or body elements; you can't have a topic inside a table, list, block quote, etc. """ class sidebar(Structural, Element): """ Sidebars are like miniature, parallel documents that occur inside other documents, providing related or reference material. A sidebar is typically offset by a border and "floats" to the side of the page; the document's main text may flow around it. Sidebars can also be likened to super-footnotes; their content is outside of the flow of the document's main text. Sidebars are allowed wherever body elements (list, table, etc.) are allowed, but only at the top level of a section or document. Sidebars cannot nest inside sidebars, topics, or body elements; you can't have a sidebar inside a table, list, block quote, etc. """ class transition(Structural, Element): pass # =============== # Body Elements # =============== class paragraph(General, TextElement): pass class compound(General, Element): pass class container(General, Element): pass class bullet_list(Sequential, Element): pass class enumerated_list(Sequential, Element): pass class list_item(Part, Element): pass class definition_list(Sequential, Element): pass class definition_list_item(Part, Element): pass class term(Part, TextElement): pass class classifier(Part, TextElement): pass class definition(Part, Element): pass class field_list(Sequential, Element): pass class field(Part, Element): pass class field_name(Part, TextElement): pass class field_body(Part, Element): pass class option(Part, Element): child_text_separator = '' class option_argument(Part, TextElement): def astext(self): return self.get('delimiter', ' ') + TextElement.astext(self) class option_group(Part, Element): child_text_separator = ', ' class option_list(Sequential, Element): pass class option_list_item(Part, Element): child_text_separator = ' ' class option_string(Part, TextElement): pass class description(Part, Element): pass class literal_block(General, FixedTextElement): pass class doctest_block(General, FixedTextElement): pass class line_block(General, Element): pass class line(Part, TextElement): indent = None class block_quote(General, Element): pass class attribution(Part, TextElement): pass class attention(Admonition, Element): pass class caution(Admonition, Element): pass class danger(Admonition, Element): pass class error(Admonition, Element): pass class important(Admonition, Element): pass class note(Admonition, Element): pass class tip(Admonition, Element): pass class hint(Admonition, Element): pass class warning(Admonition, Element): pass class admonition(Admonition, Element): pass class comment(Special, Invisible, FixedTextElement): pass class substitution_definition(Special, Invisible, TextElement): pass class target(Special, Invisible, Inline, TextElement, Targetable): pass class footnote(General, BackLinkable, Element, Labeled, Targetable): pass class citation(General, BackLinkable, Element, Labeled, Targetable): pass class label(Part, TextElement): pass class figure(General, Element): pass class caption(Part, TextElement): pass class legend(Part, Element): pass class table(General, Element): pass class tgroup(Part, Element): pass class colspec(Part, Element): pass class thead(Part, Element): pass class tbody(Part, Element): pass class row(Part, Element): pass class entry(Part, Element): pass class system_message(Special, BackLinkable, PreBibliographic, Element): """ System message element. Do not instantiate this class directly; use ``document.reporter.info/warning/error/severe()`` instead. """ def __init__(self, message=None, *children, **attributes): if message: p = paragraph('', message) children = (p,) + children try: Element.__init__(self, '', *children, **attributes) except: print 'system_message: children=%r' % (children,) raise def astext(self): line = self.get('line', '') return u'%s:%s: (%s/%s) %s' % (self['source'], line, self['type'], self['level'], Element.astext(self)) class pending(Special, Invisible, Element): """ The "pending" element is used to encapsulate a pending operation: the operation (transform), the point at which to apply it, and any data it requires. Only the pending operation's location within the document is stored in the public document tree (by the "pending" object itself); the operation and its data are stored in the "pending" object's internal instance attributes. For example, say you want a table of contents in your reStructuredText document. The easiest way to specify where to put it is from within the document, with a directive:: .. contents:: But the "contents" directive can't do its work until the entire document has been parsed and possibly transformed to some extent. So the directive code leaves a placeholder behind that will trigger the second phase of its processing, something like this:: <pending ...public attributes...> + internal attributes Use `document.note_pending()` so that the `docutils.transforms.Transformer` stage of processing can run all pending transforms. """ def __init__(self, transform, details=None, rawsource='', *children, **attributes): Element.__init__(self, rawsource, *children, **attributes) self.transform = transform """The `docutils.transforms.Transform` class implementing the pending operation.""" self.details = details or {} """Detail data (dictionary) required by the pending operation.""" def pformat(self, indent=' ', level=0): internals = [ '.. internal attributes:', ' .transform: %s.%s' % (self.transform.__module__, self.transform.__name__), ' .details:'] details = self.details.items() details.sort() for key, value in details: if isinstance(value, Node): internals.append('%7s%s:' % ('', key)) internals.extend(['%9s%s' % ('', line) for line in value.pformat().splitlines()]) elif value and isinstance(value, ListType) \ and isinstance(value[0], Node): internals.append('%7s%s:' % ('', key)) for v in value: internals.extend(['%9s%s' % ('', line) for line in v.pformat().splitlines()]) else: internals.append('%7s%s: %r' % ('', key, value)) return (Element.pformat(self, indent, level) + ''.join([(' %s%s\n' % (indent * level, line)) for line in internals])) def copy(self): return self.__class__(self.transform, self.details, self.rawsource, **self.attributes) class raw(Special, Inline, PreBibliographic, FixedTextElement): """ Raw data that is to be passed untouched to the Writer. """ pass # ================= # Inline Elements # ================= class emphasis(Inline, TextElement): pass class strong(Inline, TextElement): pass class literal(Inline, TextElement): pass class reference(General, Inline, Referential, TextElement): pass class footnote_reference(Inline, Referential, TextElement): pass class citation_reference(Inline, Referential, TextElement): pass class substitution_reference(Inline, TextElement): pass class title_reference(Inline, TextElement): pass class abbreviation(Inline, TextElement): pass class acronym(Inline, TextElement): pass class superscript(Inline, TextElement): pass class subscript(Inline, TextElement): pass class image(General, Inline, Element): def astext(self): return self.get('alt', '') class inline(Inline, TextElement): pass class problematic(Inline, TextElement): pass class generated(Inline, TextElement): pass # ======================================== # Auxiliary Classes, Functions, and Data # ======================================== node_class_names = """ Text abbreviation acronym address admonition attention attribution author authors block_quote bullet_list caption caution citation citation_reference classifier colspec comment compound contact container copyright danger date decoration definition definition_list definition_list_item description docinfo doctest_block document emphasis entry enumerated_list error field field_body field_list field_name figure footer footnote footnote_reference generated header hint image important inline label legend line line_block list_item literal literal_block note option option_argument option_group option_list option_list_item option_string organization paragraph pending problematic raw reference revision row rubric section sidebar status strong subscript substitution_definition substitution_reference subtitle superscript system_message table target tbody term tgroup thead tip title title_reference topic transition version warning""".split() """A list of names of all concrete Node subclasses.""" class NodeVisitor: """ "Visitor" pattern [GoF95]_ abstract superclass implementation for document tree traversals. Each node class has corresponding methods, doing nothing by default; override individual methods for specific and useful behaviour. The `dispatch_visit()` method is called by `Node.walk()` upon entering a node. `Node.walkabout()` also calls the `dispatch_departure()` method before exiting a node. The dispatch methods call "``visit_`` + node class name" or "``depart_`` + node class name", resp. This is a base class for visitors whose ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types encountered (such as for `docutils.writers.Writer` subclasses). Unimplemented methods will raise exceptions. For sparse traversals, where only certain node types are of interest, subclass `SparseNodeVisitor` instead. When (mostly or entirely) uniform processing is desired, subclass `GenericNodeVisitor`. .. [GoF95] Gamma, Helm, Johnson, Vlissides. *Design Patterns: Elements of Reusable Object-Oriented Software*. Addison-Wesley, Reading, MA, USA, 1995. """ optional = () """ Tuple containing node class names (as strings). No exception will be raised if writers do not implement visit or departure functions for these node classes. Used to ensure transitional compatibility with existing 3rd-party writers. """ def __init__(self, document): self.document = document def dispatch_visit(self, node): """ Call self."``visit_`` + node class name" with `node` as parameter. If the ``visit_...`` method does not exist, call self.unknown_visit. """ node_name = node.__class__.__name__ method = getattr(self, 'visit_' + node_name, self.unknown_visit) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_visit calling %s for %s' % (method.__name__, node_name)) return method(node) def dispatch_departure(self, node): """ Call self."``depart_`` + node class name" with `node` as parameter. If the ``depart_...`` method does not exist, call self.unknown_departure. """ node_name = node.__class__.__name__ method = getattr(self, 'depart_' + node_name, self.unknown_departure) self.document.reporter.debug( 'docutils.nodes.NodeVisitor.dispatch_departure calling %s for %s' % (method.__name__, node_name)) return method(node) def unknown_visit(self, node): """ Called when entering unknown `Node` types. Raise an exception unless overridden. """ if (node.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s visiting unknown node type: %s' % (self.__class__, node.__class__.__name__)) def unknown_departure(self, node): """ Called before exiting unknown `Node` types. Raise exception unless overridden. """ if (node.document.settings.strict_visitor or node.__class__.__name__ not in self.optional): raise NotImplementedError( '%s departing unknown node type: %s' % (self.__class__, node.__class__.__name__)) class SparseNodeVisitor(NodeVisitor): """ Base class for sparse traversals, where only certain node types are of interest. When ``visit_...`` & ``depart_...`` methods should be implemented for *all* node types (such as for `docutils.writers.Writer` subclasses), subclass `NodeVisitor` instead. """ class GenericNodeVisitor(NodeVisitor): """ Generic "Visitor" abstract superclass, for simple traversals. Unless overridden, each ``visit_...`` method calls `default_visit()`, and each ``depart_...`` method (when using `Node.walkabout()`) calls `default_departure()`. `default_visit()` (and `default_departure()`) must be overridden in subclasses. Define fully generic visitors by overriding `default_visit()` (and `default_departure()`) only. Define semi-generic visitors by overriding individual ``visit_...()`` (and ``depart_...()``) methods also. `NodeVisitor.unknown_visit()` (`NodeVisitor.unknown_departure()`) should be overridden for default behavior. """ def default_visit(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def default_departure(self, node): """Override for generic, uniform traversals.""" raise NotImplementedError def _call_default_visit(self, node): self.default_visit(node) def _call_default_departure(self, node): self.default_departure(node) def _nop(self, node): pass def _add_node_class_names(names): """Save typing with dynamic assignments:""" for _name in names: setattr(GenericNodeVisitor, "visit_" + _name, _call_default_visit) setattr(GenericNodeVisitor, "depart_" + _name, _call_default_departure) setattr(SparseNodeVisitor, 'visit_' + _name, _nop) setattr(SparseNodeVisitor, 'depart_' + _name, _nop) _add_node_class_names(node_class_names) class TreeCopyVisitor(GenericNodeVisitor): """ Make a complete copy of a tree or branch, including element attributes. """ def __init__(self, document): GenericNodeVisitor.__init__(self, document) self.parent_stack = [] self.parent = [] def get_tree_copy(self): return self.parent[0] def default_visit(self, node): """Copy the current node, and make it the new acting parent.""" newnode = node.copy() self.parent.append(newnode) self.parent_stack.append(self.parent) self.parent = newnode def default_departure(self, node): """Restore the previous acting parent.""" self.parent = self.parent_stack.pop() class TreePruningException(Exception): """ Base class for `NodeVisitor`-related tree pruning exceptions. Raise subclasses from within ``visit_...`` or ``depart_...`` methods called from `Node.walk()` and `Node.walkabout()` tree traversals to prune the tree traversed. """ pass class SkipChildren(TreePruningException): """ Do not visit any children of the current node. The current node's siblings and ``depart_...`` method are not affected. """ pass class SkipSiblings(TreePruningException): """ Do not visit any more siblings (to the right) of the current node. The current node's children and its ``depart_...`` method are not affected. """ pass class SkipNode(TreePruningException): """ Do not visit the current node's children, and do not call the current node's ``depart_...`` method. """ pass class SkipDeparture(TreePruningException): """ Do not call the current node's ``depart_...`` method. The current node's children and siblings are not affected. """ pass class NodeFound(TreePruningException): """ Raise to indicate that the target of a search has been found. This exception must be caught by the client; it is not caught by the traversal code. """ pass def make_id(string): """ Convert `string` into an identifier and return it. Docutils identifiers will conform to the regular expression ``[a-z](-?[a-z0-9]+)*``. For CSS compatibility, identifiers (the "class" and "id" attributes) should have no underscores, colons, or periods. Hyphens may be used. - The `HTML 4.01 spec`_ defines identifiers based on SGML tokens: ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). - However the `CSS1 spec`_ defines identifiers based on the "name" token, a tighter interpretation ("flex" tokenizer notation; "latin1" and "escape" 8-bit characters have been replaced with entities):: unicode \\[0-9a-f]{1,4} latin1 [&iexcl;-&yuml;] escape {unicode}|\\[ -~&iexcl;-&yuml;] nmchar [-a-z0-9]|{latin1}|{escape} name {nmchar}+ The CSS1 "nmchar" rule does not include underscores ("_"), colons (":"), or periods ("."), therefore "class" and "id" attributes should not contain these characters. They should be replaced with hyphens ("-"). Combined with HTML's requirements (the first character must be a letter; no "unicode", "latin1", or "escape" characters), this results in the ``[a-z](-?[a-z0-9]+)*`` pattern. .. _HTML 4.01 spec: http://www.w3.org/TR/html401 .. _CSS1 spec: http://www.w3.org/TR/REC-CSS1 """ id = _non_id_chars.sub('-', ' '.join(string.lower().split())) id = _non_id_at_ends.sub('', id) return str(id) _non_id_chars = re.compile('[^a-z0-9]+') _non_id_at_ends = re.compile('^[-0-9]+|-+$') def dupname(node, name): node['dupnames'].append(name) node['names'].remove(name) # Assume that this method is referenced, even though it isn't; we # don't want to throw unnecessary system_messages. node.referenced = 1 def fully_normalize_name(name): """Return a case- and whitespace-normalized name.""" return ' '.join(name.lower().split()) def whitespace_normalize_name(name): """Return a whitespace-normalized name.""" return ' '.join(name.split()) def serial_escape(value): """Escape string values that are elements of a list, for serialization.""" return value.replace('\\', r'\\').replace(' ', r'\ ') # # # Local Variables: # indent-tabs-mode: nil # sentence-end-double-space: t # fill-column: 78 # End:
{ "repo_name": "hugs/selenium", "path": "selenium/src/py/lib/docutils/nodes.py", "copies": "5", "size": "60875", "license": "apache-2.0", "hash": -3565896469857413000, "line_mean": 32.4906515581, "line_max": 79, "alpha_frac": 0.5765585216, "autogenerated": false, "ratio": 4.3054671476059125, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7382025669205913, "avg_score": null, "num_lines": null }
""" I/O classes provide a uniform API for low-level input and output. Subclasses will exist for a variety of input/output mechanisms. """ __docformat__ = 'reStructuredText' import sys try: import locale except: pass import re from types import UnicodeType from docutils import TransformSpec class Input(TransformSpec): """ Abstract base class for input wrappers. """ component_type = 'input' default_source_path = None def __init__(self, source=None, source_path=None, encoding=None, error_handler='strict'): self.encoding = encoding """Text encoding for the input source.""" self.error_handler = error_handler """Text decoding error handler.""" self.source = source """The source of input data.""" self.source_path = source_path """A text reference to the source.""" if not source_path: self.source_path = self.default_source_path self.successful_encoding = None """The encoding that successfully decoded the source data.""" def __repr__(self): return '%s: source=%r, source_path=%r' % (self.__class__, self.source, self.source_path) def read(self): raise NotImplementedError def decode(self, data): """ Decode a string, `data`, heuristically. Raise UnicodeError if unsuccessful. The client application should call ``locale.setlocale`` at the beginning of processing:: locale.setlocale(locale.LC_ALL, '') """ if self.encoding and self.encoding.lower() == 'unicode': assert isinstance(data, UnicodeType), ( 'input encoding is "unicode" ' 'but input is not a unicode object') if isinstance(data, UnicodeType): # Accept unicode even if self.encoding != 'unicode'. return data if self.encoding: # We believe the user/application when the encoding is # explicitly given. encodings = [self.encoding] else: data_encoding = self.determine_encoding_from_data(data) if data_encoding: # If the data declares its encoding (explicitly or via a BOM), # we believe it. encodings = [data_encoding] else: # Apply heuristics only if no encoding is explicitly given and # no BOM found. Start with UTF-8, because that only matches # data that *IS* UTF-8: encodings = ['utf-8'] try: encodings.append(locale.nl_langinfo(locale.CODESET)) except: pass try: encodings.append(locale.getlocale()[1]) except: pass try: encodings.append(locale.getdefaultlocale()[1]) except: pass # fallback encoding: encodings.append('latin-1') error = None error_details = '' for enc in encodings: if not enc: continue try: decoded = unicode(data, enc, self.error_handler) self.successful_encoding = enc # Return decoded, removing BOMs. return decoded.replace(u'\ufeff', u'') except (UnicodeError, LookupError), error: pass if error is not None: error_details = '\n(%s: %s)' % (error.__class__.__name__, error) raise UnicodeError( 'Unable to decode input data. Tried the following encodings: ' '%s.%s' % (', '.join([repr(enc) for enc in encodings if enc]), error_details)) coding_slug = re.compile("coding[:=]\s*([-\w.]+)") """Encoding declaration pattern.""" byte_order_marks = (('\xef\xbb\xbf', 'utf-8'), ('\xfe\xff', 'utf-16-be'), ('\xff\xfe', 'utf-16-le'),) """Sequence of (start_bytes, encoding) tuples to for encoding detection. The first bytes of input data are checked against the start_bytes strings. A match indicates the given encoding.""" def determine_encoding_from_data(self, data): """ Try to determine the encoding of `data` by looking *in* `data`. Check for a byte order mark (BOM) or an encoding declaration. """ # check for a byte order mark: for start_bytes, encoding in self.byte_order_marks: if data.startswith(start_bytes): return encoding # check for an encoding declaration pattern in first 2 lines of file: for line in data.splitlines()[:2]: match = self.coding_slug.search(line) if match: return match.group(1) return None class Output(TransformSpec): """ Abstract base class for output wrappers. """ component_type = 'output' default_destination_path = None def __init__(self, destination=None, destination_path=None, encoding=None, error_handler='strict'): self.encoding = encoding """Text encoding for the output destination.""" self.error_handler = error_handler or 'strict' """Text encoding error handler.""" self.destination = destination """The destination for output data.""" self.destination_path = destination_path """A text reference to the destination.""" if not destination_path: self.destination_path = self.default_destination_path def __repr__(self): return ('%s: destination=%r, destination_path=%r' % (self.__class__, self.destination, self.destination_path)) def write(self, data): """`data` is a Unicode string, to be encoded by `self.encode`.""" raise NotImplementedError def encode(self, data): if self.encoding and self.encoding.lower() == 'unicode': assert isinstance(data, UnicodeType), ( 'the encoding given is "unicode" but the output is not ' 'a Unicode string') return data if not isinstance(data, UnicodeType): # Non-unicode (e.g. binary) output. return data else: try: return data.encode(self.encoding, self.error_handler) except ValueError: # ValueError is raised if there are unencodable chars # in data and the error_handler isn't found. if self.error_handler == 'xmlcharrefreplace': # We are using xmlcharrefreplace with a Python # version that doesn't support it (2.1 or 2.2), so # we emulate its behavior. return ''.join([self.xmlcharref_encode(char) for char in data]) else: raise def xmlcharref_encode(self, char): """Emulate Python 2.3's 'xmlcharrefreplace' encoding error handler.""" try: return char.encode(self.encoding, 'strict') except UnicodeError: return '&#%i;' % ord(char) class FileInput(Input): """ Input for single, simple file-like objects. """ def __init__(self, source=None, source_path=None, encoding=None, error_handler='strict', autoclose=1, handle_io_errors=1): """ :Parameters: - `source`: either a file-like object (which is read directly), or `None` (which implies `sys.stdin` if no `source_path` given). - `source_path`: a path to a file, which is opened and then read. - `encoding`: the expected text encoding of the input file. - `error_handler`: the encoding error handler to use. - `autoclose`: close automatically after read (boolean); always false if `sys.stdin` is the source. - `handle_io_errors`: summarize I/O errors here, and exit? """ Input.__init__(self, source, source_path, encoding, error_handler) self.autoclose = autoclose self.handle_io_errors = handle_io_errors if source is None: if source_path: try: self.source = open(source_path) except IOError, error: if not handle_io_errors: raise print >>sys.stderr, '%s: %s' % (error.__class__.__name__, error) print >>sys.stderr, ( 'Unable to open source file for reading (%r). Exiting.' % source_path) sys.exit(1) else: self.source = sys.stdin self.autoclose = None if not source_path: try: self.source_path = self.source.name except AttributeError: pass def read(self): """ Read and decode a single file and return the data (Unicode string). """ try: data = self.source.read() finally: if self.autoclose: self.close() return self.decode(data) def close(self): self.source.close() class FileOutput(Output): """ Output for single, simple file-like objects. """ def __init__(self, destination=None, destination_path=None, encoding=None, error_handler='strict', autoclose=1, handle_io_errors=1): """ :Parameters: - `destination`: either a file-like object (which is written directly) or `None` (which implies `sys.stdout` if no `destination_path` given). - `destination_path`: a path to a file, which is opened and then written. - `autoclose`: close automatically after write (boolean); always false if `sys.stdout` is the destination. """ Output.__init__(self, destination, destination_path, encoding, error_handler) self.opened = 1 self.autoclose = autoclose self.handle_io_errors = handle_io_errors if destination is None: if destination_path: self.opened = None else: self.destination = sys.stdout self.autoclose = None if not destination_path: try: self.destination_path = self.destination.name except AttributeError: pass def open(self): try: self.destination = open(self.destination_path, 'w') except IOError, error: if not self.handle_io_errors: raise print >>sys.stderr, '%s: %s' % (error.__class__.__name__, error) print >>sys.stderr, ('Unable to open destination file for writing ' '(%r). Exiting.' % self.destination_path) sys.exit(1) self.opened = 1 def write(self, data): """Encode `data`, write it to a single file, and return it.""" output = self.encode(data) if not self.opened: self.open() try: self.destination.write(output) finally: if self.autoclose: self.close() return output def close(self): self.destination.close() self.opened = None class StringInput(Input): """ Direct string input. """ default_source_path = '<string>' def read(self): """Decode and return the source string.""" return self.decode(self.source) class StringOutput(Output): """ Direct string output. """ default_destination_path = '<string>' def write(self, data): """Encode `data`, store it in `self.destination`, and return it.""" self.destination = self.encode(data) return self.destination class NullInput(Input): """ Degenerate input: read nothing. """ default_source_path = 'null input' def read(self): """Return a null string.""" return u'' class NullOutput(Output): """ Degenerate output: write nothing. """ default_destination_path = 'null output' def write(self, data): """Do nothing ([don't even] send data to the bit bucket).""" pass class DocTreeInput(Input): """ Adapter for document tree input. The document tree must be passed in the ``source`` parameter. """ default_source_path = 'doctree input' def read(self): """Return the document tree.""" return self.source
{ "repo_name": "brownman/selenium-webdriver", "path": "selenium/src/py/lib/docutils/io.py", "copies": "5", "size": "13686", "license": "apache-2.0", "hash": -5286476432987192000, "line_mean": 31.2184466019, "line_max": 80, "alpha_frac": 0.5249890399, "autogenerated": false, "ratio": 4.706327372764787, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7731316412664787, "avg_score": null, "num_lines": null }
""" This is the ``docutils.parsers.restructuredtext.states`` module, the core of the reStructuredText parser. It defines the following: :Classes: - `RSTStateMachine`: reStructuredText parser's entry point. - `NestedStateMachine`: recursive StateMachine. - `RSTState`: reStructuredText State superclass. - `Inliner`: For parsing inline markup. - `Body`: Generic classifier of the first line of a block. - `SpecializedBody`: Superclass for compound element members. - `BulletList`: Second and subsequent bullet_list list_items - `DefinitionList`: Second+ definition_list_items. - `EnumeratedList`: Second+ enumerated_list list_items. - `FieldList`: Second+ fields. - `OptionList`: Second+ option_list_items. - `RFC2822List`: Second+ RFC2822-style fields. - `ExtensionOptions`: Parses directive option fields. - `Explicit`: Second+ explicit markup constructs. - `SubstitutionDef`: For embedded directives in substitution definitions. - `Text`: Classifier of second line of a text block. - `SpecializedText`: Superclass for continuation lines of Text-variants. - `Definition`: Second line of potential definition_list_item. - `Line`: Second line of overlined section title or transition marker. - `Struct`: An auxiliary collection class. :Exception classes: - `MarkupError` - `ParserError` - `MarkupMismatch` :Functions: - `escape2null()`: Return a string, escape-backslashes converted to nulls. - `unescape()`: Return a string, nulls removed or restored to backslashes. :Attributes: - `state_classes`: set of State classes used with `RSTStateMachine`. Parser Overview =============== The reStructuredText parser is implemented as a recursive state machine, examining its input one line at a time. To understand how the parser works, please first become familiar with the `docutils.statemachine` module. In the description below, references are made to classes defined in this module; please see the individual classes for details. Parsing proceeds as follows: 1. The state machine examines each line of input, checking each of the transition patterns of the state `Body`, in order, looking for a match. The implicit transitions (blank lines and indentation) are checked before any others. The 'text' transition is a catch-all (matches anything). 2. The method associated with the matched transition pattern is called. A. Some transition methods are self-contained, appending elements to the document tree (`Body.doctest` parses a doctest block). The parser's current line index is advanced to the end of the element, and parsing continues with step 1. B. Other transition methods trigger the creation of a nested state machine, whose job is to parse a compound construct ('indent' does a block quote, 'bullet' does a bullet list, 'overline' does a section [first checking for a valid section header], etc.). - In the case of lists and explicit markup, a one-off state machine is created and run to parse contents of the first item. - A new state machine is created and its initial state is set to the appropriate specialized state (`BulletList` in the case of the 'bullet' transition; see `SpecializedBody` for more detail). This state machine is run to parse the compound element (or series of explicit markup elements), and returns as soon as a non-member element is encountered. For example, the `BulletList` state machine ends as soon as it encounters an element which is not a list item of that bullet list. The optional omission of inter-element blank lines is enabled by this nested state machine. - The current line index is advanced to the end of the elements parsed, and parsing continues with step 1. C. The result of the 'text' transition depends on the next line of text. The current state is changed to `Text`, under which the second line is examined. If the second line is: - Indented: The element is a definition list item, and parsing proceeds similarly to step 2.B, using the `DefinitionList` state. - A line of uniform punctuation characters: The element is a section header; again, parsing proceeds as in step 2.B, and `Body` is still used. - Anything else: The element is a paragraph, which is examined for inline markup and appended to the parent element. Processing continues with step 1. """ __docformat__ = 'reStructuredText' import sys import re import roman from types import TupleType from docutils import nodes, statemachine, utils, urischemes from docutils import ApplicationError, DataError from docutils.statemachine import StateMachineWS, StateWS from docutils.nodes import fully_normalize_name as normalize_name from docutils.nodes import whitespace_normalize_name from docutils.utils import escape2null, unescape, column_width from docutils.parsers.rst import directives, languages, tableparser, roles from docutils.parsers.rst.languages import en as _fallback_language_module class MarkupError(DataError): pass class UnknownInterpretedRoleError(DataError): pass class InterpretedRoleNotImplementedError(DataError): pass class ParserError(ApplicationError): pass class MarkupMismatch(Exception): pass class Struct: """Stores data attributes for dotted-attribute access.""" def __init__(self, **keywordargs): self.__dict__.update(keywordargs) class RSTStateMachine(StateMachineWS): """ reStructuredText's master StateMachine. The entry point to reStructuredText parsing is the `run()` method. """ def run(self, input_lines, document, input_offset=0, match_titles=1, inliner=None): """ Parse `input_lines` and modify the `document` node in place. Extend `StateMachineWS.run()`: set up parse-global data and run the StateMachine. """ self.language = languages.get_language( document.settings.language_code) self.match_titles = match_titles if inliner is None: inliner = Inliner() inliner.init_customizations(document.settings) self.memo = Struct(document=document, reporter=document.reporter, language=self.language, title_styles=[], section_level=0, section_bubble_up_kludge=0, inliner=inliner) self.document = document self.attach_observer(document.note_source) self.reporter = self.memo.reporter self.node = document results = StateMachineWS.run(self, input_lines, input_offset, input_source=document['source']) assert results == [], 'RSTStateMachine.run() results should be empty!' self.node = self.memo = None # remove unneeded references class NestedStateMachine(StateMachineWS): """ StateMachine run from within other StateMachine runs, to parse nested document structures. """ def run(self, input_lines, input_offset, memo, node, match_titles=1): """ Parse `input_lines` and populate a `docutils.nodes.document` instance. Extend `StateMachineWS.run()`: set up document-wide data. """ self.match_titles = match_titles self.memo = memo self.document = memo.document self.attach_observer(self.document.note_source) self.reporter = memo.reporter self.language = memo.language self.node = node results = StateMachineWS.run(self, input_lines, input_offset) assert results == [], ('NestedStateMachine.run() results should be ' 'empty!') return results class RSTState(StateWS): """ reStructuredText State superclass. Contains methods used by all State subclasses. """ nested_sm = NestedStateMachine def __init__(self, state_machine, debug=0): self.nested_sm_kwargs = {'state_classes': state_classes, 'initial_state': 'Body'} StateWS.__init__(self, state_machine, debug) def runtime_init(self): StateWS.runtime_init(self) memo = self.state_machine.memo self.memo = memo self.reporter = memo.reporter self.inliner = memo.inliner self.document = memo.document self.parent = self.state_machine.node def goto_line(self, abs_line_offset): """ Jump to input line `abs_line_offset`, ignoring jumps past the end. """ try: self.state_machine.goto_line(abs_line_offset) except EOFError: pass def no_match(self, context, transitions): """ Override `StateWS.no_match` to generate a system message. This code should never be run. """ self.reporter.severe( 'Internal error: no transition pattern match. State: "%s"; ' 'transitions: %s; context: %s; current line: %r.' % (self.__class__.__name__, transitions, context, self.state_machine.line), line=self.state_machine.abs_line_number()) return context, None, [] def bof(self, context): """Called at beginning of file.""" return [], [] def nested_parse(self, block, input_offset, node, match_titles=0, state_machine_class=None, state_machine_kwargs=None): """ Create a new StateMachine rooted at `node` and run it over the input `block`. """ if state_machine_class is None: state_machine_class = self.nested_sm if state_machine_kwargs is None: state_machine_kwargs = self.nested_sm_kwargs block_length = len(block) state_machine = state_machine_class(debug=self.debug, **state_machine_kwargs) state_machine.run(block, input_offset, memo=self.memo, node=node, match_titles=match_titles) state_machine.unlink() new_offset = state_machine.abs_line_offset() # No `block.parent` implies disconnected -- lines aren't in sync: if block.parent and (len(block) - block_length) != 0: # Adjustment for block if modified in nested parse: self.state_machine.next_line(len(block) - block_length) return new_offset def nested_list_parse(self, block, input_offset, node, initial_state, blank_finish, blank_finish_state=None, extra_settings={}, match_titles=0, state_machine_class=None, state_machine_kwargs=None): """ Create a new StateMachine rooted at `node` and run it over the input `block`. Also keep track of optional intermediate blank lines and the required final one. """ if state_machine_class is None: state_machine_class = self.nested_sm if state_machine_kwargs is None: state_machine_kwargs = self.nested_sm_kwargs.copy() state_machine_kwargs['initial_state'] = initial_state state_machine = state_machine_class(debug=self.debug, **state_machine_kwargs) if blank_finish_state is None: blank_finish_state = initial_state state_machine.states[blank_finish_state].blank_finish = blank_finish for key, value in extra_settings.items(): setattr(state_machine.states[initial_state], key, value) state_machine.run(block, input_offset, memo=self.memo, node=node, match_titles=match_titles) blank_finish = state_machine.states[blank_finish_state].blank_finish state_machine.unlink() return state_machine.abs_line_offset(), blank_finish def section(self, title, source, style, lineno, messages): """Check for a valid subsection and create one if it checks out.""" if self.check_subsection(source, style, lineno): self.new_subsection(title, lineno, messages) def check_subsection(self, source, style, lineno): """ Check for a valid subsection header. Return 1 (true) or None (false). When a new section is reached that isn't a subsection of the current section, back up the line count (use ``previous_line(-x)``), then ``raise EOFError``. The current StateMachine will finish, then the calling StateMachine can re-examine the title. This will work its way back up the calling chain until the correct section level isreached. @@@ Alternative: Evaluate the title, store the title info & level, and back up the chain until that level is reached. Store in memo? Or return in results? :Exception: `EOFError` when a sibling or supersection encountered. """ memo = self.memo title_styles = memo.title_styles mylevel = memo.section_level try: # check for existing title style level = title_styles.index(style) + 1 except ValueError: # new title style if len(title_styles) == memo.section_level: # new subsection title_styles.append(style) return 1 else: # not at lowest level self.parent += self.title_inconsistent(source, lineno) return None if level <= mylevel: # sibling or supersection memo.section_level = level # bubble up to parent section if len(style) == 2: memo.section_bubble_up_kludge = 1 # back up 2 lines for underline title, 3 for overline title self.state_machine.previous_line(len(style) + 1) raise EOFError # let parent section re-evaluate if level == mylevel + 1: # immediate subsection return 1 else: # invalid subsection self.parent += self.title_inconsistent(source, lineno) return None def title_inconsistent(self, sourcetext, lineno): error = self.reporter.severe( 'Title level inconsistent:', nodes.literal_block('', sourcetext), line=lineno) return error def new_subsection(self, title, lineno, messages): """Append new subsection to document tree. On return, check level.""" memo = self.memo mylevel = memo.section_level memo.section_level += 1 section_node = nodes.section() self.parent += section_node textnodes, title_messages = self.inline_text(title, lineno) titlenode = nodes.title(title, '', *textnodes) name = normalize_name(titlenode.astext()) section_node['names'].append(name) section_node += titlenode section_node += messages section_node += title_messages self.document.note_implicit_target(section_node, section_node) offset = self.state_machine.line_offset + 1 absoffset = self.state_machine.abs_line_offset() + 1 newabsoffset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=absoffset, node=section_node, match_titles=1) self.goto_line(newabsoffset) if memo.section_level <= mylevel: # can't handle next section? raise EOFError # bubble up to supersection # reset section_level; next pass will detect it properly memo.section_level = mylevel def paragraph(self, lines, lineno): """ Return a list (paragraph & messages) & a boolean: literal_block next? """ data = '\n'.join(lines).rstrip() if re.search(r'(?<!\\)(\\\\)*::$', data): if len(data) == 2: return [], 1 elif data[-3] in ' \n': text = data[:-3].rstrip() else: text = data[:-1] literalnext = 1 else: text = data literalnext = 0 textnodes, messages = self.inline_text(text, lineno) p = nodes.paragraph(data, '', *textnodes) p.line = lineno return [p] + messages, literalnext def inline_text(self, text, lineno): """ Return 2 lists: nodes (text and inline elements), and system_messages. """ return self.inliner.parse(text, lineno, self.memo, self.parent) def unindent_warning(self, node_name): return self.reporter.warning( '%s ends without a blank line; unexpected unindent.' % node_name, line=(self.state_machine.abs_line_number() + 1)) def build_regexp(definition, compile=1): """ Build, compile and return a regular expression based on `definition`. :Parameter: `definition`: a 4-tuple (group name, prefix, suffix, parts), where "parts" is a list of regular expressions and/or regular expression definitions to be joined into an or-group. """ name, prefix, suffix, parts = definition part_strings = [] for part in parts: if type(part) is TupleType: part_strings.append(build_regexp(part, None)) else: part_strings.append(part) or_group = '|'.join(part_strings) regexp = '%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s' % locals() if compile: return re.compile(regexp, re.UNICODE) else: return regexp class Inliner: """ Parse inline markup; call the `parse()` method. """ def __init__(self): self.implicit_dispatch = [(self.patterns.uri, self.standalone_uri),] """List of (pattern, bound method) tuples, used by `self.implicit_inline`.""" def init_customizations(self, settings): """Setting-based customizations; run when parsing begins.""" if settings.pep_references: self.implicit_dispatch.append((self.patterns.pep, self.pep_reference)) if settings.rfc_references: self.implicit_dispatch.append((self.patterns.rfc, self.rfc_reference)) def parse(self, text, lineno, memo, parent): # Needs to be refactored for nested inline markup. # Add nested_parse() method? """ Return 2 lists: nodes (text and inline elements), and system_messages. Using `self.patterns.initial`, a pattern which matches start-strings (emphasis, strong, interpreted, phrase reference, literal, substitution reference, and inline target) and complete constructs (simple reference, footnote reference), search for a candidate. When one is found, check for validity (e.g., not a quoted '*' character). If valid, search for the corresponding end string if applicable, and check it for validity. If not found or invalid, generate a warning and ignore the start-string. Implicit inline markup (e.g. standalone URIs) is found last. """ self.reporter = memo.reporter self.document = memo.document self.language = memo.language self.parent = parent pattern_search = self.patterns.initial.search dispatch = self.dispatch remaining = escape2null(text) processed = [] unprocessed = [] messages = [] while remaining: match = pattern_search(remaining) if match: groups = match.groupdict() method = dispatch[groups['start'] or groups['backquote'] or groups['refend'] or groups['fnend']] before, inlines, remaining, sysmessages = method(self, match, lineno) unprocessed.append(before) messages += sysmessages if inlines: processed += self.implicit_inline(''.join(unprocessed), lineno) processed += inlines unprocessed = [] else: break remaining = ''.join(unprocessed) + remaining if remaining: processed += self.implicit_inline(remaining, lineno) return processed, messages openers = '\'"([{<' closers = '\'")]}>' start_string_prefix = (r'((?<=^)|(?<=[-/: \n%s]))' % re.escape(openers)) end_string_suffix = (r'((?=$)|(?=[-/:.,;!? \n\x00%s]))' % re.escape(closers)) non_whitespace_before = r'(?<![ \n])' non_whitespace_escape_before = r'(?<![ \n\x00])' non_whitespace_after = r'(?![ \n])' # Alphanumerics with isolated internal [-._] chars (i.e. not 2 together): simplename = r'(?:(?!_)\w)+(?:[-._](?:(?!_)\w)+)*' # Valid URI characters (see RFC 2396 & RFC 2732); # final \x00 allows backslash escapes in URIs: uric = r"""[-_.!~*'()[\];/:@&=+$,%a-zA-Z0-9\x00]""" # Delimiter indicating the end of a URI (not part of the URI): uri_end_delim = r"""[>]""" # Last URI character; same as uric but no punctuation: urilast = r"""[_~*/=+a-zA-Z0-9]""" # End of a URI (either 'urilast' or 'uric followed by a # uri_end_delim'): uri_end = r"""(?:%(urilast)s|%(uric)s(?=%(uri_end_delim)s))""" % locals() emailc = r"""[-_!~*'{|}/#?^`&=+$%a-zA-Z0-9\x00]""" email_pattern = r""" %(emailc)s+(?:\.%(emailc)s+)* # name (?<!\x00)@ # at %(emailc)s+(?:\.%(emailc)s*)* # host %(uri_end)s # final URI char """ parts = ('initial_inline', start_string_prefix, '', [('start', '', non_whitespace_after, # simple start-strings [r'\*\*', # strong r'\*(?!\*)', # emphasis but not strong r'``', # literal r'_`', # inline internal target r'\|(?!\|)'] # substitution reference ), ('whole', '', end_string_suffix, # whole constructs [# reference name & end-string r'(?P<refname>%s)(?P<refend>__?)' % simplename, ('footnotelabel', r'\[', r'(?P<fnend>\]_)', [r'[0-9]+', # manually numbered r'\#(%s)?' % simplename, # auto-numbered (w/ label?) r'\*', # auto-symbol r'(?P<citationlabel>%s)' % simplename] # citation reference ) ] ), ('backquote', # interpreted text or phrase reference '(?P<role>(:%s:)?)' % simplename, # optional role non_whitespace_after, ['`(?!`)'] # but not literal ) ] ) patterns = Struct( initial=build_regexp(parts), emphasis=re.compile(non_whitespace_escape_before + r'(\*)' + end_string_suffix), strong=re.compile(non_whitespace_escape_before + r'(\*\*)' + end_string_suffix), interpreted_or_phrase_ref=re.compile( r""" %(non_whitespace_escape_before)s ( ` (?P<suffix> (?P<role>:%(simplename)s:)? (?P<refend>__?)? ) ) %(end_string_suffix)s """ % locals(), re.VERBOSE | re.UNICODE), embedded_uri=re.compile( r""" ( (?:[ \n]+|^) # spaces or beginning of line/string < # open bracket %(non_whitespace_after)s ([^<>\x00]+) # anything but angle brackets & nulls %(non_whitespace_before)s > # close bracket w/o whitespace before ) $ # end of string """ % locals(), re.VERBOSE), literal=re.compile(non_whitespace_before + '(``)' + end_string_suffix), target=re.compile(non_whitespace_escape_before + r'(`)' + end_string_suffix), substitution_ref=re.compile(non_whitespace_escape_before + r'(\|_{0,2})' + end_string_suffix), email=re.compile(email_pattern % locals() + '$', re.VERBOSE), uri=re.compile( (r""" %(start_string_prefix)s (?P<whole> (?P<absolute> # absolute URI (?P<scheme> # scheme (http, ftp, mailto) [a-zA-Z][a-zA-Z0-9.+-]* ) : ( ( # either: (//?)? # hierarchical URI %(uric)s* # URI characters %(uri_end)s # final URI char ) ( # optional query \?%(uric)s* %(uri_end)s )? ( # optional fragment \#%(uric)s* %(uri_end)s )? ) ) | # *OR* (?P<email> # email address """ + email_pattern + r""" ) ) %(end_string_suffix)s """) % locals(), re.VERBOSE), pep=re.compile( r""" %(start_string_prefix)s ( (pep-(?P<pepnum1>\d+)(.txt)?) # reference to source file | (PEP\s+(?P<pepnum2>\d+)) # reference by name ) %(end_string_suffix)s""" % locals(), re.VERBOSE), rfc=re.compile( r""" %(start_string_prefix)s (RFC(-|\s+)?(?P<rfcnum>\d+)) %(end_string_suffix)s""" % locals(), re.VERBOSE)) def quoted_start(self, match): """Return 1 if inline markup start-string is 'quoted', 0 if not.""" string = match.string start = match.start() end = match.end() if start == 0: # start-string at beginning of text return 0 prestart = string[start - 1] try: poststart = string[end] if self.openers.index(prestart) \ == self.closers.index(poststart): # quoted return 1 except IndexError: # start-string at end of text return 1 except ValueError: # not quoted pass return 0 def inline_obj(self, match, lineno, end_pattern, nodeclass, restore_backslashes=0): string = match.string matchstart = match.start('start') matchend = match.end('start') if self.quoted_start(match): return (string[:matchend], [], string[matchend:], [], '') endmatch = end_pattern.search(string[matchend:]) if endmatch and endmatch.start(1): # 1 or more chars text = unescape(endmatch.string[:endmatch.start(1)], restore_backslashes) textend = matchend + endmatch.end(1) rawsource = unescape(string[matchstart:textend], 1) return (string[:matchstart], [nodeclass(rawsource, text)], string[textend:], [], endmatch.group(1)) msg = self.reporter.warning( 'Inline %s start-string without end-string.' % nodeclass.__name__, line=lineno) text = unescape(string[matchstart:matchend], 1) rawsource = unescape(string[matchstart:matchend], 1) prb = self.problematic(text, rawsource, msg) return string[:matchstart], [prb], string[matchend:], [msg], '' def problematic(self, text, rawsource, message): msgid = self.document.set_id(message, self.parent) problematic = nodes.problematic(rawsource, text, refid=msgid) prbid = self.document.set_id(problematic) message.add_backref(prbid) return problematic def emphasis(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.emphasis, nodes.emphasis) return before, inlines, remaining, sysmessages def strong(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.strong, nodes.strong) return before, inlines, remaining, sysmessages def interpreted_or_phrase_ref(self, match, lineno): end_pattern = self.patterns.interpreted_or_phrase_ref string = match.string matchstart = match.start('backquote') matchend = match.end('backquote') rolestart = match.start('role') role = match.group('role') position = '' if role: role = role[1:-1] position = 'prefix' elif self.quoted_start(match): return (string[:matchend], [], string[matchend:], []) endmatch = end_pattern.search(string[matchend:]) if endmatch and endmatch.start(1): # 1 or more chars textend = matchend + endmatch.end() if endmatch.group('role'): if role: msg = self.reporter.warning( 'Multiple roles in interpreted text (both ' 'prefix and suffix present; only one allowed).', line=lineno) text = unescape(string[rolestart:textend], 1) prb = self.problematic(text, text, msg) return string[:rolestart], [prb], string[textend:], [msg] role = endmatch.group('suffix')[1:-1] position = 'suffix' escaped = endmatch.string[:endmatch.start(1)] rawsource = unescape(string[matchstart:textend], 1) if rawsource[-1:] == '_': if role: msg = self.reporter.warning( 'Mismatch: both interpreted text role %s and ' 'reference suffix.' % position, line=lineno) text = unescape(string[rolestart:textend], 1) prb = self.problematic(text, text, msg) return string[:rolestart], [prb], string[textend:], [msg] return self.phrase_ref(string[:matchstart], string[textend:], rawsource, escaped, unescape(escaped)) else: rawsource = unescape(string[rolestart:textend], 1) nodelist, messages = self.interpreted(rawsource, escaped, role, lineno) return (string[:rolestart], nodelist, string[textend:], messages) msg = self.reporter.warning( 'Inline interpreted text or phrase reference start-string ' 'without end-string.', line=lineno) text = unescape(string[matchstart:matchend], 1) prb = self.problematic(text, text, msg) return string[:matchstart], [prb], string[matchend:], [msg] def phrase_ref(self, before, after, rawsource, escaped, text): match = self.patterns.embedded_uri.search(escaped) if match: text = unescape(escaped[:match.start(0)]) uri_text = match.group(2) uri = ''.join(uri_text.split()) uri = self.adjust_uri(uri) if uri: target = nodes.target(match.group(1), refuri=uri) else: raise ApplicationError('problem with URI: %r' % uri_text) if not text: text = uri else: target = None refname = normalize_name(text) reference = nodes.reference(rawsource, text, name=whitespace_normalize_name(text)) node_list = [reference] if rawsource[-2:] == '__': if target: reference['refuri'] = uri else: reference['anonymous'] = 1 else: if target: reference['refuri'] = uri target['names'].append(refname) self.document.note_explicit_target(target, self.parent) node_list.append(target) else: reference['refname'] = refname self.document.note_refname(reference) return before, node_list, after, [] def adjust_uri(self, uri): match = self.patterns.email.match(uri) if match: return 'mailto:' + uri else: return uri def interpreted(self, rawsource, text, role, lineno): role_fn, messages = roles.role(role, self.language, lineno, self.reporter) if role_fn: nodes, messages2 = role_fn(role, rawsource, text, lineno, self) return nodes, messages + messages2 else: msg = self.reporter.error( 'Unknown interpreted text role "%s".' % role, line=lineno) return ([self.problematic(rawsource, rawsource, msg)], messages + [msg]) def literal(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.literal, nodes.literal, restore_backslashes=1) return before, inlines, remaining, sysmessages def inline_internal_target(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.target, nodes.target) if inlines and isinstance(inlines[0], nodes.target): assert len(inlines) == 1 target = inlines[0] name = normalize_name(target.astext()) target['names'].append(name) self.document.note_explicit_target(target, self.parent) return before, inlines, remaining, sysmessages def substitution_reference(self, match, lineno): before, inlines, remaining, sysmessages, endstring = self.inline_obj( match, lineno, self.patterns.substitution_ref, nodes.substitution_reference) if len(inlines) == 1: subref_node = inlines[0] if isinstance(subref_node, nodes.substitution_reference): subref_text = subref_node.astext() self.document.note_substitution_ref(subref_node, subref_text) if endstring[-1:] == '_': reference_node = nodes.reference( '|%s%s' % (subref_text, endstring), '') if endstring[-2:] == '__': reference_node['anonymous'] = 1 else: reference_node['refname'] = normalize_name(subref_text) self.document.note_refname(reference_node) reference_node += subref_node inlines = [reference_node] return before, inlines, remaining, sysmessages def footnote_reference(self, match, lineno): """ Handles `nodes.footnote_reference` and `nodes.citation_reference` elements. """ label = match.group('footnotelabel') refname = normalize_name(label) string = match.string before = string[:match.start('whole')] remaining = string[match.end('whole'):] if match.group('citationlabel'): refnode = nodes.citation_reference('[%s]_' % label, refname=refname) refnode += nodes.Text(label) self.document.note_citation_ref(refnode) else: refnode = nodes.footnote_reference('[%s]_' % label) if refname[0] == '#': refname = refname[1:] refnode['auto'] = 1 self.document.note_autofootnote_ref(refnode) elif refname == '*': refname = '' refnode['auto'] = '*' self.document.note_symbol_footnote_ref( refnode) else: refnode += nodes.Text(label) if refname: refnode['refname'] = refname self.document.note_footnote_ref(refnode) if utils.get_trim_footnote_ref_space(self.document.settings): before = before.rstrip() return (before, [refnode], remaining, []) def reference(self, match, lineno, anonymous=None): referencename = match.group('refname') refname = normalize_name(referencename) referencenode = nodes.reference( referencename + match.group('refend'), referencename, name=whitespace_normalize_name(referencename)) if anonymous: referencenode['anonymous'] = 1 else: referencenode['refname'] = refname self.document.note_refname(referencenode) string = match.string matchstart = match.start('whole') matchend = match.end('whole') return (string[:matchstart], [referencenode], string[matchend:], []) def anonymous_reference(self, match, lineno): return self.reference(match, lineno, anonymous=1) def standalone_uri(self, match, lineno): if not match.group('scheme') or urischemes.schemes.has_key( match.group('scheme').lower()): if match.group('email'): addscheme = 'mailto:' else: addscheme = '' text = match.group('whole') unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=addscheme + unescaped)] else: # not a valid scheme raise MarkupMismatch def pep_reference(self, match, lineno): text = match.group(0) if text.startswith('pep-'): pepnum = int(match.group('pepnum1')) elif text.startswith('PEP'): pepnum = int(match.group('pepnum2')) else: raise MarkupMismatch ref = (self.document.settings.pep_base_url + self.document.settings.pep_file_url_template % pepnum) unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)] rfc_url = 'rfc%d.html' def rfc_reference(self, match, lineno): text = match.group(0) if text.startswith('RFC'): rfcnum = int(match.group('rfcnum')) ref = self.document.settings.rfc_base_url + self.rfc_url % rfcnum else: raise MarkupMismatch unescaped = unescape(text, 0) return [nodes.reference(unescape(text, 1), unescaped, refuri=ref)] def implicit_inline(self, text, lineno): """ Check each of the patterns in `self.implicit_dispatch` for a match, and dispatch to the stored method for the pattern. Recursively check the text before and after the match. Return a list of `nodes.Text` and inline element nodes. """ if not text: return [] for pattern, method in self.implicit_dispatch: match = pattern.search(text) if match: try: # Must recurse on strings before *and* after the match; # there may be multiple patterns. return (self.implicit_inline(text[:match.start()], lineno) + method(match, lineno) + self.implicit_inline(text[match.end():], lineno)) except MarkupMismatch: pass return [nodes.Text(unescape(text), rawsource=unescape(text, 1))] dispatch = {'*': emphasis, '**': strong, '`': interpreted_or_phrase_ref, '``': literal, '_`': inline_internal_target, ']_': footnote_reference, '|': substitution_reference, '_': reference, '__': anonymous_reference} def _loweralpha_to_int(s, _zero=(ord('a')-1)): return ord(s) - _zero def _upperalpha_to_int(s, _zero=(ord('A')-1)): return ord(s) - _zero def _lowerroman_to_int(s): return roman.fromRoman(s.upper()) class Body(RSTState): """ Generic classifier of the first line of a block. """ double_width_pad_char = tableparser.TableParser.double_width_pad_char """Padding character for East Asian double-width text.""" enum = Struct() """Enumerated list parsing information.""" enum.formatinfo = { 'parens': Struct(prefix='(', suffix=')', start=1, end=-1), 'rparen': Struct(prefix='', suffix=')', start=0, end=-1), 'period': Struct(prefix='', suffix='.', start=0, end=-1)} enum.formats = enum.formatinfo.keys() enum.sequences = ['arabic', 'loweralpha', 'upperalpha', 'lowerroman', 'upperroman'] # ORDERED! enum.sequencepats = {'arabic': '[0-9]+', 'loweralpha': '[a-z]', 'upperalpha': '[A-Z]', 'lowerroman': '[ivxlcdm]+', 'upperroman': '[IVXLCDM]+',} enum.converters = {'arabic': int, 'loweralpha': _loweralpha_to_int, 'upperalpha': _upperalpha_to_int, 'lowerroman': _lowerroman_to_int, 'upperroman': roman.fromRoman} enum.sequenceregexps = {} for sequence in enum.sequences: enum.sequenceregexps[sequence] = re.compile( enum.sequencepats[sequence] + '$') grid_table_top_pat = re.compile(r'\+-[-+]+-\+ *$') """Matches the top (& bottom) of a full table).""" simple_table_top_pat = re.compile('=+( +=+)+ *$') """Matches the top of a simple table.""" simple_table_border_pat = re.compile('=+[ =]*$') """Matches the bottom & header bottom of a simple table.""" pats = {} """Fragments of patterns used by transitions.""" pats['nonalphanum7bit'] = '[!-/:-@[-`{-~]' pats['alpha'] = '[a-zA-Z]' pats['alphanum'] = '[a-zA-Z0-9]' pats['alphanumplus'] = '[a-zA-Z0-9_-]' pats['enum'] = ('(%(arabic)s|%(loweralpha)s|%(upperalpha)s|%(lowerroman)s' '|%(upperroman)s|#)' % enum.sequencepats) pats['optname'] = '%(alphanum)s%(alphanumplus)s*' % pats # @@@ Loosen up the pattern? Allow Unicode? pats['optarg'] = '(%(alpha)s%(alphanumplus)s*|<[^<>]+>)' % pats pats['shortopt'] = r'(-|\+)%(alphanum)s( ?%(optarg)s)?' % pats pats['longopt'] = r'(--|/)%(optname)s([ =]%(optarg)s)?' % pats pats['option'] = r'(%(shortopt)s|%(longopt)s)' % pats for format in enum.formats: pats[format] = '(?P<%s>%s%s%s)' % ( format, re.escape(enum.formatinfo[format].prefix), pats['enum'], re.escape(enum.formatinfo[format].suffix)) patterns = { 'bullet': r'[-+*]( +|$)', 'enumerator': r'(%(parens)s|%(rparen)s|%(period)s)( +|$)' % pats, 'field_marker': r':(?![: ])([^:\\]|\\.)*(?<! ):( +|$)', 'option_marker': r'%(option)s(, %(option)s)*( +| ?$)' % pats, 'doctest': r'>>>( +|$)', 'line_block': r'\|( +|$)', 'grid_table_top': grid_table_top_pat, 'simple_table_top': simple_table_top_pat, 'explicit_markup': r'\.\.( +|$)', 'anonymous': r'__( +|$)', 'line': r'(%(nonalphanum7bit)s)\1* *$' % pats, 'text': r''} initial_transitions = ( 'bullet', 'enumerator', 'field_marker', 'option_marker', 'doctest', 'line_block', 'grid_table_top', 'simple_table_top', 'explicit_markup', 'anonymous', 'line', 'text') def indent(self, match, context, next_state): """Block quote.""" indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() elements = self.block_quote(indented, line_offset) self.parent += elements if not blank_finish: self.parent += self.unindent_warning('Block quote') return context, next_state, [] def block_quote(self, indented, line_offset): elements = [] while indented: (blockquote_lines, attribution_lines, attribution_offset, indented, new_line_offset) = self.split_attribution(indented, line_offset) blockquote = nodes.block_quote() self.nested_parse(blockquote_lines, line_offset, blockquote) elements.append(blockquote) if attribution_lines: attribution, messages = self.parse_attribution( attribution_lines, attribution_offset) blockquote += attribution elements += messages line_offset = new_line_offset while indented and not indented[0]: indented = indented[1:] line_offset += 1 return elements # U+2014 is an em-dash: attribution_pattern = re.compile(ur'(---?(?!-)|\u2014) *(?=[^ \n])') def split_attribution(self, indented, line_offset): """ Check for a block quote attribution and split it off: * First line after a blank line must begin with a dash ("--", "---", em-dash; matches `self.attribution_pattern`). * Every line after that must have consistent indentation. * Attributions must be preceded by block quote content. Return a tuple of: (block quote content lines, content offset, attribution lines, attribution offset, remaining indented lines). """ blank = None nonblank_seen = False for i in range(len(indented)): line = indented[i].rstrip() if line: if nonblank_seen and blank == i - 1: # last line blank match = self.attribution_pattern.match(line) if match: attribution_end, indent = self.check_attribution( indented, i) if attribution_end: a_lines = indented[i:attribution_end] a_lines.trim_left(match.end(), end=1) a_lines.trim_left(indent, start=1) return (indented[:i], a_lines, i, indented[attribution_end:], line_offset + attribution_end) nonblank_seen = True else: blank = i else: return (indented, None, None, None, None) def check_attribution(self, indented, attribution_start): """Check attribution shape """ indent = None i = attribution_start + 1 for i in range(attribution_start + 1, len(indented)): line = indented[i].rstrip() if not line: break if indent is None: indent = len(line) - len(line.lstrip()) elif len(line) - len(line.lstrip()) != indent: return None, None # bad shape; not an attribution return i, (indent or 0) def parse_attribution(self, indented, line_offset): text = '\n'.join(indented).rstrip() lineno = self.state_machine.abs_line_number() + line_offset textnodes, messages = self.inline_text(text, lineno) node = nodes.attribution(text, '', *textnodes) node.line = lineno return node, messages def bullet(self, match, context, next_state): """Bullet list item.""" bulletlist = nodes.bullet_list() self.parent += bulletlist bulletlist['bullet'] = match.string[0] i, blank_finish = self.list_item(match.end()) bulletlist += i offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=bulletlist, initial_state='BulletList', blank_finish=blank_finish) self.goto_line(new_line_offset) if not blank_finish: self.parent += self.unindent_warning('Bullet list') return [], next_state, [] def list_item(self, indent): if self.state_machine.line[indent:]: indented, line_offset, blank_finish = ( self.state_machine.get_known_indented(indent)) else: indented, indent, line_offset, blank_finish = ( self.state_machine.get_first_known_indented(indent)) listitem = nodes.list_item('\n'.join(indented)) if indented: self.nested_parse(indented, input_offset=line_offset, node=listitem) return listitem, blank_finish def enumerator(self, match, context, next_state): """Enumerated List Item""" format, sequence, text, ordinal = self.parse_enumerator(match) if not self.is_enumerated_list_item(ordinal, sequence, format): raise statemachine.TransitionCorrection('text') enumlist = nodes.enumerated_list() self.parent += enumlist if sequence == '#': enumlist['enumtype'] = 'arabic' else: enumlist['enumtype'] = sequence enumlist['prefix'] = self.enum.formatinfo[format].prefix enumlist['suffix'] = self.enum.formatinfo[format].suffix if ordinal != 1: enumlist['start'] = ordinal msg = self.reporter.info( 'Enumerated list start value not ordinal-1: "%s" (ordinal %s)' % (text, ordinal), line=self.state_machine.abs_line_number()) self.parent += msg listitem, blank_finish = self.list_item(match.end()) enumlist += listitem offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=enumlist, initial_state='EnumeratedList', blank_finish=blank_finish, extra_settings={'lastordinal': ordinal, 'format': format, 'auto': sequence == '#'}) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Enumerated list') return [], next_state, [] def parse_enumerator(self, match, expected_sequence=None): """ Analyze an enumerator and return the results. :Return: - the enumerator format ('period', 'parens', or 'rparen'), - the sequence used ('arabic', 'loweralpha', 'upperroman', etc.), - the text of the enumerator, stripped of formatting, and - the ordinal value of the enumerator ('a' -> 1, 'ii' -> 2, etc.; ``None`` is returned for invalid enumerator text). The enumerator format has already been determined by the regular expression match. If `expected_sequence` is given, that sequence is tried first. If not, we check for Roman numeral 1. This way, single-character Roman numerals (which are also alphabetical) can be matched. If no sequence has been matched, all sequences are checked in order. """ groupdict = match.groupdict() sequence = '' for format in self.enum.formats: if groupdict[format]: # was this the format matched? break # yes; keep `format` else: # shouldn't happen raise ParserError('enumerator format not matched') text = groupdict[format][self.enum.formatinfo[format].start :self.enum.formatinfo[format].end] if text == '#': sequence = '#' elif expected_sequence: try: if self.enum.sequenceregexps[expected_sequence].match(text): sequence = expected_sequence except KeyError: # shouldn't happen raise ParserError('unknown enumerator sequence: %s' % sequence) elif text == 'i': sequence = 'lowerroman' elif text == 'I': sequence = 'upperroman' if not sequence: for sequence in self.enum.sequences: if self.enum.sequenceregexps[sequence].match(text): break else: # shouldn't happen raise ParserError('enumerator sequence not matched') if sequence == '#': ordinal = 1 else: try: ordinal = self.enum.converters[sequence](text) except roman.InvalidRomanNumeralError: ordinal = None return format, sequence, text, ordinal def is_enumerated_list_item(self, ordinal, sequence, format): """ Check validity based on the ordinal value and the second line. Return true iff the ordinal is valid and the second line is blank, indented, or starts with the next enumerator or an auto-enumerator. """ if ordinal is None: return None try: next_line = self.state_machine.next_line() except EOFError: # end of input lines self.state_machine.previous_line() return 1 else: self.state_machine.previous_line() if not next_line[:1].strip(): # blank or indented return 1 result = self.make_enumerator(ordinal + 1, sequence, format) if result: next_enumerator, auto_enumerator = result try: if ( next_line.startswith(next_enumerator) or next_line.startswith(auto_enumerator) ): return 1 except TypeError: pass return None def make_enumerator(self, ordinal, sequence, format): """ Construct and return the next enumerated list item marker, and an auto-enumerator ("#" instead of the regular enumerator). Return ``None`` for invalid (out of range) ordinals. """ #" if sequence == '#': enumerator = '#' elif sequence == 'arabic': enumerator = str(ordinal) else: if sequence.endswith('alpha'): if ordinal > 26: return None enumerator = chr(ordinal + ord('a') - 1) elif sequence.endswith('roman'): try: enumerator = roman.toRoman(ordinal) except roman.RomanError: return None else: # shouldn't happen raise ParserError('unknown enumerator sequence: "%s"' % sequence) if sequence.startswith('lower'): enumerator = enumerator.lower() elif sequence.startswith('upper'): enumerator = enumerator.upper() else: # shouldn't happen raise ParserError('unknown enumerator sequence: "%s"' % sequence) formatinfo = self.enum.formatinfo[format] next_enumerator = (formatinfo.prefix + enumerator + formatinfo.suffix + ' ') auto_enumerator = formatinfo.prefix + '#' + formatinfo.suffix + ' ' return next_enumerator, auto_enumerator def field_marker(self, match, context, next_state): """Field list item.""" field_list = nodes.field_list() self.parent += field_list field, blank_finish = self.field(match) field_list += field offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=field_list, initial_state='FieldList', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Field list') return [], next_state, [] def field(self, match): name = self.parse_field_marker(match) lineno = self.state_machine.abs_line_number() indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) field_node = nodes.field() field_node.line = lineno name_nodes, name_messages = self.inline_text(name, lineno) field_node += nodes.field_name(name, '', *name_nodes) field_body = nodes.field_body('\n'.join(indented), *name_messages) field_node += field_body if indented: self.parse_field_body(indented, line_offset, field_body) return field_node, blank_finish def parse_field_marker(self, match): """Extract & return field name from a field marker match.""" field = match.group()[1:] # strip off leading ':' field = field[:field.rfind(':')] # strip off trailing ':' etc. return field def parse_field_body(self, indented, offset, node): self.nested_parse(indented, input_offset=offset, node=node) def option_marker(self, match, context, next_state): """Option list item.""" optionlist = nodes.option_list() try: listitem, blank_finish = self.option_list_item(match) except MarkupError, (message, lineno): # This shouldn't happen; pattern won't match. msg = self.reporter.error( 'Invalid option list marker: %s' % message, line=lineno) self.parent += msg indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) blockquote, messages = self.block_quote(indented, line_offset) self.parent += blockquote self.parent += messages if not blank_finish: self.parent += self.unindent_warning('Option list') return [], next_state, [] self.parent += optionlist optionlist += listitem offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=optionlist, initial_state='OptionList', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Option list') return [], next_state, [] def option_list_item(self, match): offset = self.state_machine.abs_line_offset() options = self.parse_option_marker(match) indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) if not indented: # not an option list item self.goto_line(offset) raise statemachine.TransitionCorrection('text') option_group = nodes.option_group('', *options) description = nodes.description('\n'.join(indented)) option_list_item = nodes.option_list_item('', option_group, description) if indented: self.nested_parse(indented, input_offset=line_offset, node=description) return option_list_item, blank_finish def parse_option_marker(self, match): """ Return a list of `node.option` and `node.option_argument` objects, parsed from an option marker match. :Exception: `MarkupError` for invalid option markers. """ optlist = [] optionstrings = match.group().rstrip().split(', ') for optionstring in optionstrings: tokens = optionstring.split() delimiter = ' ' firstopt = tokens[0].split('=') if len(firstopt) > 1: # "--opt=value" form tokens[:1] = firstopt delimiter = '=' elif (len(tokens[0]) > 2 and ((tokens[0].startswith('-') and not tokens[0].startswith('--')) or tokens[0].startswith('+'))): # "-ovalue" form tokens[:1] = [tokens[0][:2], tokens[0][2:]] delimiter = '' if len(tokens) > 1 and (tokens[1].startswith('<') and tokens[-1].endswith('>')): # "-o <value1 value2>" form; join all values into one token tokens[1:] = [' '.join(tokens[1:])] if 0 < len(tokens) <= 2: option = nodes.option(optionstring) option += nodes.option_string(tokens[0], tokens[0]) if len(tokens) > 1: option += nodes.option_argument(tokens[1], tokens[1], delimiter=delimiter) optlist.append(option) else: raise MarkupError( 'wrong number of option tokens (=%s), should be 1 or 2: ' '"%s"' % (len(tokens), optionstring), self.state_machine.abs_line_number() + 1) return optlist def doctest(self, match, context, next_state): data = '\n'.join(self.state_machine.get_text_block()) self.parent += nodes.doctest_block(data, data) return [], next_state, [] def line_block(self, match, context, next_state): """First line of a line block.""" block = nodes.line_block() self.parent += block lineno = self.state_machine.abs_line_number() line, messages, blank_finish = self.line_block_line(match, lineno) block += line self.parent += messages if not blank_finish: offset = self.state_machine.line_offset + 1 # next line new_line_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=block, initial_state='LineBlock', blank_finish=0) self.goto_line(new_line_offset) if not blank_finish: self.parent += self.reporter.warning( 'Line block ends without a blank line.', line=(self.state_machine.abs_line_number() + 1)) if len(block): if block[0].indent is None: block[0].indent = 0 self.nest_line_block_lines(block) return [], next_state, [] def line_block_line(self, match, lineno): """Return one line element of a line_block.""" indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), until_blank=1) text = u'\n'.join(indented) text_nodes, messages = self.inline_text(text, lineno) line = nodes.line(text, '', *text_nodes) if match.string.rstrip() != '|': # not empty line.indent = len(match.group(1)) - 1 return line, messages, blank_finish def nest_line_block_lines(self, block): for index in range(1, len(block)): if block[index].indent is None: block[index].indent = block[index - 1].indent self.nest_line_block_segment(block) def nest_line_block_segment(self, block): indents = [item.indent for item in block] least = min(indents) new_items = [] new_block = nodes.line_block() for item in block: if item.indent > least: new_block.append(item) else: if len(new_block): self.nest_line_block_segment(new_block) new_items.append(new_block) new_block = nodes.line_block() new_items.append(item) if len(new_block): self.nest_line_block_segment(new_block) new_items.append(new_block) block[:] = new_items def grid_table_top(self, match, context, next_state): """Top border of a full table.""" return self.table_top(match, context, next_state, self.isolate_grid_table, tableparser.GridTableParser) def simple_table_top(self, match, context, next_state): """Top border of a simple table.""" return self.table_top(match, context, next_state, self.isolate_simple_table, tableparser.SimpleTableParser) def table_top(self, match, context, next_state, isolate_function, parser_class): """Top border of a generic table.""" nodelist, blank_finish = self.table(isolate_function, parser_class) self.parent += nodelist if not blank_finish: msg = self.reporter.warning( 'Blank line required after table.', line=self.state_machine.abs_line_number() + 1) self.parent += msg return [], next_state, [] def table(self, isolate_function, parser_class): """Parse a table.""" block, messages, blank_finish = isolate_function() if block: try: parser = parser_class() tabledata = parser.parse(block) tableline = (self.state_machine.abs_line_number() - len(block) + 1) table = self.build_table(tabledata, tableline) nodelist = [table] + messages except tableparser.TableMarkupError, detail: nodelist = self.malformed_table( block, ' '.join(detail.args)) + messages else: nodelist = messages return nodelist, blank_finish def isolate_grid_table(self): messages = [] blank_finish = 1 try: block = self.state_machine.get_text_block(flush_left=1) except statemachine.UnexpectedIndentationError, instance: block, source, lineno = instance.args messages.append(self.reporter.error('Unexpected indentation.', source=source, line=lineno)) blank_finish = 0 block.disconnect() # for East Asian chars: block.pad_double_width(self.double_width_pad_char) width = len(block[0].strip()) for i in range(len(block)): block[i] = block[i].strip() if block[i][0] not in '+|': # check left edge blank_finish = 0 self.state_machine.previous_line(len(block) - i) del block[i:] break if not self.grid_table_top_pat.match(block[-1]): # find bottom blank_finish = 0 # from second-last to third line of table: for i in range(len(block) - 2, 1, -1): if self.grid_table_top_pat.match(block[i]): self.state_machine.previous_line(len(block) - i + 1) del block[i+1:] break else: messages.extend(self.malformed_table(block)) return [], messages, blank_finish for i in range(len(block)): # check right edge if len(block[i]) != width or block[i][-1] not in '+|': messages.extend(self.malformed_table(block)) return [], messages, blank_finish return block, messages, blank_finish def isolate_simple_table(self): start = self.state_machine.line_offset lines = self.state_machine.input_lines limit = len(lines) - 1 toplen = len(lines[start].strip()) pattern_match = self.simple_table_border_pat.match found = 0 found_at = None i = start + 1 while i <= limit: line = lines[i] match = pattern_match(line) if match: if len(line.strip()) != toplen: self.state_machine.next_line(i - start) messages = self.malformed_table( lines[start:i+1], 'Bottom/header table border does ' 'not match top border.') return [], messages, i == limit or not lines[i+1].strip() found += 1 found_at = i if found == 2 or i == limit or not lines[i+1].strip(): end = i break i += 1 else: # reached end of input_lines if found: extra = ' or no blank line after table bottom' self.state_machine.next_line(found_at - start) block = lines[start:found_at+1] else: extra = '' self.state_machine.next_line(i - start - 1) block = lines[start:] messages = self.malformed_table( block, 'No bottom table border found%s.' % extra) return [], messages, not extra self.state_machine.next_line(end - start) block = lines[start:end+1] # for East Asian chars: block.pad_double_width(self.double_width_pad_char) return block, [], end == limit or not lines[end+1].strip() def malformed_table(self, block, detail=''): block.replace(self.double_width_pad_char, '') data = '\n'.join(block) message = 'Malformed table.' lineno = self.state_machine.abs_line_number() - len(block) + 1 if detail: message += '\n' + detail error = self.reporter.error(message, nodes.literal_block(data, data), line=lineno) return [error] def build_table(self, tabledata, tableline, stub_columns=0): colwidths, headrows, bodyrows = tabledata table = nodes.table() tgroup = nodes.tgroup(cols=len(colwidths)) table += tgroup for colwidth in colwidths: colspec = nodes.colspec(colwidth=colwidth) if stub_columns: colspec.attributes['stub'] = 1 stub_columns -= 1 tgroup += colspec if headrows: thead = nodes.thead() tgroup += thead for row in headrows: thead += self.build_table_row(row, tableline) tbody = nodes.tbody() tgroup += tbody for row in bodyrows: tbody += self.build_table_row(row, tableline) return table def build_table_row(self, rowdata, tableline): row = nodes.row() for cell in rowdata: if cell is None: continue morerows, morecols, offset, cellblock = cell attributes = {} if morerows: attributes['morerows'] = morerows if morecols: attributes['morecols'] = morecols entry = nodes.entry(**attributes) row += entry if ''.join(cellblock): self.nested_parse(cellblock, input_offset=tableline+offset, node=entry) return row explicit = Struct() """Patterns and constants used for explicit markup recognition.""" explicit.patterns = Struct( target=re.compile(r""" ( _ # anonymous target | # *OR* (?!_) # no underscore at the beginning (?P<quote>`?) # optional open quote (?![ `]) # first char. not space or # backquote (?P<name> # reference name .+? ) %(non_whitespace_escape_before)s (?P=quote) # close quote if open quote used ) (?<!(?<!\x00):) # no unescaped colon at end %(non_whitespace_escape_before)s [ ]? # optional space : # end of reference name ([ ]+|$) # followed by whitespace """ % vars(Inliner), re.VERBOSE), reference=re.compile(r""" ( (?P<simple>%(simplename)s)_ | # *OR* ` # open backquote (?![ ]) # not space (?P<phrase>.+?) # hyperlink phrase %(non_whitespace_escape_before)s `_ # close backquote, # reference mark ) $ # end of string """ % vars(Inliner), re.VERBOSE | re.UNICODE), substitution=re.compile(r""" ( (?![ ]) # first char. not space (?P<name>.+?) # substitution text %(non_whitespace_escape_before)s \| # close delimiter ) ([ ]+|$) # followed by whitespace """ % vars(Inliner), re.VERBOSE),) def footnote(self, match): lineno = self.state_machine.abs_line_number() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) label = match.group(1) name = normalize_name(label) footnote = nodes.footnote('\n'.join(indented)) footnote.line = lineno if name[0] == '#': # auto-numbered name = name[1:] # autonumber label footnote['auto'] = 1 if name: footnote['names'].append(name) self.document.note_autofootnote(footnote) elif name == '*': # auto-symbol name = '' footnote['auto'] = '*' self.document.note_symbol_footnote(footnote) else: # manually numbered footnote += nodes.label('', label) footnote['names'].append(name) self.document.note_footnote(footnote) if name: self.document.note_explicit_target(footnote, footnote) else: self.document.set_id(footnote, footnote) if indented: self.nested_parse(indented, input_offset=offset, node=footnote) return [footnote], blank_finish def citation(self, match): lineno = self.state_machine.abs_line_number() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) label = match.group(1) name = normalize_name(label) citation = nodes.citation('\n'.join(indented)) citation.line = lineno citation += nodes.label('', label) citation['names'].append(name) self.document.note_citation(citation) self.document.note_explicit_target(citation, citation) if indented: self.nested_parse(indented, input_offset=offset, node=citation) return [citation], blank_finish def hyperlink_target(self, match): pattern = self.explicit.patterns.target lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented( match.end(), until_blank=1, strip_indent=0) blocktext = match.string[:match.end()] + '\n'.join(block) block = [escape2null(line) for line in block] escaped = block[0] blockindex = 0 while 1: targetmatch = pattern.match(escaped) if targetmatch: break blockindex += 1 try: escaped += block[blockindex] except IndexError: raise MarkupError('malformed hyperlink target.', lineno) del block[:blockindex] block[0] = (block[0] + ' ')[targetmatch.end()-len(escaped)-1:].strip() target = self.make_target(block, blocktext, lineno, targetmatch.group('name')) return [target], blank_finish def make_target(self, block, block_text, lineno, target_name): target_type, data = self.parse_target(block, block_text, lineno) if target_type == 'refname': target = nodes.target(block_text, '', refname=normalize_name(data)) target.indirect_reference_name = data self.add_target(target_name, '', target, lineno) self.document.note_indirect_target(target) return target elif target_type == 'refuri': target = nodes.target(block_text, '') self.add_target(target_name, data, target, lineno) return target else: return data def parse_target(self, block, block_text, lineno): """ Determine the type of reference of a target. :Return: A 2-tuple, one of: - 'refname' and the indirect reference name - 'refuri' and the URI - 'malformed' and a system_message node """ if block and block[-1].strip()[-1:] == '_': # possible indirect target reference = ' '.join([line.strip() for line in block]) refname = self.is_reference(reference) if refname: return 'refname', refname reference = ''.join([''.join(line.split()) for line in block]) return 'refuri', unescape(reference) def is_reference(self, reference): match = self.explicit.patterns.reference.match( whitespace_normalize_name(reference)) if not match: return None return unescape(match.group('simple') or match.group('phrase')) def add_target(self, targetname, refuri, target, lineno): target.line = lineno if targetname: name = normalize_name(unescape(targetname)) target['names'].append(name) if refuri: uri = self.inliner.adjust_uri(refuri) if uri: target['refuri'] = uri else: raise ApplicationError('problem with URI: %r' % refuri) self.document.note_explicit_target(target, self.parent) else: # anonymous target if refuri: target['refuri'] = refuri target['anonymous'] = 1 self.document.note_anonymous_target(target) def substitution_def(self, match): pattern = self.explicit.patterns.substitution lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), strip_indent=0) blocktext = (match.string[:match.end()] + '\n'.join(block)) block.disconnect() escaped = escape2null(block[0].rstrip()) blockindex = 0 while 1: subdefmatch = pattern.match(escaped) if subdefmatch: break blockindex += 1 try: escaped = escaped + ' ' + escape2null(block[blockindex].strip()) except IndexError: raise MarkupError('malformed substitution definition.', lineno) del block[:blockindex] # strip out the substitution marker block[0] = (block[0].strip() + ' ')[subdefmatch.end()-len(escaped)-1:-1] if not block[0]: del block[0] offset += 1 while block and not block[-1].strip(): block.pop() subname = subdefmatch.group('name') substitution_node = nodes.substitution_definition(blocktext) substitution_node.line = lineno if not block: msg = self.reporter.warning( 'Substitution definition "%s" missing contents.' % subname, nodes.literal_block(blocktext, blocktext), line=lineno) return [msg], blank_finish block[0] = block[0].strip() substitution_node['names'].append( nodes.whitespace_normalize_name(subname)) new_abs_offset, blank_finish = self.nested_list_parse( block, input_offset=offset, node=substitution_node, initial_state='SubstitutionDef', blank_finish=blank_finish) i = 0 for node in substitution_node[:]: if not (isinstance(node, nodes.Inline) or isinstance(node, nodes.Text)): self.parent += substitution_node[i] del substitution_node[i] else: i += 1 for node in substitution_node.traverse(nodes.Element): if self.disallowed_inside_substitution_definitions(node): pformat = nodes.literal_block('', node.pformat().rstrip()) msg = self.reporter.error( 'Substitution definition contains illegal element:', pformat, nodes.literal_block(blocktext, blocktext), line=lineno) return [msg], blank_finish if len(substitution_node) == 0: msg = self.reporter.warning( 'Substitution definition "%s" empty or invalid.' % subname, nodes.literal_block(blocktext, blocktext), line=lineno) return [msg], blank_finish self.document.note_substitution_def( substitution_node, subname, self.parent) return [substitution_node], blank_finish def disallowed_inside_substitution_definitions(self, node): if (node['ids'] or isinstance(node, nodes.reference) and node.get('anonymous') or isinstance(node, nodes.footnote_reference) and node.get('auto')): return 1 else: return 0 def directive(self, match, **option_presets): """Returns a 2-tuple: list of nodes, and a "blank finish" boolean.""" type_name = match.group(1) directive_function, messages = directives.directive( type_name, self.memo.language, self.document) self.parent += messages if directive_function: return self.run_directive( directive_function, match, type_name, option_presets) else: return self.unknown_directive(type_name) def run_directive(self, directive_fn, match, type_name, option_presets): """ Parse a directive then run its directive function. Parameters: - `directive_fn`: The function implementing the directive. Uses function attributes ``arguments``, ``options``, and/or ``content`` if present. - `match`: A regular expression match object which matched the first line of the directive. - `type_name`: The directive name, as used in the source text. - `option_presets`: A dictionary of preset options, defaults for the directive options. Currently, only an "alt" option is passed by substitution definitions (value: the substitution name), which may be used by an embedded image directive. Returns a 2-tuple: list of nodes, and a "blank finish" boolean. """ lineno = self.state_machine.abs_line_number() initial_line_offset = self.state_machine.line_offset indented, indent, line_offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), strip_top=0) block_text = '\n'.join(self.state_machine.input_lines[ initial_line_offset : self.state_machine.line_offset + 1]) try: arguments, options, content, content_offset = ( self.parse_directive_block(indented, line_offset, directive_fn, option_presets)) except MarkupError, detail: error = self.reporter.error( 'Error in "%s" directive:\n%s.' % (type_name, ' '.join(detail.args)), nodes.literal_block(block_text, block_text), line=lineno) return [error], blank_finish result = directive_fn(type_name, arguments, options, content, lineno, content_offset, block_text, self, self.state_machine) return (result, blank_finish or self.state_machine.is_next_line_blank()) def parse_directive_block(self, indented, line_offset, directive_fn, option_presets): arguments = [] options = {} argument_spec = getattr(directive_fn, 'arguments', None) if argument_spec and argument_spec[:2] == (0, 0): argument_spec = None option_spec = getattr(directive_fn, 'options', None) content_spec = getattr(directive_fn, 'content', None) if indented and not indented[0].strip(): indented.trim_start() line_offset += 1 while indented and not indented[-1].strip(): indented.trim_end() if indented and (argument_spec or option_spec): for i in range(len(indented)): if not indented[i].strip(): break else: i += 1 arg_block = indented[:i] content = indented[i+1:] content_offset = line_offset + i + 1 else: content = indented content_offset = line_offset arg_block = [] while content and not content[0].strip(): content.trim_start() content_offset += 1 if option_spec: options, arg_block = self.parse_directive_options( option_presets, option_spec, arg_block) if arg_block and not argument_spec: raise MarkupError('no arguments permitted; blank line ' 'required before content block') if argument_spec: arguments = self.parse_directive_arguments( argument_spec, arg_block) if content and not content_spec: raise MarkupError('no content permitted') return (arguments, options, content, content_offset) def parse_directive_options(self, option_presets, option_spec, arg_block): options = option_presets.copy() for i in range(len(arg_block)): if arg_block[i][:1] == ':': opt_block = arg_block[i:] arg_block = arg_block[:i] break else: opt_block = [] if opt_block: success, data = self.parse_extension_options(option_spec, opt_block) if success: # data is a dict of options options.update(data) else: # data is an error string raise MarkupError(data) return options, arg_block def parse_directive_arguments(self, argument_spec, arg_block): required, optional, last_whitespace = argument_spec arg_text = '\n'.join(arg_block) arguments = arg_text.split() if len(arguments) < required: raise MarkupError('%s argument(s) required, %s supplied' % (required, len(arguments))) elif len(arguments) > required + optional: if last_whitespace: arguments = arg_text.split(None, required + optional - 1) else: raise MarkupError( 'maximum %s argument(s) allowed, %s supplied' % (required + optional, len(arguments))) return arguments def parse_extension_options(self, option_spec, datalines): """ Parse `datalines` for a field list containing extension options matching `option_spec`. :Parameters: - `option_spec`: a mapping of option name to conversion function, which should raise an exception on bad input. - `datalines`: a list of input strings. :Return: - Success value, 1 or 0. - An option dictionary on success, an error string on failure. """ node = nodes.field_list() newline_offset, blank_finish = self.nested_list_parse( datalines, 0, node, initial_state='ExtensionOptions', blank_finish=1) if newline_offset != len(datalines): # incomplete parse of block return 0, 'invalid option block' try: options = utils.extract_extension_options(node, option_spec) except KeyError, detail: return 0, ('unknown option: "%s"' % detail.args[0]) except (ValueError, TypeError), detail: return 0, ('invalid option value: %s' % ' '.join(detail.args)) except utils.ExtensionOptionError, detail: return 0, ('invalid option data: %s' % ' '.join(detail.args)) if blank_finish: return 1, options else: return 0, 'option data incompletely parsed' def unknown_directive(self, type_name): lineno = self.state_machine.abs_line_number() indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(0, strip_indent=0) text = '\n'.join(indented) error = self.reporter.error( 'Unknown directive type "%s".' % type_name, nodes.literal_block(text, text), line=lineno) return [error], blank_finish def comment(self, match): if not match.string[match.end():].strip() \ and self.state_machine.is_next_line_blank(): # an empty comment? return [nodes.comment()], 1 # "A tiny but practical wart." indented, indent, offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end()) while indented and not indented[-1].strip(): indented.trim_end() text = '\n'.join(indented) return [nodes.comment(text, text)], blank_finish explicit.constructs = [ (footnote, re.compile(r""" \.\.[ ]+ # explicit markup start \[ ( # footnote label: [0-9]+ # manually numbered footnote | # *OR* \# # anonymous auto-numbered footnote | # *OR* \#%s # auto-number ed?) footnote label | # *OR* \* # auto-symbol footnote ) \] ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE)), (citation, re.compile(r""" \.\.[ ]+ # explicit markup start \[(%s)\] # citation label ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE)), (hyperlink_target, re.compile(r""" \.\.[ ]+ # explicit markup start _ # target indicator (?![ ]|$) # first char. not space or EOL """, re.VERBOSE)), (substitution_def, re.compile(r""" \.\.[ ]+ # explicit markup start \| # substitution indicator (?![ ]|$) # first char. not space or EOL """, re.VERBOSE)), (directive, re.compile(r""" \.\.[ ]+ # explicit markup start (%s) # directive name [ ]? # optional space :: # directive delimiter ([ ]+|$) # whitespace or end of line """ % Inliner.simplename, re.VERBOSE | re.UNICODE))] def explicit_markup(self, match, context, next_state): """Footnotes, hyperlink targets, directives, comments.""" nodelist, blank_finish = self.explicit_construct(match) self.parent += nodelist self.explicit_list(blank_finish) return [], next_state, [] def explicit_construct(self, match): """Determine which explicit construct this is, parse & return it.""" errors = [] for method, pattern in self.explicit.constructs: expmatch = pattern.match(match.string) if expmatch: try: return method(self, expmatch) except MarkupError, (message, lineno): # never reached? errors.append(self.reporter.warning(message, line=lineno)) break nodelist, blank_finish = self.comment(match) return nodelist + errors, blank_finish def explicit_list(self, blank_finish): """ Create a nested state machine for a series of explicit markup constructs (including anonymous hyperlink targets). """ offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=self.parent, initial_state='Explicit', blank_finish=blank_finish, match_titles=self.state_machine.match_titles) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Explicit markup') def anonymous(self, match, context, next_state): """Anonymous hyperlink targets.""" nodelist, blank_finish = self.anonymous_target(match) self.parent += nodelist self.explicit_list(blank_finish) return [], next_state, [] def anonymous_target(self, match): lineno = self.state_machine.abs_line_number() block, indent, offset, blank_finish \ = self.state_machine.get_first_known_indented(match.end(), until_blank=1) blocktext = match.string[:match.end()] + '\n'.join(block) block = [escape2null(line) for line in block] target = self.make_target(block, blocktext, lineno, '') return [target], blank_finish def line(self, match, context, next_state): """Section title overline or transition marker.""" if self.state_machine.match_titles: return [match.string], 'Line', [] elif match.string.strip() == '::': raise statemachine.TransitionCorrection('text') elif len(match.string.strip()) < 4: msg = self.reporter.info( 'Unexpected possible title overline or transition.\n' "Treating it as ordinary text because it's so short.", line=self.state_machine.abs_line_number()) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = self.state_machine.line msg = self.reporter.severe( 'Unexpected section title or transition.', nodes.literal_block(blocktext, blocktext), line=self.state_machine.abs_line_number()) self.parent += msg return [], next_state, [] def text(self, match, context, next_state): """Titles, definition lists, paragraphs.""" return [match.string], 'Text', [] class RFC2822Body(Body): """ RFC2822 headers are only valid as the first constructs in documents. As soon as anything else appears, the `Body` state should take over. """ patterns = Body.patterns.copy() # can't modify the original patterns['rfc2822'] = r'[!-9;-~]+:( +|$)' initial_transitions = [(name, 'Body') for name in Body.initial_transitions] initial_transitions.insert(-1, ('rfc2822', 'Body')) # just before 'text' def rfc2822(self, match, context, next_state): """RFC2822-style field list item.""" fieldlist = nodes.field_list(classes=['rfc2822']) self.parent += fieldlist field, blank_finish = self.rfc2822_field(match) fieldlist += field offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=fieldlist, initial_state='RFC2822List', blank_finish=blank_finish) self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning( 'RFC2822-style field list') return [], next_state, [] def rfc2822_field(self, match): name = match.string[:match.string.find(':')] indented, indent, line_offset, blank_finish = \ self.state_machine.get_first_known_indented(match.end(), until_blank=1) fieldnode = nodes.field() fieldnode += nodes.field_name(name, name) fieldbody = nodes.field_body('\n'.join(indented)) fieldnode += fieldbody if indented: self.nested_parse(indented, input_offset=line_offset, node=fieldbody) return fieldnode, blank_finish class SpecializedBody(Body): """ Superclass for second and subsequent compound element members. Compound elements are lists and list-like constructs. All transition methods are disabled (redefined as `invalid_input`). Override individual methods in subclasses to re-enable. For example, once an initial bullet list item, say, is recognized, the `BulletList` subclass takes over, with a "bullet_list" node as its container. Upon encountering the initial bullet list item, `Body.bullet` calls its ``self.nested_list_parse`` (`RSTState.nested_list_parse`), which starts up a nested parsing session with `BulletList` as the initial state. Only the ``bullet`` transition method is enabled in `BulletList`; as long as only bullet list items are encountered, they are parsed and inserted into the container. The first construct which is *not* a bullet list item triggers the `invalid_input` method, which ends the nested parse and closes the container. `BulletList` needs to recognize input that is invalid in the context of a bullet list, which means everything *other than* bullet list items, so it inherits the transition list created in `Body`. """ def invalid_input(self, match=None, context=None, next_state=None): """Not a compound element member. Abort this state machine.""" self.state_machine.previous_line() # back up so parent SM can reassess raise EOFError indent = invalid_input bullet = invalid_input enumerator = invalid_input field_marker = invalid_input option_marker = invalid_input doctest = invalid_input line_block = invalid_input grid_table_top = invalid_input simple_table_top = invalid_input explicit_markup = invalid_input anonymous = invalid_input line = invalid_input text = invalid_input class BulletList(SpecializedBody): """Second and subsequent bullet_list list_items.""" def bullet(self, match, context, next_state): """Bullet list item.""" if match.string[0] != self.parent['bullet']: # different bullet: new list self.invalid_input() listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish return [], next_state, [] class DefinitionList(SpecializedBody): """Second and subsequent definition_list_items.""" def text(self, match, context, next_state): """Definition lists.""" return [match.string], 'Definition', [] class EnumeratedList(SpecializedBody): """Second and subsequent enumerated_list list_items.""" def enumerator(self, match, context, next_state): """Enumerated list item.""" format, sequence, text, ordinal = self.parse_enumerator( match, self.parent['enumtype']) if ( format != self.format or (sequence != '#' and (sequence != self.parent['enumtype'] or self.auto or ordinal != (self.lastordinal + 1))) or not self.is_enumerated_list_item(ordinal, sequence, format)): # different enumeration: new list self.invalid_input() if sequence == '#': self.auto = 1 listitem, blank_finish = self.list_item(match.end()) self.parent += listitem self.blank_finish = blank_finish self.lastordinal = ordinal return [], next_state, [] class FieldList(SpecializedBody): """Second and subsequent field_list fields.""" def field_marker(self, match, context, next_state): """Field list field.""" field, blank_finish = self.field(match) self.parent += field self.blank_finish = blank_finish return [], next_state, [] class OptionList(SpecializedBody): """Second and subsequent option_list option_list_items.""" def option_marker(self, match, context, next_state): """Option list item.""" try: option_list_item, blank_finish = self.option_list_item(match) except MarkupError, (message, lineno): self.invalid_input() self.parent += option_list_item self.blank_finish = blank_finish return [], next_state, [] class RFC2822List(SpecializedBody, RFC2822Body): """Second and subsequent RFC2822-style field_list fields.""" patterns = RFC2822Body.patterns initial_transitions = RFC2822Body.initial_transitions def rfc2822(self, match, context, next_state): """RFC2822-style field list item.""" field, blank_finish = self.rfc2822_field(match) self.parent += field self.blank_finish = blank_finish return [], 'RFC2822List', [] blank = SpecializedBody.invalid_input class ExtensionOptions(FieldList): """ Parse field_list fields for extension options. No nested parsing is done (including inline markup parsing). """ def parse_field_body(self, indented, offset, node): """Override `Body.parse_field_body` for simpler parsing.""" lines = [] for line in list(indented) + ['']: if line.strip(): lines.append(line) elif lines: text = '\n'.join(lines) node += nodes.paragraph(text, text) lines = [] class LineBlock(SpecializedBody): """Second and subsequent lines of a line_block.""" blank = SpecializedBody.invalid_input def line_block(self, match, context, next_state): """New line of line block.""" lineno = self.state_machine.abs_line_number() line, messages, blank_finish = self.line_block_line(match, lineno) self.parent += line self.parent.parent += messages self.blank_finish = blank_finish return [], next_state, [] class Explicit(SpecializedBody): """Second and subsequent explicit markup construct.""" def explicit_markup(self, match, context, next_state): """Footnotes, hyperlink targets, directives, comments.""" nodelist, blank_finish = self.explicit_construct(match) self.parent += nodelist self.blank_finish = blank_finish return [], next_state, [] def anonymous(self, match, context, next_state): """Anonymous hyperlink targets.""" nodelist, blank_finish = self.anonymous_target(match) self.parent += nodelist self.blank_finish = blank_finish return [], next_state, [] blank = SpecializedBody.invalid_input class SubstitutionDef(Body): """ Parser for the contents of a substitution_definition element. """ patterns = { 'embedded_directive': re.compile(r'(%s)::( +|$)' % Inliner.simplename, re.UNICODE), 'text': r''} initial_transitions = ['embedded_directive', 'text'] def embedded_directive(self, match, context, next_state): nodelist, blank_finish = self.directive(match, alt=self.parent['names'][0]) self.parent += nodelist if not self.state_machine.at_eof(): self.blank_finish = blank_finish raise EOFError def text(self, match, context, next_state): if not self.state_machine.at_eof(): self.blank_finish = self.state_machine.is_next_line_blank() raise EOFError class Text(RSTState): """ Classifier of second line of a text block. Could be a paragraph, a definition list item, or a title. """ patterns = {'underline': Body.patterns['line'], 'text': r''} initial_transitions = [('underline', 'Body'), ('text', 'Body')] def blank(self, match, context, next_state): """End of paragraph.""" paragraph, literalnext = self.paragraph( context, self.state_machine.abs_line_number() - 1) self.parent += paragraph if literalnext: self.parent += self.literal_block() return [], 'Body', [] def eof(self, context): if context: self.blank(None, context, None) return [] def indent(self, match, context, next_state): """Definition list item.""" definitionlist = nodes.definition_list() definitionlistitem, blank_finish = self.definition_list_item(context) definitionlist += definitionlistitem self.parent += definitionlist offset = self.state_machine.line_offset + 1 # next line newline_offset, blank_finish = self.nested_list_parse( self.state_machine.input_lines[offset:], input_offset=self.state_machine.abs_line_offset() + 1, node=definitionlist, initial_state='DefinitionList', blank_finish=blank_finish, blank_finish_state='Definition') self.goto_line(newline_offset) if not blank_finish: self.parent += self.unindent_warning('Definition list') return [], 'Body', [] def underline(self, match, context, next_state): """Section title.""" lineno = self.state_machine.abs_line_number() title = context[0].rstrip() underline = match.string.rstrip() source = title + '\n' + underline messages = [] if column_width(title) > len(underline): if len(underline) < 4: if self.state_machine.match_titles: msg = self.reporter.info( 'Possible title underline, too short for the title.\n' "Treating it as ordinary text because it's so short.", line=lineno) self.parent += msg raise statemachine.TransitionCorrection('text') else: blocktext = context[0] + '\n' + self.state_machine.line msg = self.reporter.warning( 'Title underline too short.', nodes.literal_block(blocktext, blocktext), line=lineno) messages.append(msg) if not self.state_machine.match_titles: blocktext = context[0] + '\n' + self.state_machine.line msg = self.reporter.severe( 'Unexpected section title.', nodes.literal_block(blocktext, blocktext), line=lineno) self.parent += messages self.parent += msg return [], next_state, [] style = underline[0] context[:] = [] self.section(title, source, style, lineno - 1, messages) return [], next_state, [] def text(self, match, context, next_state): """Paragraph.""" startline = self.state_machine.abs_line_number() - 1 msg = None try: block = self.state_machine.get_text_block(flush_left=1) except statemachine.UnexpectedIndentationError, instance: block, source, lineno = instance.args msg = self.reporter.error('Unexpected indentation.', source=source, line=lineno) lines = context + list(block) paragraph, literalnext = self.paragraph(lines, startline) self.parent += paragraph self.parent += msg if literalnext: try: self.state_machine.next_line() except EOFError: pass self.parent += self.literal_block() return [], next_state, [] def literal_block(self): """Return a list of nodes.""" indented, indent, offset, blank_finish = \ self.state_machine.get_indented() while indented and not indented[-1].strip(): indented.trim_end() if not indented: return self.quoted_literal_block() data = '\n'.join(indented) literal_block = nodes.literal_block(data, data) literal_block.line = offset + 1 nodelist = [literal_block] if not blank_finish: nodelist.append(self.unindent_warning('Literal block')) return nodelist def quoted_literal_block(self): abs_line_offset = self.state_machine.abs_line_offset() offset = self.state_machine.line_offset parent_node = nodes.Element() new_abs_offset = self.nested_parse( self.state_machine.input_lines[offset:], input_offset=abs_line_offset, node=parent_node, match_titles=0, state_machine_kwargs={'state_classes': (QuotedLiteralBlock,), 'initial_state': 'QuotedLiteralBlock'}) self.goto_line(new_abs_offset) return parent_node.children def definition_list_item(self, termline): indented, indent, line_offset, blank_finish = \ self.state_machine.get_indented() definitionlistitem = nodes.definition_list_item( '\n'.join(termline + list(indented))) lineno = self.state_machine.abs_line_number() - 1 definitionlistitem.line = lineno termlist, messages = self.term(termline, lineno) definitionlistitem += termlist definition = nodes.definition('', *messages) definitionlistitem += definition if termline[0][-2:] == '::': definition += self.reporter.info( 'Blank line missing before literal block (after the "::")? ' 'Interpreted as a definition list item.', line=line_offset+1) self.nested_parse(indented, input_offset=line_offset, node=definition) return definitionlistitem, blank_finish classifier_delimiter = re.compile(' +: +') def term(self, lines, lineno): """Return a definition_list's term and optional classifiers.""" assert len(lines) == 1 text_nodes, messages = self.inline_text(lines[0], lineno) term_node = nodes.term() node_list = [term_node] for i in range(len(text_nodes)): node = text_nodes[i] if isinstance(node, nodes.Text): parts = self.classifier_delimiter.split(node.rawsource) if len(parts) == 1: node_list[-1] += node else: node_list[-1] += nodes.Text(parts[0].rstrip()) for part in parts[1:]: classifier_node = nodes.classifier('', part) node_list.append(classifier_node) else: node_list[-1] += node return node_list, messages class SpecializedText(Text): """ Superclass for second and subsequent lines of Text-variants. All transition methods are disabled. Override individual methods in subclasses to re-enable. """ def eof(self, context): """Incomplete construct.""" return [] def invalid_input(self, match=None, context=None, next_state=None): """Not a compound element member. Abort this state machine.""" raise EOFError blank = invalid_input indent = invalid_input underline = invalid_input text = invalid_input class Definition(SpecializedText): """Second line of potential definition_list_item.""" def eof(self, context): """Not a definition.""" self.state_machine.previous_line(2) # so parent SM can reassess return [] def indent(self, match, context, next_state): """Definition list item.""" definitionlistitem, blank_finish = self.definition_list_item(context) self.parent += definitionlistitem self.blank_finish = blank_finish return [], 'DefinitionList', [] class Line(SpecializedText): """ Second line of over- & underlined section title or transition marker. """ eofcheck = 1 # @@@ ??? """Set to 0 while parsing sections, so that we don't catch the EOF.""" def eof(self, context): """Transition marker at end of section or document.""" marker = context[0].strip() if self.memo.section_bubble_up_kludge: self.memo.section_bubble_up_kludge = 0 elif len(marker) < 4: self.state_correction(context) if self.eofcheck: # ignore EOFError with sections lineno = self.state_machine.abs_line_number() - 1 transition = nodes.transition(rawsource=context[0]) transition.line = lineno self.parent += transition self.eofcheck = 1 return [] def blank(self, match, context, next_state): """Transition marker.""" lineno = self.state_machine.abs_line_number() - 1 marker = context[0].strip() if len(marker) < 4: self.state_correction(context) transition = nodes.transition(rawsource=marker) transition.line = lineno self.parent += transition return [], 'Body', [] def text(self, match, context, next_state): """Potential over- & underlined title.""" lineno = self.state_machine.abs_line_number() - 1 overline = context[0] title = match.string underline = '' try: underline = self.state_machine.next_line() except EOFError: blocktext = overline + '\n' + title if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Incomplete section title.', nodes.literal_block(blocktext, blocktext), line=lineno) self.parent += msg return [], 'Body', [] source = '%s\n%s\n%s' % (overline, title, underline) overline = overline.rstrip() underline = underline.rstrip() if not self.transitions['underline'][0].match(underline): blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Missing matching underline for section title overline.', nodes.literal_block(source, source), line=lineno) self.parent += msg return [], 'Body', [] elif overline != underline: blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.severe( 'Title overline & underline mismatch.', nodes.literal_block(source, source), line=lineno) self.parent += msg return [], 'Body', [] title = title.rstrip() messages = [] if column_width(title) > len(overline): blocktext = overline + '\n' + title + '\n' + underline if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 2) else: msg = self.reporter.warning( 'Title overline too short.', nodes.literal_block(source, source), line=lineno) messages.append(msg) style = (overline[0], underline[0]) self.eofcheck = 0 # @@@ not sure this is correct self.section(title.lstrip(), source, style, lineno + 1, messages) self.eofcheck = 1 return [], 'Body', [] indent = text # indented title def underline(self, match, context, next_state): overline = context[0] blocktext = overline + '\n' + self.state_machine.line lineno = self.state_machine.abs_line_number() - 1 if len(overline.rstrip()) < 4: self.short_overline(context, blocktext, lineno, 1) msg = self.reporter.error( 'Invalid section title or transition marker.', nodes.literal_block(blocktext, blocktext), line=lineno) self.parent += msg return [], 'Body', [] def short_overline(self, context, blocktext, lineno, lines=1): msg = self.reporter.info( 'Possible incomplete section title.\nTreating the overline as ' "ordinary text because it's so short.", line=lineno) self.parent += msg self.state_correction(context, lines) def state_correction(self, context, lines=1): self.state_machine.previous_line(lines) context[:] = [] raise statemachine.StateCorrection('Body', 'text') class QuotedLiteralBlock(RSTState): """ Nested parse handler for quoted (unindented) literal blocks. Special-purpose. Not for inclusion in `state_classes`. """ patterns = {'initial_quoted': r'(%(nonalphanum7bit)s)' % Body.pats, 'text': r''} initial_transitions = ('initial_quoted', 'text') def __init__(self, state_machine, debug=0): RSTState.__init__(self, state_machine, debug) self.messages = [] self.initial_lineno = None def blank(self, match, context, next_state): if context: raise EOFError else: return context, next_state, [] def eof(self, context): if context: text = '\n'.join(context) literal_block = nodes.literal_block(text, text) literal_block.line = self.initial_lineno self.parent += literal_block else: self.parent += self.reporter.warning( 'Literal block expected; none found.', line=self.state_machine.abs_line_number()) self.state_machine.previous_line() self.parent += self.messages return [] def indent(self, match, context, next_state): assert context, ('QuotedLiteralBlock.indent: context should not ' 'be empty!') self.messages.append( self.reporter.error('Unexpected indentation.', line=self.state_machine.abs_line_number())) self.state_machine.previous_line() raise EOFError def initial_quoted(self, match, context, next_state): """Match arbitrary quote character on the first line only.""" self.remove_transition('initial_quoted') quote = match.string[0] pattern = re.compile(re.escape(quote)) # New transition matches consistent quotes only: self.add_transition('quoted', (pattern, self.quoted, self.__class__.__name__)) self.initial_lineno = self.state_machine.abs_line_number() return [match.string], next_state, [] def quoted(self, match, context, next_state): """Match consistent quotes on subsequent lines.""" context.append(match.string) return context, next_state, [] def text(self, match, context, next_state): if context: self.messages.append( self.reporter.error('Inconsistent literal block quoting.', line=self.state_machine.abs_line_number())) self.state_machine.previous_line() raise EOFError state_classes = (Body, BulletList, DefinitionList, EnumeratedList, FieldList, OptionList, LineBlock, ExtensionOptions, Explicit, Text, Definition, Line, SubstitutionDef, RFC2822Body, RFC2822List) """Standard set of State classes used to start `RSTStateMachine`."""
{ "repo_name": "hugs/selenium", "path": "selenium/src/py/lib/docutils/parsers/rst/states.py", "copies": "5", "size": "127736", "license": "apache-2.0", "hash": 7439565529592130000, "line_mean": 41.0667565745, "line_max": 80, "alpha_frac": 0.5338980397, "autogenerated": false, "ratio": 4.467855893669115, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7501753933369115, "avg_score": null, "num_lines": null }
__author__ = "David John Gagne <djgagne@ou.edu>" import numpy as np from ContingencyTable import ContingencyTable class ROC(object): def __init__(self, forecasts, observations, thresholds, obs_threshold): self.forecasts = forecasts self.observations = observations self.thresholds = thresholds self.obs_threshold = obs_threshold self.pod = np.zeros(thresholds.shape) self.pofd = np.zeros(thresholds.shape) self.far = np.zeros(thresholds.shape) self.calc_roc() def calc_roc(self): ct = ContingencyTable(0, 0, 0, 0) for t, threshold in enumerate(self.thresholds): tp = np.count_nonzero((self.forecasts >= threshold) & (self.observations >= self.obs_threshold)) fp = np.count_nonzero((self.forecasts >= threshold) & (self.observations < self.obs_threshold)) fn = np.count_nonzero((self.forecasts < threshold) & (self.observations >= self.obs_threshold)) tn = np.count_nonzero((self.forecasts < threshold) & (self.observations < self.obs_threshold)) ct.update(tp, fp, fn, tn) self.pod[t] = ct.pod() self.pofd[t] = ct.pofd() self.far[t] = ct.far() def auc(self): return -np.trapz(self.pod, self.pofd) class Reliability(object): def __init__(self, forecasts, observations, thresholds, obs_threshold): self.forecasts = forecasts self.observations = observations self.thresholds = thresholds self.obs_threshold = obs_threshold self.pos_relative_frequency = np.zeros(self.thresholds.shape) self.total_relative_frequency = np.zeros(self.thresholds.shape) def calc_reliability_curve(self): pos_frequency = np.zeros(self.thresholds.shape) total_frequency = np.zeros(self.thresholds.shape) for t, threshold in enumerate(self.thresholds[:-1]): pos_frequency[t] = np.count_nonzero((threshold <= self.forecasts) & (self.forecasts < self.thresholds[t+1]) & (self.forecasts > self.obs_threshold)) total_frequency[t] = np.count_nonzero((threshold <= self.forecasts) & (self.forecasts < self.thresholds[t+1])) if total_frequency[t] > 0: self.pos_relative_frequency[t] = pos_frequency[t] / float(total_frequency[t]) self.total_relative_frequency[t] = total_frequency / self.forecasts.size else: self.pos_relative_frequency[t] = np.nan self.pos_relative_frequency[-1] = np.nan
{ "repo_name": "djgagne/hagelslag-unidata", "path": "hagelslag/evaluation/ProbabilityMetrics.py", "copies": "1", "size": "2825", "license": "mit", "hash": -1582675608383027700, "line_mean": 45.3114754098, "line_max": 93, "alpha_frac": 0.5720353982, "autogenerated": false, "ratio": 3.995756718528996, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5067792116728996, "avg_score": null, "num_lines": null }
import numpy as np from ..annotations import Annotations from ..utils import verbose from .artifact_detection import _annotations_from_mask @verbose def annotate_nan(raw, *, verbose=None): """Detect segments with NaN and return a new Annotations instance. Parameters ---------- raw : instance of Raw Data to find segments with NaN values. %(verbose)s Returns ------- annot : instance of Annotations New channel-specific annotations for the data. """ data, times = raw.get_data(return_times=True) onsets, durations, ch_names = list(), list(), list() for row, ch_name in zip(data, raw.ch_names): annot = _annotations_from_mask(times, np.isnan(row), 'BAD_NAN') onsets.extend(annot.onset) durations.extend(annot.duration) ch_names.extend([[ch_name]] * len(annot)) annot = Annotations(onsets, durations, 'BAD_NAN', ch_names=ch_names) return annot
{ "repo_name": "mne-tools/mne-python", "path": "mne/preprocessing/annotate_nan.py", "copies": "4", "size": "1029", "license": "bsd-3-clause", "hash": -8441289135116528000, "line_mean": 28.4, "line_max": 72, "alpha_frac": 0.657920311, "autogenerated": false, "ratio": 3.5605536332179932, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6218473944217993, "avg_score": null, "num_lines": null }
__author__ = 'David Karchmer' # https://github.com/ampervue/docker-ffmpeg import sys import argparse import os from subprocess import Popen, PIPE FFMPEG_CMD = ['ffmpeg'] def execute_ffmpeg(args): command = FFMPEG_CMD + args print('Calling: ' + str(command)) pipe = Popen(command, stderr=PIPE) print(str(pipe.stderr.read())) pipe.terminate() print('Done with FFMPEG') def create_thumbnail(input_file_name): #thumbnail_file_name = input_file_name[:-3] + '.jpg' thumbnail_file_name = 'thumbnail.jpg' if os.path.isfile(thumbnail_file_name): os.remove(thumbnail_file_name) # Create a 100x100 thumbnail for the given video ffmpeg_args = ['-i', input_file_name, '-vcodec', 'mjpeg', '-vframes', '1', '-ss', '2', '-s', '100x100', thumbnail_file_name] execute_ffmpeg(ffmpeg_args) return thumbnail_file_name def main(arguments): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--file', dest='file', type=str, help='Input File to Process') args = parser.parse_args(arguments) print(args) if not args.file: print('ERROR: Input file is required') thumbnail_file = create_thumbnail(args.file) if os.path.isfile(thumbnail_file): print('Thmbnail Created: ' + thumbnail_file) else: print('ERROR: Something went wrong') if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
{ "repo_name": "ampervue/docker-ffmpeg", "path": "example/app/script.py", "copies": "1", "size": "1730", "license": "mit", "hash": 7789743415754592000, "line_mean": 23.7142857143, "line_max": 90, "alpha_frac": 0.5647398844, "autogenerated": false, "ratio": 3.914027149321267, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4978767033721267, "avg_score": null, "num_lines": null }
__author__ = 'David Karchmer' # https://github.com/ampervue/docker-python27-ffmpeg import sys import argparse import os from subprocess import Popen, PIPE FFMPEG_CMD = ['ffmpeg'] def execute_ffmpeg(args): command = FFMPEG_CMD + args print('Calling: ' + str(command)) pipe = Popen(command, stderr=PIPE) print(str(pipe.stderr.read())) pipe.terminate() print('Done with FFMPEG') def create_thumbnail(input_file_name): #thumbnail_file_name = input_file_name[:-3] + '.jpg' thumbnail_file_name = 'thumbnail.jpg' if os.path.isfile(thumbnail_file_name): os.remove(thumbnail_file_name) # Create a 100x100 thumbnail for the given video ffmpeg_args = ['-i', input_file_name, '-vcodec', 'mjpeg', '-vframes', '1', '-ss', '2', '-s', '100x100', thumbnail_file_name] execute_ffmpeg(ffmpeg_args) return thumbnail_file_name def main(arguments): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('--file', dest='file', type=str, help='Input File to Process') args = parser.parse_args(arguments) print(args) if not args.file: print('ERROR: Input file is required') thumbnail_file = create_thumbnail(args.file) if os.path.isfile(thumbnail_file): print('Thmbnail Created: ' + thumbnail_file) else: print('ERROR: Something went wrong') if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
{ "repo_name": "ampervue/docker-python34-ffmpeg", "path": "example/app/script.py", "copies": "2", "size": "1739", "license": "mit", "hash": 232259103183536480, "line_mean": 23.8428571429, "line_max": 90, "alpha_frac": 0.5664174813, "autogenerated": false, "ratio": 3.9078651685393258, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5474282649839326, "avg_score": null, "num_lines": null }
__author__ = "David Katz-Wigmore" from File_Creator import WriteFile import ttk import Tkinter as tk import Get_Providers class App(tk.Frame): def __init__(self, master, dictionary): """ Initializes the main frame which will be known as self :param master: :param dictionary: :return: """ tk.Frame.__init__(self, master) self.grid(column=0, row=1, sticky="N,W,S,E") self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.dict = dictionary self.values_dict = {} self.grant_choices = ["C15", "ZZ-127"] self.hp_or_rrh = ["HP", "RRH"] self.reporting_categories = sorted(["Choose a reporting category", "Name", "Social Security Number", "Date of Birth", "Race", "Ethnicity", "Gender", "Veteran Status", "Disabling Condition", "Homeless Living Situation", "Project Entry Date", "Project Exit Date", "Destination", "Personal ID", "Household ID", "Relationship to Head of Household", "Client Location", "Length of Time on Street", "Income Sources (Entry)", "Income Sources (Exit)", "Non-Cash Benefits (Entry)", "Non-Cash Benefits (Exit)", "Insurance (Entry)", "Insurance (Exit)", "Services Provided", "Financial Assistance Provided", "Move-In Date", "Non-Homeless Living Situation", "Date of Move-In", "Year Entered Military Service", "Year Separated from Military Service", "Theaters of Operation", "Military Branch", "Discharge Status", "Household Income as a % of AMI", "HP Screening Score", "Last Permanent Address", "Total Monthly Income (Entry)", "Total Monthly Income (Exit)", "Continuously Homeless One Year", "Times Homeless Past Three Years", "No Head of Household", "Residence Prior to Project Entry", "Multiple Heads of Household", "VAMC Station Number", "Very High Monthly Income (Entry)", "Very High Monthly Income (Exit)" ]) self.state = tk.StringVar(self) self.provider = tk.StringVar(self) self.hp_rrh = tk.StringVar(self) self.grant = tk.StringVar(self) self.reporting_category = tk.StringVar(self) self.value = tk.StringVar(self) self.state.trace("w", self.update_options) self.state_menu = tk.OptionMenu(self, self.state, *self.dict.keys()) self.provider_menu = tk.OptionMenu(self, self.provider, "") self.hp_rrh_menu = tk.OptionMenu(self, self.hp_rrh, *self.hp_or_rrh) self.grant_menu = tk.OptionMenu(self, self.grant, *self.grant_choices) self.reporting_categories_menu = tk.OptionMenu(self, self.reporting_category, *self.reporting_categories) self.values = ttk.Entry(self, width=48, textvariable=self.value) self.add_button = ttk.Button(self, command=self.addition, text="Add") self.tree = ttk.Treeview(self, columns=("Reporting Category", "Error Values"), selectmode="extended", show="headings" ) self.tree.column("#0", width=10) self.tree.column("Reporting Category", width=50) self.tree.heading(0, text="Reporting Category") self.tree.heading(1, text="Error Values") self.y_scroll = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview) self.tree.configure(yscrollcommand=self.y_scroll.set) self.clear = ttk.Button(self, command=self.clear_all, text="Clear All") self.process_button = ttk.Button(self, command=self.process, text="Process") self.state.set("Select Your State") self.provider.set("Select Your Provider") self.grant.set("Select Your Grant") self.hp_rrh.set("Select HP or RRH") self.reporting_category.set("Choose the Reporting Category") self.state_menu.grid(column=0, row=1, padx=2, sticky="E") self.provider_menu.grid(column=1, row=1, padx=2, sticky="E") self.grant_menu.grid(column=2, row=1, padx=2, sticky="W") self.hp_rrh_menu.grid(column=3, row=1, padx=2, sticky="w") self.reporting_categories_menu.grid(column=0, row=2, padx=2, sticky="E") self.values.grid(column=1, columnspan=2, row=2, sticky="W, E") self.add_button.grid(column=3, row=2, sticky="W") self.tree.grid(column=0, columnspan=4, row=3, sticky="E, W") self.y_scroll.grid(column=4, row=3, sticky="N, W, S") self.clear.grid(column=2, row=4, sticky="E") self.process_button.grid(column=3, row=4, sticky="E") def addition(self): """ Adds a new value to the val_dict where the category is the key and the ctid#'s (along with the other included information) is the value. :return: """ self.values_dict[self.reporting_category.get()] = self.value.get() self.set_list() def clear_all(self): """ Clears all the values from the tree widget and the value_dict allowing a new report to be processed without closing and re-opening the program. :return: """ self.values_dict.clear() for child_id in self.tree.get_children(): self.tree.delete(child_id) def process(self): """ Calls the WriteFile function, which converts the value_dict into an excel file. The name of this file will be printed to the terminal window to show that the process is complete :return: """ name = self.provider.get() + " " + self.grant.get() + " " + self.hp_rrh.get() + ".xls" try: WriteFile(str(name), self.values_dict) print(name) except ValueError: print("An error occurred and your file was not saved.") def set_list(self): """ defines the listbox that displays the keys & values of the values_dict. :return: """ for child_id in self.tree.get_children(): self.tree.delete(child_id) for key in self.values_dict.keys(): self.tree.insert("", index="end", values=(key, self.values_dict[key])) def update_options(self, *args): """ This method allows the provider menu to update depending on which state is selected. :param args: :return: """ providers = self.dict[self.state.get()] menu = self.provider_menu["menu"] menu.delete(0, 'end') for provider in providers: menu.add_command(label=provider, command=lambda region=provider: self.provider.set(region)) if __name__ == "__main__": root = tk.Tk() make_dict = Get_Providers.MakeDictionary() app = App(root, make_dict.read_csv()) app.mainloop()
{ "repo_name": "katzwigmore/SSVF-Repositry-DQ-Processor", "path": "RepositoryDQProcessor.py", "copies": "1", "size": "8768", "license": "mit", "hash": 2356222925528093000, "line_mean": 44.4300518135, "line_max": 117, "alpha_frac": 0.4738822993, "autogenerated": false, "ratio": 4.557172557172557, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5531054856472558, "avg_score": null, "num_lines": null }
__author__ = 'David Katz-Wigmore' from re import * from xlwt import * class WriteFile(object): service_point_equivalent_field_names = { "Name": "First/Last Name", "Social Security Number": "SSID", "Date of Birth": "DoB", "Race": "Race 1", "Ethnicity": "Ethnicity", "Gender": "Gender", "Veteran Status": "Veteran Status", "Disabling Condition": "Disabling Condition", "Homeless Living Situation": "Residence Prior to Project Entry", "Project Entry Date": "Entry Date", "Project Exit Date": "Exit Date", "Destination": "Exit Destination", "Personal ID": "CTID", "Household ID": "Household ID", "Relationship to Head of Household": "Relationship to Head of Household", "Client Location": "Client Location", "Length of Time on Street": "Total Number of Months Continuously Homeless Immediately Prior to Project Entry", "Income Sources (Entry)": "Monthly Income (HUD) <-- in the Entry", "Income Sources (Exit)": "Monthly Income (HUD) <-- in the Exit", "Non-Cash Benefits (Entry)": "Non-Cash Benefits (HUD) <-- in the Entry", "Non-Cash Benefits (Exit)": "Non-Cash Benefits (HUD) <-- in the Exit", "Insurance (Entry)": "Health Insurance (HUD) <-- in the Entry", "Insurance (Exit)": "Health Insurance (HUD) <-- in the Exit", "Services Provided": "Services Provided", "Financial Assistance Provided": "Financial Assistance Provided <-- in each service", "Move-In Date": "Initial Placement/Eviction Prevention Date", "Non-Homeless Living Situation": "Residence Prior to Project Entry Does Not Equal Homeless", "Date of Move-In": "Placement Date <-- in Client's Residence / Last Permanent Address", "Year Entered Military Service": "Year Entered Military Service", "Year Separated from Military Service": "Year Separated from Military Service", "Theaters of Operation": "Combat/War Zone", "Military Branch": "Military Branch", "Discharge Status": "Discharge Type", "HP Screening Score": "HP Screening Score", "Household Income as a % of AMI": "Percentage of AMI", "Last Permanent Address": "Client's Residence / Last Permanent Address", "Total Monthly Income (Entry)": "Total Monthly Income (Entry)", "Total Monthly Income (Exit)": "Total Monthly Income (Exit)", "Continuously Homeless One Year": "Continuously Homeless for at Least One Year", "Times Homeless Past Three Years": "Number of Times the Client has been Homeless in the Past Three Years", "No Head of Household": "Relationship to Head of Household & Head of Household", "Residence Prior to Project Entry": "Residence Prior to Project Entry", "Multiple Heads of Household": "Relationship to Head of Household & Head of Household", "VAMC Station Number": "VAMC Station Number", "Very High Monthly Income (Entry)": "Total Monthly Income/Monthly Income (HUD)/Percentage of AMI/" "Percent of Median Family Income", "Very High Monthly Income (Exit)": "Total Monthly Income/Monthly Income (HUD)/Percentage of AMI/" "Percent of Median Family Income" } def __init__(self, title, data_dict): self.data_dict = data_dict self.title = title self.d = {} self.wb = Workbook() self.edit_sheet = self.wb.add_sheet("DQ") self.run() def ctid_finder(self, data, d): """ Finds CTID #'s by searching through the data's values using regex. :param data: :param d: :return: """ search_pattern = compile(u"(?:\d{2}\/\d{2}\/\d{4})|(\d{4,})") for key in data: # print "Wub!" d[key] = findall(search_pattern, self.data_dict[key]) def title_write(self, data): """ Writes the column heads to the excel sheet. :param data: :return: """ col = 0 for key in data.keys(): r = 0 # print "Ping!" # print "Col: %d, Row: %d" % (col, r) # print key self.edit_sheet.write(r, col, self.service_point_equivalent_field_names[key]) self.data_write(col, r, key) col += 1 def data_write(self, col, row, key): """ Writes CTID #'s to columns beneath the appropriate column heading. :param col: :param row: :param key: :return: """ for value in self.d[key]: try: if int(value) > 1: row += 1 # print "Pong!" # print "Col: %d, Row: %d" % (col, row) # print value self.edit_sheet.write(row, col, int(value)) else: pass except ValueError: pass else: pass def run(self): """ Initializes the class methods in sequence. :return: """ self.ctid_finder(self.data_dict, self.d) self.title_write(self.d) self.wb.save(self.title)
{ "repo_name": "katzwigmore/SSVF-Repositry-DQ-Processor", "path": "File_Creator.py", "copies": "1", "size": "5332", "license": "mit", "hash": -1898365183019421200, "line_mean": 41.656, "line_max": 118, "alpha_frac": 0.5639534884, "autogenerated": false, "ratio": 3.657064471879287, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4721017960279287, "avg_score": null, "num_lines": null }
import board import neopixel import time DELAY = .09 #Controls rate of scan, smaller is faster RED = (60,0,0) WHITE = (20,20,20) BLUE = (0,0,60) p = neopixel.NeoPixel(board.NEOPIXEL, 10) def getColor(n): color = n%3 if color == 1: return RED elif color == 2: return WHITE else: return BLUE def scan(t): for i in range(10): if i+2 < 10: p[i] = getColor(i) p[i+1] = getColor(i+1) p[i+2] = getColor(i+2) p[i-1] = (0,0,0) elif i+1 < 10: p[i] = getColor(i) p[i+1] = getColor(i+1) p[i-1] = (0,0,0) else: p[i] = getColor(i) p[i-1] = (0,0,0) p.write() time.sleep(t) for i in range(8,0,-1): if i-2 > 0: p[i-2] = getColor(i-2) p[i-1] = getColor(i-1) p[i] = getColor(i) p[i+1] = (0,0,0) p.write() time.sleep(t) while True: scan(DELAY)
{ "repo_name": "DaveKT/CircuitPython_Examples", "path": "docs/USAscan.py", "copies": "1", "size": "1297", "license": "mit", "hash": 7681253337298976000, "line_mean": 21.7543859649, "line_max": 70, "alpha_frac": 0.5096376253, "autogenerated": false, "ratio": 2.6797520661157024, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8599850837612255, "avg_score": 0.01790777076068946, "num_lines": 57 }
import board import neopixel import time import busio import adafruit_lis3dh ACCEL_RANGE = adafruit_lis3dh.RANGE_16_G p = neopixel.NeoPixel(board.NEOPIXEL, 10) i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA) lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=25) lis3dh.range = ACCEL_RANGE while True: if(lis3dh.acceleration[0] < 1 and lis3dh.acceleration[0] > -1): p.fill((0,50,10)) elif(lis3dh.acceleration[0] < 3 and lis3dh.acceleration[0] > -3): p.fill((0,0,50)) elif(lis3dh.acceleration[0] < 6 and lis3dh.acceleration[0] > -6): p.fill((25, 0, 25)) elif(lis3dh.acceleration[0] < 10 and lis3dh.acceleration[0] > -10): p.fill((50, 0, 10)) else: p.fill((0,0,0)) p.write() time.sleep(.05)
{ "repo_name": "DaveKT/CircuitPython_Examples", "path": "docs/accelerometer.py", "copies": "1", "size": "1144", "license": "mit", "hash": 2708187882784760300, "line_mean": 27.6, "line_max": 71, "alpha_frac": 0.6809440559, "autogenerated": false, "ratio": 2.4288747346072186, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8576879762480981, "avg_score": 0.006587805605247465, "num_lines": 40 }
import board import digitalio import neopixel p = neopixel.NeoPixel(board.NEOPIXEL, 10) #Initialize Buttons A and B button_a = digitalio.DigitalInOut(board.BUTTON_A) button_a.switch_to_input(pull=digitalio.Pull.DOWN) button_b = digitalio.DigitalInOut(board.BUTTON_B) button_b.switch_to_input(pull=digitalio.Pull.DOWN) def blue_star(): for i in range(10): if i%2 == 0: p[i] = (0,15,50) else: p[i] = (0,0,0) p.write() def white_circle(): for i in range(10): p[i] = (25, 25, 25) p.write() def black(): for i in range(10): p[i] = (0, 0, 0) p.write() while True: if button_a.value: blue_star() elif button_b.value: white_circle() else: black()
{ "repo_name": "DaveKT/CircuitPython_Examples", "path": "docs/buttons.py", "copies": "1", "size": "1049", "license": "mit", "hash": 3901396078308828700, "line_mean": 20.4081632653, "line_max": 70, "alpha_frac": 0.6224976168, "autogenerated": false, "ratio": 2.7973333333333334, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.39198309501333334, "avg_score": null, "num_lines": null }
__author__ = 'David L Gibbs' import scipy.sparse as sp import scipy.sparse.linalg as lin import numpy as np def weightsum(nodes,tup): totwt = 0.0 for ti in tup: totwt += nodes[ti][2] return(totwt) def scoreSoln(soln, s, smat, nodes): # soln -- the solutions set S # smat -- nxn sparse matrix # s -- the program state wt = weightsum(nodes,soln) n = (smat.shape[0]) ts = [i for i in xrange(n) if i not in soln] # set T idn = sp.eye(len(ts),len(ts)) pst = subMatrix(soln, ts, smat) # prob of S to T pts = subMatrix(ts, soln, smat) # prob of T to S ptt = subMatrix(ts, ts, smat) # prob of T to T lap = sp.csc_matrix(idn-ptt) pst_t = sp.csc_matrix(pst.transpose()) lap_t = sp.csc_matrix(lap.transpose()) if s["mode"] == "both": return(scoreBoth(s,lap,pts,lap_t,pst_t,wt)) elif s["mode"] == "tx": return(scoreTX(s,lap_t,pst_t,wt)) elif s["mode"] == "rx": return(scoreRX(s,lap,pts,wt)) else: print "ScoreSoln Error! mode must be rx, tx, or both." sys.exit(1) def scoreBoth(s,lap,pts,lap_t,pst_t,wt): try: f = lin.spsolve(lap, pts) h = lin.spsolve(lap_t, pst_t) except: # a singular matrix ... must solve each vector separately vecs = pts.shape[1] vlen = pts.shape[0] #print(vecs) fsolns = [] hsolns = [] for i in range(vecs): pts2 = pts[:,i].todense() pst_t2 = pst_t[:,i].todense() f1 = lin.bicgstab(lap, pts2)[0] h1 = lin.bicgstab(lap_t, pst_t2)[0] fsolns.append(f1) hsolns.append(h1) f = np.matrix(fsolns) h = np.matrix(hsolns) f = f.transpose() h = h.transpose() if type(f) == type(np.array([])): # came back as an array fh = f+h score = fh.sum() touch = (fh > s["tx"]).sum() else: # came back as a sparse matrix fsum = np.array(f.sum(1)).flatten() hsum = np.array(h.sum(1)).flatten() fh = fsum + hsum touch = sum(fh > s["tx"]) # best score; best touch # return((touch+wt, touch)) def scoreRX(s,lap,pts,wt): f = lin.spsolve(lap, pts) if type(f) == type(np.array([])): # came back as an array ftouch = sum(f > s["rx"]) else: # came back as a sparse matrix fsum = np.array(f.sum(1)).flatten() ftouch = sum(fsum > s["rx"]) return((ftouch+wt, ftouch)) def scoreTX(s, lap_t, pst_t, wt): try: h = lin.spsolve(lap_t, pst_t) except: # a singular matrix ... must solve each vector separately vecs = pst_t.shape[1] hsolns = [] for i in range(vecs): pst_t2 = pst_t[:,i].todense() h1 = lin.bicgstab(lap_t, pst_t2)[0] hsolns.append(h1) h = np.matrix(hsolns) h = h.transpose() if type(h) == type(np.array([])): # came back as an array htouch = sum(h > s["tx"]) else: # came back as a sparse matrix hsum = np.array(h.sum(1)).flatten() htouch = sum(hsum > s["tx"]) return((htouch+wt, htouch)) def scoreMats(soln, s, smat): # ss -- the solutions set S # smat -- nxn sparse matrix # ts -- the set T n = (smat.shape[0]) ts = [i for i in xrange(n) if i not in soln] idn = sp.eye(len(ts)) pst = subMatrix(soln, ts, smat) pts = subMatrix(ts, soln, smat) ptt = subMatrix(ts, ts, smat) lap = sp.csc_matrix(idn-ptt) pst_t = sp.csc_matrix(pst.transpose()) lap_t = sp.csc_matrix(lap.transpose()) f = lin.spsolve(lap, pts) h = lin.spsolve(lap_t, pst_t) return((f,h)) def subMatrix(rows, cols, A): a1 = A.tocsc()[:,cols] a2 = a1.tocsr()[rows,:] return(a2) #return(A.tocsr()[rows,:].tocsc()[:,cols]) def scoreMax(solns, s): sortedSolns = sorted(solns, key=lambda x: x[1][1], reverse=True) if (sortedSolns[0][1][1] > sortedSolns[1][1][1]): # if the top two scores are the same, then we need to consider the edge weights solns = [ x for x in solns if x[1][1] == sortedSolns[0][1][1] ] # get out the solns that have the same top touch sortedSolns = sorted(solns, key=lambda x: x[1][0], reverse=True) # sort by the score within that group. return(sortedSolns[0])
{ "repo_name": "Gibbsdavidl/miergolf", "path": "src/diffusion.py", "copies": "1", "size": "4336", "license": "bsd-3-clause", "hash": -3225911251495464400, "line_mean": 30.6496350365, "line_max": 120, "alpha_frac": 0.5479704797, "autogenerated": false, "ratio": 2.8302872062663185, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38782576859663187, "avg_score": null, "num_lines": null }
__author__ = 'davidl' from ate_notify_monitor.new_notifier.drivers.base_driver import BaseMonitorDriver import ate_notify_monitor.new_notifier.config from tornado.options import options class HttpMonitorDriver(BaseMonitorDriver): def __init__(self, logger): self.logger = logger self.monitor_http_host = options.monitor_http_host def notify(self, fixture_id, info): url = 'http://{}/wssrv/api/notification'.format(self.monitor_url) self.__logger.debug(url) status_list['fixture_id'] = fixture_id status_list['timestamp'] = time.time() # data = {'fixture_id': fixture_id,'status_list':status_list} headers = {'content-type': 'application/json'} # self.__logger.debug('url: {}'.format( url)) try: r = requests.post(url, data=json.dumps(status_list), headers=headers, timeout=5.0) except Exception as e: self.__logger.debug('updating monitor failed: {}'.format(str(e))) def notify_blocking_request(self, fixture_id, info): print (info) return True
{ "repo_name": "davidvoler/ate_meteor", "path": "launcher/api/python/notifier/drivers/http_driver.py", "copies": "1", "size": "1092", "license": "mit", "hash": -2535891325735407600, "line_mean": 36.6551724138, "line_max": 94, "alpha_frac": 0.6437728938, "autogenerated": false, "ratio": 3.701694915254237, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4845467809054237, "avg_score": null, "num_lines": null }
__author__ = 'davidl' from tasks import run_sequence, report_execution_status import uuid import time def main(): uuts = [{'serial': '11101', 'id': 0}, {'serial': '11102', 'id': 1}, {'serial': '11103', 'id': 2}, {'serial': '11104', 'id': 3}] sequence = [ {'name': 'test1', 'unique_lock': None, 'wait_lock': None,'progress':10}, {'name': 'test2', 'unique_lock': None, 'wait_lock': None,'progress':20}, {'name': 'test3', 'unique_lock': None, 'wait_lock': None,'progress':30}, {'name': 'test4', 'unique_lock': None, 'wait_lock': None,'progress':40}, {'name': 'test5', 'unique_lock': None, 'wait_lock': None,'progress':50}, {'name': 'test_on_switch', 'unique_lock': None, 'wait_lock': 'on_switch','progress':60}, {'name': 'test6_ps', 'unique_lock': 'ps', 'wait_lock': None,'progress':65}, {'name': 'test7', 'unique_lock': None, 'wait_lock': None,'progress':70}, {'name': 'test8', 'unique_lock': None, 'wait_lock': None,'progress':80}, {'name': 'test9', 'unique_lock': None, 'wait_lock': None,'progress':85}, {'name': 'test10', 'unique_lock': None, 'wait_lock': None,'progress':90}, {'name': 'test11', 'unique_lock': None, 'wait_lock': None,'progress':95}, {'name': 'cleanup', 'unique_lock': None, 'wait_lock': None,'progress':100}, ] execution_id = str(uuid.uuid4()) fixture_id = 'kay8KPM4yGXiCJHui' report_execution_status(fixture_id, 'running') print (uuts) for uut in uuts: res = run_sequence.delay(fixture_id, execution_id, uut, sequence) print (res) if __name__ == '__main__': main()
{ "repo_name": "davidvoler/ate_meteor", "path": "launcher/celery_client.py", "copies": "1", "size": "1915", "license": "mit", "hash": 6116088632255652000, "line_mean": 29.3968253968, "line_max": 73, "alpha_frac": 0.4877284595, "autogenerated": false, "ratio": 3.377425044091711, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4365153503591711, "avg_score": null, "num_lines": null }
__author__ = 'davidl' from tornado.options import define define("monitor_http_driver", default=False, help='use http driver to send notification', type=bool) define("monitor_redis_driver", default=False, help='use redis driver to send notification', type=bool) define("monitor_ddp_driver", default=False, help='use ddp driver to send notification', type=bool) define("monitor_http_host", default='', help='address of http server for notification', type=str) define("monitor_http_timeout", default=60, help='http timeout in seconds', type=int) define("monitor_redis_host", default='', help='address of redis server for notification', type=str) define("monitor_redis_port", default=6379, help='address of redis server for notification', type=int) define("monitor_redis_db", default=0, help='address of redis server for notification', type=int) define("monitor_ddp_host", default='', help='address of ddp server for notification', type=str) define("monitor_user_timeout", default=60, help='User response timeout in seconds', type=int)
{ "repo_name": "davidvoler/ate_meteor", "path": "launcher/api/python/notifier/config.py", "copies": "1", "size": "1041", "license": "mit", "hash": -246966360515027600, "line_mean": 48.5714285714, "line_max": 102, "alpha_frac": 0.7531219981, "autogenerated": false, "ratio": 3.7446043165467624, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9732713988058689, "avg_score": 0.0530024653176146, "num_lines": 21 }
__author__ = 'davidl' import redis from ate_notify_monitor.new_notifier.drivers.base_driver import BaseMonitorDriver import ate_notify_monitor.new_notifier.config from tornado.options import options class RedisMonitorDriver(BaseMonitorDriver): def __init__(self, logger): self.logger = logger self.redis_host = options.monitor_redis_host self.redis_db = options.monitor_redis_db self.redis_port = options.monitor_redis_port self.pool = redis.ConnectionPool(host=self.redis_host, port=self.redis_port, db=self.redis_db) self._redis_connection = redis.Redis(connection_pool=self.pool) self.pub_sub_channel = self._redis_connection.pubsub() def notify(self, fixture_id, info): self._redis_connection.publish(fixture_id, info) def notify_blocking_request(self, fixture_id, info): """ TODO: use publish and subscribe to a new channel for response :param info: :return: """ print (info) return True
{ "repo_name": "davidvoler/ate_meteor", "path": "launcher/api/python/notifier/drivers/redis_driver.py", "copies": "1", "size": "1029", "license": "mit", "hash": 6098932888038103000, "line_mean": 35.75, "line_max": 102, "alpha_frac": 0.6783284742, "autogenerated": false, "ratio": 3.811111111111111, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49894395853111106, "avg_score": null, "num_lines": null }
__author__ = 'davidl' import time from redlock import RedLock from redis import Redis import pickle """ dlm = RedLock('example') my_lock = dlm.acquire() print ('now example is locked') dlm.release() print ('now example it is free') """ class ExecutionStatusLock(object): def __init__(self, execution_id, process_id): self.redis = Redis() self.execution_id = execution_id self.process_id = process_id self.active_key = 'active:{}'.format(self.execution_id) self.redis.hset(self.active_key, self.process_id, 1) print ('process_id:{} - is now active'.format(self.process_id)) def end_process(self): self.redis.hdel(self.active_key, self.process_id) print ('process_id:{} - exited'.format(self.process_id)) def _are_all_ready(self, resource): pipe = self.redis.pipeline() pipe.hlen(self.active_key) pipe.hlen('{}:{}'.format(self.execution_id, resource)) res = pipe.execute() # print(res) if res[0] <= res[1]: return True else: return False def wait_for_all(self, resource, retry=6000, interval=0.01): resource_key = '{}:{}'.format(self.execution_id, resource) self.redis.hset(resource_key, self.process_id, 1) print ('Waiting for all:{}'.format(resource)) for i in range(retry): if self._are_all_ready(resource): print ('Resource :{} after {} retry'.format(resource, i)) return True time.sleep(interval) print('Expired after {} seconds'.format(retry * interval)) return False class SharedWaitResource(object): """ Process safe shared resource shared amongst few running process. Scenario: The first process may change the resource state (on/off) Then it should wait for other running process to get to the point where the resource is needed. When all Active process """ def __init__(self, execution_id, process_id, resource): self.redis = Redis() self.execution_id = execution_id self.resource = resource self.process_id = process_id self.key = '{}:{}'.format(self.execution_id, self.resource) self.active_key = 'active:{}'.format(self.execution_id) def active_process(self): active = self.redis.get(self.active_key) print ('Active Process:{}'.format(active)) print (active) return len(active) def get_state(self): resource_key = { 'state': None, 'waiting': [] } self.redis.setnx(self.key, resource_key) resource_key = self.redis.get(self.key) return resource_key['state'] def set_state(self, state): resource_key = { 'state': state, 'waiting': [self.process_id] } self.redis.setnx(self.key, resource_key) resource_key = self.redis.get(self.key) print (resource_key) print (resource_key) print (type(resource_key)) if resource_key['state'] == state: return True else: return False def when_ready(self, retry=500, interval=0.02): print ('when_ready') # self.access_key.acquire() # What if lock resource_key = self.redis.get(self.key) print(resource_key) if not resource_key: # Someone deleted the resource or it was never created. Raise Exception print ('when_ready: no resource key') return False else: if self.process_id not in resource_key['waiting']: resource_key['waiting'].append(self.process_id) self.redis.set(self.key, resource_key) self.access_key.release() for i in range(0, retry): resource_key = self.redis.get(self.key) print (resource_key) if len(resource_key['waiting']) >= self.active_process(): return True else: time.sleep(interval) # here we should raise timeout exception print ('when_ready: Exceeded wait time') return False def set_and_wait(self, state, retry=500, interval=0.02): if not self.set_state(state): print ('set_and_wait:Fail') return False return self.when_ready(retry, interval)
{ "repo_name": "davidvoler/ate_meteor", "path": "launcher/api/python/locks.py", "copies": "1", "size": "4399", "license": "mit", "hash": -5002636137272893000, "line_mean": 32.0751879699, "line_max": 99, "alpha_frac": 0.5855876336, "autogenerated": false, "ratio": 3.899822695035461, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.99713491519355, "avg_score": 0.0028122353399921227, "num_lines": 133 }
__author__ = 'davidl' controller_template = \ """ (function () { /** * This Controllers ........ * * using the following services * */ function $ClassName$Controller($ClassName$Service) { var self = this; self.list = []; self.load = function () { var req = $ClassName$Service.load(self.serial); req.success(function (data) { if (data.status == 0) { self.list = data.data; } else { self.error = data.error; } }).error(function (data) { self.error = data; }); }; self.load(); } angular.module('ate.common') .controller('$ClassName$Controller', ['$ClassName$Service', $ClassName$Controller]); }()); """ def create_controller(class_name, module_name): #ret = handler_template.format(class_name, module_name) ret = controller_template.replace('$ClassName$',class_name) ret = ret.replace('$module_name$',module_name) return ret
{ "repo_name": "davidvoler/mongodb-tornado-angular", "path": "utils/generator/templates/controller.py", "copies": "2", "size": "1085", "license": "mit", "hash": 1096822488146406400, "line_mean": 25.4634146341, "line_max": 92, "alpha_frac": 0.5142857143, "autogenerated": false, "ratio": 4.09433962264151, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.560862533694151, "avg_score": null, "num_lines": null }
__author__ = 'davidl' from src.base_handler import BaseHandler from bson.json_util import dumps, loads from bson.objectid import ObjectId from admin.drivers.projects import ProjectsManager from tornado.options import options class ProjectHoursAdminHandler(BaseHandler): """ Project hours admin handler """ def initialize(self): pass def get(self): """ get implementation :return: :rtype: """ status = 0 error = '' debug = '' data = None result = ProjectsManager.load_projects() if result: data = result else: data = None status = -10 error = "Can't find projects in database" debug = "Could be OK if database is new or cleaned up" self.write(dumps({ 'status': status, 'error': error, 'debug': debug, 'data': data })) def put(self): """ put implementation :return: :rtype: """ status = -10 error = 'Save failed for some reason' debug = 'Have no idea why this would happen, check mongod!' data = None body = loads(self.request.body.decode("utf-8")) result = ProjectsManager.save_projects(body, user=self.get_current_user()) if result is True: status = 0 error = '' debug = '' data = True self.write(dumps({ 'status': status, 'error': error, 'debug': debug, 'data': data }))
{ "repo_name": "miooim/project_hours", "path": "src/admin/ph_admin_handler.py", "copies": "1", "size": "1642", "license": "mit", "hash": -4845135100976659000, "line_mean": 22.7971014493, "line_max": 82, "alpha_frac": 0.512180268, "autogenerated": false, "ratio": 4.4863387978142075, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0001746114894360049, "num_lines": 69 }
__author__ = 'davidl' from src.base_handler import BaseHandler from bson.json_util import dumps, loads from bson.objectid import ObjectId from src.utils import get_logger, get_mongodb_connection, get_driver from tornado.options import options class LoginHandler(BaseHandler): def initialize(self): self.connection = get_mongodb_connection() self._db = self.connection[options.auth_db] self.logger = get_logger('auth') self.auth_driver = get_driver(options.auth_driver) def user_permissions(self, user): """ Get a list of actions the user can perform :param user: a mongo user document :return: """ try: user_groups = user['groups'] except: return [] groups = self._db['groups'].find({'_id': {'$in': user_groups}}) print(groups) ret = [] for g in groups: for action in g['actions']: ret.append(action) return ret def get(self): username = self.get_current_user() if not username: self.write(dumps({ 'status': -1, 'error': 'user is not logged in', 'debug': '', 'data': [] })) return user = self._db['users'].find_one({'username': username}) print(user) perms = self.user_permissions(user) self.write(dumps({ 'status': 0, 'error': '', 'debug': '', 'data': perms })) def post(self): """ Post action is used for login Expecting username password in request body :return: """ body = loads(self.request.body.decode("utf-8")) try: username = body['username'] password = body['password'] except: self.write({'status': -2, 'error': 'User or password are missing', 'user': None, 'debug': ''}) return auth = self.auth_driver.auth_user(username, password) print (auth) if auth['data']: user = self._db['users'].find_one({'username': username}) if not user: oid = ObjectId() self._db['users'].insert({'_id': str(oid), 'username': username, 'groups': [], 'is_new': True}) user = self._db['users'].find_one({'_id': username}) self.set_cookie(options.auth_cookie_name, username) auth['permission'] = self.user_permissions(user) self.write(dumps(auth)) self.finish() else: self.write(dumps(auth)) self.finish() def put(self): self.write(dumps({'status': 0})) self.clear_cookie(options.auth_cookie_name)
{ "repo_name": "miooim/project_hours", "path": "src/auth/login_handler.py", "copies": "1", "size": "2878", "license": "mit", "hash": 7548004615290385000, "line_mean": 29.2947368421, "line_max": 111, "alpha_frac": 0.5090340514, "autogenerated": false, "ratio": 4.270029673590504, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.012963659147869675, "num_lines": 95 }
__author__ = 'davidl' from src.base_handler import BaseHandler from bson.json_util import dumps, loads from bson.objectid import ObjectId from src.utils import get_logger from tornado.options import options class LoginHandler(BaseHandler): def initialize(self): self.logger = get_logger('auth') def post(self): """ Post action is used for login Expecting username password in request body :return: """ body = loads(self.request.body.decode("utf-8")) authenticated = -1 error = 'Wrong password' user_type = '' try: username = body['username'] password = body['password'] except: self.write({'status': -2, 'error': 'User or password are missing', 'user': None, 'debug': ''}) return if username == 'dev': if password ==options.dev_pass: authenticated = 0 error = '' user_type = 'dev' elif username == 'opr': if password ==options.opr_pass: authenticated = 0 error = '' user_type = 'opr' elif username == 'tst': if password ==options.tst_pass: authenticated = 0 error = '' user_type = 'tst' else: error = 'Wrong username - username can be dev, opr or tst' self.set_cookie(options.auth_cookie_name, username) self.write(dumps({'status': authenticated, 'error': error, 'data': user_type})) def put(self): self.write(dumps({'status': 0})) self.clear_cookie(options.auth_cookie_name)
{ "repo_name": "davidvoler/social-language-learning-platform", "path": "src/home/login_handler.py", "copies": "1", "size": "1806", "license": "mit", "hash": 1374196998189038600, "line_mean": 26.3636363636, "line_max": 70, "alpha_frac": 0.5071982281, "autogenerated": false, "ratio": 4.47029702970297, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.547749525780297, "avg_score": null, "num_lines": null }
__author__ = 'davidl' import os import ldap3 from tornado.options import options from ldap3 import Server, Connection from utils import get_logger, get_mongodb_connection class LdapAuth(object): """ Authentication with LDAP/Active Directory """ def __init__(self): self.connection = get_mongodb_connection() self._db = self.connection[options.auth_db] self.logger = get_logger('auth') def auth_user(self, username, password): """ Authenticate a user with username password :param username: :param password: :return: { status:0 = ok, any other number indicating an error error:'describe the error to the user' debug:'debug information to be used during development' data: True/False : True valid username password, False - user name password ok } """ status = 0 error = '' debug = '' data = True server = Server(options.active_directory_server) connection = Connection(server, user=options.active_directory_username, password=options.active_directory_password, auto_bind=ldap3.AUTO_BIND_NO_TLS, authentication=ldap3.AUTH_SIMPLE) with connection: if not connection.search(options.active_directory_search_def, '(sAMAccountName={})'.format(username), ldap3.SEARCH_SCOPE_WHOLE_SUBTREE, attributes=ldap3.ALL_ATTRIBUTES): debug = 'Error Connecting to active directory server' status = -2 data = False else: try: c2 = Connection(server, user=connection.response[0]['dn'], password=password, auto_bind=ldap3.AUTO_BIND_NO_TLS, authentication=ldap3.AUTH_SIMPLE) except ldap3.core.exceptions.LDAPBindError as e: debug = str(e) data = False status = -1 error = 'Wrong username/password' return {'status': status, 'error': error, 'debug': debug, 'data': data} def user_permission(self, username, action): """ Checks if user has permission to do certain action :param username: :param action: :return: a dictionary with the following format { status: 0 = ok, any other number indicating an error error:'describe the error to the user' debug:'debug information to be used during development' data: True/False : True user has permission for action, False - user has no permission for action } """ raise NotImplementedError('user_permission must be implemented')
{ "repo_name": "miooim/project_hours", "path": "src/auth/ldap_auth.py", "copies": "1", "size": "2927", "license": "mit", "hash": -4326190120200604000, "line_mean": 35.6, "line_max": 113, "alpha_frac": 0.5616672361, "autogenerated": false, "ratio": 4.846026490066225, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5907693726166225, "avg_score": null, "num_lines": null }
__author__ = 'davidl' import pprint from utils import get_driver from tornado.options import options from xmlrpc.server_process import get_xml_process def xmlrpc_start(): server = get_xml_process() return server.start() def xmlrpc_stop(): server = get_xml_process() return server.stop() def xmlrpc_restart(): server = get_xml_process() return server.restart() def system_status(): """ use this format to pass status information icons can come from this site http://materialdesignicons.com/ remember to add mdi- as prefix :return: """ server = get_xml_process() status = server.status() return { 'type': 'system_status', 'error': status['error'], 'result': status['result'] } def tf_health_status(force=False): """ use this format to pass status information icons can come from this site http://materialdesignicons.com/ remember to add mdi- as prefix :param force: if true forces tf_health rescan :type force: bool :return: """ server = get_xml_process() status = server.tf_health(force) status.pop('cavities', 0) return { 'type': 'test_fixture_health', 'error': status['error'], 'result': status['result'] } def cavity_status(): """ use this format to pass status information icons can come from this site http://materialdesignicons.com/ remember to add mdi- as prefix :return: """ server = get_xml_process() status = server.cavities() return { 'type': 'cavity_status', 'error': status['error'], 'result': status['result'] } def get_tf_class(): storage = get_driver(options.storage_driver) tf_info = storage.get_tf_info() if not tf_info['class_path']: print('Test Fixture Class is not defined please use admin to set class') exit(0) return tf_info['class_path'] def set_tf_class(cls_name): storage = get_driver(options.storage_driver) tf_info = storage.get_tf_info() tf_info['class_path'] = cls_name tf_info = storage.set_tf_info(tf_info)
{ "repo_name": "davidvoler/ate_meteor", "path": "xmlrpc/utilities.py", "copies": "1", "size": "2144", "license": "mit", "hash": 1941659048136198000, "line_mean": 22.5604395604, "line_max": 80, "alpha_frac": 0.625, "autogenerated": false, "ratio": 3.664957264957265, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47899572649572647, "avg_score": null, "num_lines": null }
__author__ = 'davidl' template = \ """ (function () { /** * This Controllers ........ * * using the following services * */ function $ClassName$Controller($ClassName$Service) { var self = this; self.list = []; self.load = function () { var req = $ClassName$Service.load(self.serial); req.success(function (data) { if (data.status == 0) { self.list = data.data; } else { self.error = data.error; } }).error(function (data) { self.error = data; }); }; self.load(); } angular.module('ate.common') .controller('$ClassName$Controller', ['$ClassName$Service', $ClassName$Controller]); }()); """ def create_service(class_name, module_name): #ret = handler_template.format(class_name, module_name) ret = template.replace('$ClassName$',class_name) ret = ret.replace('$module_name$',module_name) return ret
{ "repo_name": "davidvoler/mongodb-tornado-angular", "path": "utils/generator/templates/service.py", "copies": "2", "size": "1060", "license": "mit", "hash": -8469060442097092000, "line_mean": 24.8536585366, "line_max": 92, "alpha_frac": 0.5047169811, "autogenerated": false, "ratio": 4.061302681992337, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5566019663092336, "avg_score": null, "num_lines": null }
__author__ = 'David Manouchehri (david@davidmanouchehri.com)' __license__ = 'MIT' ''' I am using the following content as input for my experiment, if you use another you may have varying success. SHA512 (v30.MPG) = 20b65b62cf523b15a157e563e90105e68e3f9b8df64afea5ce3323ad4b69e76bff56a738bc484ca30adee6c01cd0d5b3cbfb5243a35f8e87717159a016d71f01 SHA512 (v40.MPG) = bed9a9af5eae471affd4d3c44c5ec56e7330c0499404f7cdb083fa01a61894336bb2cdfd93ca6b1d1ee2bcac9d8bef12675d0cb957b6c2f6feedc09d5de627be SHA512 (v50.MPG) = 46194b6fbe2e03bea56ed999e0106fd713930799834fc1a252fcfda036bc99751943181969c3d15b61480bfa8046c3810c649687025ba4d896fc994c7af5235e From: http://www.engr.mun.ca/~migara/eng1040/Labs/src/Mechanical/Videos.zip All content from Memorial University is strictly their own property, please speak to them regarding licensing. None of their content has been included in this project to avoid any question of Intellectual Property. ''' ''' Resources used include: http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_video/py_meanshift/py_meanshift.html By Alexander Mordvintsev & Abid K. http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_video_display/py_video_display.html By the opencv dev team. ''' import cv2 # I'm using OpenCV 3 with Python 3 support compiled in. import numpy as np import argparse # Needed to accept the file names parser = argparse.ArgumentParser() parser.add_argument("filename", help="the filename of the video (MPG only)") args = parser.parse_args() # from multiprocessing import Process, Queue # OpenCV has multithreading itself, still other tricks can be applied. # I can be a bit lazier when it comes to my OpenCV programming, because Python will be executing it in parallel anyway. print('Written by ' + __author__ + '. All content is under the ' + __license__ + ' license.') print('Reading: ' + args.filename) cap = cv2.VideoCapture(args.filename) # Load the file # Grab the first frame ret, frame = cap.read() # Not exactly sure what values mean what c, r, w, h = 325, 200, 50, 100 # QUESTION: This numbers seem to jump around wildly for position, why? track_window = (c, r, w, h) # Create a region of interest roi = frame[r:r+h, c:c+w] hsv_roi = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv_roi, np.array((0., 60., 32.)), np.array((180., 255., 255.))) roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0, 180]) cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX) # Setup the termination criteria, either 10 iteration or move by at least 1 pt term_criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 0, 0) lower = np.array([110, 0, 0]) upper = np.array([130, 255, 255]) # lower = np.uint8([[[150, 100, 200]]]) # upper = np.uint8([[[255, 255, 255]]]) fgbg = cv2.createBackgroundSubtractorMOG2() while cap.isOpened(): # Bit redundant ret, frame = cap.read() # I think this might skip the first frame? # Only continue if the frame can be read if ret: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1) ret, gray = cv2.threshold(gray, 127, 255, 0) #gray2 = gray.copy() #mask2 = np.zeros(gray.shape, np.uint8) # Apply meanshift to find the new location ret, track_window = cv2.meanShift(gray, track_window, term_criteria) # Draw the results x, y, w, h = track_window img2 = cv2.rectangle(gray, (x, y), (x+w, y+h), 255, 2) #mask = cv2.inRange(hsv, lower, upper) fgmask = fgbg.apply(frame) #res = cv2.bitwise_and(frame, frame, mask=mask2) cv2.imshow('img2', gray) else: print('End of file, no more frames could be read.') break # cv2.imshow('frame', frame) if cv2.waitKey(0) & 0xFF == ord('q'): break # If other parts of the program needed cap, then releasing would matter cap.release() # Burn everything! cv2.destroyAllWindows()
{ "repo_name": "Manouchehri/PingPongDetector", "path": "main.py", "copies": "1", "size": "4021", "license": "mit", "hash": 7375586070926709000, "line_mean": 38.0485436893, "line_max": 147, "alpha_frac": 0.7097736881, "autogenerated": false, "ratio": 2.8138558432470258, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.40236295313470255, "avg_score": null, "num_lines": null }
__author__ = 'David Moreno García' def serialize_grades(grades): """ Returns an string with the representation of the grades in XML format. :param grades: grades to serialize :return: an string with the representation in the desired format """ result = '<scores>\n' for student_id, grade in grades.items(): result += "\t<score>\n\t\t<studentId>" + str(student_id) + "</studentId>\n" result += "\t\t<value>" + str(grade.grade) + "</value>\n\t</score>\n" return result + '</scores>' def serialize_statistics(statistics): """ Returns an string with the representation of the statistics in XML format. :param statistics: statistics to serialize :return: an string with the representation in the desired format """ result = '<statistics>\n' for question_id, correct_answers in statistics.items(): result += "\t<item>\n\t\t<questionId>" + str(question_id) + "</questionId>\n" result += "\t\t<correctAnswers>" + str(correct_answers) + "</correctAnswers>\n\t</item>\n" return result + '</statistics>'
{ "repo_name": "davidmogar/quizzer-python", "path": "quizzer/serializers/assessment_xml_serializer.py", "copies": "1", "size": "1099", "license": "mit", "hash": -476887358642406600, "line_mean": 32.303030303, "line_max": 98, "alpha_frac": 0.6429872495, "autogenerated": false, "ratio": 3.7094594594594597, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9843021692663407, "avg_score": 0.0018850032592104473, "num_lines": 33 }
__author__ = 'David Moser <david.moser@bitmovin.com>' import unittest from bitcodin import create_job from bitcodin import create_input from bitcodin import create_encoding_profile from bitcodin import delete_input from bitcodin import delete_encoding_profile from bitcodin import Job from bitcodin import Input from bitcodin import AudioStreamConfig from bitcodin import VideoStreamConfig from bitcodin import EncodingProfile from bitcodin.test.config import test_video_url from bitcodin.test.bitcodin_test_case import BitcodinTestCase class CreateJobKeepAspectRatioTestCase(BitcodinTestCase): def setUp(self): super(CreateJobKeepAspectRatioTestCase, self).setUp() input_url = test_video_url input = Input(input_url) self.input = create_input(input) video_configs = list() video_configs.append(VideoStreamConfig( default_stream_id=0, bitrate=4800000, profile='Main', preset='premium', height=600, width=1920 )) video_configs.append(VideoStreamConfig( default_stream_id=0, bitrate=2400000, profile='Main', preset='premium', width=1024 )) video_configs.append(VideoStreamConfig( default_stream_id=0, bitrate=1200000, profile='Main', preset='premium', height=720 )) audio_stream_config = AudioStreamConfig(default_stream_id=0, bitrate=192000) encoding_profile = EncodingProfile('API Test Profile', video_configs, [audio_stream_config]) self.encoding_profile = create_encoding_profile(encoding_profile) self.manifests = ['m3u8', 'mpd'] def runTest(self): job = Job( input_id=self.input.input_id, encoding_profile_id=self.encoding_profile.encoding_profile_id, manifest_types=self.manifests ) self.job = create_job(job) self.assertEquals(self.job.input.input_id, job.inputId) self.assertEquals(self.job.input.url, self.input.url) self.assertEquals(self.job.encoding_profiles[0].encoding_profile_id, job.encodingProfileId) self.wait_until_job_finished(self.job.job_id) def tearDown(self): delete_input(self.input.input_id) delete_encoding_profile(self.encoding_profile.encoding_profile_id) super(CreateJobKeepAspectRatioTestCase, self).tearDown() if __name__ == '__main__': unittest.main()
{ "repo_name": "bitmovin/bitcodin-python", "path": "bitcodin/test/job/testcase_create_job_keep_aspect_ratio.py", "copies": "1", "size": "2538", "license": "unlicense", "hash": -6120671490315326000, "line_mean": 33.2972972973, "line_max": 100, "alpha_frac": 0.658392435, "autogenerated": false, "ratio": 3.8165413533834585, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9972794214330665, "avg_score": 0.00042791481055895735, "num_lines": 74 }
__author__ = 'David Moser <david.moser@bitmovin.net>' import requests from .exceptions import BitcodinError from .exceptions import BitcodinInternalServerError from .exceptions import BitcodinApiKeyNotAuthorizedError from .exceptions import BitcodinBadRequestError from .exceptions import BitcodinNotFoundError class RestClient(object): def __init__(self): pass @staticmethod def _raise_error(result): if result.status_code == 500: raise BitcodinInternalServerError('An HTTP 500 Internal Server Error occured', result.text) try: json_result = result.json() except ValueError: raise BitcodinError('An error occured which response could not be JSON-decoded.', result.text) if result.status_code == 404: raise BitcodinNotFoundError( 'The API URL you requested does not exist', json_result ) elif result.status_code == 401: raise BitcodinApiKeyNotAuthorizedError( 'The API Key used in the request was not authorized to access the API.', json_result ) elif result.status_code == 400: raise BitcodinBadRequestError('The API received a invalid request.', json_result) else: raise BitcodinError('An error occured while communicating with the bitcodin API', json_result) @staticmethod def post(url=None, headers=None, content=None): result = requests.post(url, data=content, headers=headers) if result.status_code == 201 or result.status_code == 200: if result.text == '': return result.text return result.json() else: RestClient._raise_error(result) @staticmethod def get(url=None, headers=None): result = requests.get(url, headers=headers) if result.status_code != 200: RestClient._raise_error(result) return result.json() @staticmethod def put(self): pass @staticmethod def patch(url=None, headers=None, content=None): result = requests.patch(url, data=content, headers=headers) if result.status_code != 200: RestClient._raise_error(result) return result.json() @staticmethod def delete(url=None, headers=None): result = requests.delete(url, headers=headers) if result.status_code == 204: return True elif result.status_code == 200: return result.json() else: RestClient._raise_error(result)
{ "repo_name": "bitmovin/bitcodin-python", "path": "bitcodin/rest.py", "copies": "1", "size": "2617", "license": "unlicense", "hash": -3637697540175103500, "line_mean": 30.1547619048, "line_max": 106, "alpha_frac": 0.6259075277, "autogenerated": false, "ratio": 4.413153456998313, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5539060984698313, "avg_score": null, "num_lines": null }