Inline a compiled bibliography (.bbl) in place of a bibliography
        environment. The document is modified in place.
962028
def inline_bbl(self):
        
        bbl_path = os.path.splitext(self._filepath)[0] + ".bbl"
        try:
            with codecs.open(bbl_path, 'r', encoding='utf-8') as f:
                bbl_text = f.read()
        except IOError:
            print("Cannot open bibliography {0}".format(bbl_path))
        self.text = texutils.inline_bbl(self.text, bbl_text)
1115556
def replace_references(self, node):
        
        href = node.getAttribute('href')
        if href is None:
            return
        id = href.getValue()
        ref = self.catalog.get(id)
        if ref is None:
            log.error('soap multiref: %s, not-resolved', id)
            return
        node.append(ref.children)
        node.setText(ref.getText())
        for a in ref.attributes:
            if a.name != 'id':
                node.append(a)
        node.remove(href)
934254
private void bracketProcessBoundary(BracketData bd, int lastCcPos,
                                        byte contextLevel, byte embeddingLevel) {
        IsoRun pLastIsoRun = bd.isoRuns[bd.isoRunLast];
        if ((DirPropFlag(dirProps[lastCcPos]) & MASK_ISO) != 0) /* after an isolate */
            return;
        if (NoOverride(embeddingLevel) > NoOverride(contextLevel))  /* not a PDF */
            contextLevel = embeddingLevel;
        pLastIsoRun.limit = pLastIsoRun.start;
        pLastIsoRun.level = embeddingLevel;
        pLastIsoRun.lastStrong = pLastIsoRun.lastBase = pLastIsoRun.contextDir = (byte)(contextLevel & 1);
        pLastIsoRun.contextPos = lastCcPos;
    }
463238
public InlineMorph with(String line) {
        if (scriptBuilder.length() == 0) {
            appendBoilerplate(line);
        }
        scriptBuilder
                .append(line)
                .append("\n");
        return this;
    }
162268
@CommandDescList({
		@CommandDesc(longName = "bibliography",
				description = "generate a bibliography",
				command = BibliographyCommand.class),
		@CommandDesc(longName = "citation",
				description = "generate citations",
				command = CitationCommand.class),
		@CommandDesc(longName = "list",
				description = "display sorted list of available citation IDs",
				command = ListCommand.class),
		@CommandDesc(longName = "lint",
				description = "validate citation items",
				command = LintCommand.class),
		@CommandDesc(longName = "json",
				description = "convert input bibliography to JSON",
				command = JsonCommand.class),
		@CommandDesc(longName = "mendeley",
				description = "connect to Mendeley Web",
				command = MendeleyCommand.class),
		@CommandDesc(longName = "zotero",
				description = "connect to Zotero",
				command = ZoteroCommand.class),
		@CommandDesc(longName = "shell",
				description = "run citeproc-java in interactive mode",
				command = ShellCommand.class),
		@CommandDesc(longName = "help",
				description = "display help for a given command",
				command = HelpCommand.class)
	})
	public void setCommand(AbstractCSLToolCommand command) {
		if (command instanceof ProviderCommand) {
			this.command = new InputFileCommand((ProviderCommand)command);
		} else {
			this.command = command;
		}
	}
1316399
def reference_text(ref):
    '''
    '''

    ref_wrap = textwrap.TextWrapper(initial_indent='', subsequent_indent=' ' * 8)

    s = ''
    if ref['type'] == 'unpublished':
        s += ref_wrap.fill(', '.join(ref['authors'])) + '\n'
        s += ref_wrap.fill(ref['title']) + '\n'
        s += ref_wrap.fill(ref['note']) + '\n'
    elif ref['type'] == 'article':
        s += ref_wrap.fill(', '.join(ref['authors'])) + '\n'
        s += ref_wrap.fill(ref['title']) + '\n'
        s += '{}, {}, {} ({})'.format(ref['journal'], ref['volume'], ref['page'], ref['year'])
        s += '\n' + ref['doi']
    elif ref['type'] == 'incollection':
        s += ref_wrap.fill(', '.join(ref['authors']))
        s += ref_wrap.fill('\n{}'.format(ref['title']))
        s += ref_wrap.fill('\nin \'{}\''.format(ref['booktitle']))
        if 'editors' in ref:
            s += ref_wrap.fill('\ned. ' + ', '.join(ref['editors']))
        if 'series' in ref:
            s += '\n{}, {}, {} ({})'.format(ref['series'], ref['volume'], ref['page'], ref['year'])
        if 'doi' in ref:
            s += '\n' + ref['doi']
    elif ref['type'] == 'techreport':
        s += ref_wrap.fill(', '.join(ref['authors']))
        s += ref_wrap.fill('\n{}'.format(ref['title']))
        s += '\n\'{}\''.format(ref['institution'])
        s += '\nTechnical Report {}'.format(ref['number'])
        s += '\n{}'.format(ref['year'])
        if 'doi' in ref:
            s += '\n' + ref['doi']
    elif ref['type'] == 'misc':
        s += ref_wrap.fill(', '.join(ref['authors'])) + '\n'
        s += ref_wrap.fill(ref['title'])
        if 'note' in ref:
            s += '\n' + ref['note']
        if 'doi' in ref:
            s += '\n' + ref['doi']
    else:
        raise RuntimeError('Cannot handle reference type {}'.format(ref['type']))
    return s
587074
function Reference(reference) {
  if (!reference) {
    throw new Error('You must supply a Bible reference, either a string (i.e. "Mark 2") or an object (i.e. { book: 1, chapter: 2, verse: 1 })');
  }

  // If reference is a string
  if (typeof reference === 'string') {

    // Strip out any periods, usually used for abbreviations, i.e. Mk. 2
    reference = reference.replace(/\./g,'');

    this.source = reference;

    // Match up to last letter - thats the book. Everything else === the chapter/verse
    var referenceParts = reference.match(/(.+[A-Za-z])\s+(.+)/);
    var bookName = referenceParts[1];
    var chapterAndVerse = referenceParts[2];

    // Lookup the book
    this.book = Reference.bookIdFromName(bookName);

    // Split on ":" for chapter and verse. If it's a chapter reference
    // (e.g. John 1) then @verse === undefined
    var chapterAndVerseParts = chapterAndVerse.split(':');
    this.chapter = Number(chapterAndVerseParts[0]);
    this.verse = chapterAndVerseParts[1] ? Number(chapterAndVerseParts[1]) : null;

  // If it's not a string, try parsing as an object
  } else {
    if (!reference.book) {
      throw new Error('The object you supplied does not seem to be a Bible reference (there is no "book" property)');
    }

    var hasBook = typeof reference.book === 'number';
    var hasChapter = typeof reference.chapter === 'number';
    var validVerseIfPresent = reference.verse == null || typeof reference.verse === 'number';

    if (hasBook && hasChapter && validVerseIfPresent) {
      this.book = reference.book;
      this.chapter = reference.chapter;
      this.verse = reference.verse;
    }
  }
}
838794
def apply(self):
        """"""
        # In this phase, we replace the substitutions in hyperlinks
        # with the contents of the sub-nodes introduced during phase 1.
        # We also remove those temporary nodes from the tree.
        subst_re = re.compile(self.subst_pattern)

        # Apply the substitutions to hyperlink references.
        for link in self.document.traverse(nodes.reference):
            substitutions = link.get('varlinks')
            if not substitutions:
                continue

            replacer = self._replace(substitutions, link.children, 1)
            link['refuri'] = subst_re.sub(replacer, link['refuri'])
            content = subst_re.sub(replacer, link[0])
            # Cleanup the temporary nodes and recreate the node's content.
            link.clear()
            del link['varlinks']
            link.append(nodes.Text(content))

        # Do the same with hyperlink targets.
        for link in self.document.traverse(nodes.target):
            substitutions = link.get('varlinks')
            if not substitutions:
                continue

            replacer = self._replace(substitutions, link.children, 0)
            link['refuri'] = subst_re.sub(replacer, link['refuri'])
            # Cleanup the temporary nodes.
            link.clear()
            del link['varlinks']
699829
def translate_book(translators=(HyperlinkStyleCorrector().translate, translate_line_footnotes),
                   book_dir=BOOK_PATH, dest=None, include_tags=None,
                   ext='.nlpiabak', skip_untitled=True):
    
    if callable(translators) or not hasattr(translators, '__len__'):
        translators = (translators,)

    sections = get_tagged_sections(book_dir=book_dir, include_tags=include_tags)
    file_line_maps = []

    for fileid, (filepath, tagged_lines) in enumerate(sections):
        logger.info('filepath={}'.format(filepath))
        destpath = filepath
        if not dest:
            copyfile(filepath, filepath + '.' + ext.lstrip('.'))
        elif os.path.sep in dest:
            destpath = os.path.join(dest, os.path.basename(filepath))
        else:
            destpath = os.path.join(os.path.dirname(filepath), dest, os.path.basename(filepath))
        ensure_dir_exists(os.path.dirname(destpath))
        with open(destpath, 'w') as fout:
            logger.info('destpath={}'.format(destpath))
            for lineno, (tag, line) in enumerate(tagged_lines):
                if (include_tags is None or tag in include_tags or
                        any((tag.startswith(t) for t in include_tags))):
                    for translate in translators:
                        new_line = translate(line)  # TODO: be smarter about writing to files in-place
                        if line != new_line:
                            file_line_maps.append((fileid, lineno, filepath, destpath, line, new_line))
                            line = new_line
                fout.write(line)
    return file_line_maps
851146
def parse_bibliography(source, loc, tokens):
    
    bib = structures.Bibliography()
    for entry in tokens:
        bib.add(entry)
    return bib
528776
def serialize(self, pid, record, links_factory=None, **kwargs):
        
        data = self.serializer.serialize(pid, record, links_factory)
        source = self._get_source(data)
        style = CitationStylesStyle(validate=False, **self._get_args(**kwargs))
        bib = CitationStylesBibliography(style, source, formatter.plain)
        citation = Citation([CitationItem(pid.pid_value)])
        bib.register(citation)

        return self._clean_result(''.join(bib.bibliography()[0]))
908680
def _ref_bib(key, ref):
    '''
    '''
    s = ''

    s += '@{}{{{},\n'.format(ref['type'], key)

    entry_lines = []
    for k, v in ref.items():
        if k == 'type':
            continue

        # Handle authors/editors
        if k == 'authors':
            entry_lines.append('    author = {{{}}}'.format(' and '.join(v)))
        elif k == 'editors':
            entry_lines.append('    editor = {{{}}}'.format(' and '.join(v)))
        else:
            entry_lines.append('    {} = {{{}}}'.format(k, v))

    s += ',\n'.join(entry_lines)
    s += '\n}'

    return s
1247330
def process_link(self, env, refnode, has_explicit_title, title, target):
        
        refnode['chpl:module'] = env.temp_data.get('chpl:module')
        refnode['chpl:class'] = env.temp_data.get('chpl:class')
        if not has_explicit_title:
            # Only has a meaning for the target.
            title = title.lstrip('.')

            # Only has a meaning for the title.
            target = target.lstrip('~')

            if title[0:1] == '~':
                title = title[1:]
                dot = title.rfind('.')
                if dot != -1:
                    title = title[dot+1:]

        # IF the first character is a dot, search more specific names
        # first. Else, search builtins first.
        if target[0:1] == '.':
            target = target[1:]
            refnode['refspecific'] = True

        return title, target
245179
def _make_resource_from_inline(reference):
    """"""
    uri = DataURI(reference.uri)
    data = io.BytesIO(uri.data)
    mimetype = uri.mimetype
    res = Resource('dummy', data, mimetype)
    res.id = res.filename
    return res
777433
def compile(manager, path, allow_naked_names, allow_nested, disallow_unqualified_translocations,
            no_identifier_validation, no_citation_clearing, required_annotations, skip_tqdm, verbose):
    """"""
    if verbose:
        logging.basicConfig(level=logging.DEBUG)
        log.setLevel(logging.DEBUG)
        log.debug('using connection: %s', manager.engine.url)

    click.secho('Compilation', fg='red', bold=True)
    if skip_tqdm:
        click.echo('```')
    graph = from_path(
        path,
        manager=manager,
        use_tqdm=(not (skip_tqdm or verbose)),
        allow_nested=allow_nested,
        allow_naked_names=allow_naked_names,
        disallow_unqualified_translocations=disallow_unqualified_translocations,
        citation_clearing=(not no_citation_clearing),
        required_annotations=required_annotations,
        no_identifier_validation=no_identifier_validation,
        allow_definition_failures=True,
    )
    if skip_tqdm:
        click.echo('```')
    to_pickle(graph, get_corresponding_pickle_path(path))

    click.echo('')
    _print_summary(graph, ticks=skip_tqdm)

    sys.exit(0 if 0 == graph.number_of_warnings() else 1)
321808
def _init_compiled(cls, dialect, connection, dbapi_connection,
                       compiled, parameters):
        """"""

        self = cls.__new__(cls)
        self.root_connection = connection
        self._dbapi_connection = dbapi_connection
        self.dialect = connection.dialect

        self.compiled = compiled

        # this should be caught in the engine before
        # we get here
        assert compiled.can_execute

        self.execution_options = compiled.execution_options.union(
            connection._execution_options)

        self.result_column_struct = (
            compiled._result_columns, compiled._ordered_columns,
            compiled._textual_ordered_columns)

        self.unicode_statement = util.text_type(compiled)
        if not dialect.supports_unicode_statements:
            self.statement = self.unicode_statement.encode(
                self.dialect.encoding)
        else:
            self.statement = self.unicode_statement

        self.isinsert = compiled.isinsert
        self.isupdate = compiled.isupdate
        self.isdelete = compiled.isdelete
        self.is_text = compiled.isplaintext

        if not parameters:
            self.compiled_parameters = [compiled.construct_params()]
        else:
            self.compiled_parameters = \
                [compiled.construct_params(m, _group_number=grp) for
                 grp, m in enumerate(parameters)]

            self.executemany = len(parameters) > 1

        self.cursor = self.create_cursor()

        if self.isinsert or self.isupdate or self.isdelete:
            self.is_crud = True
            self._is_explicit_returning = bool(compiled.statement._returning)
            self._is_implicit_returning = bool(
                compiled.returning and not compiled.statement._returning)

        if self.compiled.insert_prefetch or self.compiled.update_prefetch:
            if self.executemany:
                self._process_executemany_defaults()
            else:
                self._process_executesingle_defaults()

        processors = compiled._bind_processors

        # Convert the dictionary of bind parameter values
        # into a dict or list to be sent to the DBAPI's
        # execute() or executemany() method.
        parameters = []
        if dialect.positional:
            for compiled_params in self.compiled_parameters:
                param = []
                for key in self.compiled.positiontup:
                    if key in processors:
                        param.append(processors[key](compiled_params[key]))
                    else:
                        param.append(compiled_params[key])
                parameters.append(dialect.execute_sequence_format(param))
        else:
            encode = not dialect.supports_unicode_statements
            for compiled_params in self.compiled_parameters:

                if encode:
                    param = dict(
                        (
                            dialect._encoder(key)[0],
                            processors[key](compiled_params[key])
                            if key in processors
                            else compiled_params[key]
                        )
                        for key in compiled_params
                    )
                else:
                    param = dict(
                        (
                            key,
                            processors[key](compiled_params[key])
                            if key in processors
                            else compiled_params[key]
                        )
                        for key in compiled_params
                    )

                parameters.append(param)
        self.parameters = dialect.execute_sequence_format(parameters)

        self.statement = compiled
        return self
556551
def inline(self) -> str:
        
        doc = self.api
        for p in self.properties:
            doc += " {0}".format(p)
        return doc