| 202 | return lastChild |
| 203 | |
| 204 | def insert(self, position, newChild): |
| 205 | if isinstance(newChild, basestring) \ |
| 206 | and not isinstance(newChild, NavigableString): |
| 207 | newChild = NavigableString(newChild) |
| 208 | |
| 209 | position = min(position, len(self.contents)) |
| 210 | if hasattr(newChild, 'parent') and newChild.parent is not None: |
| 211 | # We're 'inserting' an element that's already one |
| 212 | # of this object's children. |
| 213 | if newChild.parent is self: |
| 214 | index = self.index(newChild) |
| 215 | if index > position: |
| 216 | # Furthermore we're moving it further down the |
| 217 | # list of this object's children. That means that |
| 218 | # when we extract this element, our target index |
| 219 | # will jump down one. |
| 220 | position = position - 1 |
| 221 | newChild.extract() |
| 222 | |
| 223 | newChild.parent = self |
| 224 | previousChild = None |
| 225 | if position == 0: |
| 226 | newChild.previousSibling = None |
| 227 | newChild.previous = self |
| 228 | else: |
| 229 | previousChild = self.contents[position-1] |
| 230 | newChild.previousSibling = previousChild |
| 231 | newChild.previousSibling.nextSibling = newChild |
| 232 | newChild.previous = previousChild._lastRecursiveChild() |
| 233 | if newChild.previous: |
| 234 | newChild.previous.next = newChild |
| 235 | |
| 236 | newChildsLastElement = newChild._lastRecursiveChild() |
| 237 | |
| 238 | if position >= len(self.contents): |
| 239 | newChild.nextSibling = None |
| 240 | |
| 241 | parent = self |
| 242 | parentsNextSibling = None |
| 243 | while not parentsNextSibling: |
| 244 | parentsNextSibling = parent.nextSibling |
| 245 | parent = parent.parent |
| 246 | if not parent: # This is the last element in the document. |
| 247 | break |
| 248 | if parentsNextSibling: |
| 249 | newChildsLastElement.next = parentsNextSibling |
| 250 | else: |
| 251 | newChildsLastElement.next = None |
| 252 | else: |
| 253 | nextChild = self.contents[position] |
| 254 | newChild.nextSibling = nextChild |
| 255 | if newChild.nextSibling: |
| 256 | newChild.nextSibling.previousSibling = newChild |
| 257 | newChildsLastElement.next = nextChild |
| 258 | |
| 259 | if newChildsLastElement.next: |
| 260 | newChildsLastElement.next.previous = newChildsLastElement |
| 261 | self.contents.insert(position, newChild) |