コード例 #1
0
ファイル: commentar.py プロジェクト: hlamer/kate
def inline_comment():
    ''' Append or align an inlined comment at position 60 for the current line or the selection.

        Move cursor to the start of a comment, if nothing has changed.
        If there wasn't any comment aside of #else/#endif put corresponding #if condition as default
        comment text
    '''
    document = kate.activeDocument()
    view = kate.activeView()
    pos = view.cursorPosition()
    commentCh = common.getCommentStyleForDoc(document)

    if view.selection():
        # If selected smth on a single line...
        common.extendSelectionToWholeLine(view)

        selectedText = view.selectionText().split('\n')
        if not bool(selectedText[-1]):
            selectedText = selectedText[0:-1]
        insertionText = []
        firstColumn = -1
        for textLine in selectedText:
            (currentLine, column) = processLine(textLine, commentCh)
            if firstColumn == -1:
                firstColumn = column
            insertionText += currentLine

        # Modify current document
        if bool(insertionText):
            document.startEditing()
            document.removeText(view.selectionRange())
            pos = view.cursorPosition()
            document.insertText(pos, '\n'.join(insertionText) + '\n')
            pos.setColumn(firstColumn)
            view.setCursorPosition(pos)
            view.removeSelection()
            document.endEditing()

    else:
        (text, column) = processLine(document.line(pos.line()), commentCh)

        # Apply result (if smth really has changed)
        originalText = document.line(pos.line())
        if bool(text) and (len(text) != 1 or originalText != text[0]):
            document.startEditing()                         # Start edit transaction:
            document.removeLine(pos.line())                 # Remove current line
            # insert resulting text line by line...
            pos.setColumn(0)
            document.insertText(pos, '\n'.join(text) + '\n')
            document.endEditing()                           # End transaction

        # Move cursor to desired position
        pos.setColumn(column)
        view.setCursorPosition(pos)
コード例 #2
0
ファイル: commentar.py プロジェクト: hlamer/kate
def turnFromBlockComment():
    document = kate.activeDocument()
    view = kate.activeView()
    pos = view.cursorPosition()

    if view.selection():
        sr = view.selectionRange()
        start = sr.start().line()
        end = sr.end().line()
    else:
        # Try to detect block comment (/* ... */)
        r = common.getTextBlockAroundCursor(
            document
          , pos
          , [pred.blockCommentStart, neg(pred.startsWith('*'))]
          , [pred.blockCommentEnd, neg(pred.startsWith('*'))]
          )

        start = r.start().line() - 1
        end = r.end().line() + 1

    # Replace comments
    insertionText = list()
    align = None
    for i in range(start, end):
        line = str(document.line(i))
        sline = line.lstrip()
        if align == None:
            align = ' ' * (len(line) - len(sline))
        if sline.startswith('/**') or sline.startswith('*/'):
            continue
        if sline.startswith('*'):
            insertionText.append(align + sline.replace('*', '///', 1))

    originRange = KTextEditor.Range(start, 0, end, 0)
    pos.setPosition(start, len(align) + 3)
    insertPos = KTextEditor.Cursor(start, 0)

    # Update the document
    if bool(insertionText):
        document.startEditing()                             # Start edit transaction:
        document.removeText(originRange)                    # Remove current line

        # insert resulting text line by line...
        document.insertText(insertPos, '\n'.join(insertionText) + '\n')

        # Move cursor to desired position
        view.setCursorPosition(pos)
        document.endEditing()                               # End transaction
コード例 #3
0
ファイル: commentar.py プロジェクト: hlamer/kate
def move_above():
    '''Move an inlined comment before the current line w/ same indentation level'''
    document = kate.activeDocument()
    view = kate.activeView()
    pos = view.cursorPosition()
    commentCh = common.getCommentStyleForDoc(document)

    insertionText = list()
    line = document.line(pos.line())
    # Split a line before and after a comment
    (before, comment, after) = str(line).partition(commentCh)

    before_ls = before.lstrip()
    column = len(before) - len(before_ls)
    doxCommentOffset = 0
    # Is there is a comment in a line?
    if bool(comment):
        # Yeah! It is... Now what about any text??
        if bool(before.strip()):
            if after[0:2] == '/<':
                after = '/' + after[2:]
                doxCommentOffset = 1
            insertionText.append(' ' * column + comment + after)
        else:
            # There is comment alone... Just leave it...
            return
    else:
        # Oops! There is no inline comment... Ok just add new one above.
        insertionText.append(' ' * column + commentCh)

    column += len(commentCh) + doxCommentOffset
    insertionText.append(before.rstrip());

    # Update the document
    if bool(insertionText):
        document.startEditing()                             # Start edit transaction:
        document.removeLine(pos.line())                     # Remove current line

        # insert resulting text line by line...
        pos.setColumn(0)
        document.insertText(pos, '\n'.join(insertionText) + '\n')

        # Move cursor to desired position
        pos.setColumn(column)
        view.setCursorPosition(pos)
        document.endEditing()                               # End transaction
コード例 #4
0
ファイル: commentar.py プロジェクト: hlamer/kate
def turnToBlockComment():
    document = kate.activeDocument()
    view = kate.activeView()
    pos = view.cursorPosition()

    if view.selection():
        sr = view.selectionRange()
        start = sr.start().line()
        end = sr.end().line()
    else:
        r = common.getTextBlockAroundCursor(
            document
          , pos
          , [neg(any_of(pred.startsWith('///'), pred.startsWith('//!')))]
          , [neg(any_of(pred.startsWith('///'), pred.startsWith('//!')))]
          )
        start = r.start().line()
        end = r.end().line()

    # Replace comments in every line
    insertionText = list()
    align = None
    for i in range(start, end):
        line = str(document.line(i))
        sline = line.lstrip()
        if align == None:
            align = ' ' * (len(line) - len(sline))
        insertionText.append(align + sline.replace('///', ' *', 1).replace('//!', ' *', 1))

    originRange = KTextEditor.Range(start, 0, end, 0)
    pos.setPosition(start + 1, len(align) + 3)
    insertPos = KTextEditor.Cursor(start, 0)

    # Update the document
    if bool(insertionText):
        document.startEditing()                             # Start edit transaction:
        document.removeText(originRange)                    # Remove current line

        # insert resulting text ...
        document.insertText(insertPos, align + '/**\n' + '\n'.join(insertionText) + '\n' + align + ' */\n');

        # Move cursor to desired position
        view.setCursorPosition(pos)
        document.endEditing()                               # End transaction
コード例 #5
0
ファイル: commentar.py プロジェクト: hlamer/kate
def changeParagraphWidth(step):
    view = kate.activeView()
    doc = kate.activeDocument()
    pos = view.cursorPosition()

    originRange, isBlock = getParagraphRange(doc, pos)
    if originRange.isEmpty():
        kate.ui.popup(
            i18nc('@title:window', 'Alert')
          , i18nc(
                '@info:tooltip'
              , 'Unable to detect a commented paragraph at cursor...'
              )
          , 'dialog-information'
          )
        return                                              # Dunno what to do on empty range!

    indent = common.getCurrentLineIndentation(view)         # detect current align
    # Processing:
    # 0) split text into left stripped lines
    originalText = view.document().text(originRange)
    lines = [line.lstrip() for line in originalText.split('\n')]
    # 1) detect comment style
    comment = [c.strip() for c in lines[0].split(' ')][0]
    # 2) strip leading comments (and possible left spaces) from each line
    lines = [line[len(comment):].lstrip() for line in lines]
    # 3) get a desired width of the current paragraph
    if step == -1:
        # 3.1) For shrink it is really simple: we just want to fit last word
        # to the next line, and it is enough to specify max(line size) - 1
        newSize = len(max(lines, key=len)) - 1
    elif step == 1:
        # 3.2) To extend paragraph we just want to append a first word from the next
        # after longest line.
        currentMax = 0
        prevLineWasLongest = False
        delta = 0
        for line in lines:
            # 3.2.1) if current maximum was changed on prevoius iteration,
            # get length of a first word on a line
            if prevLineWasLongest:
                # NOTE +1 for one space
                delta = len([word.strip() for word in line.split(' ')][0]) + 1
            # 3.2.2) is current line longer than we've seen before?
            lineSize = len(line)
            prevLineWasLongest = bool(currentMax < lineSize)
            if prevLineWasLongest:
                currentMax = lineSize
        newSize = currentMax + delta
    else:
        assert(not 'Incorrect step specified')

    # 4) wrap the text
    res = textwrap.wrap(' '.join(lines), newSize, break_long_words=False)
    # 5) form a text from the result list
    align = ' ' * indent + comment + ' '
    text = align + ('\n' + align).join(res) + '\n'

    # Return text only if smth really changed
    if originalText != text:                                # Update document only if smth really has changed
        doc.startEditing()                                  # Start edit transaction:
        doc.removeText(originRange)                         # Remove the origin range
        doc.insertText(originRange.start(), text)           # Insert modified text
        view.setCursorPosition(originRange.start())         # Move cursor to the start of the origin range
        doc.endEditing()                                    # End transaction
コード例 #6
0
ファイル: commentar.py プロジェクト: hlamer/kate
def move_inline():
    ''' Move a comment at the current line as inline comment of the next line
        (if latter has no comment yet)
    '''
    document = kate.activeDocument()
    view = kate.activeView()
    pos = view.cursorPosition()
    commentCh = common.getCommentStyleForDoc(document)

    insertionText = []
    currentLine = document.line(pos.line())
    auxLine2Remove = 0
    # Split a line before and after a comment
    (before, comment, after) = currentLine.partition(commentCh)

    # Is there some text on a line?
    if bool(before.strip()):
        return                                              # Aha... move cursor co comment u stupid bastard!
    else:
        # No! What about comment?
        if bool(comment):
            # Aha... the comment is here. Ok. Lets get a line below the current...
            lineBelow = document.line(pos.line() + 1)
            (b_before, b_comment, b_after) = lineBelow.partition(commentCh)
            auxLine2Remove = 1
            # Check for text and comment in it...
            if bool(b_before.strip()):
                # Text present... Comment?
                if bool(b_comment):
                    # Comment too... just leave it...
                    return
                else:
                    # Just text.... no comment. Ok lets work!
                    # (if there is some space remains for inline comment)
                    b_before_s = b_before.rstrip()
                    if len(b_before_s) > kate.configuration[COMMENT_START_POS]:
                        # Oops! No space remains! Get outa here
                        return
                    else:
                        doxCommentOffset = 0
                        if after[0:2] == '/ ':
                            after = '/< ' + after[2:]
                            doxCommentOffset = 2
                        insertionText.append(
                            b_before_s + ' ' * (kate.configuration[COMMENT_START_POS] - len(b_before_s)) + commentCh + after.rstrip()
                            )
                        column = kate.configuration[COMMENT_START_POS] + 3 + doxCommentOffset
            else:
                # No text on the line below! Dunno what damn user wants...
                return
        else:
            # Nothing! Just blank line... Dunno what to do...
            return
        pass

    # Update the document
    if bool(insertionText):
        document.startEditing()                             # Start edit transaction:
        if auxLine2Remove != 0:
            document.removeLine(pos.line() + auxLine2Remove)
        document.removeLine(pos.line())     # Remove current line

        # insert resulting text line by line...
        pos.setColumn(0)
        document.insertText(pos, '\n'.join(insertionText) + '\n')

        # Move cursor to desired position
        pos.setColumn(column)
        view.setCursorPosition(pos)
        document.endEditing()                               # End transaction