Advertisement
TheHanna

Building a text editor with PyQt: Part 2 - Indent/Dedent Fix

Oct 10th, 2014
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.29 KB | None | 0 0
  1. def indent(self):
  2.     # Grab the cursor
  3.     cursor = self.text.textCursor()
  4.  
  5.     if cursor.hasSelection():
  6.         # Store the current line/block number
  7.         temp = cursor.blockNumber()
  8.         direction = None
  9.         diff = None
  10.  
  11.         # Determine cursor position relative to selection start/end
  12.         # Move to opposite position
  13.         # Set cursor movement direction
  14.         # Calculate range of selection
  15.         if cursor.position() == cursor.selectionStart():
  16.             cursor.setPosition(cursor.selectionEnd())
  17.             direction = QtGui.QTextCursor.Up
  18.             diff = cursor.blockNumber() - temp
  19.         elif cursor.position() == cursor.selectionEnd():
  20.             cursor.setPosition(cursor.selectionStart())
  21.             direction = QtGui.QTextCursor.Down
  22.             diff = temp
  23.  
  24.         # Iterate over lines
  25.         for n in range(diff + 1):
  26.             # Move to start of each line
  27.             cursor.movePosition(QtGui.QTextCursor.StartOfLine)
  28.             # Insert tabbing
  29.             cursor.insertText('\t')
  30.             # And move to next line
  31.             cursor.movePosition(direction)
  32.  
  33.     # If there is no selection just insert a tab
  34.     else:
  35.         cursor.insertText('\t')
  36.  
  37. def dedent(self):
  38.     # Grab the cursor
  39.     cursor = self.text.textCursor()
  40.  
  41.     if cursor.hasSelection():
  42.         # Store the current line/block number
  43.         temp = cursor.blockNumber()
  44.         direction = None
  45.         diff = None
  46.  
  47.         # Determine cursor position relative to selection start/end
  48.         # Move to opposite position
  49.         # Set cursor movement direction
  50.         # Calculate range of selection
  51.         if cursor.position() == cursor.selectionStart():
  52.             cursor.setPosition(cursor.selectionEnd())
  53.             direction = QtGui.QTextCursor.Up
  54.             diff = cursor.blockNumber() - temp
  55.         elif cursor.position() == cursor.selectionEnd():
  56.             cursor.setPosition(cursor.selectionStart())
  57.             direction = QtGui.QTextCursor.Down
  58.             diff = temp
  59.  
  60.         # Iterate over lines
  61.         for n in range(diff + 1):
  62.             self.handleDedent(cursor)
  63.             # Move up
  64.             cursor.movePosition(direction)
  65.  
  66.     # If there is no selection just insert a tab
  67.     else:
  68.         self.handleDedent(cursor)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement