"""
URLEncode.py - A Jython macro for jEdit that escapes
the selected text, if any text is selected, or the
entire buffer, if no text is selected, using 
``urllib.quote_plus()``. Special characters are replaced
with their ``%xx`` equivlents.

Copyright 2002 (C) Ollie Rutherfurd <oliver@rutherfurd.net>
$Id: URLEncode.py 28 2003-03-25 22:40:28Z oliver $
"""

from urllib import quote_plus

def urlencode(textArea):

    textArea.getBuffer().beginCompoundEdit()
    try:
        selections = textArea.getSelection()
        caret_pos = textArea.getCaretPosition()
        textArea.setCaretPosition(0)
        if len(selections) == 0:
            textArea.setText(quote_plus(textArea.getText()))
        else:
            for i in range(len(selections), 0, -1):
                selection = selections[i-1]
                start,end = selection.getStart(), selection.getEnd()
                text = textArea.getText(start, end-start)
                textArea.getBuffer().remove(start, end-start)
                textArea.getBuffer().insert(start, quote_plus(text))

        # was getting exceptions related to the caret being
        # out of bounds, so we move it to 0 then try to place
        # it either in the original location or at the end
        # of the buffer if it was beyond the buffer.
        if caret_pos < textArea.getBuffer().getLength():
            textArea.setCaretPosition(caret_pos)
        else:
            textArea.setCaretPosition(textArea.getBuffer().getLength())

    finally:
        textArea.getBuffer().endCompoundEdit()

if __name__ in ('__main__','main'):
    urlencode(init.textArea)

# :indentSize=4:lineSeparator=\n:noTabs=true:tabSize=4:


