earwig / mwparserfromhell

A Python parser for MediaWiki wikicode
https://mwparserfromhell.readthedocs.io/
MIT License
741 stars 75 forks source link

How to get a node range in a section? #244

Closed mrkowalski closed 4 years ago

mrkowalski commented 4 years ago

Is this possible to get a range of nodes that will still have all the methods of a section? In other words, to get a subset of a section that is still a section? :) How?

If not, this is a feature request.

earwig commented 4 years ago

Sorry for the delay replying. Yes, this is a possible. You can select any subset of a Wikicode's node list and wrap it in a new Wikicode object. Changes to one will propagate to the other. For example:

>>> code = mwparserfromhell.parse('{{a}}{{b}}{{c}}{{d}}{{e}}')
>>> code.nodes[1:3]
['{{b}}', '{{c}}']
>>> sub = mwparserfromhell.wikicode.Wikicode(code.nodes[1:3])
>>> sub
'{{b}}{{c}}'
>>> sub.append('{{c2}}')
>>> code
'{{a}}{{b}}{{c}}{{c2}}{{d}}{{e}}'

This can be done recursively as many times as you like. You can also call get_section() on the section returned by get_section(), assuming you want an actual heading-bounded section of a page and not some arbitrary slice of the node list.