|
| 1 | +# encoding: utf-8 |
| 2 | + |
| 3 | +""" |
| 4 | +Bookmarks-related proxy types. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import ( |
| 8 | + absolute_import, division, print_function, unicode_literals |
| 9 | +) |
| 10 | + |
| 11 | +from collections import Sequence |
| 12 | +from docx.oxml.bookmark import CT_BookmarkEnd, CT_BookmarkStart |
| 13 | +from docx.shared import ElementProxy |
| 14 | + |
| 15 | + |
| 16 | +class Bookmarks(Sequence): |
| 17 | + def __init__(self, document_elm): |
| 18 | + super(Bookmarks, self).__init__() |
| 19 | + self._document = self._element = document_elm |
| 20 | + |
| 21 | + def __iter__(self): |
| 22 | + for bookmarkStart in self._bookmarkStarts: |
| 23 | + yield Bookmark(bookmarkStart) |
| 24 | + |
| 25 | + def __getitem__(self, idx): |
| 26 | + bookmarkStart = self._bookmarkStarts[idx] |
| 27 | + return Bookmark(bookmarkStart) |
| 28 | + |
| 29 | + def __len__(self): |
| 30 | + return len(self._bookmarkStarts) |
| 31 | + |
| 32 | + def get(self, name, default=None): |
| 33 | + for bookmarkStart in self._bookmarkStarts: |
| 34 | + if bookmarkStart.name == name: |
| 35 | + return Bookmark(bookmarkStart) |
| 36 | + return default |
| 37 | + |
| 38 | + def add_bookmark(self): |
| 39 | + return Bookmark(self._element) |
| 40 | + |
| 41 | + @property |
| 42 | + def _bookmarkStarts(self): |
| 43 | + return self._document.xpath('.//w:bookmarkStart') |
| 44 | + |
| 45 | + |
| 46 | +class Bookmark(ElementProxy): |
| 47 | + def __init__(self, doc_element): |
| 48 | + super(Bookmark, self).__init__(doc_element) |
| 49 | + self._element = doc_element |
| 50 | + |
| 51 | + def add_bookmark_start(self, id, name): |
| 52 | + bmrk = self._element._add_bookmarkStart() |
| 53 | + bmrk.name = name |
| 54 | + bmrk.bmrk_id = str(id) |
| 55 | + return self._element.append(bmrk) |
| 56 | + |
| 57 | + def add_bookmark_end(self, id): |
| 58 | + bmrk = self._element._add_bookmarkEnd() |
| 59 | + bmrk.bmrk_id = str(1) |
| 60 | + return self._element.append(bmrk) |
0 commit comments