Пример #1
0
  /**
   * Expand the string template and replaces the selection with the expansion of the template. The
   * template String may contain any of the following special tags.
   * <li>{@code #{selection}} replaced with the selection, if any. If there is no selection, then
   *     the {@code #{selection}} tag will be removed.
   * <li>{@code #{p:AnyText}} will be replaced by {@code any text} and then set the text selection
   *     to {@code AnyText}
   *
   *     <p>This methood does NOT perform any indentation and the template should generally span one
   *     line only
   */
  public static void insertSimpleTemplate(JTextComponent target, String template) {
    String selected = target.getSelectedText();
    selected = (selected == null) ? "" : selected;
    StringBuffer sb = new StringBuffer(template.length());
    Matcher pm = PTAGS_PATTERN.matcher(template.replace(TEMPLATE_SELECTION, selected));
    int selStart = -1, selEnd = -1;
    int lineStart = 0;
    while (pm.find()) {
      selStart = pm.start() + lineStart;
      pm.appendReplacement(sb, pm.group(1));
      selEnd = sb.length();
    }
    pm.appendTail(sb);
    // String expanded = template.replace(TEMPLATE_SELECTION, selected);

    if (selStart >= 0) {
      selStart += target.getSelectionStart();
      selEnd += target.getSelectionStart();
    }
    target.replaceSelection(sb.toString());
    if (selStart >= 0) {
      // target.setCaretPosition(selStart);
      target.select(selStart, selEnd);
    }
  }
Пример #2
0
 /**
  * Create a Transferable to use as the source for a data transfer.
  *
  * @param comp The component holding the data to be transfered. This argument is provided to
  *     enable sharing of TransferHandlers by multiple components.
  * @return The representation of the data to be transfered.
  */
 protected Transferable createTransferable(JComponent comp) {
   exportComp = (JTextComponent) comp;
   shouldRemove = true;
   p0 = exportComp.getSelectionStart();
   p1 = exportComp.getSelectionEnd();
   return (p0 != p1) ? (new TextTransferable(exportComp, p0, p1)) : null;
 }
Пример #3
0
 /**
  * If the selection is multi lined, then the full lines are selected, otherwise, nothing is done.
  *
  * @return true if the selection is multi-line, or a whole line
  */
 public static boolean selectLines(JTextComponent target) {
   if (target.getSelectionStart() == target.getSelectionEnd()) {
     return false;
   }
   PlainDocument pDoc = (PlainDocument) target.getDocument();
   Element es = pDoc.getParagraphElement(target.getSelectionStart());
   // if more than one line is selected, we need to subtract one from the end
   // so that we do not select the line with the caret and no selection in it
   Element ee = pDoc.getParagraphElement(target.getSelectionEnd() - 1);
   if (es.equals(ee) && ee.getEndOffset() != target.getSelectionEnd()) {
     return false;
   }
   int start = es.getStartOffset();
   int end = ee.getEndOffset();
   target.select(start, end - 1);
   return true;
 }
Пример #4
0
 public void insertBreak(JTextComponent text) {
   indentationLogic = ((EditorPane) text).getIndentationLogic();
   boolean noSelection = text.getSelectionStart() == text.getSelectionEnd();
   if (noSelection) {
     insertNewlineWithAutoIndent(text);
   } else {
     text.replaceSelection("\n");
     // TODO insertNewlineWithAutoIndent
   }
 }
Пример #5
0
    private void outdentText(JTextComponent textComponent) throws BadLocationException {
      int tabSize =
          ((Integer) textComponent.getDocument().getProperty(PlainDocument.tabSizeAttribute))
              .intValue();

      String selectedText = textComponent.getSelectedText();
      int newLineIndex = selectedText != null ? selectedText.indexOf('\n') : -1;

      if (newLineIndex >= 0) {
        int originalSelectionStart = textComponent.getSelectionStart();
        int selectionStart = originalSelectionStart;
        int selectionEnd = textComponent.getSelectionEnd();

        int lastNewLineBeforeSelection = textComponent.getText(0, selectionStart).lastIndexOf('\n');
        int begin = lastNewLineBeforeSelection >= 0 ? lastNewLineBeforeSelection : 0;
        int end = selectionEnd;

        String text = textComponent.getText(begin, end - begin);
        if (lastNewLineBeforeSelection < 0) {
          text = "\n" + text;
        }
        int len = text.length();
        StringBuffer out = new StringBuffer(len);
        for (int i = 0; i < len; i++) {
          char ch = text.charAt(i);
          out.append(ch);
          if (ch == '\n' && i < len - 1) {
            char next = text.charAt(i + 1);
            int stripCount = 0;
            if (next == '\t') {
              stripCount = 1;
            } else {
              for (; stripCount < tabSize && i + 1 + stripCount < len; stripCount++) {
                next = text.charAt(i + 1 + stripCount);
                if (next != ' ' && next != '\t') {
                  break;
                }
              }
            }

            selectionEnd -= stripCount;
            if (i + begin < originalSelectionStart - 1) {
              selectionStart -= stripCount;
            }
            i += stripCount;
          }
        }

        textComponent.select(begin, end);
        textComponent.replaceSelection(
            lastNewLineBeforeSelection < 0 ? out.toString().substring(1) : out.toString());

        textComponent.select(selectionStart, selectionEnd);
      }
    }
  private GsfCodeTemplateFilter(JTextComponent component, int offset) {
    this.startOffset = offset;
    this.endOffset = component.getSelectionStart() == offset ? component.getSelectionEnd() : -1;
    Document doc = component.getDocument();
    CodeCompletionHandler completer =
        doc == null ? null : GsfCompletionProvider.getCompletable(doc, startOffset);

    if (completer != null) {
      templates = completer.getApplicableTemplates(doc, startOffset, endOffset);
    }
  }
 public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) {
   try {
     if (c.getSelectionStart() == c.getSelectionEnd()) { // if no
       // selection
       Rectangle r = c.modelToView(c.getCaretPosition());
       g.setColor(col);
       g.fillRect(0, r.y, c.getWidth(), r.height);
     }
   } catch (BadLocationException ignore) {
   }
 }
 @Override
 public void actionPerformed(ActionEvent evt) {
   JComponent c = target;
   if (c == null
       && (KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner()
           instanceof JComponent)) {
     c =
         (JComponent)
             KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
   }
   if (c != null && c.isEnabled()) {
     if (c instanceof EditableComponent) {
       ((EditableComponent) c).clearSelection();
     } else if (c instanceof JTextComponent) {
       JTextComponent tc = ((JTextComponent) c);
       tc.select(tc.getSelectionStart(), tc.getSelectionStart());
     } else {
       c.getToolkit().beep();
     }
   }
 }
Пример #9
0
 /**
  * Return the lines that span the selection (split as an array of Strings) if there is no
  * selection then current line is returned.
  *
  * <p>Note that the strings returned will not contain the terminating line feeds If the document
  * is empty, then an empty string array is returned. So you can always iterate over the returned
  * array without a null check
  *
  * <p>The text component will then have the full lines set as selection
  *
  * @return String[] of lines spanning selection / or line containing dot
  */
 public static String[] getSelectedLines(JTextComponent target) {
   String[] lines = null;
   try {
     PlainDocument pDoc = (PlainDocument) target.getDocument();
     int start = pDoc.getParagraphElement(target.getSelectionStart()).getStartOffset();
     int end;
     if (target.getSelectionStart() == target.getSelectionEnd()) {
       end = pDoc.getParagraphElement(target.getSelectionEnd()).getEndOffset();
     } else {
       // if more than one line is selected, we need to subtract one from the end
       // so that we do not select the line with the caret and no selection in it
       end = pDoc.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset();
     }
     target.select(start, end);
     lines = pDoc.getText(start, end - start).split("\n");
     target.select(start, end);
   } catch (BadLocationException ex) {
     Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex);
     lines = EMPTY_STRING_ARRAY;
   }
   return lines;
 }
Пример #10
0
 /**
  * Determines whether the image is selected, and if it's the only thing selected.
  *
  * @return 0 if not selected, 1 if selected, 2 if exclusively selected. "Exclusive" selection is
  *     only returned when editable.
  */
 protected int getSelectionState() {
   int p0 = fElement.getStartOffset();
   int p1 = fElement.getEndOffset();
   if (fContainer instanceof JTextComponent) {
     JTextComponent textComp = (JTextComponent) fContainer;
     int start = textComp.getSelectionStart();
     int end = textComp.getSelectionEnd();
     if (start <= p0 && end >= p1) {
       if (start == p0 && end == p1 && isEditable()) return 2;
       else return 1;
     }
   }
   return 0;
 }
Пример #11
0
 /**
  * Expand the string template and replaces the selection with the expansion of the template. The
  * template String may contain any of the following special tags.
  * <li>{@code #{selection}} replaced with the selection, if any. If there is no selection, then
  *     the {@code #{selection}} tag will be removed.
  * <li>{@code #{p:any text}} will be replaced by {@code any text} and then set selection to {@code
  *     any text}
  *
  *     <p>This method properly handles indentation as follows: The indentation of the whole block
  *     will match the indentation of the caret line, or the line with the beginning of the
  *     selection, if the selection is in whole line, i.e.e one or more lines of selected text.
  *     {@see selectLines()}
  *
  * @param target JEditorCOmponent to be affected
  * @param templateLines template split as a String array of lines.
  */
 public static void insertLinesTemplate(JTextComponent target, String[] templateLines) {
   // get some stuff we'll need:
   String thisIndent = getIndent(getLineAt(target, target.getSelectionStart()));
   String[] selLines = getSelectedLines(target);
   int selStart = -1, selEnd = -1;
   StringBuffer sb = new StringBuffer();
   for (String tLine : templateLines) {
     int selNdx = tLine.indexOf("#{selection}");
     if (selNdx >= 0) {
       // for each of the selected lines:
       for (String selLine : selLines) {
         sb.append(tLine.subSequence(0, selNdx));
         sb.append(selLine);
         sb.append('\n');
       }
     } else {
       sb.append(thisIndent);
       // now check for any ptags
       Matcher pm = PTAGS_PATTERN.matcher(tLine);
       int lineStart = sb.length();
       while (pm.find()) {
         selStart = pm.start() + lineStart;
         pm.appendReplacement(sb, pm.group(1));
         selEnd = sb.length();
       }
       pm.appendTail(sb);
       sb.append('\n');
     }
   }
   int ofst = target.getSelectionStart();
   target.replaceSelection(sb.toString());
   if (selStart >= 0) {
     // target.setCaretPosition(selStart);
     target.select(ofst + selStart, ofst + selEnd);
   }
 }
    public boolean isActive(DrawContext ctx, MarkFactory.DrawMark mark) {
      boolean active;
      if (mark != null) {
        active = mark.activateLayer;
      } else {
        JTextComponent c = ctx.getEditorUI().getComponent();
        active =
            (c != null)
                && c.getCaret().isSelectionVisible()
                && ctx.getFragmentOffset() >= c.getSelectionStart()
                && ctx.getFragmentOffset() < c.getSelectionEnd();
      }

      return active;
    }
Пример #13
0
 public void keyPressed(KeyEvent e) {
   if (isDisplayable()) setPopupVisible(true);
   hitBackspace = false;
   switch (e.getKeyCode()) {
       // determine if the pressed key is backspace (needed by the remove method)
     case KeyEvent.VK_BACK_SPACE:
       hitBackspace = true;
       hitBackspaceOnSelection = editor.getSelectionStart() != editor.getSelectionEnd();
       break;
       // ignore delete key
     case KeyEvent.VK_DELETE:
       e.consume();
       getToolkit().beep();
       break;
   }
 }
Пример #14
0
    private void indentText(JTextComponent textComponent) throws BadLocationException {
      String selectedText = textComponent.getSelectedText();
      int newLineIndex = selectedText != null ? selectedText.indexOf('\n') : -1;

      if (newLineIndex >= 0) {
        int originalSelectionStart = textComponent.getSelectionStart();
        int selectionStart = originalSelectionStart;
        int selectionEnd = textComponent.getSelectionEnd();

        int lastNewLineBeforeSelection = textComponent.getText(0, selectionStart).lastIndexOf('\n');
        int begin = lastNewLineBeforeSelection >= 0 ? lastNewLineBeforeSelection : 0;
        int end = selectionEnd;

        String text = textComponent.getText(begin, end - begin);
        int len = text.length();
        StringBuffer out = new StringBuffer(len);
        if (lastNewLineBeforeSelection < 0) {
          out.insert(0, '\t');
          selectionStart++;
          selectionEnd++;
        }
        for (int i = 0; i < len; i++) {
          char ch = text.charAt(i);
          out.append(ch);
          if (ch == '\n' && i < len - 1) {
            out.append("\t");
            selectionEnd++;
            if (begin + i < originalSelectionStart) {
              selectionStart++;
            }
          }
        }

        textComponent.select(begin, end);
        textComponent.replaceSelection(out.toString());

        textComponent.select(selectionStart, selectionEnd);
      } else {
        textComponent.replaceSelection("\t");
      }
    }
 // Create a Transferable implementation that contains the selected text.
 protected Transferable createTransferable(JComponent c) {
   if (c != textComponent) { // ###
     System.out.println("*** createTransferable(): c=" + c);
   }
   source = (JTextComponent) c;
   int start = source.getSelectionStart();
   int end = source.getSelectionEnd();
   Document doc = source.getDocument();
   if (start == end) {
     return null;
   }
   try {
     p0 = doc.createPosition(start);
     p1 = doc.createPosition(end);
     System.out.println(">>> createTransferable(): p0=" + p0 + ", p1=" + p1);
   } catch (BadLocationException e) {
     System.out.println(
         "*** createTransferable(): "
             + "Can't create position - unable to remove text from source.");
   }
   shouldRemove = true;
   String data = source.getSelectedText();
   return new StringSelection(data);
 }