def _link_tree(links, notebook, path):
    # Convert a list of links (of any type) into a parsetree
    #~ print('LINKS: ', links)
    #~ print('NOTEBOOK and PATH:', notebook, path)
    builder = ParseTreeBuilder()
    builder.start(FORMATTEDTEXT)
    for i in range(len(links)):
        if i > 0:
            builder.text(' ')

        link = links[i]
        type = link_type(link)
        isimage = False
        if type == 'interwiki':
            prefix = notebook.interwiki + '?'
            if link.startswith(prefix):
                link = link[len(prefix):]
                type = link_type(link)
        elif type == 'file':
            try:
                file = File(link)
                isimage = file.isimage()
            except:
                pass

        logger.debug('Pasting link: %s (type: %s, isimage: %s)', link, type,
                     isimage)

        if isimage:
            src = notebook.relative_filepath(file, path) or file.uri
            builder.append(IMAGE, {'src': src})
        elif link.startswith('@'):
            # FIXME - is this ever used ??
            builder.append(TAG, {'name': links[i][1:]}, links[i])
        else:
            name = None
            if type == 'page':
                anchor = None
                if '#' in link:
                    link, anchor = link.split('#', 1)
                target = Path(Path.makeValidPageName(
                    link))  # Assume links are always absolute
                href = notebook.pages.create_link(path, target)
                href.anchor = anchor
                link = href.to_wiki_link()
                if notebook.config['Notebook']['short_links']:
                    name = href.parts()[-1]
                    if anchor:
                        name += '#' + anchor
            elif type == 'file':
                file = File(link)  # Assume links are always URIs
                link = notebook.relative_filepath(file, path) or file.uri

            builder.append(LINK, {'href': link}, name or link)

    builder.end(FORMATTEDTEXT)
    tree = builder.get_parsetree()
    tree.resolve_images(notebook, path)
    tree.decode_urls()
    return tree
Beispiel #2
0
def _link_tree(links, notebook, path):
    # Convert a list of links (of any type) into a parsetree
    #~ print 'LINKS: ', links
    #~ print 'NOTEBOOK and PATH:', notebook, path
    builder = ParseTreeBuilder()
    builder.start(FORMATTEDTEXT)
    for i in range(len(links)):
        if i > 0:
            builder.text(' ')

        link = links[i]
        type = link_type(link)
        isimage = False
        if type == 'file':
            try:
                file = File(link)
                isimage = file.isimage()
            except:
                pass

        logger.debug('Pasting link: %s (type: %s, isimage: %s)', link, type,
                     isimage)

        if isimage:
            src = notebook.relative_filepath(file, path) or file.uri
            builder.append(IMAGE, {'src': src})
        elif link.startswith('@'):
            # FIXME - is this ever used ??
            builder.append(TAG, {'name': links[i][1:]}, links[i])
        else:
            if type == 'page':
                target = Path(Path.makeValidPageName(
                    link))  # Assume links are always absolute
                href = notebook.pages.create_link(path, target)
                link = href.to_wiki_link()
            elif type == 'file':
                file = File(link)  # Assume links are always URIs
                link = notebook.relative_filepath(file, path) or file.uri

            builder.append(LINK, {'href': link}, link)

    builder.end(FORMATTEDTEXT)
    tree = builder.get_parsetree()
    tree.resolve_images(notebook, path)
    tree.decode_urls()
    return tree
Beispiel #3
0
def _link_tree(links, notebook, path):
	# Convert a list of links (of any type) into a parsetree
	#~ print 'LINKS: ', links
	#~ print 'NOTEBOOK and PATH:', notebook, path
	builder = ParseTreeBuilder()
	builder.start(FORMATTEDTEXT)
	for i in range(len(links)):
		if i > 0:
			builder.text(' ')

		link = links[i]
		type = link_type(link)
		isimage = False
		if type == 'file':
			try:
				file = File(link)
				isimage = file.isimage()
			except:
				pass

		logger.debug('Pasting link: %s (type: %s, isimage: %s)', link, type, isimage)

		if isimage:
			src = notebook.relative_filepath(file, path) or file.uri
			builder.append(IMAGE, {'src': src})
		elif link.startswith('@'):
			# FIXME - is this ever used ??
			builder.append(TAG, {'name': links[i][1:]}, links[i])
		else:
			if type == 'page':
				href = Path(notebook.cleanup_pathname(link)) # Assume links are always absolute
				link = notebook.relative_link(path, href) or link
			elif type == 'file':
				file = File(link) # Assume links are always URIs
				link = notebook.relative_filepath(file, path) or file.uri

			builder.append(LINK, {'href': link}, link)

	builder.end(FORMATTEDTEXT)
	tree = builder.get_parsetree()
	tree.resolve_images(notebook, path)
	tree.decode_urls()
	return tree
Beispiel #4
0
class HeadingSplitter(Visitor):

	def __init__(self, max_level=None):
		self.max_level = max_level or 999
		self._builder = ParseTreeBuilder()
		self.headings = []

	def _split(self):
		self._builder.end(FORMATTEDTEXT)
		tree = self._builder.get_parsetree()
		if tree.hascontent:
			self.headings.append(tree)
		self._builder = ParseTreeBuilder()
		self._builder.start(FORMATTEDTEXT)

	def _close(self):
		tree = self._builder.get_parsetree()
		if tree.hascontent:
			self.headings.append(tree)

	def start(self, tag, attrib=None):
		if tag is HEADING and int(attrib['level']) <= self.max_level:
			self._split()
		self._builder.start(tag, attrib)

	def end(self, tag):
		self._builder.end(tag)
		if tag == FORMATTEDTEXT:
			self._close()

	def text(self, text):
		self._builder.text(text)

	def append(self, tag, attrib=None, text=None):
		if tag is HEADING and int(attrib['level']) <= self.max_level:
			self._split()
		self._builder.append(tag, attrib, text)
Beispiel #5
0
class HeadingSplitter(Visitor):

	def __init__(self, max_level=None):
		self.max_level = max_level or 999
		self._builder = ParseTreeBuilder()
		self.headings = []

	def _split(self):
		self._builder.end(FORMATTEDTEXT)
		tree = self._builder.get_parsetree()
		if tree.hascontent:
			self.headings.append(tree)
		self._builder = ParseTreeBuilder()
		self._builder.start(FORMATTEDTEXT)

	def _close(self):
		tree = self._builder.get_parsetree()
		if tree.hascontent:
			self.headings.append(tree)

	def start(self, tag, attrib=None):
		if tag is HEADING and int(attrib['level']) <= self.max_level:
			self._split()
		self._builder.start(tag, attrib)

	def end(self, tag):
		self._builder.end(tag)
		if tag == FORMATTEDTEXT:
			self._close()

	def text(self, text):
		self._builder.text(text)

	def append(self, tag, attrib=None, text=None):
		if tag is HEADING and int(attrib['level']) <= self.max_level:
			self._split()
		self._builder.append(tag, attrib, text)
Beispiel #6
0
def parsetree_from_selectiondata(selectiondata,
                                 notebook=None,
                                 path=None,
                                 text_format='plain'):
    '''Function to get a parsetree based on the selectiondata contents
	if at all possible. Used by both copy-paste and drag-and-drop
	methods.

	The 'notebook' and optional 'path' arguments are used to format
	links relative to the page which is the target for the pasting or
	drop operation.

	For image data, the parameters notebook and page are used
	to save the image to the correct attachment folder and return a
	parsetree with the correct image link.

	@param selectiondata: a C{Gtk.SelectionData} object
	@param notebook: a L{Notebook} object
	@param path: a L{Path} object
	@param text_format: format to parse pasted text, as a special case

		- "verbatim" will wrap content in VERBARIM_BLOCK or VERBATIM element based on the content
		- "verbatim-pre" will wrap the content in a VERBATIM_BLOCK element and
		- "verbatim-code" will wrap the content in a VERBATIM element

	@returns: a L{ParseTree} or C{None}
	'''
    # TODO: check relative linking for all parsetrees !!!

    targetname = selectiondata.get_target().name()
    if targetname == PARSETREE_TARGET_NAME:
        return ParseTree().fromstring(selectiondata.get_data())
    elif targetname in (INTERNAL_PAGELIST_TARGET_NAME, PAGELIST_TARGET_NAME) \
    or targetname in URI_TARGET_NAMES:
        links = selectiondata.get_uris()
        return _link_tree(links, notebook, path)
    elif targetname in TEXT_TARGET_NAMES:
        # plain text parser should highlight urls etc.
        # FIXME some apps drop text/uri-list as a text/plain mimetype
        # try to catch this situation by a check here
        text = selectiondata.get_text()
        if text:
            if text_format in ('verbatim', 'verbatim-pre', 'verbatim-code'):
                if text_format == 'verbatim':
                    tag_name = 'pre' if '\n' in text else 'code'
                else:
                    tag_name = text_format[9:]
                builder = ParseTreeBuilder(partial=True)
                builder.start('zim-tree', {})
                builder.start(tag_name, {})
                builder.text(text)
                builder.end(tag_name)
                builder.end('zim-tree')
                return builder.get_parsetree()
            else:
                return get_format(text_format).Parser().parse(text,
                                                              partial=True)
        else:
            return None
    elif targetname in IMAGE_TARGET_NAMES:
        # save image
        pixbuf = selectiondata.get_pixbuf()
        if not pixbuf:
            return None

        dir = notebook.get_attachments_dir(path)
        assert isinstance(dir, LocalFolder) or hasattr(
            dir, '_folder') and isinstance(dir._folder, LocalFolder)
        # XXX: assert we have local path  - HACK to deal with FilesAttachmentFolder
        if not dir.exists():
            logger.debug("Creating attachment dir: %s", dir)
            dir.touch()

        format, extension = _get_image_info(targetname)
        if format is None or format == 'bmp':
            # default to png format
            # special casing bmp since many window apps use it internally
            # but is quite large to store, so compress by using png
            format, extension = 'png', 'png'

        file = dir.new_file('pasted_image.%s' % extension)
        logger.debug("Saving image from clipboard to %s", file)
        pixbuf.savev(file.path, format, [], [])
        FS.emit('path-created', file)  # notify version control

        links = [file.uri]
        return _link_tree(links, notebook, path)
    else:
        return None