Ejemplo n.º 1
0
  /**
   * Generates initial content for a new R script file.
   *
   * @param su the R source unit to create the source for. The unit does not need to exist
   * @param lineDelimiter the line delimiter to be used
   * @return the new content or <code>null</code> if the template is undefined or empty
   * @throws CoreException thrown when the evaluation of the code template fails
   */
  public static EvaluatedTemplate getNewRFileContent(
      final RResourceUnit su, final String lineDelimiter) throws CoreException {
    final Template template =
        RUIPlugin.getDefault()
            .getRCodeGenerationTemplateStore()
            .findTemplate(RCodeTemplatesContextType.NEW_RSCRIPTFILE);
    if (template == null) {
      return null;
    }

    final RCodeTemplatesContext context =
        new RCodeTemplatesContext(
            RCodeTemplatesContextType.NEW_RSCRIPTFILE_CONTEXTTYPE, su, lineDelimiter);

    try {
      final TemplateBuffer buffer = context.evaluate(template);
      if (buffer == null) {
        return null;
      }
      return new TemplatesUtil.EvaluatedTemplate(buffer, lineDelimiter);
    } catch (final Exception e) {
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              RUI.PLUGIN_ID,
              NLS.bind(
                  TemplateMessages.TemplateEvaluation_error_description, template.getDescription()),
              e));
    }
  }
Ejemplo n.º 2
0
  /**
   * Computes the relevance to match the relevance values generated by the core content assistant.
   *
   * @return a sensible relevance value.
   */
  private int computeRelevance() {
    // see org.eclipse.jdt.internal.codeassist.RelevanceConstants
    final int R_DEFAULT = 0;
    final int R_INTERESTING = 5;
    final int R_CASE = 10;
    final int R_NON_RESTRICTED = 3;
    final int R_EXACT_NAME = 4;
    final int R_INLINE_TAG = 31;

    int base = R_DEFAULT + R_INTERESTING + R_NON_RESTRICTED;

    try {
      if (fContext instanceof DocumentTemplateContext) {
        DocumentTemplateContext templateContext = (DocumentTemplateContext) fContext;
        IDocument document = templateContext.getDocument();

        String content = document.get(fRegion.getOffset(), fRegion.getLength());
        if (content.length() > 0 && fTemplate.getName().startsWith(content)) base += R_CASE;
        if (fTemplate.getName().equalsIgnoreCase(content)) base += R_EXACT_NAME;
        if (fContext instanceof JavaDocContext) base += R_INLINE_TAG;
      }
    } catch (BadLocationException e) {
      // ignore - not a case sensitive match then
    }

    // see CompletionProposalCollector.computeRelevance
    // just under keywords, but better than packages
    final int TEMPLATE_RELEVANCE = 1;
    return base * 16 + TEMPLATE_RELEVANCE;
  }
Ejemplo n.º 3
0
  /**
   * Inspects the context of the compilation unit around <code>completionPosition</code> and feeds
   * the collector with proposals.
   *
   * @param viewer the text viewer
   * @param completionPosition the context position in the document of the text viewer
   * @param compilationUnit the compilation unit (may be <code>null</code>)
   */
  public void complete(ITextViewer viewer, int completionPosition, IRubyScript compilationUnit) {
    IDocument document = viewer.getDocument();

    if (!(fContextType instanceof RubyScriptContextType)) return;

    Point selection = viewer.getSelectedRange();

    // remember selected text
    String selectedText = null;
    if (selection.y != 0) {
      try {
        selectedText = document.get(selection.x, selection.y);
      } catch (BadLocationException e) {
      }
    }

    RubyScriptContext context =
        ((RubyScriptContextType) fContextType)
            .createContext(document, completionPosition, selection.y, compilationUnit);
    context.setVariable("selection", selectedText); // $NON-NLS-1$
    int start = context.getStart();
    int end = context.getEnd();
    IRegion region = new Region(start, end - start);

    Template[] templates = RubyPlugin.getDefault().getTemplateStore().getTemplates();

    if (selection.y == 0) {
      for (int i = 0; i != templates.length; i++)
        if (context.canEvaluate(templates[i]))
          fProposals.add(
              new TemplateProposal(
                  templates[i],
                  context,
                  region,
                  RubyPluginImages.get(RubyPluginImages.IMG_OBJS_TEMPLATE)));

    } else {

      if (context.getKey().length() == 0) context.setForceEvaluation(true);

      boolean multipleLinesSelected = areMultipleLinesSelected(viewer);

      for (int i = 0; i != templates.length; i++) {
        Template template = templates[i];
        if (context.canEvaluate(template)
            && template.getContextTypeId().equals(context.getContextType().getId())
            && (!multipleLinesSelected && template.getPattern().indexOf($_WORD_SELECTION) != -1
                || (multipleLinesSelected
                    && template.getPattern().indexOf($_LINE_SELECTION) != -1))) {
          fProposals.add(
              new TemplateProposal(
                  templates[i],
                  context,
                  region,
                  RubyPluginImages.get(RubyPluginImages.IMG_OBJS_TEMPLATE)));
        }
      }
    }
  }
 public CodeClipDialog(
     Shell parentShell, Shell contextShell, TemplatePersistenceData templatePersistenceData) {
   super(parentShell);
   this.contextShell = contextShell;
   this.templatePersistenceData = templatePersistenceData;
   Template template = templatePersistenceData.getTemplate();
   abbrev = template.getName();
   description = template.getDescription();
   expansion = template.getPattern();
   contentType = template.getContextTypeId();
   setHelpAvailable(false);
 }
  private boolean hasCompatibleContextType(Template template) {
    String key = getKey();
    if (template.matches(key, getContextType().getId())) return true;

    if (fCompatibleContextTypeIds == null) return false;

    Iterator<String> iter = fCompatibleContextTypeIds.iterator();
    while (iter.hasNext()) {
      if (template.matches(key, iter.next())) return true;
    }

    return false;
  }
Ejemplo n.º 6
0
  /*
   * @see org.eclipse.ui.texteditor.templates.TemplatePreferencePage#updateViewerInput()
   */
  protected void updateViewerInput() {
    IStructuredSelection selection = (IStructuredSelection) getTableViewer().getSelection();
    SourceViewer viewer = getViewer();

    if (selection.size() == 1 && selection.getFirstElement() instanceof TemplatePersistenceData) {
      TemplatePersistenceData data = (TemplatePersistenceData) selection.getFirstElement();
      Template template = data.getTemplate();
      viewer.getDocument().set(template.getPattern());

    } else {
      viewer.getDocument().set("");
    }
  }
Ejemplo n.º 7
0
 /*
  * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension6#getStyledDisplayString()
  * @since 3.4
  */
 @Override
 public StyledString getStyledDisplayString() {
   if (fDisplayString == null) {
     String[] arguments = new String[] {fTemplate.getName(), fTemplate.getDescription()};
     String decorated =
         Messages.format(TemplateContentAssistMessages.TemplateProposal_displayString, arguments);
     StyledString string = new StyledString(fTemplate.getName(), StyledString.COUNTER_STYLER);
     fDisplayString =
         StyledCellLabelProvider.styleDecoratedString(
             decorated, StyledString.QUALIFIER_STYLER, string);
   }
   return fDisplayString;
 }
Ejemplo n.º 8
0
 private Template indentTemplatePattern(final Template template, final boolean indentFrom0) {
   String pattern = template.getPattern();
   final String whiteSpacePrefix = indentFrom0 ? "" : getWhiteSpacePrefix();
   try {
     pattern = IndentAction.indentLines(0, 0, pattern, true, whiteSpacePrefix);
   } catch (final RpcException e) {
     ErlLogger.error(e);
   }
   return new Template(
       template.getName(),
       template.getDescription(),
       template.getContextTypeId(),
       pattern,
       template.isAutoInsertable());
 }
  /**
   * Evaluates a 'java' template in the context of a compilation unit
   *
   * @param template the template to be evaluated
   * @param compilationUnit the compilation unit in which to evaluate the template
   * @param position the position inside the compilation unit for which to evaluate the template
   * @return the evaluated template
   * @throws CoreException in case the template is of an unknown context type
   * @throws BadLocationException in case the position is invalid in the compilation unit
   * @throws TemplateException in case the evaluation fails
   */
  public static String evaluateTemplate(
      Template template, ICompilationUnit compilationUnit, int position)
      throws CoreException, BadLocationException, TemplateException {

    TemplateContextType contextType =
        JavaPlugin.getDefault()
            .getTemplateContextRegistry()
            .getContextType(template.getContextTypeId());
    if (!(contextType instanceof CompilationUnitContextType))
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              JavaUI.ID_PLUGIN,
              IStatus.ERROR,
              JavaTemplateMessages.JavaContext_error_message,
              null));

    IDocument document = new Document();
    if (compilationUnit != null && compilationUnit.exists())
      document.set(compilationUnit.getSource());

    CompilationUnitContext context =
        ((CompilationUnitContextType) contextType)
            .createContext(document, position, 0, compilationUnit);
    context.setForceEvaluation(true);

    TemplateBuffer buffer = context.evaluate(template);
    if (buffer == null) return null;
    return buffer.getString();
  }
  /*
   * @see TemplateContext#canEvaluate(Template templates)
   */
  @Override
  public boolean canEvaluate(Template template) {
    if (!hasCompatibleContextType(template)) return false;

    if (fForceEvaluation) return true;

    String key = getKey();
    return (key.length() > 0 || !isAfterDot())
        && template.getName().toLowerCase().startsWith(key.toLowerCase());
  }
 private int getRelevance(Template template, int lineOffset, String prefix) {
   boolean blockTemplate = templates == null ? false : templates.isBlock(template);
   if (blockTemplate) {
     if (template.getName().startsWith(prefix)) {
       return lineOffset == 0 ? 95 : 75;
     }
     return lineOffset == 0 ? 85 : 0;
   }
   return super.getRelevance(template, prefix);
 }
 private boolean isSelectionBasedMatch(Template template, TemplateContext context) {
   String pattern = template.getPattern();
   Set<String> vars = new HashSet<>();
   Matcher matcher = VARIABLE_PATTERN.matcher(pattern);
   while (matcher.find()) {
     String variableName = matcher.group(1);
     if (vars.add(variableName)) {
       String variable = context.getVariable(variableName);
       if (variable != null && variable.length() > 0) {
         return true;
       }
     }
   }
   return false;
 }
Ejemplo n.º 13
0
 @NotNull
 private ICompletionProposal[] makeTemplateProposals(
     ITextViewer viewer, int documentOffset, String wordPart) {
   wordPart = wordPart.toLowerCase();
   final List<SQLTemplateCompletionProposal> templateProposals = new ArrayList<>();
   // Templates
   for (Template template : editor.getTemplatesPage().getTemplateStore().getTemplates()) {
     if (template.getName().toLowerCase().startsWith(wordPart)) {
       templateProposals.add(
           new SQLTemplateCompletionProposal(
               template,
               new SQLContext(
                   SQLTemplatesRegistry.getInstance()
                       .getTemplateContextRegistry()
                       .getContextType(template.getContextTypeId()),
                   viewer.getDocument(),
                   new Position(wordDetector.getStartOffset(), wordDetector.getLength()),
                   editor),
               new Region(documentOffset, 0),
               null));
     }
   }
   return templateProposals.toArray(new ICompletionProposal[templateProposals.size()]);
 }
Ejemplo n.º 14
0
 /*
  * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent)
  */
 @Override
 public boolean validate(IDocument document, int offset, DocumentEvent event) {
   try {
     int replaceOffset = getReplaceOffset();
     if (offset >= replaceOffset) {
       String content = document.get(replaceOffset, offset - replaceOffset);
       String templateName = fTemplate.getName().toLowerCase();
       boolean valid = templateName.startsWith(content.toLowerCase());
       if (!valid
           && fContext instanceof JavaDocContext
           && templateName.startsWith("<")) { // $NON-NLS-1$
         valid = templateName.startsWith(content.toLowerCase(), 1);
       }
       return valid;
     }
   } catch (BadLocationException e) {
     // concurrent modification - ignore
   }
   return false;
 }
Ejemplo n.º 15
0
  /** @param template */
  protected void drop(Template template, int dropCaretOffset, int length) {
    IDocument document = editor.getTextEditor().getTextViewer().getDocument();
    ContextTypeRegistry registry = XMLUIPlugin.getDefault().getTemplateContextRegistry();
    if (registry != null) {
      TemplateContextType type = registry.getContextType(template.getContextTypeId());

      DocumentTemplateContext templateContext =
          new DocumentTemplateContext(type, document, new Position(dropCaretOffset, length));
      if (templateContext.canEvaluate(template)) {
        try {
          TemplateBuffer templateBuffer = templateContext.evaluate(template);
          String templateString = templateBuffer.getString();
          document.replace(dropCaretOffset, length, templateString);

          StyledText styledText = editor.getTextWidget();
          int position = getCursorOffset(templateBuffer) + dropCaretOffset;
          styledText.setCaretOffset(position);
          styledText.setFocus();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    }
  }
Ejemplo n.º 16
0
 /*
  * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getReplacementString()
  */
 @Override
 public CharSequence getPrefixCompletionText(IDocument document, int completionOffset) {
   // bug 114360 - don't make selection templates prefix-completable
   if (isSelectionTemplate()) return ""; // $NON-NLS-1$
   return fTemplate.getName();
 }
Ejemplo n.º 17
0
  /**
   * Generates content for the Roxygen comment for the given class definition
   *
   * @param rClass class element
   * @param lineDelimiter the line delimiter to be used
   * @return
   * @throws CoreException thrown when the evaluation of the code template fails
   */
  public static EvaluatedTemplate getClassRoxygenComment(
      final IRClass rClass, final String lineDelimiter) throws CoreException {
    final Template template =
        RUIPlugin.getDefault()
            .getRCodeGenerationTemplateStore()
            .findTemplate(RCodeTemplatesContextType.ROXYGEN_S4CLASS_TEMPLATE);
    if (template == null) {
      return null;
    }

    final ISourceUnit su = rClass.getSourceUnit();
    final RCodeTemplatesContext context =
        new RCodeTemplatesContext(
            RCodeTemplatesContextType.ROXYGEN_CLASS_CONTEXTTYPE, su, lineDelimiter);
    context.setRElement(rClass);

    try {
      final TemplateBuffer buffer = context.evaluate(template);
      if (buffer == null) {
        return null;
      }
      final EvaluatedTemplate data = new EvaluatedTemplate(buffer, lineDelimiter);

      final AbstractDocument content = data.startPostEdit();
      final StringBuilder tagBuffer = new StringBuilder(64);
      final TemplateVariable slotVariable =
          TemplatesUtil.findVariable(buffer, RCodeTemplatesContextType.ROXYGEN_SLOT_TAGS_VARIABLE);
      final Position[] slotPositions =
          new Position[(slotVariable != null) ? slotVariable.getOffsets().length : 0];
      for (int i = 0; i < slotPositions.length; i++) {
        slotPositions[i] = new Position(slotVariable.getOffsets()[i], slotVariable.getLength());
        content.addPosition(slotPositions[i]);
      }

      if (slotPositions.length > 0) {
        String[] tags = null;
        final List<? extends IModelElement> slots =
            rClass.getModelChildren(IRElement.R_S4SLOT_FILTER);
        final int count = slots.size();
        tags = new String[count];
        for (int i = 0; i < count; i++) {
          final IRSlot slot = (IRSlot) slots.get(i);
          tagBuffer.append("@slot "); // $NON-NLS-1$
          tagBuffer.append(slot.getElementName().getDisplayName());
          tagBuffer.append(" "); // $NON-NLS-1$
          tags[i] = tagBuffer.toString();
          tagBuffer.setLength(0);
        }
        for (final Position pos : slotPositions) {
          insertRoxygen(content, pos, tags);
        }
      }

      data.finishPostEdit();
      return data;
    } catch (final Exception e) {
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              RUI.PLUGIN_ID,
              NLS.bind(
                  TemplateMessages.TemplateEvaluation_error_description, template.getDescription()),
              e));
    }
  }
  /**
   * Saves the templates as XML.
   *
   * @param templates the templates to save
   * @param result the stream result to write to
   * @throws IOException if writing the templates fails
   */
  private void save(TemplatePersistenceData[] templates, StreamResult result) throws IOException {
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document document = builder.newDocument();

      Node root = document.createElement(TEMPLATE_ROOT);
      document.appendChild(root);

      for (int i = 0; i < templates.length; i++) {
        TemplatePersistenceData data = templates[i];
        Template template = data.getTemplate();

        Node node = document.createElement(TEMPLATE_ELEMENT);
        root.appendChild(node);

        NamedNodeMap attributes = node.getAttributes();

        String id = data.getId();
        if (id != null) {
          Attr idAttr = document.createAttribute(ID_ATTRIBUTE);
          idAttr.setValue(id);
          attributes.setNamedItem(idAttr);
        }

        if (template != null) {
          Attr name = document.createAttribute(NAME_ATTRIBUTE);
          name.setValue(template.getName());
          attributes.setNamedItem(name);
        }

        if (template != null) {
          Attr proposalDesc = document.createAttribute(PROPOSAL_POPUP_DESCRIPTION);
          if (template instanceof SQLTemplate) {
            proposalDesc.setValue(((SQLTemplate) template).getProposalPopupDescription());
          }
          attributes.setNamedItem(proposalDesc);
        }

        if (template != null) {
          Attr description = document.createAttribute(DESCRIPTION_ATTRIBUTE);
          description.setValue(template.getDescription());
          attributes.setNamedItem(description);
        }

        if (template != null) {
          Attr context = document.createAttribute(CONTEXT_ATTRIBUTE);
          context.setValue(template.getContextTypeId());
          attributes.setNamedItem(context);
        }

        Attr enabled = document.createAttribute(ENABLED_ATTRIBUTE);
        enabled.setValue(data.isEnabled() ? Boolean.toString(true) : Boolean.toString(false));
        attributes.setNamedItem(enabled);

        Attr deleted = document.createAttribute(DELETED_ATTRIBUTE);
        deleted.setValue(data.isDeleted() ? Boolean.toString(true) : Boolean.toString(false));
        attributes.setNamedItem(deleted);

        if (template != null) {
          Attr autoInsertable = document.createAttribute(AUTO_INSERTABLE_ATTRIBUTE);
          autoInsertable.setValue(
              template.isAutoInsertable() ? Boolean.toString(true) : Boolean.toString(false));
          attributes.setNamedItem(autoInsertable);
        }

        if (template != null) {
          Text pattern = document.createTextNode(template.getPattern());
          node.appendChild(pattern);
        }
      }

      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // $NON-NLS-1$
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // $NON-NLS-1$
      DOMSource source = new DOMSource(document);

      transformer.transform(source, result);

    } catch (ParserConfigurationException e) {
      Assert.isTrue(false);
    } catch (TransformerException e) {
      if (e.getException() instanceof IOException) throw (IOException) e.getException();
      Assert.isTrue(false);
    }
  }
Ejemplo n.º 19
0
 /*
  * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension4#isAutoInsertable()
  */
 @Override
 public boolean isAutoInsertable() {
   if (isSelectionTemplate()) return false;
   return fTemplate.isAutoInsertable();
 }
  /** Override to improve matching accuracy */
  @Override
  public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {

    ITextSelection selection = (ITextSelection) viewer.getSelectionProvider().getSelection();

    // adjust offset to end of normalized selection
    if (selection.getOffset() == offset) {
      offset = selection.getOffset() + selection.getLength();
    }

    String prefix = extractPrefix(viewer, offset);
    Region region = new Region(offset - prefix.length(), prefix.length());
    TemplateContext context = createContext(viewer, region);
    if (context == null) {
      return new ICompletionProposal[0];
    }
    Region selectionRegion = new Region(selection.getOffset(), selection.getLength());
    TemplateContext selectionContext = createContext(viewer, selectionRegion);

    int lineOffset = 0;
    try {
      IRegion lineInformationOfOffset = viewer.getDocument().getLineInformationOfOffset(offset);
      lineOffset = offset - lineInformationOfOffset.getOffset();
    } catch (BadLocationException e1) {
      // ignore
    }

    String selectionText = selection.getText();
    context.setVariable("selection", selectionText); // $NON-NLS-1$
    selectionContext.setVariable("selection", selectionText); // $NON-NLS-1$
    context.setVariable("text", selectionText); // $NON-NLS-1$
    selectionContext.setVariable("text", selectionText); // $NON-NLS-1$

    Template[] templates = getTemplates(context.getContextType().getId());

    List<ICompletionProposal> matches = new ArrayList<>(templates.length);
    for (Template template : templates) {
      try {
        context.getContextType().validate(template.getPattern());
      } catch (TemplateException e) {
        continue;
      }
      if (!template.matches(prefix, context.getContextType().getId())) {
        continue;
      }
      boolean selectionBasedMatch = isSelectionBasedMatch(template, context);
      if (template.getName().startsWith(prefix) || selectionBasedMatch) {

        int relevance = getRelevance(template, lineOffset, prefix);
        if (selectionBasedMatch) {
          matches.add(
              createProposal(template, selectionContext, (IRegion) selectionRegion, relevance));
        } else {
          matches.add(createProposal(template, context, (IRegion) region, relevance));
        }
      }
    }

    Collections.sort(matches, proposalComparator);

    return matches.toArray(new ICompletionProposal[matches.size()]);
  }
Ejemplo n.º 21
0
 @Override
 public boolean canEvaluate(final Template template) {
   final String key = getKey();
   return key.length() != 0 && template.getName().toLowerCase().startsWith(key.toLowerCase());
 }
Ejemplo n.º 22
0
  /**
   * Generates content for the Roxygen comment for the given function definition
   *
   * @param rMethod function element
   * @param lineDelimiter the line delimiter to be used
   * @return
   * @throws CoreException thrown when the evaluation of the code template fails
   */
  public static EvaluatedTemplate getCommonFunctionRoxygenComment(
      final IRMethod rMethod, final String lineDelimiter) throws CoreException {
    final Template template =
        RUIPlugin.getDefault()
            .getRCodeGenerationTemplateStore()
            .findTemplate(RCodeTemplatesContextType.ROXYGEN_COMMONFUNCTION_TEMPLATE);
    if (template == null) {
      return null;
    }

    final ISourceUnit su = rMethod.getSourceUnit();
    final RCodeTemplatesContext context =
        new RCodeTemplatesContext(
            RCodeTemplatesContextType.ROXYGEN_COMMONFUNCTION_CONTEXTTYPE, su, lineDelimiter);
    context.setRElement(rMethod);

    try {
      final TemplateBuffer buffer = context.evaluate(template);
      if (buffer == null) {
        return null;
      }
      final EvaluatedTemplate data = new EvaluatedTemplate(buffer, lineDelimiter);

      final AbstractDocument content = data.startPostEdit();
      final StringBuilder tagBuffer = new StringBuilder(64);
      final TemplateVariable paramVariable =
          TemplatesUtil.findVariable(buffer, RCodeTemplatesContextType.ROXYGEN_PARAM_TAGS_VARIABLE);
      final Position[] paramPositions =
          new Position[(paramVariable != null) ? paramVariable.getOffsets().length : 0];
      for (int i = 0; i < paramPositions.length; i++) {
        paramPositions[i] = new Position(paramVariable.getOffsets()[i], paramVariable.getLength());
        content.addPosition(paramPositions[i]);
      }

      if (paramPositions.length > 0) {
        String[] tags = null;
        final ArgsDefinition args = rMethod.getArgsDefinition();
        if (args != null) {
          final int count = args.size();
          tags = new String[count];
          for (int i = 0; i < count; i++) {
            tagBuffer.append("@param "); // $NON-NLS-1$
            tagBuffer.append(args.get(i).name);
            tagBuffer.append(" "); // $NON-NLS-1$
            tags[i] = tagBuffer.toString();
            tagBuffer.setLength(0);
          }
        }
        for (final Position pos : paramPositions) {
          insertRoxygen(content, pos, tags);
        }
      }

      data.finishPostEdit();
      return data;
    } catch (final Exception e) {
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              RUI.PLUGIN_ID,
              NLS.bind(
                  TemplateMessages.TemplateEvaluation_error_description, template.getDescription()),
              e));
    }
  }
Ejemplo n.º 23
0
  /**
   * Generates content for the Roxygen comment for the given method definition
   *
   * @param rMethod function element
   * @param lineDelimiter the line delimiter to be used
   * @return
   * @throws CoreException thrown when the evaluation of the code template fails
   */
  public static EvaluatedTemplate getMethodRoxygenComment(
      final IRMethod rMethod, final String lineDelimiter) throws CoreException {
    final Template template =
        RUIPlugin.getDefault()
            .getRCodeGenerationTemplateStore()
            .findTemplate(RCodeTemplatesContextType.ROXYGEN_S4METHOD_TEMPLATE);
    if (template == null) {
      return null;
    }

    final ISourceUnit su = rMethod.getSourceUnit();
    final RCodeTemplatesContext context =
        new RCodeTemplatesContext(
            RCodeTemplatesContextType.ROXYGEN_METHOD_CONTEXTTYPE, su, lineDelimiter);
    context.setRElement(rMethod);

    try {
      final TemplateBuffer buffer = context.evaluate(template);
      if (buffer == null) {
        return null;
      }
      final EvaluatedTemplate data = new EvaluatedTemplate(buffer, lineDelimiter);

      final AbstractDocument content = data.startPostEdit();
      final StringBuilder sb = new StringBuilder(64);

      final Position[] sigPositions;
      String sigText = null;
      {
        final TemplateVariable variable =
            TemplatesUtil.findVariable(buffer, RCodeTemplatesContextType.ROXYGEN_SIG_LIST_VARIABLE);
        sigPositions = new Position[(variable != null) ? variable.getOffsets().length : 0];
        for (int i = 0; i < sigPositions.length; i++) {
          sigPositions[i] = new Position(variable.getOffsets()[i], variable.getLength());
          content.addPosition(sigPositions[i]);
        }

        if (sigPositions.length > 0) {
          final ArgsDefinition args = rMethod.getArgsDefinition();
          if (args != null) {
            final int count = args.size();
            for (int i = 0; i < count; i++) {
              final Arg arg = args.get(i);
              if (arg.className == null || arg.className.equals("ANY")) { // $NON-NLS-1$
                break;
              }
              sb.append(arg.className);
              sb.append(","); // $NON-NLS-1$
            }
            if (sb.length() > 0) {
              sigText = sb.substring(0, sb.length() - 1);
              sb.setLength(0);
            }
          }
        }
      }
      final Position[] paramPositions;
      String[] paramTags = null;
      {
        final TemplateVariable variable =
            TemplatesUtil.findVariable(
                buffer, RCodeTemplatesContextType.ROXYGEN_PARAM_TAGS_VARIABLE);
        paramPositions = new Position[(variable != null) ? variable.getOffsets().length : 0];
        for (int i = 0; i < paramPositions.length; i++) {
          paramPositions[i] = new Position(variable.getOffsets()[i], variable.getLength());
          content.addPosition(paramPositions[i]);
        }

        if (paramPositions.length > 0) {
          String list = null;
          final ArgsDefinition args = rMethod.getArgsDefinition();
          if (args != null) {
            final int count = args.size();
            paramTags = new String[count];
            for (int i = 0; i < count; i++) {
              sb.append("@param "); // $NON-NLS-1$
              sb.append(args.get(i).name);
              sb.append(" "); // $NON-NLS-1$
              paramTags[i] = sb.toString();
              sb.setLength(0);
            }
          }
        }
      }

      if (sigPositions != null) {
        for (final Position pos : sigPositions) {
          insertRoxygen(content, pos, sigText);
        }
      }
      if (paramPositions != null) {
        for (final Position pos : paramPositions) {
          insertRoxygen(content, pos, paramTags);
        }
      }

      data.finishPostEdit();
      return data;
    } catch (final Exception e) {
      throw new CoreException(
          new Status(
              IStatus.ERROR,
              RUI.PLUGIN_ID,
              NLS.bind(
                  TemplateMessages.TemplateEvaluation_error_description, template.getDescription()),
              e));
    }
  }
Ejemplo n.º 24
0
  /**
   * Inspects the context of the compilation unit around <code>completionPosition</code> and feeds
   * the collector with proposals.
   *
   * @param viewer the text viewer
   * @param completionPosition the context position in the document of the text viewer
   * @param translationUnit the translation unit (may be <code>null</code>)
   */
  public void complete(
      ITextViewer viewer, int completionPosition, ITranslationUnit translationUnit) {
    if (!(fContextType instanceof TranslationUnitContextType)) return;

    IDocument document = viewer.getDocument();
    Point selection = viewer.getSelectedRange();
    boolean linesSelected = areLinesSelected(viewer);
    boolean showLineSelectionTemplates = linesSelected;
    boolean showWordSelectionTemplates = !linesSelected || isOnlyWordOnLine(viewer);
    if (linesSelected) {
      // adjust line selection to start at column 1 and end at line delimiter
      try {
        IRegion startLine = document.getLineInformationOfOffset(selection.x);
        IRegion endLine = document.getLineInformationOfOffset(selection.x + selection.y - 1);
        completionPosition = selection.x = startLine.getOffset();
        selection.y = endLine.getOffset() + endLine.getLength() - startLine.getOffset();
      } catch (BadLocationException exc) {
      }
    }
    Position position = new Position(completionPosition, selection.y);

    // remember selected text
    String selectedText = null;
    if (selection.y != 0) {
      try {
        selectedText = document.get(selection.x, selection.y);
        document.addPosition(position);
        fPositions.put(document, position);
      } catch (BadLocationException e) {
      }
    }

    TranslationUnitContext context =
        ((TranslationUnitContextType) fContextType)
            .createContext(document, position, translationUnit);
    context.setVariable("selection", selectedText); // $NON-NLS-1$
    int start = context.getStart();
    int end = context.getEnd();
    IRegion region = new Region(start, end - start);

    Template[] templates = CUIPlugin.getDefault().getTemplateStore().getTemplates();

    Image image = CDTSharedImages.getImage(CDTSharedImages.IMG_OBJS_TEMPLATE);
    if (selection.y == 0) {
      for (int i = 0; i != templates.length; i++)
        if (context.canEvaluate(templates[i]))
          fProposals.add(new CTemplateProposal(templates[i], context, region, image));

    } else {

      if (linesSelected || context.getKey().length() == 0) context.setForceEvaluation(true);

      for (int i = 0; i != templates.length; i++) {
        Template template = templates[i];
        if (context.canEvaluate(template)
            && template.getContextTypeId().equals(context.getContextType().getId())
            && ((showWordSelectionTemplates && template.getPattern().indexOf($_WORD_SELECTION) != -1
                || (showLineSelectionTemplates
                    && template.getPattern().indexOf($_LINE_SELECTION) != -1)))) {
          fProposals.add(new CTemplateProposal(templates[i], context, region, image));
        }
      }
    }
  }