public StringBuffer generateCode(int _type, String _info) {
   StringBuffer code = new StringBuffer();
   String genName, passName;
   int index = name.lastIndexOf('.');
   if (index >= 0) genName = name.substring(index + 1).toLowerCase();
   else genName = name.toLowerCase();
   if (_info != null && _info.trim().length() > 0) passName = _info;
   else {
     passName = getName();
     if (passName.startsWith("Osejs.")) passName = passName.substring(6);
   }
   index = 0;
   for (Editor editor : pageList) {
     if (editor instanceof CodeEditor) {
       index++;
       ((CodeEditor) editor).setCodeName(genName + index);
     } else if (editor instanceof EquationEditor) {
       index++;
       ((EquationEditor) editor).setCodeName(genName + index);
     }
     // if (editor.isActive())
     code.append(editor.generateCode(_type, passName));
   }
   return code;
 }
  private static void restoreBlockSelection(
      Editor editor, List<RangeMarker> caretsAfter, int caretLine) {
    int column = -1;
    int minLine = Integer.MAX_VALUE;
    int maxLine = -1;
    for (RangeMarker marker : caretsAfter) {
      if (marker.isValid()) {
        LogicalPosition lp = editor.offsetToLogicalPosition(marker.getStartOffset());
        if (column == -1) {
          column = lp.column;
        } else if (column != lp.column) {
          return;
        }
        minLine = Math.min(minLine, lp.line);
        maxLine = Math.max(maxLine, lp.line);

        if (lp.line == caretLine) {
          editor.getCaretModel().moveToLogicalPosition(lp);
        }
      }
    }
    editor
        .getSelectionModel()
        .setBlockSelection(
            new LogicalPosition(minLine, column), new LogicalPosition(maxLine, column));
  }
  @Nullable
  public static TextRange pasteTransferable(
      final Editor editor, @Nullable Producer<Transferable> producer) {
    String text = getStringContent(producer);
    if (text == null) return null;

    if (editor.getCaretModel().supportsMultipleCarets()) {
      int caretCount = editor.getCaretModel().getAllCarets().size();
      final Iterator<String> segments =
          new ClipboardTextPerCaretSplitter().split(text, caretCount).iterator();
      editor
          .getCaretModel()
          .runForEachCaret(
              new CaretAction() {
                @Override
                public void perform(Caret caret) {
                  insertStringAtCaret(editor, segments.next(), false, true);
                }
              });
      return null;
    } else {
      int caretOffset = editor.getCaretModel().getOffset();
      insertStringAtCaret(editor, text, false, true);
      return new TextRange(caretOffset, caretOffset + text.length());
    }
  }
 public void startTemplateWithPrefix(
     final Editor editor,
     final TemplateImpl template,
     final int templateStart,
     @Nullable final PairProcessor<String, String> processor,
     @Nullable final String argument) {
   final int caretOffset = editor.getCaretModel().getOffset();
   final TemplateState templateState = initTemplateState(editor);
   CommandProcessor commandProcessor = CommandProcessor.getInstance();
   commandProcessor.executeCommand(
       myProject,
       () -> {
         editor.getDocument().deleteString(templateStart, caretOffset);
         editor.getCaretModel().moveToOffset(templateStart);
         editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
         editor.getSelectionModel().removeSelection();
         Map<String, String> predefinedVarValues = null;
         if (argument != null) {
           predefinedVarValues = new HashMap<String, String>();
           predefinedVarValues.put(TemplateImpl.ARG, argument);
         }
         templateState.start(template, processor, predefinedVarValues);
       },
       CodeInsightBundle.message("insert.code.template.command"),
       null);
 }
  @Nullable
  public Runnable startNonCustomTemplates(
      final Map<TemplateImpl, String> template2argument,
      final Editor editor,
      @Nullable final PairProcessor<String, String> processor) {
    final int caretOffset = editor.getCaretModel().getOffset();
    final Document document = editor.getDocument();
    final CharSequence text = document.getCharsSequence();

    if (template2argument == null || template2argument.isEmpty()) {
      return null;
    }
    if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), myProject)) {
      return null;
    }

    return () -> {
      if (template2argument.size() == 1) {
        TemplateImpl template = template2argument.keySet().iterator().next();
        String argument = template2argument.get(template);
        int templateStart = getTemplateStart(template, argument, caretOffset, text);
        startTemplateWithPrefix(editor, template, templateStart, processor, argument);
      } else {
        ListTemplatesHandler.showTemplatesLookup(myProject, editor, template2argument);
      }
    };
  }
Exemplo n.º 6
0
  @Override
  public void execute(
      final Editor editor,
      final DataContext dataContext,
      @Nullable final Producer<Transferable> producer) {
    if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return;

    final Document document = editor.getDocument();
    if (!FileDocumentManager.getInstance()
        .requestWriting(document, CommonDataKeys.PROJECT.getData(dataContext))) {
      return;
    }

    DataContext context = dataContext;
    if (producer != null) {
      context =
          new DataContext() {
            @Override
            public Object getData(@NonNls String dataId) {
              return PasteAction.TRANSFERABLE_PROVIDER.is(dataId)
                  ? producer
                  : dataContext.getData(dataId);
            }
          };
    }

    final Project project = editor.getProject();
    if (project == null
        || editor.isColumnMode()
        || editor.getSelectionModel().hasBlockSelection()
        || editor.getCaretModel().getCaretCount() > 1) {
      if (myOriginalHandler != null) {
        myOriginalHandler.execute(editor, context);
      }
      return;
    }

    final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if (file == null) {
      if (myOriginalHandler != null) {
        myOriginalHandler.execute(editor, context);
      }
      return;
    }

    document.startGuardedBlockChecking();
    try {
      for (PasteProvider provider : Extensions.getExtensions(EP_NAME)) {
        if (provider.isPasteEnabled(context)) {
          provider.performPaste(context);
          return;
        }
      }
      doPaste(editor, project, file, document, producer);
    } catch (ReadOnlyFragmentModificationException e) {
      EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(e);
    } finally {
      document.stopGuardedBlockChecking();
    }
  }
  public static void typeInStringAtCaretHonorBlockSelection(
      final Editor editor, final String str, final boolean toProcessOverwriteMode)
      throws ReadOnlyFragmentModificationException {
    Document doc = editor.getDocument();
    final SelectionModel selectionModel = editor.getSelectionModel();
    if (selectionModel.hasBlockSelection()) {
      RangeMarker guard = selectionModel.getBlockSelectionGuard();
      if (guard != null) {
        DocumentEvent evt = new MockDocumentEvent(doc, editor.getCaretModel().getOffset());
        ReadOnlyFragmentModificationException e =
            new ReadOnlyFragmentModificationException(evt, guard);
        EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(doc).handle(e);
      } else {
        final LogicalPosition start = selectionModel.getBlockStart();
        final LogicalPosition end = selectionModel.getBlockEnd();
        assert start != null;
        assert end != null;

        int column = Math.min(start.column, end.column);
        int startLine = Math.min(start.line, end.line);
        int endLine = Math.max(start.line, end.line);
        deleteBlockSelection(editor);
        for (int i = startLine; i <= endLine; i++) {
          editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(i, column));
          insertStringAtCaret(editor, str, toProcessOverwriteMode, true);
        }
        selectionModel.setBlockSelection(
            new LogicalPosition(startLine, column + str.length()),
            new LogicalPosition(endLine, column + str.length()));
      }
    } else {
      insertStringAtCaret(editor, str, toProcessOverwriteMode, true);
    }
  }
 public StringBuffer saveStringBuffer() {
   StringBuffer save = new StringBuffer();
   for (java.util.Enumeration<Editor> e = pageList.elements(); e.hasMoreElements(); ) {
     Editor page = e.nextElement();
     save.append(
         "<"
             + name
             + ".Page>\n"
             + "<Type>"
             + typeOfPage(page)
             + "</Type>\n"
             + "<Name>"
             + page.getName()
             + "</Name>\n"
             + "<Active>"
             + page.isActive()
             + "</Active>\n"
             + "<"
             + contentDelim
             + ">\n");
     save.append(page.saveStringBuffer());
     save.append("</" + contentDelim + ">\n" + "</" + name + ".Page>\n");
   }
   return save;
 }
 private void moveUpAndDownPage(boolean _up) {
   int index = tabbedPanel.getSelectedIndex();
   if (index < 0) return;
   Editor page = pageList.get(index);
   if (page == null) return;
   if (_up) {
     if (index == 0) return;
     pageList.removeElementAt(index);
     pageList.insertElementAt(page, index - 1);
     tabbedPanel.removeTabAt(index);
     tabbedPanel.insertTab(
         page.isActive() ? page.getName() : page.getName() + " (D)",
         null,
         page.getComponent(),
         tooltip,
         index - 1);
   } else {
     if (index == (pageList.size() - 1)) return;
     pageList.removeElementAt(index);
     pageList.insertElementAt(page, index + 1);
     tabbedPanel.removeTabAt(index);
     tabbedPanel.insertTab(
         page.isActive() ? page.getName() : page.getName() + " (D)",
         null,
         page.getComponent(),
         tooltip,
         index + 1);
   }
   tabbedPanel.setSelectedComponent(page.getComponent());
   changed = true;
 }
  /**
   * Creates an EditorView for the given entry. This function must be used while constructing the
   * views corresponding to the the object-model. The resulting EditorView is also added to the end
   * of mEditors
   */
  private View createEditorView(ValuesDelta entry) {
    final View view;
    final int layoutResId = EditorUiUtils.getLayoutResourceId(mKind.mimeType);
    try {
      view = mInflater.inflate(layoutResId, mEditors, false);
    } catch (Exception e) {
      throw new RuntimeException(
          "Cannot allocate editor with layout resource ID "
              + layoutResId
              + " for MIME type "
              + mKind.mimeType
              + " with error "
              + e.toString());
    }

    view.setEnabled(isEnabled());

    if (view instanceof Editor) {
      Editor editor = (Editor) view;
      editor.setDeletable(true);
      editor.setValues(mKind, entry, mState, mReadOnly, mViewIdGenerator);
      editor.setEditorListener(this);
    }
    mEditors.addView(view);
    return view;
  }
Exemplo n.º 11
0
  protected void encodeMarkup(FacesContext context, Editor editor) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    String clientId = editor.getClientId(context);
    String valueToRender = ComponentUtils.getValueToRender(context, editor);
    String inputId = clientId + "_input";

    String style = editor.getStyle();
    style = style == null ? "visibility:hidden" : "visibility:hidden;" + style;

    writer.startElement("div", editor);
    writer.writeAttribute("id", clientId, null);
    writer.writeAttribute("style", style, null);
    if (editor.getStyleClass() != null) {
      writer.writeAttribute("class", editor.getStyleClass(), null);
    }

    writer.startElement("textarea", null);
    writer.writeAttribute("id", inputId, null);
    writer.writeAttribute("name", inputId, null);

    if (valueToRender != null) {
      writer.write(valueToRender);
    }

    writer.endElement("textarea");

    writer.endElement("div");
  }
Exemplo n.º 12
0
  /** Add import statements to the current tab for the specified library */
  public void importLibrary(UserLibrary lib) throws IOException {
    // make sure the user didn't hide the sketch folder
    ensureExistence();

    List<String> list = lib.getIncludes();
    if (list == null) {
      File srcFolder = lib.getSrcFolder();
      String[] headers = Base.headerListFromIncludePath(srcFolder);
      list = Arrays.asList(headers);
    }
    if (list.isEmpty()) {
      return;
    }

    // import statements into the main sketch file (code[0])
    // if the current code is a .java file, insert into current
    // if (current.flavor == PDE) {
    SketchFile file = editor.getCurrentTab().getSketchFile();
    if (file.isExtension(Sketch.SKETCH_EXTENSIONS)) editor.selectTab(0);

    // could also scan the text in the file to see if each import
    // statement is already in there, but if the user has the import
    // commented out, then this will be a problem.
    StringBuilder buffer = new StringBuilder();
    for (String aList : list) {
      buffer.append("#include <");
      buffer.append(aList);
      buffer.append(">\n");
    }
    buffer.append('\n');
    buffer.append(editor.getCurrentTab().getText());
    editor.getCurrentTab().setText(buffer.toString());
    editor.getCurrentTab().setSelection(0, 0); // scroll to start
  }
 public void testSerializableToBlob() throws Exception {
   Book book = new Book();
   Editor editor = new Editor();
   editor.setName("O'Reilly");
   book.setEditor(editor);
   book.setCode2(new char[] {'r'});
   Session s;
   Transaction tx;
   s = openSession();
   tx = s.beginTransaction();
   s.persist(book);
   tx.commit();
   s.close();
   s = openSession();
   tx = s.beginTransaction();
   Book loadedBook = (Book) s.get(Book.class, book.getId());
   assertNotNull(loadedBook.getEditor());
   assertEquals(book.getEditor().getName(), loadedBook.getEditor().getName());
   loadedBook.setEditor(null);
   tx.commit();
   s.close();
   s = openSession();
   tx = s.beginTransaction();
   loadedBook = (Book) s.get(Book.class, book.getId());
   assertNull(loadedBook.getEditor());
   tx.commit();
   s.close();
 }
  /**
   * Validates that content of the editor as well as caret and selection matches one specified in
   * data file that should be formed with the same format as one used in configureByFile
   *
   * @param message - this check specific message. Added to text, caret position, selection
   *     checking. May be null
   * @param filePath - relative path from %IDEA_INSTALLATION_HOME%/testData/
   * @param ignoreTrailingSpaces - whether trailing spaces in editor in data file should be stripped
   *     prior to comparing.
   */
  protected void checkResultByFile(
      @Nullable String message,
      @TestDataFile @NotNull String filePath,
      final boolean ignoreTrailingSpaces) {
    bringRealEditorBack();

    getProject().getComponent(PostprocessReformattingAspect.class).doPostponedFormatting();
    if (ignoreTrailingSpaces) {
      final Editor editor = myEditor;
      TrailingSpacesStripper.stripIfNotCurrentLine(editor.getDocument(), false);
      EditorUtil.fillVirtualSpaceUntilCaret(editor);
    }

    PsiDocumentManager.getInstance(getProject()).commitAllDocuments();

    String fullPath = getTestDataPath() + filePath;

    File ioFile = new File(fullPath);

    assertTrue(getMessage("Cannot find file " + fullPath, message), ioFile.exists());
    String fileText = null;
    try {
      fileText = FileUtil.loadFile(ioFile, CharsetToolkit.UTF8_CHARSET);
    } catch (IOException e) {
      LOG.error(e);
    }
    checkResultByText(
        message,
        StringUtil.convertLineSeparators(fileText),
        ignoreTrailingSpaces,
        getTestDataPath() + "/" + filePath);
  }
  @NotNull
  private LookupImpl obtainLookup(Editor editor) {
    CompletionAssertions.checkEditorValid(editor);
    LookupImpl existing = (LookupImpl) LookupManager.getActiveLookup(editor);
    if (existing != null && existing.isCompletion()) {
      existing.markReused();
      if (!autopopup) {
        existing.setFocusDegree(LookupImpl.FocusDegree.FOCUSED);
      }
      return existing;
    }

    LookupImpl lookup =
        (LookupImpl)
            LookupManager.getInstance(editor.getProject())
                .createLookup(
                    editor, LookupElement.EMPTY_ARRAY, "", new LookupArranger.DefaultArranger());
    if (editor.isOneLineMode()) {
      lookup.setCancelOnClickOutside(true);
      lookup.setCancelOnOtherWindowOpen(true);
    }
    lookup.setFocusDegree(
        autopopup ? LookupImpl.FocusDegree.UNFOCUSED : LookupImpl.FocusDegree.FOCUSED);
    return lookup;
  }
Exemplo n.º 16
0
 /** Update an Editor type panel in Show Panels sub menu */
 public void updateEditorPanel(Editor panel) {
   if (panelsList.size() == 0) {
     return;
   }
   for (int i = 0; i < panelsList.size(); i++) {
     Object o = panelsList.get(i);
     if (o == panel) {
       JCheckBoxMenuItem r = (JCheckBoxMenuItem) panelsSubMenu.getItem(i);
       if (panel instanceof LayoutEditor) {
         if (panel.isVisible()) {
           r.setSelected(true);
         } else {
           r.setSelected(false);
         }
       } else {
         if (panel.getTargetFrame().isVisible()) {
           r.setSelected(true);
         } else {
           r.setSelected(false);
         }
       }
       return;
     }
   }
 }
Exemplo n.º 17
0
  @Override
  public boolean touchDragged(int screenX, int screenY, int pointer) {

    if (currently_pressed_object != null) {
      //	System.out.println ("touch draggeding object!");

      Vector2 modified_values = (get_screen_to_stage_coordinates(screenX, screenY));

      ////
      // compensate for movie_display_group_offset

      modified_values.sub(view.MOVIE_DISPLAY_GROUP_OFFSET);

      ////
      // compensate for click position offset, otherwise the dragging will always occur with the
      // cursor at the lower left of the oject

      if (click_offset != null) modified_values.sub(click_offset);

      currently_pressed_object.set_position(modified_values);
      currently_pressed_object.update_properties();

      //				editor.get_properties_editor ().update_rows ();
      editor.get_properties_editor().update_rows_data();

      editor.get_display_info_panel().update_currently_pressed_object(currently_pressed_object);
    }
    return false;
  }
Exemplo n.º 18
0
  private void removeFromEditor() {
    Editor editor = mySearchResults.getEditor();
    if (myReplacementBalloon != null) {
      myReplacementBalloon.hide();
    }

    if (editor != null) {

      for (VisibleAreaListener visibleAreaListener : myVisibleAreaListenersToRemove) {
        editor.getScrollingModel().removeVisibleAreaListener(visibleAreaListener);
      }
      myVisibleAreaListenersToRemove.clear();
      Project project = mySearchResults.getProject();
      if (project != null && !project.isDisposed()) {
        for (RangeHighlighter h : myHighlighters) {
          HighlightManager.getInstance(project).removeSegmentHighlighter(editor, h);
        }
        if (myCursorHighlighter != null) {
          HighlightManager.getInstance(project)
              .removeSegmentHighlighter(editor, myCursorHighlighter);
          myCursorHighlighter = null;
        }
      }
      myHighlighters.clear();
      if (myListeningSelection) {
        editor.getSelectionModel().removeSelectionListener(this);
        myListeningSelection = false;
      }
    }
  }
Exemplo n.º 19
0
 /** Delete a panel from Show Panel sub menu */
 public void deletePanel(Editor panel) {
   if (log.isDebugEnabled()) {
     log.debug("deletePanel");
   }
   if (panelsList.size() == 0) {
     return;
   }
   for (int i = 0; i < panelsList.size(); i++) {
     Object o = panelsList.get(i);
     if (o == panel) {
       // Editors that are their own TargetFrame dispose themselves
       if (!panel.equals(panel.getTargetFrame())) {
         panel.getTargetFrame().dispose();
       }
       panelsList.remove(panel);
       panelsSubMenu.remove(i);
       // If there are no panels on the list,
       // replace the 'No Panels' menu item
       if (panelsList.size() == 0) {
         panelsSubMenu.add(noPanelsItem);
       }
       return;
     }
   }
 }
  /**
   * Configures given editor to wrap at given width, assuming characters are of given width
   *
   * @return whether any actual wraps of editor contents were created as a result of turning on soft
   *     wraps
   */
  @TestOnly
  public static boolean configureSoftWraps(
      Editor editor, final int visibleWidth, final int charWidthInPixels) {
    editor.getSettings().setUseSoftWraps(true);
    SoftWrapModelImpl model = (SoftWrapModelImpl) editor.getSoftWrapModel();
    model.setSoftWrapPainter(
        new SoftWrapPainter() {
          @Override
          public int paint(
              @NotNull Graphics g,
              @NotNull SoftWrapDrawingType drawingType,
              int x,
              int y,
              int lineHeight) {
            return charWidthInPixels;
          }

          @Override
          public int getDrawingHorizontalOffset(
              @NotNull Graphics g,
              @NotNull SoftWrapDrawingType drawingType,
              int x,
              int y,
              int lineHeight) {
            return charWidthInPixels;
          }

          @Override
          public int getMinDrawingWidth(@NotNull SoftWrapDrawingType drawingType) {
            return charWidthInPixels;
          }

          @Override
          public boolean canUse() {
            return true;
          }

          @Override
          public void reinit() {}
        });
    model.reinitSettings();

    SoftWrapApplianceManager applianceManager = model.getApplianceManager();
    applianceManager.setWidthProvider(
        new SoftWrapApplianceManager.VisibleAreaWidthProvider() {
          @Override
          public int getVisibleAreaWidth() {
            return visibleWidth;
          }
        });
    model.setEditorTextRepresentationHelper(
        new DefaultEditorTextRepresentationHelper(editor) {
          @Override
          public int charWidth(char c, int fontType) {
            return charWidthInPixels;
          }
        });
    applianceManager.registerSoftWrapIfNecessary();
    return !model.getRegisteredSoftWraps().isEmpty();
  }
 /** Creates a new page of the given type with the given code */
 protected Editor createPage(String _type, String _name, String _code) {
   Editor page = new CodeEditor(ejs, this);
   page.setName(_name);
   if (_code != null) page.readString(_code);
   else page.clear();
   return page;
 }
Exemplo n.º 22
0
  private void altCommitToOriginal(@NotNull DocumentEvent e) {
    final PsiFile origPsiFile =
        PsiDocumentManager.getInstance(myProject).getPsiFile(myOrigDocument);
    String newText = myNewDocument.getText();
    // prepare guarded blocks
    LinkedHashMap<String, String> replacementMap = new LinkedHashMap<String, String>();
    int count = 0;
    for (RangeMarker o : ContainerUtil.reverse(((DocumentEx) myNewDocument).getGuardedBlocks())) {
      String replacement = o.getUserData(REPLACEMENT_KEY);
      String tempText = "REPLACE" + (count++) + Long.toHexString(StringHash.calc(replacement));
      newText =
          newText.substring(0, o.getStartOffset()) + tempText + newText.substring(o.getEndOffset());
      replacementMap.put(tempText, replacement);
    }
    // run preformat processors
    final int hostStartOffset = myAltFullRange.getStartOffset();
    myEditor.getCaretModel().moveToOffset(hostStartOffset);
    for (CopyPastePreProcessor preProcessor :
        Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
      newText = preProcessor.preprocessOnPaste(myProject, origPsiFile, myEditor, newText, null);
    }
    myOrigDocument.replaceString(hostStartOffset, myAltFullRange.getEndOffset(), newText);
    // replace temp strings for guarded blocks
    for (String tempText : replacementMap.keySet()) {
      int idx =
          CharArrayUtil.indexOf(
              myOrigDocument.getCharsSequence(),
              tempText,
              hostStartOffset,
              myAltFullRange.getEndOffset());
      myOrigDocument.replaceString(idx, idx + tempText.length(), replacementMap.get(tempText));
    }
    // JAVA: fix occasional char literal concatenation
    fixDocumentQuotes(myOrigDocument, hostStartOffset - 1);
    fixDocumentQuotes(myOrigDocument, myAltFullRange.getEndOffset());

    // reformat
    PsiDocumentManager.getInstance(myProject).commitDocument(myOrigDocument);
    Runnable task =
        () -> {
          try {
            CodeStyleManager.getInstance(myProject)
                .reformatRange(origPsiFile, hostStartOffset, myAltFullRange.getEndOffset(), true);
          } catch (IncorrectOperationException e1) {
            // LOG.error(e);
          }
        };
    DocumentUtil.executeInBulk(myOrigDocument, true, task);

    PsiElement newInjected =
        InjectedLanguageManager.getInstance(myProject)
            .findInjectedElementAt(origPsiFile, hostStartOffset);
    DocumentWindow documentWindow =
        newInjected == null ? null : InjectedLanguageUtil.getDocumentWindow(newInjected);
    if (documentWindow != null) {
      myEditor.getCaretModel().moveToOffset(documentWindow.injectedToHost(e.getOffset()));
      myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    }
  }
 private void releaseAllEditors() {
   for (final Editor editor : myEditors.values()) {
     if (!editor.isDisposed()) {
       EditorFactory.getInstance().releaseEditor(editor);
     }
   }
   myEditors.clear();
 }
 private static void zeroWidthBlockSelectionAtCaretColumn(
     final Editor editor, final int startLine, final int endLine) {
   int caretColumn = editor.getCaretModel().getLogicalPosition().column;
   editor
       .getSelectionModel()
       .setBlockSelection(
           new LogicalPosition(startLine, caretColumn), new LogicalPosition(endLine, caretColumn));
 }
  public void commentRange(
      int startOffset,
      int endOffset,
      String commentPrefix,
      String commentSuffix,
      Commenter commenter) {
    final CharSequence chars = myDocument.getCharsSequence();
    LogicalPosition caretPosition = myCaret.getLogicalPosition();

    if (startOffset == 0 || chars.charAt(startOffset - 1) == '\n') {
      if (endOffset == myDocument.getTextLength()
          || endOffset > 0 && chars.charAt(endOffset - 1) == '\n') {
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
        CommonCodeStyleSettings settings =
            CodeStyleSettingsManager.getSettings(myProject).getCommonSettings(myFile.getLanguage());
        String space;
        if (!settings.BLOCK_COMMENT_AT_FIRST_COLUMN) {
          final FileType fileType = myFile.getFileType();
          int line1 = myEditor.offsetToLogicalPosition(startOffset).line;
          int line2 = myEditor.offsetToLogicalPosition(endOffset - 1).line;
          Indent minIndent =
              CommentUtil.getMinLineIndent(myProject, myDocument, line1, line2, fileType);
          if (minIndent == null) {
            minIndent = codeStyleManager.zeroIndent();
          }
          space = codeStyleManager.fillIndent(minIndent, fileType);
        } else {
          space = "";
        }
        final StringBuilder nestingPrefix = new StringBuilder(space).append(commentPrefix);
        if (!commentPrefix.endsWith("\n")) {
          nestingPrefix.append("\n");
        }
        final StringBuilder nestingSuffix = new StringBuilder(space);
        nestingSuffix.append(
            commentSuffix.startsWith("\n") ? commentSuffix.substring(1) : commentSuffix);
        nestingSuffix.append("\n");
        TextRange range =
            insertNestedComments(
                startOffset,
                endOffset,
                nestingPrefix.toString(),
                nestingSuffix.toString(),
                commenter);
        myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
        LogicalPosition pos = new LogicalPosition(caretPosition.line + 1, caretPosition.column);
        myCaret.moveToLogicalPosition(pos);
        return;
      }
    }

    TextRange range =
        insertNestedComments(startOffset, endOffset, commentPrefix, commentSuffix, commenter);
    myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
    LogicalPosition pos =
        new LogicalPosition(caretPosition.line, caretPosition.column + commentPrefix.length());
    myCaret.moveToLogicalPosition(pos);
  }
Exemplo n.º 26
0
 public XMLEditableString create() throws InvalidOperationException {
   XMLEditableString editableString = new XMLEditableString(this.string.toString());
   Editor editor = editableString.getEditor();
   for (int[] tag : tags) {
     editor.setXMLTag(tag[0], tag[1]);
   }
   editor.commitChanges();
   return editableString;
 }
  private boolean navigateInRequestedEditor() {
    DataContext ctx = DataManager.getInstance().getDataContext();
    Editor e = NAVIGATE_IN_EDITOR.getData(ctx);
    if (e == null) return false;
    if (FileDocumentManager.getInstance().getFile(e.getDocument()) != myFile) return false;

    navigateIn(e);
    return true;
  }
Exemplo n.º 28
0
  /** Remove a piece of code from the sketch and from the disk. */
  public void handleDeleteCode() throws IOException {
    SketchFile current = editor.getCurrentTab().getSketchFile();
    editor.status.clearState();
    // make sure the user didn't hide the sketch folder
    ensureExistence();

    // if read-only, give an error
    if (isReadOnly(
        BaseNoGui.librariesIndexer.getInstalledLibraries(), BaseNoGui.getExamplesPath())) {
      // if the files are read-only, need to first do a "save as".
      Base.showMessage(
          tr("Sketch is Read-Only"),
          tr(
              "Some files are marked \"read-only\", so you'll\n"
                  + "need to re-save the sketch in another location,\n"
                  + "and try again."));
      return;
    }

    // confirm deletion with user, yes/no
    Object[] options = {tr("OK"), tr("Cancel")};
    String prompt =
        current.isPrimary()
            ? tr("Are you sure you want to delete this sketch?")
            : I18n.format(tr("Are you sure you want to delete \"{0}\"?"), current.getPrettyName());
    int result =
        JOptionPane.showOptionDialog(
            editor,
            prompt,
            tr("Delete"),
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[0]);
    if (result == JOptionPane.YES_OPTION) {
      if (current.isPrimary()) {
        sketch.delete();
        editor.base.handleClose(editor);
      } else {
        // delete the file
        if (!current.delete(sketch.getBuildPath().toPath())) {
          Base.showMessage(
              tr("Couldn't do it"),
              I18n.format(tr("Could not delete \"{0}\"."), current.getFileName()));
          return;
        }

        // just set current tab to the main tab
        editor.selectTab(0);

        // update the tabs
        editor.header.repaint();
      }
    }
  }
Exemplo n.º 29
0
 public void handlePress(Point p, Editor ed) {
   ed.liftEl(this, p);
   if (parent == null) {
     if (editor != null) {
       editor.remove(this);
     }
   } else {
     parent.remove(this);
   }
 }
 private void renameCurrentPage(String _name) {
   int index = tabbedPanel.getSelectedIndex();
   if (index < 0) return;
   _name = getUniqueName(_name); // Gonzalo 070128
   tabbedPanel.setTitleAt(index, _name);
   Editor page = pageList.get(index);
   page.setName(_name);
   if (!page.isActive()) tabbedPanel.setTitleAt(index, page.getName() + " (D)");
   changed = true;
 }