Duplicate selected text or current line
501634
def _onShortcutDuplicateLine(self):
        
        cursor = self.textCursor()
        if cursor.hasSelection():  # duplicate selection
            text = cursor.selectedText()
            selectionStart, selectionEnd = cursor.selectionStart(), cursor.selectionEnd()
            cursor.setPosition(selectionEnd)
            cursor.insertText(text)
            # restore selection
            cursor.setPosition(selectionStart)
            cursor.setPosition(selectionEnd, QTextCursor.KeepAnchor)
            self.setTextCursor(cursor)
        else:
            line = cursor.blockNumber()
            self.lines.insert(line + 1, self.lines[line])
            self.ensureCursorVisible()

        self._updateExtraSelections()
1011996
def edit_line(self, line):
        """"""
        for code, code_obj in self.code_objs.items():
            line = self.__edit_line(line, code, code_obj)
        return line
820798
function highlight(text, lang, options){

    function makeSafe(str){
      return str
        .replace(/\r\n|\n\r|\r/g, '\n')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;');
    }

    function normalize(text){
      text = text
        // cut first empty lines
        .replace(/^(?:\s*[\n]+)+?([ \t]*)/, '$1')
        .trimRight();

      // fix empty strings
      text = text.replace(/\n[ \t]+\n/g, '\n\n');

      // normalize text offset
      var minOffset = 1000;
      var lines = text.split(/\n+/);
      var startLine = Number(text.match(/^function/) != null); // fix for function.toString()

      for (var i = startLine; i < lines.length; i++)
      {
        var m = lines[i].match(/^\s*/);
        if (m[0].length < minOffset)
          minOffset = m[0].length;
        if (minOffset == 0)
          break;
      }

      if (minOffset > 0)
        text = text.replace(new RegExp('(^|\\n) {' + minOffset + '}', 'g'), '$1');

      return text;
    }

    function defaultWrapper(line, idx){
      return (
        '<div class="line ' + (idx % 2 ? 'odd' : 'even') + lineClass + '">' +
          '<span class="lineContent">' +
            (!options.noLineNumber
              ? '<input class="lineNumber" value="' + lead(idx + 1, numberWidth) + '" type="none" unselectable="on" readonly="readonly" tabindex="-1" />' +
                '<span class="over"></span>'
              : ''
            ) +
            line + '\r\n' +
          '</span>' +
        '</div>'
      );
    }

    //  MAIN PART

    if (!options)
      options = {};

    // prepare text
    var rangeStart = -1;
    var rangeEnd = -1;
    var rangeName = '';

    if (options.range)
    {
      var left = makeSafe(text.substr(0, options.range[0]));
      var range = makeSafe(text.substring(options.range[0], options.range[1]));
      var right = makeSafe(text.substr(options.range[1]));

      rangeStart = left.length;
      rangeEnd = rangeStart + range.length;
      rangeName = options.range[2] || 'range';

      text = left + range + right;
    }
    else
    {
      text = makeSafe(text);
    }

    if (!options.keepFormat)
      text = normalize(text || '');

    var parser = LANG_PARSER[lang] || LANG_PARSER.text;
    var html = parser(text, rangeStart, rangeEnd, rangeName);

    var lines = html.split('\n');
    var numberWidth = String(lines.length).length;
    var lineClass = (options.noLineNumber ? '' : ' hasLineNumber');
    var offsetRx = new RegExp('^(<span class="' + rangeName + '">)?([ \\t]+)');

    lines = lines
      .map(function(line){
        return line.replace(offsetRx, function(m, rangeSpan, spaces){
          return (rangeSpan || '') + repeat('\xA0', spaces.replace(/\t/g, '  ').length);
        });
      })
      .map(options.wrapper || defaultWrapper);

    return options.lines ? lines : lines.join('');
  }
1106888
function selectText(element)
			{
				if(element)
				{
					var element = element[0];
					
					if (document.body.createTextRange)
					{
						var range = document.body.createTextRange();
						range.moveToElementText(element);
						range.select();
					}
					else if (window.getSelection)
					{
						var selection = window.getSelection();  
						var range = document.createRange();
						
						if(element != "undefined" && element != null)
						{
							range.selectNodeContents(element);
							
							selection.removeAllRanges();
							selection.addRange(range);
							
							if($(element).is(":empty"))
							{
								$(element).append("&nbsp;");
									selectText($(element));
							}
						}
					}
				}
			}
452853
def paste(self):
        """"""
        if self.has_selected_text():
            self.remove_selected_text()
        self.insert_text(QApplication.clipboard().text())
449394
function pasteHandler(context, event)
        {
            var data = event.clipboardData.getData("Text");
            if (!data)
                return;
            var colonIdx = data.indexOf(":");
            if (colonIdx < 0)
                return;
            var name = data.substring(0, colonIdx).trim();
            var value = data.substring(colonIdx + 1).trim();

            event.preventDefault();

            if (!("originalName" in context)) {
                context.originalName = this.nameElement.textContent;
                context.originalValue = this.valueElement.textContent;
            }
            this.property.name = name;
            this.property.value = value;
            this.nameElement.textContent = name;
            this.valueElement.textContent = value;
            this.nameElement.normalize();
            this.valueElement.normalize();

            this.editingCommitted(event.target.textContent, context, "forward");
        }
1092042
def _copy_selection(self, *event):
        
        if react_to_event(self.view, self.view.editor, event):
            logger.debug("copy selection")
            global_clipboard.copy(self.model.selection)
            return True
1322476
public void duplicate(Text destination) {
        System.arraycopy(chars, pos, destination.chars, destination.pos, len);
        destination.len = len;
    }
579506
def _select_input(self):
        """"""
        line, index = self.get_position('eof')
        if self.current_prompt_pos is None:
            pline, pindex = line, index
        else:
            pline, pindex = self.current_prompt_pos
        self.setSelection(pline, pindex, line, index)
521326
def OnCopy(self, event):
        """"""

        focus = self.main_window.FindFocus()

        if isinstance(focus, wx.TextCtrl):
            # Copy selection from TextCtrl if in focus
            focus.Copy()

        else:
            selection = self.main_window.grid.selection
            data = self.main_window.actions.copy(selection)
            self.main_window.clipboard.set_clipboard(data)

        event.Skip()
216253
private LinkedList<Change> lineMode(String text1, String text2) {
        // Scan the text on a line-by-line basis first.
        LinesToCharsResult b = linesToChars(text1, text2);
        text1 = b.chars1;
        text2 = b.chars2;
        List<String> linearray = b.lineArray;

        LinkedList<Change> diffs = main(text1, text2, false);

        // Convert the diff back to original text.
        charsToLines(diffs, linearray);
        // Eliminate freak matches (e.g. blank lines)
        cleanupSemantic(diffs);

        // Rediff any replacement blocks, this time character-by-character.
        // Add a dummy entry at the end.
        diffs.add(new Change(Operation.EQUAL, ""));
        int count_delete = 0;
        int count_insert = 0;
        String text_delete = "";
        String text_insert = "";
        ListIterator<Change> pointer = diffs.listIterator();
        Change thisDiff = pointer.next();
        while (thisDiff != null) {
            switch (thisDiff.operation) {
                case INSERT:
                    count_insert++;
                    text_insert += thisDiff.text;
                    break;
                case DELETE:
                    count_delete++;
                    text_delete += thisDiff.text;
                    break;
                case EQUAL:
                    // Upon reaching an equality, check for prior redundancies.
                    if (count_delete >= 1 && count_insert >= 1) {
                        // Delete the offending records and add the merged ones.
                        pointer.previous();
                        for (int j = 0; j < count_delete + count_insert; j++) {
                            pointer.previous();
                            pointer.remove();
                        }
                        main(text_delete, text_insert, false).forEach(pointer::add);
                    }
                    count_insert = 0;
                    count_delete = 0;
                    text_delete = "";
                    text_insert = "";
                    break;
            }
            thisDiff = pointer.hasNext() ? pointer.next() : null;
        }
        diffs.removeLast();  // Remove the dummy entry at the end.

        return diffs;
    }
1370695
def OnCellText(self, event):
        """"""

        row, col, _ = self.grid.actions.cursor
        self.grid.GetTable().SetValue(row, col, event.code)

        event.Skip()
224559
def cut(self):
        
        cursorPos = self._qpart.cursorPosition
        topLeft = (min(self._start[0], cursorPos[0]),
                   min(self._start[1], cursorPos[1]))
        self.copy()
        self.delete()

        """Move cursor to top-left corner of the selection,
        so that if text gets pasted again, original text will be restored"""
        self._qpart.cursorPosition = topLeft
115883
function() {

      var x, y, z, arr, edits, isEditable, configs, isConfig, el, html,li, parent, els, isDefault, removeElement, element, modal, body, attr, div, label, control, option, menuItem, els, text, block;


      // clean pasted text, #ref: http://bit.ly/1Tr8IR3
      document.addEventListener('paste', function(e) {

        if(e.target.nodeName == 'TEXTAREA') {
          // do nothing
        }
        else {
          // cancel paste
          e.preventDefault();

          // get text representation of clipboard
          var text = e.clipboardData.getData("text/plain");

          // insert text manually
          document.execCommand("insertHTML", false, text);
        }

      });


      // get contentEditable elements
      arr = document.querySelectorAll('body');

      for (x = 0; x < arr.length; x += 1) {

        // delegate CLICK, FOCUS event
        ['click', 'focus'].forEach(function(e) {

          arr[x].addEventListener(e, function(e) {

            if (e.target.hasAttribute('hashedit-element')) {
              element = e.target;

              // get value of text node
              var text = hashedit.getTextNodeValue(element);

              // if text is set to "Tap to update" select all the text
              if(text === hashedit.i18n('Tap to update')) {
                document.execCommand('selectAll', false, null);
              }

            }
            else {
              element = hashedit.findParentBySelector(e.target, '[hashedit-element]');
            }

            // remove all current elements
            els = document.querySelectorAll('[current-hashedit-element]');

            for (y = 0; y < els.length; y += 1) {
              els[y].removeAttribute('current-hashedit-element');
            }

            // set current element
            if (element) {
              element.setAttribute('current-hashedit-element', 'true');
            }

            // check for remove element
            if (e.target.matches('.hashedit-remove')  || hashedit.findParentBySelector(e.target, '.hashedit-remove') !== null) {
              element.remove();
            }
            // check for properties element
            else if (e.target.matches('.hashedit-properties')  ||  hashedit.findParentBySelector(e.target, '.hashedit-properties') !== null) {

              hashedit.current.node = element;

              isDefault = true;

              // get menuItem
              menuItem = null;

              // see if the element matches a plugin selector
              for (x = 0; x < hashedit.menu.length; x += 1) {

                if (element.matches(hashedit.menu[x].selector)) {

                  menuItem = hashedit.menu[x];

                  if (hashedit.menu[x].configure) {
                    isDefault = false;
                    hashedit.menu[x].configure();
                  }

                }

              }

              if (isDefault === true) {

                modal = document.getElementById('hashedit-element-settings-modal');
                body = modal.querySelector('.hashedit-modal-body');

                // remove existing custom attributes
                els = body.querySelectorAll('.hashedit-custom-attr');

                for(y=0; y<els.length; y++) {
                  els[y].parentNode.removeChild(els[y]);
                }

                // setup custom attributes
                if(menuItem != null) {

                  if(menuItem.attributes) {

                    for(y=0; y<menuItem.attributes.length; y++){

                      attr = menuItem.attributes[y];

                      div = document.createElement('div');
                      div.setAttribute('class', 'hashedit-custom-attr');

                      label = document.createElement('label');
                      label.innerHTML = attr.label;

                      div.appendChild(label);

                      if(attr.type == 'text'){
                        control = document.createElement('input');
                        control.setAttribute('type', 'text');
                        control.setAttribute('data-model', 'node.' + attr.attr);
                        control.setAttribute('name', 'attr');

                        div.appendChild(control);
                      }

                      if(attr.type == 'select'){
                        control = document.createElement('select');
                        control.setAttribute('data-model', 'node.' + attr.attr);
                        control.setAttribute('name', 'attr');

                        // create options
                        if(attr.values != null) {

                          for(z=0; z<attr.values.length; z++){

                            option = document.createElement('option');

                            // determine if hashed array
                            if(attr.values[z].text) {
                              option.setAttribute('value', attr.values[z].value);
                              option.innerHTML = attr.values[z].text;
                            }
                            else {
                              option.setAttribute('value', attr.values[z]);
                              option.innerHTML = attr.values[z];
                            }

                            control.appendChild(option);
                          }

                        }

                        div.appendChild(control);

                      }

                      body.appendChild(div);

                    }


                  }

                }

                // bind
                hashedit.bind();

                // show modal
                modal.setAttribute('visible', 'true');

              }

            }
            // add block
            else if (e.target.matches('.hashedit-block-add') || hashedit.findParentBySelector(e.target, '.hashedit-block-add') !== null) {

              block = hashedit.findParentBySelector(e.target, '[hashedit-block]');

              if(block !== null) {
                hashedit.showLayoutDialog(block);
              }

            }
            // properites block
            else if (e.target.matches('.hashedit-block-properties') || hashedit.findParentBySelector(e.target, '.hashedit-block-properties') !== null) {

              block = hashedit.findParentBySelector(e.target, '[hashedit-block]');

              if(block !== null) {

                var modal = document.getElementById('hashedit-block-settings-modal');

                // show modal
                modal.setAttribute('visible', 'true');

                hashedit.current.node = block;
                hashedit.bind();

              }

            }
            // move block up
            else if (e.target.matches('.hashedit-block-up') ||  hashedit.findParentBySelector(e.target, '.hashedit-block-up') !== null) {

              block = hashedit.findParentBySelector(e.target, '[hashedit-block]');

              if(block.previousElementSibling != null) {

                if(block.previousElementSibling.hasAttribute('hashedit-block') === true) {
                  block.parentNode.insertBefore(block, block.previousElementSibling);
                }

              }

              hashedit.setupBlocks();

            }
            // move block down
            else if (e.target.matches('.hashedit-block-down') ||  hashedit.findParentBySelector(e.target, '.hashedit-block-down') !== null) {

              block = hashedit.findParentBySelector(e.target, '[hashedit-block]');

              if(block.nextElementSibling != null) {

                if(block.nextElementSibling.hasAttribute('hashedit-block') === true) {
                  block.nextElementSibling.parentNode.insertBefore(block.nextElementSibling, block);
                }

              }

              hashedit.setupBlocks();

            }
            // remove block
            else if (e.target.matches('.hashedit-block-remove') ||  hashedit.findParentBySelector(e.target, '.hashedit-block-remove') !== null) {

              block = hashedit.findParentBySelector(e.target, '[hashedit-block]');
              block.remove();

              hashedit.setupBlocks();

            }
            // remove block
            else if (hashedit.findParentBySelector(e.target, '.hashedit-block-duplicate') !== null) {

              block = hashedit.findParentBySelector(e.target, '[hashedit-block]');

              hashedit.duplicateBlock(block, 'before');

              hashedit.setupBlocks();

            }
            // handle links
            else if (e.target.nodeName == 'A') {

                // hide .hashedit-config, .hashedit-modal
                edits = document.querySelectorAll('[hashedit]');

                // determines whether the element is a configuration
                isEditable = false;

                for (x = 0; x < edits.length; x += 1) {

                  if (edits[x].contains(e.target) === true) {
                    isEditable = true;
                  }

                }

                if (isEditable) {
                  hashedit.showLinkDialog();
                }
            }
            else if (e.target.nodeName == 'IMG') {
                hashedit.current.node = e.target;
                hashedit.current.image = e.target;

                // hide .hashedit-config, .hashedit-modal
                edits = document.querySelectorAll('[hashedit]');

                // determines whether the element is a configuration
                isEditable = false;

                for (x = 0; x < edits.length; x += 1) {

                  if (edits[x].contains(e.target) === true) {
                    isEditable = true;
                  }

                }

                if (isEditable) {
                  hashedit.showImageDialog();
                }
            }
            else if (e.target.hasAttribute('contentEditable')) {

              // shows the text options
              hashedit.showTextOptions(e.target);

            }
            else if (e.target.parentNode.hasAttribute('contentEditable') && e.target.parentNode) {

              // shows the text options
              hashedit.showTextOptions(e.target);

            }
            else if (e.target.className == 'dz-hidden-input') {
              // do nothing
            }
            else {
              // hide .hashedit-config, .hashedit-modal
              configs = document.querySelectorAll(
                '.hashedit-config, .hashedit-modal, .hashedit-menu'
              );

              // determines whether the element is a configuration
              isConfig = false;

              for (x = 0; x < configs.length; x += 1) {

                if (configs[x].contains(e.target) === true) {
                  isConfig = true;
                }

              }

              // hide if not in config
              if (isConfig === false) {

                for (x = 0; x < configs.length; x += 1) {
                  configs[x].removeAttribute('visible');
                }

              }
            }

          });

        });


        // delegate INPUT event
        ['input'].forEach(function(e) {
          arr[x].addEventListener(e, function(e) {

            if (e.target.hasAttribute('contentEditable')) {

              el = e.target;

              while (el !== null) {

                var node = el.childNodes[0];

                if (hashedit.debug === true) {
                  console.log('input event');
                  console.log(el.nodeName);
                }

                // get value of text node
                var text = hashedit.getTextNodeValue(el);

                // if text is blank and the element has only one child node, add "Tap to update" to prevent the editor from breaking
                if(text === '' && el.childNodes.length == 1) {
                  text = document.createTextNode(hashedit.i18n('Tap to update'));
                  el.insertBefore(text, el.firstChild);
                  document.execCommand('selectAll', false, null);
                }

                html = el.innerHTML;

                // strip out &nbsps
                html = hashedit.replaceAll(html, '&nbsp;', ' ');

                // trim
                html = html.trim();

                // set to null
                el = null;
              }

            }


          });

        });

        // delegate INPUT event
        ['keydown'].forEach(function(e) {
          arr[x].addEventListener(e, function(e) {

            if (e.target.hasAttribute('contentEditable')) {

              el = e.target;

              // ENTER key
              if (e.keyCode === 13) {

                if (el.nodeName == 'LI') {

                  // create LI
                  li = document.createElement('li');
                  li.setAttribute('contentEditable', true);

                  // append LI
                  el.parentNode.appendChild(li);

                  el.parentNode.lastChild.focus();

                  e.preventDefault();
                  e.stopPropagation();

                }
                else if (el.nodeName == 'P') {

                  var node = hashedit.append('<p>' + hashedit.i18n('Tap to update') + '</p>');

                  hashedit.current.node = node;


                  e.preventDefault();
                  e.stopPropagation();

                }

              }

              // DELETE key
              if (e.keyCode === 8) {

                if (el.nodeName == 'LI') {

                  if (el.innerHTML === '') {

                    if (el.previousSibling !== null) {

                      parent = el.parentNode;

                      el.remove();

                      parent.lastChild.focus();
                    }

                    e.preventDefault();
                    e.stopPropagation();
                  }

                } // end LI

              }

            }


          });

        });

      }

    }
1368386
def _currentLineExtraSelections(self):
        
        if self._currentLineColor is None:
            return []

        def makeSelection(cursor):
            selection = QTextEdit.ExtraSelection()
            selection.format.setBackground(self._currentLineColor)
            selection.format.setProperty(QTextFormat.FullWidthSelection, True)
            cursor.clearSelection()
            selection.cursor = cursor
            return selection

        rectangularSelectionCursors = self._rectangularSelection.cursors()
        if rectangularSelectionCursors:
            return [makeSelection(cursor) \
                        for cursor in rectangularSelectionCursors]
        else:
            return [makeSelection(self.textCursor())]
1106686
function dup( text, count ) {

    let result = "";

    for ( let i = 1; i <= count; i++ ) result += text;

    return result;

}
193820
def newline_text(self, text, indent = False):
        """"""
        self.newline(indent)
        self.text(text)