#!/usr/bin/python

import pyatspi

def listener(event):
    try:
        if event.source.getRole() == pyatspi.ROLE_TERMINAL:
            return
    except:
        return

    try:
        hyperText = event.source.queryHypertext()
        nLinks = hyperText.getNLinks()
    except:
        return

    allLinks = [hyperText.getLink(i) for i in range(nLinks)]
    linkOffsets = [(l.startIndex, l.endIndex) for l in allLinks]
    print("\nAccessible has %i links: %s" % (nLinks, linkOffsets))

    text = event.source.queryText()
    for startIndex, endIndex in linkOffsets:
        linkString = text.getText(startIndex, endIndex)
        print("  Link text: <%s>" % linkString)

pyatspi.Registry.registerEventListener(listener, "object:text-caret-moved")
pyatspi.Registry.start()
