/**
   * Read the available profiles from the internal XML file and return them as collection.
   *
   * @return returns a list of <code>CustomProfile</code> or <code>null</code>
   */
  private List<Profile> readOldForCompatibility(IScopeContext instanceScope) {

    // in 3.0 M9 and less the profiles were stored in a file in the plugin's meta data
    final String STORE_FILE = "code_formatter_profiles.xml"; // $NON-NLS-1$

    File file = JavaPlugin.getDefault().getStateLocation().append(STORE_FILE).toFile();
    if (!file.exists()) return null;

    try {
      // note that it's wrong to use a file reader when XML declares UTF-8: Kept for compatibility
      final FileReader reader = new FileReader(file);
      try {
        List<Profile> res = readProfilesFromStream(new InputSource(reader));
        if (res != null) {
          for (int i = 0; i < res.size(); i++) {
            fProfileVersioner.update((CustomProfile) res.get(i));
          }
          writeProfiles(res, instanceScope);
        }
        file.delete(); // remove after successful write
        return res;
      } finally {
        reader.close();
      }
    } catch (CoreException e) {
      JavaPlugin.log(e); // log but ignore
    } catch (IOException e) {
      JavaPlugin.log(e); // log but ignore
    }
    return null;
  }
  public static void checkCurrentOptionsVersion() {
    PreferencesAccess access = PreferencesAccess.getOriginalPreferences();
    ProfileVersioner profileVersioner = new ProfileVersioner();

    IScopeContext instanceScope = access.getInstanceScope();
    IEclipsePreferences uiPreferences = instanceScope.getNode(JavaUI.ID_PLUGIN);
    int version = uiPreferences.getInt(PREF_FORMATTER_PROFILES + VERSION_KEY_SUFFIX, 0);
    if (version >= profileVersioner.getCurrentVersion()) {
      return; // is up to date
    }
    try {
      List<Profile> profiles =
          (new FormatterProfileStore(profileVersioner)).readProfiles(instanceScope);
      if (profiles == null) {
        profiles = new ArrayList<Profile>();
      }
      ProfileManager manager =
          new FormatterProfileManager(profiles, instanceScope, access, profileVersioner);
      if (manager.getSelected() instanceof CustomProfile) {
        manager.commitChanges(instanceScope); // updates JavaCore options
      }
      uiPreferences.putInt(
          PREF_FORMATTER_PROFILES + VERSION_KEY_SUFFIX, profileVersioner.getCurrentVersion());
      savePreferences(instanceScope);
    } catch (CoreException e) {
      JavaPlugin.log(e);
    } catch (BackingStoreException e) {
      JavaPlugin.log(e);
    }
  }
  private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) {
    if (c.offset == -1 || d.getLength() == 0) return;

    try {
      int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);
      int line = d.getLineOfOffset(p);
      int start = d.getLineOffset(line);
      int whiteend = findEndOfWhiteSpace(d, start, c.offset);

      JavaHeuristicScanner scanner = new JavaHeuristicScanner(d);
      JavaIndenter indenter = new JavaIndenter(d, scanner, fProject);

      // shift only when line does not contain any text up to the closing bracket
      if (whiteend == c.offset) {
        // evaluate the line with the opening bracket that matches out closing bracket
        int reference = indenter.findReferencePosition(c.offset, false, true, false, false);
        int indLine = d.getLineOfOffset(reference);
        if (indLine != -1 && indLine != line) {
          // take the indent of the found line
          StringBuffer replaceText = new StringBuffer(getIndentOfLine(d, indLine));
          // add the rest of the current line including the just added close bracket
          replaceText.append(d.get(whiteend, c.offset - whiteend));
          replaceText.append(c.text);
          // modify document command
          c.length += c.offset - start;
          c.offset = start;
          c.text = replaceText.toString();
        }
      }
    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }
  }
Esempio n. 4
0
  private void runOnMultiple(final ICompilationUnit[] cus) {
    ICleanUp[] cleanUps = getCleanUps(cus);
    if (cleanUps == null) return;

    MultiStatus status =
        new MultiStatus(
            JavaUI.ID_PLUGIN, IStatus.OK, ActionMessages.CleanUpAction_MultiStateErrorTitle, null);
    for (int i = 0; i < cus.length; i++) {
      ICompilationUnit cu = cus[i];

      if (!ActionUtil.isOnBuildPath(cu)) {
        String cuLocation = BasicElementLabels.getPathLabel(cu.getPath(), false);
        String message =
            Messages.format(ActionMessages.CleanUpAction_CUNotOnBuildpathMessage, cuLocation);
        status.add(new Status(IStatus.INFO, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null));
      }
    }
    if (!status.isOK()) {
      ErrorDialog.openError(getShell(), getActionName(), null, status);
      return;
    }

    try {
      performRefactoring(cus, cleanUps);
    } catch (InvocationTargetException e) {
      JavaPlugin.log(e);
      if (e.getCause() instanceof CoreException) showUnexpectedError((CoreException) e.getCause());
    }
  }
 private static String encode(String str) {
   try {
     return URLEncoder.encode(str, fgDefaultEncoding);
   } catch (UnsupportedEncodingException e) {
     JavaPlugin.log(e);
   }
   return ""; //$NON-NLS-1$
 }
 /*
  * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.IStructuredSelection)
  */
 @Override
 public void selectionChanged(IStructuredSelection selection) {
   try {
     setEnabled(canEnable(selection));
   } catch (JavaModelException exception) {
     if (JavaModelUtil.isExceptionToBeLogged(exception)) JavaPlugin.log(exception);
     setEnabled(false);
   }
 }
Esempio n. 7
0
 private void xmlReadRefactoring(JarPackageData jarPackage, Element element)
     throws java.io.IOException {
   if (element.getNodeName().equals("storedRefactorings")) { // $NON-NLS-1$
     jarPackage.setExportStructuralOnly(
         getBooleanAttribute(
             element, "structuralOnly", jarPackage.isExportStructuralOnly())); // $NON-NLS-1$
     jarPackage.setDeprecationAware(
         getBooleanAttribute(
             element, "deprecationInfo", jarPackage.isDeprecationAware())); // $NON-NLS-1$
     List<IAdaptable> elements = new ArrayList<IAdaptable>();
     int count = 1;
     String value = element.getAttribute("project" + count); // $NON-NLS-1$
     while (value != null && !"".equals(value)) { // $NON-NLS-1$
       final IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(value);
       if (project.exists()) elements.add(project);
       count++;
       value = element.getAttribute("project" + count); // $NON-NLS-1$
     }
     jarPackage.setRefactoringProjects(elements.toArray(new IProject[elements.size()]));
     elements.clear();
     count = 1;
     IRefactoringHistoryService service = RefactoringCore.getHistoryService();
     try {
       service.connect();
       value = element.getAttribute("refactoring" + count); // $NON-NLS-1$
       while (value != null && !"".equals(value)) { // $NON-NLS-1$
         final ByteArrayInputStream stream =
             new ByteArrayInputStream(value.getBytes("UTF-8")); // $NON-NLS-1$
         try {
           final RefactoringHistory history =
               service.readRefactoringHistory(stream, RefactoringDescriptor.NONE);
           if (history != null) {
             final RefactoringDescriptorProxy[] descriptors = history.getDescriptors();
             if (descriptors.length > 0) {
               for (int index = 0; index < descriptors.length; index++) {
                 elements.add(descriptors[index]);
               }
             }
           }
         } catch (CoreException exception) {
           JavaPlugin.log(exception);
         }
         count++;
         value = element.getAttribute("refactoring" + count); // $NON-NLS-1$
       }
     } finally {
       service.disconnect();
     }
     jarPackage.setRefactoringDescriptors(
         elements.toArray(new RefactoringDescriptorProxy[elements.size()]));
   }
 }
 public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encoded) {
   StringTokenizer tok = new StringTokenizer(encoded, " "); // $NON-NLS-1$
   ArrayList<IClasspathEntry> res = new ArrayList<IClasspathEntry>();
   while (tok.hasMoreTokens()) {
     try {
       tok.nextToken(); // desc: ignore
       int kind = Integer.parseInt(tok.nextToken());
       IPath path = decodePath(tok.nextToken());
       IPath attachPath = decodePath(tok.nextToken());
       IPath attachRoot = decodePath(tok.nextToken());
       boolean isExported = Boolean.valueOf(tok.nextToken()).booleanValue();
       switch (kind) {
         case IClasspathEntry.CPE_SOURCE:
           res.add(JavaCore.newSourceEntry(path));
           break;
         case IClasspathEntry.CPE_LIBRARY:
           res.add(JavaCore.newLibraryEntry(path, attachPath, attachRoot, isExported));
           break;
         case IClasspathEntry.CPE_VARIABLE:
           res.add(JavaCore.newVariableEntry(path, attachPath, attachRoot, isExported));
           break;
         case IClasspathEntry.CPE_PROJECT:
           res.add(JavaCore.newProjectEntry(path, isExported));
           break;
         case IClasspathEntry.CPE_CONTAINER:
           res.add(JavaCore.newContainerEntry(path, isExported));
           break;
       }
     } catch (NumberFormatException e) {
       String message = PreferencesMessages.NewJavaProjectPreferencePage_error_decode;
       JavaPlugin.log(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, message, e));
     } catch (NoSuchElementException e) {
       String message = PreferencesMessages.NewJavaProjectPreferencePage_error_decode;
       JavaPlugin.log(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, message, e));
     }
   }
   return res.toArray(new IClasspathEntry[res.size()]);
 }
Esempio n. 9
0
 private void collectCompilationUnits(Object element, Collection<IJavaElement> result) {
   try {
     if (element instanceof IJavaElement) {
       IJavaElement elem = (IJavaElement) element;
       if (elem.exists()) {
         switch (elem.getElementType()) {
           case IJavaElement.TYPE:
             if (elem.getParent().getElementType() == IJavaElement.COMPILATION_UNIT) {
               result.add(elem.getParent());
             }
             break;
           case IJavaElement.COMPILATION_UNIT:
             result.add(elem);
             break;
           case IJavaElement.IMPORT_CONTAINER:
             result.add(elem.getParent());
             break;
           case IJavaElement.PACKAGE_FRAGMENT:
             collectCompilationUnits((IPackageFragment) elem, result);
             break;
           case IJavaElement.PACKAGE_FRAGMENT_ROOT:
             collectCompilationUnits((IPackageFragmentRoot) elem, result);
             break;
           case IJavaElement.JAVA_PROJECT:
             IPackageFragmentRoot[] roots = ((IJavaProject) elem).getPackageFragmentRoots();
             for (int k = 0; k < roots.length; k++) {
               collectCompilationUnits(roots[k], result);
             }
             break;
         }
       }
     } else if (element instanceof LogicalPackage) {
       IPackageFragment[] packageFragments = ((LogicalPackage) element).getFragments();
       for (int k = 0; k < packageFragments.length; k++) {
         IPackageFragment pack = packageFragments[k];
         if (pack.exists()) {
           collectCompilationUnits(pack, result);
         }
       }
     } else if (element instanceof IWorkingSet) {
       IWorkingSet workingSet = (IWorkingSet) element;
       IAdaptable[] elements = workingSet.getElements();
       for (int j = 0; j < elements.length; j++) {
         collectCompilationUnits(elements[j], result);
       }
     }
   } catch (JavaModelException e) {
     if (JavaModelUtil.isExceptionToBeLogged(e)) JavaPlugin.log(e);
   }
 }
Esempio n. 10
0
  private void run(ICompilationUnit cu) {
    if (!ActionUtil.isEditable(fEditor, getShell(), cu)) return;

    ICleanUp[] cleanUps = getCleanUps(new ICompilationUnit[] {cu});
    if (cleanUps == null) return;

    if (!ElementValidator.check(cu, getShell(), getActionName(), fEditor != null)) return;

    try {
      performRefactoring(new ICompilationUnit[] {cu}, cleanUps);
    } catch (InvocationTargetException e) {
      JavaPlugin.log(e);
      if (e.getCause() instanceof CoreException) showUnexpectedError((CoreException) e.getCause());
    }
  }
Esempio n. 11
0
  /**
   * Remembers the selection of a right hand side type (proposal type) for a certain left hand side
   * (expected type) in content assist.
   *
   * @param lhs the left hand side / expected type
   * @param rhs the selected right hand side
   */
  public void remember(IType lhs, IType rhs) {
    Assert.isLegal(lhs != null);
    Assert.isLegal(rhs != null);

    try {
      if (!isCacheableRHS(rhs)) return;
      ITypeHierarchy hierarchy = rhs.newSupertypeHierarchy(getProgressMonitor());
      if (hierarchy.contains(lhs)) {
        // TODO remember for every member of the LHS hierarchy or not? Yes for now.
        IType[] allLHSides = hierarchy.getAllSupertypes(lhs);
        String rhsQualifiedName = rhs.getFullyQualifiedName();
        for (int i = 0; i < allLHSides.length; i++)
          rememberInternal(allLHSides[i], rhsQualifiedName);
        rememberInternal(lhs, rhsQualifiedName);
      }
    } catch (JavaModelException x) {
      JavaPlugin.log(x);
    }
  }
  private static IAction[] getTemplateActions(JavaEditor editor) {
    ITextSelection textSelection = getTextSelection(editor);
    if (textSelection == null || textSelection.getLength() == 0) return null;

    ICompilationUnit cu = JavaUI.getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
    if (cu == null) return null;

    QuickTemplateProcessor quickTemplateProcessor = new QuickTemplateProcessor();
    IInvocationContext context =
        new AssistContext(cu, textSelection.getOffset(), textSelection.getLength());

    try {
      IJavaCompletionProposal[] proposals = quickTemplateProcessor.getAssists(context, null);
      if (proposals == null || proposals.length == 0) return null;

      return getActionsFromProposals(proposals, context.getSelectionOffset(), editor.getViewer());
    } catch (CoreException e) {
      JavaPlugin.log(e);
    }
    return null;
  }
Esempio n. 13
0
 private boolean isEnabled(IStructuredSelection selection) {
   Object[] selected = selection.toArray();
   for (int i = 0; i < selected.length; i++) {
     try {
       if (selected[i] instanceof IJavaElement) {
         IJavaElement elem = (IJavaElement) selected[i];
         if (elem.exists()) {
           switch (elem.getElementType()) {
             case IJavaElement.TYPE:
               return elem.getParent().getElementType()
                   == IJavaElement.COMPILATION_UNIT; // for browsing perspective
             case IJavaElement.COMPILATION_UNIT:
               return true;
             case IJavaElement.IMPORT_CONTAINER:
               return true;
             case IJavaElement.PACKAGE_FRAGMENT:
             case IJavaElement.PACKAGE_FRAGMENT_ROOT:
               IPackageFragmentRoot root =
                   (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
               return (root.getKind() == IPackageFragmentRoot.K_SOURCE);
             case IJavaElement.JAVA_PROJECT:
               // https://bugs.eclipse.org/bugs/show_bug.cgi?id=65638
               return true;
           }
         }
       } else if (selected[i] instanceof LogicalPackage) {
         return true;
       } else if (selected[i] instanceof IWorkingSet) {
         IWorkingSet workingSet = (IWorkingSet) selected[i];
         return IWorkingSetIDs.JAVA.equals(workingSet.getId());
       }
     } catch (JavaModelException e) {
       if (!e.isDoesNotExist()) {
         JavaPlugin.log(e);
       }
     }
   }
   return false;
 }
Esempio n. 14
0
  private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) {
    if (c.offset < 1 || d.getLength() == 0) return;

    JavaHeuristicScanner scanner = new JavaHeuristicScanner(d);

    int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);

    try {
      // current line
      int line = d.getLineOfOffset(p);
      int lineOffset = d.getLineOffset(line);

      // make sure we don't have any leading comments etc.
      if (d.get(lineOffset, p - lineOffset).trim().length() != 0) return;

      // line of last Java code
      int pos = scanner.findNonWhitespaceBackward(p, JavaHeuristicScanner.UNBOUND);
      if (pos == -1) return;
      int lastLine = d.getLineOfOffset(pos);

      // only shift if the last java line is further up and is a braceless block candidate
      if (lastLine < line) {

        JavaIndenter indenter = new JavaIndenter(d, scanner, fProject);
        StringBuffer indent = indenter.computeIndentation(p, true);
        String toDelete = d.get(lineOffset, c.offset - lineOffset);
        if (indent != null && !indent.toString().equals(toDelete)) {
          c.text = indent.append(c.text).toString();
          c.length += c.offset - lineOffset;
          c.offset = lineOffset;
        }
      }

    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }
  }
Esempio n. 15
0
  private static CompilationUnitInfo getCompilationUnitForMethod(IDocument document, int offset) {
    try {
      JavaHeuristicScanner scanner = new JavaHeuristicScanner(document);

      IRegion sourceRange = scanner.findSurroundingBlock(offset);
      if (sourceRange == null) return null;
      String source = document.get(sourceRange.getOffset(), sourceRange.getLength());

      StringBuffer contents = new StringBuffer();
      contents.append("class ____C{void ____m()"); // $NON-NLS-1$
      final int methodOffset = contents.length();
      contents.append(source);
      contents.append('}');

      char[] buffer = contents.toString().toCharArray();

      return new CompilationUnitInfo(buffer, sourceRange.getOffset() - methodOffset);

    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }

    return null;
  }
 /**
  * Finds the start position in the property file. We assume that the key is the first match on a
  * line.
  *
  * @param propertyName the property name
  * @return the start position of the property name in the file, -1 if not found
  */
 private int findPropertyNameStartPosition(String propertyName) {
   // Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19319
   InputStream stream = null;
   LineReader lineReader = null;
   String encoding;
   try {
     encoding = fPropertiesFile.getCharset();
   } catch (CoreException e1) {
     encoding = "ISO-8859-1"; // $NON-NLS-1$
   }
   try {
     stream = createInputStream(fPropertiesFile);
     lineReader = new LineReader(stream, encoding);
   } catch (CoreException cex) {
     // failed to get input stream
     JavaPlugin.log(cex);
     return -1;
   } catch (IOException e) {
     if (stream != null) {
       try {
         stream.close();
       } catch (IOException ce) {
         JavaPlugin.log(ce);
       }
     }
     return -1;
   }
   int start = 0;
   try {
     StringBuffer buf = new StringBuffer(80);
     int eols = lineReader.readLine(buf);
     int keyLength = propertyName.length();
     while (eols > 0) {
       String line = buf.toString();
       int i = line.indexOf(propertyName);
       int charPos = i + keyLength;
       char terminatorChar = 0;
       boolean hasNoValue = (charPos >= line.length());
       if (i > -1 && !hasNoValue) terminatorChar = line.charAt(charPos);
       if (line.trim().startsWith(propertyName)
           && (hasNoValue || Character.isWhitespace(terminatorChar) || terminatorChar == '=')) {
         start += line.indexOf(propertyName);
         eols = -17; // found key
       } else {
         start += line.length() + eols;
         buf.setLength(0);
         eols = lineReader.readLine(buf);
       }
     }
     if (eols != -17)
       start =
           -1; // key not found in file. See bug 63794. This can happen if the key contains escaped
               // characters.
   } catch (IOException ex) {
     JavaPlugin.log(ex);
     return -1;
   } finally {
     try {
       lineReader.close();
     } catch (IOException ex) {
       JavaPlugin.log(ex);
     }
   }
   return start;
 }
Esempio n. 17
0
  private void smartIndentUponE(IDocument d, DocumentCommand c) {
    if (c.offset < 4 || d.getLength() == 0) return;

    try {
      String content = d.get(c.offset - 3, 3);
      if (content.equals("els")) { // $NON-NLS-1$
        JavaHeuristicScanner scanner = new JavaHeuristicScanner(d);
        int p = c.offset - 3;

        // current line
        int line = d.getLineOfOffset(p);
        int lineOffset = d.getLineOffset(line);

        // make sure we don't have any leading comments etc.
        if (d.get(lineOffset, p - lineOffset).trim().length() != 0) return;

        // line of last Java code
        int pos = scanner.findNonWhitespaceBackward(p - 1, JavaHeuristicScanner.UNBOUND);
        if (pos == -1) return;
        int lastLine = d.getLineOfOffset(pos);

        // only shift if the last java line is further up and is a braceless block candidate
        if (lastLine < line) {

          JavaIndenter indenter = new JavaIndenter(d, scanner, fProject);
          int ref = indenter.findReferencePosition(p, true, false, false, false);
          if (ref == JavaHeuristicScanner.NOT_FOUND) return;
          int refLine = d.getLineOfOffset(ref);
          String indent = getIndentOfLine(d, refLine);

          if (indent != null) {
            c.text = indent.toString() + "else"; // $NON-NLS-1$
            c.length += c.offset - lineOffset;
            c.offset = lineOffset;
          }
        }

        return;
      }

      if (content.equals("cas")) { // $NON-NLS-1$
        JavaHeuristicScanner scanner = new JavaHeuristicScanner(d);
        int p = c.offset - 3;

        // current line
        int line = d.getLineOfOffset(p);
        int lineOffset = d.getLineOffset(line);

        // make sure we don't have any leading comments etc.
        if (d.get(lineOffset, p - lineOffset).trim().length() != 0) return;

        // line of last Java code
        int pos = scanner.findNonWhitespaceBackward(p - 1, JavaHeuristicScanner.UNBOUND);
        if (pos == -1) return;
        int lastLine = d.getLineOfOffset(pos);

        // only shift if the last java line is further up and is a braceless block candidate
        if (lastLine < line) {

          JavaIndenter indenter = new JavaIndenter(d, scanner, fProject);
          int ref = indenter.findReferencePosition(p, false, false, false, true);
          if (ref == JavaHeuristicScanner.NOT_FOUND) return;
          int refLine = d.getLineOfOffset(ref);
          int nextToken = scanner.nextToken(ref, JavaHeuristicScanner.UNBOUND);
          String indent;
          if (nextToken == Symbols.TokenCASE || nextToken == Symbols.TokenDEFAULT)
            indent = getIndentOfLine(d, refLine);
          else // at the brace of the switch
          indent = indenter.computeIndentation(p).toString();

          if (indent != null) {
            c.text = indent.toString() + "case"; // $NON-NLS-1$
            c.length += c.offset - lineOffset;
            c.offset = lineOffset;
          }
        }

        return;
      }

    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }
  }
Esempio n. 18
0
  private void smartIndentAfterNewLine(IDocument d, DocumentCommand c) {
    JavaHeuristicScanner scanner = new JavaHeuristicScanner(d);
    JavaIndenter indenter = new JavaIndenter(d, scanner, fProject);
    StringBuffer indent = indenter.computeIndentation(c.offset);
    if (indent == null) indent = new StringBuffer();

    int docLength = d.getLength();
    if (c.offset == -1 || docLength == 0) return;

    try {
      int p = (c.offset == docLength ? c.offset - 1 : c.offset);
      int line = d.getLineOfOffset(p);

      StringBuffer buf = new StringBuffer(c.text + indent);

      IRegion reg = d.getLineInformation(line);
      int lineEnd = reg.getOffset() + reg.getLength();

      int contentStart = findEndOfWhiteSpace(d, c.offset, lineEnd);
      c.length = Math.max(contentStart - c.offset, 0);

      int start = reg.getOffset();
      ITypedRegion region = TextUtilities.getPartition(d, fPartitioning, start, true);
      if (IJavaPartitions.JAVA_DOC.equals(region.getType()))
        start = d.getLineInformationOfOffset(region.getOffset()).getOffset();

      // insert closing brace on new line after an unclosed opening brace
      if (getBracketCount(d, start, c.offset, true) > 0
          && closeBrace()
          && !isClosed(d, c.offset, c.length)) {
        c.caretOffset = c.offset + buf.length();
        c.shiftsCaret = false;

        // copy old content of line behind insertion point to new line
        // unless we think we are inserting an anonymous type definition

        if (c.offset == 0
            || computeAnonymousPosition(d, c.offset - 1, fPartitioning, lineEnd) == -1) {
          if (lineEnd - contentStart > 0) {
            c.length = lineEnd - c.offset;
            buf.append(d.get(contentStart, lineEnd - contentStart).toCharArray());
          }
        }

        buf.append(TextUtilities.getDefaultLineDelimiter(d));
        StringBuffer reference = null;
        int nonWS = findEndOfWhiteSpace(d, start, lineEnd);
        if (nonWS < c.offset && d.getChar(nonWS) == '{')
          reference = new StringBuffer(d.get(start, nonWS - start));
        else reference = indenter.getReferenceIndentation(c.offset);
        if (reference != null) buf.append(reference);
        buf.append('}');
      }
      // insert extra line upon new line between two braces
      else if (c.offset > start && contentStart < lineEnd && d.getChar(contentStart) == '}') {
        int firstCharPos = scanner.findNonWhitespaceBackward(c.offset - 1, start);
        if (firstCharPos != JavaHeuristicScanner.NOT_FOUND && d.getChar(firstCharPos) == '{') {
          c.caretOffset = c.offset + buf.length();
          c.shiftsCaret = false;

          StringBuffer reference = null;
          int nonWS = findEndOfWhiteSpace(d, start, lineEnd);
          if (nonWS < c.offset && d.getChar(nonWS) == '{')
            reference = new StringBuffer(d.get(start, nonWS - start));
          else reference = indenter.getReferenceIndentation(c.offset);

          buf.append(TextUtilities.getDefaultLineDelimiter(d));

          if (reference != null) buf.append(reference);
        }
      }
      c.text = buf.toString();

    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }
  }
Esempio n. 19
0
  private void smartPaste(IDocument document, DocumentCommand command) {
    int newOffset = command.offset;
    int newLength = command.length;
    String newText = command.text;

    try {
      JavaHeuristicScanner scanner = new JavaHeuristicScanner(document);
      JavaIndenter indenter = new JavaIndenter(document, scanner, fProject);
      int offset = newOffset;

      // reference position to get the indent from
      int refOffset = indenter.findReferencePosition(offset);
      if (refOffset == JavaHeuristicScanner.NOT_FOUND) return;
      int peerOffset = getPeerPosition(document, command);
      peerOffset = indenter.findReferencePosition(peerOffset);
      if (peerOffset != JavaHeuristicScanner.NOT_FOUND) refOffset = Math.min(refOffset, peerOffset);

      // eat any WS before the insertion to the beginning of the line
      int firstLine =
          1; // don't format the first line per default, as it has other content before it
      IRegion line = document.getLineInformationOfOffset(offset);
      String notSelected = document.get(line.getOffset(), offset - line.getOffset());
      if (notSelected.trim().length() == 0) {
        newLength += notSelected.length();
        newOffset = line.getOffset();
        firstLine = 0;
      }

      // prefix: the part we need for formatting but won't paste
      IRegion refLine = document.getLineInformationOfOffset(refOffset);
      String prefix = document.get(refLine.getOffset(), newOffset - refLine.getOffset());

      // handle the indentation computation inside a temporary document
      Document temp = new Document(prefix + newText);
      DocumentRewriteSession session =
          temp.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
      scanner = new JavaHeuristicScanner(temp);
      indenter = new JavaIndenter(temp, scanner, fProject);
      installJavaStuff(temp);

      // indent the first and second line
      // compute the relative indentation difference from the second line
      // (as the first might be partially selected) and use the value to
      // indent all other lines.
      boolean isIndentDetected = false;
      StringBuffer addition = new StringBuffer();
      int insertLength = 0;
      int firstLineInsertLength = 0;
      int firstLineIndent = 0;
      int first = document.computeNumberOfLines(prefix) + firstLine; // don't format first line
      int lines = temp.getNumberOfLines();
      int tabLength = getVisualTabLengthPreference();
      boolean changed = false;
      for (int l = first;
          l < lines;
          l++) { // we don't change the number of lines while adding indents

        IRegion r = temp.getLineInformation(l);
        int lineOffset = r.getOffset();
        int lineLength = r.getLength();

        if (lineLength == 0) // don't modify empty lines
        continue;

        if (!isIndentDetected) {

          // indent the first pasted line
          String current = getCurrentIndent(temp, l);
          StringBuffer correct = indenter.computeIndentation(lineOffset);
          if (correct == null) return; // bail out

          insertLength = subtractIndent(correct, current, addition, tabLength);
          if (l == first) {
            firstLineInsertLength = insertLength;
            firstLineIndent = current.length();
          }
          if (l != first && temp.get(lineOffset, lineLength).trim().length() != 0) {
            isIndentDetected = true;
            if (firstLineIndent >= current.length()) insertLength = firstLineInsertLength;
            if (insertLength == 0) {
              // no adjustment needed, bail out
              if (firstLine == 0) {
                // but we still need to adjust the first line
                command.offset = newOffset;
                command.length = newLength;
                if (changed) break; // still need to get the leading indent of the first line
              }
              return;
            }
          } else {
            changed = insertLength != 0;
          }
        }

        // relatively indent all pasted lines
        if (insertLength > 0) addIndent(temp, l, addition, tabLength);
        else if (insertLength < 0) cutIndent(temp, l, -insertLength, tabLength);
      }

      removeJavaStuff(temp);
      temp.stopRewriteSession(session);
      newText = temp.get(prefix.length(), temp.getLength() - prefix.length());

      command.offset = newOffset;
      command.length = newLength;
      command.text = newText;

    } catch (BadLocationException e) {
      JavaPlugin.log(e);
    }
  }