#!/usr/bin/env python3

import html
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

def maybeReplace(edit):
    if maybeReplace.busy:
        return
    maybeReplace.busy = True
    try:
        cursor = edit.textCursor()
        cursor.select(QTextCursor.WordUnderCursor)
        word = cursor.selectedText()
        replacement = dict(dns="DomainNameServer", hg="Mercury").get(word)
        if replacement is not None:
            start = cursor.selectionStart()
            cursor.beginEditBlock()
            cursor.clearSelection()
            cursor.setPosition(start)
            cursor.setPosition(start + len(word),
                               QTextCursor.KeepAnchor)
            cursor.insertText(html.escape(replacement))
            cursor.endEditBlock()
    finally:
        maybeReplace.busy = False
maybeReplace.busy = False

app = QApplication(sys.argv)
app.setCursorFlashTime(0)
edit = QTextEdit()
edit.cursorPositionChanged.connect(lambda: maybeReplace(edit))
edit.show()
app.exec_()
