@Override
 public void run(Result result, SchedulerEvent event) {
   try {
     ALGParserResult sjResult = (ALGParserResult) result;
     List<ParseException> syntaxErrors = sjResult.getJavaParser().syntaxErrors;
     Document document = result.getSnapshot().getSource().getDocument(false);
     List<ErrorDescription> errors = new ArrayList<ErrorDescription>();
     for (ParseException syntaxError : syntaxErrors) {
       Token token = syntaxError.currentToken;
       int start =
           NbDocument.findLineOffset((StyledDocument) document, token.beginLine - 1)
               + token.beginColumn
               - 1;
       int end =
           NbDocument.findLineOffset((StyledDocument) document, token.endLine - 1)
               + token.endColumn;
       ErrorDescription errorDescription =
           ErrorDescriptionFactory.createErrorDescription(
               Severity.ERROR,
               syntaxError.getMessage(),
               document,
               document.createPosition(start),
               document.createPosition(end));
       errors.add(errorDescription);
     }
     HintsController.setErrors(document, "simple-java", errors);
   } catch (BadLocationException ex1) {
     Exceptions.printStackTrace(ex1);
   } catch (org.netbeans.modules.parsing.spi.ParseException ex1) {
     Exceptions.printStackTrace(ex1);
   }
 }
  private static String getIdentifier(StyledDocument doc, JEditorPane ep, int offset) {
    String t = null;
    if ((ep.getSelectionStart() <= offset) && (offset <= ep.getSelectionEnd()))
      t = ep.getSelectedText();
    if (t != null) return t;

    int line = NbDocument.findLineNumber(doc, offset);
    int col = NbDocument.findLineColumn(doc, offset);
    try {
      Element lineElem = NbDocument.findLineRootElement(doc).getElement(line);

      if (lineElem == null) return null;
      int lineStartOffset = lineElem.getStartOffset();
      int lineLen = lineElem.getEndOffset() - lineStartOffset;
      t = doc.getText(lineStartOffset, lineLen);
      int identStart = col;
      while (identStart > 0
          && (Character.isJavaIdentifierPart(t.charAt(identStart - 1))
              || (t.charAt(identStart - 1) == '.'))) {
        identStart--;
      }
      int identEnd = col;
      while (identEnd < lineLen && Character.isJavaIdentifierPart(t.charAt(identEnd))) {
        identEnd++;
      }

      if (identStart == identEnd) return null;
      return t.substring(identStart, identEnd);
    } catch (BadLocationException e) {
      return null;
    }
  }
 @Override
 public void actionPerformed(ActionEvent ev) {
   JEditorPane pane = NbDocument.findRecentEditorPane(context);
   if (null != pane) {
     doLineOperation(pane);
   }
 }
 /** *** Annotation Stuff ******* */
 static void processAnnotations(
     NbEditorDocument doc,
     List<PPLine> lineList) { // XXX needs to be split for errors and warnings
   final ArrayList<ErrorDescription> errs = new ArrayList();
   DataObject dob = NbEditorUtilities.getDataObject(doc);
   FileObject fo = dob == null ? null : dob.getPrimaryFile();
   for (PPLine line : lineList) {
     for (PPLine.Error err : line.getErrors()) {
       PPToken tok = err.token;
       int shift =
           (tok.getType() == LineParserTokens.END_OF_FILE
                   || tok.getType() == LineParserTokens.END_OF_LINE
                   || tok.getType() == LineParserTokens.OTHER_TEXT)
               ? Math.max(1, tok.getPadding().length())
               : 0;
       int loff = NbDocument.findLineOffset(doc, line.getLineNumber() - 1);
       errs.add(
           ErrorDescriptionFactory.createErrorDescription(
               err.warning ? Severity.WARNING : Severity.ERROR,
               err.message,
               fo,
               loff + tok.getColumn() - shift,
               loff + tok.getColumn() + tok.getText().length()));
     }
     ArrayList<Fix> fixes = new ArrayList();
     int start = Utilities.getRowStartFromLineOffset(doc, line.getLineNumber() - 1);
     if (line.getTokens().size() > 1
         && "//#include".equals(line.getTokens().get(0).getText())) { // NOI18N
       fixes.add(
           new InlineIncludeHint(
               (NbEditorDocument) doc, start, line.getTokens().get(1).getText()));
     } else if (line.getType() == PPLine.OLDIF || line.getType() == PPLine.OLDENDIF) {
       PPBlockInfo b = line.getBlock();
       while (b != null && b.getType() != PPLine.OLDIF) {
         b = b.getParent();
       }
       if (b != null) fixes.add(new ReplaceOldSyntaxHint(doc, lineList, b));
     }
     if (line.getType() == PPLine.UNKNOWN)
       fixes.add(new DisableHint((NbEditorDocument) doc, start));
     if (fixes.size() > 0)
       errs.add(
           ErrorDescriptionFactory.createErrorDescription(
               Severity.HINT,
               NbBundle.getMessage(DocumentPreprocessor.class, "LBL_PreprocessorHint"),
               fixes,
               doc,
               line.getLineNumber())); // NOI18N
   }
   HintsController.setErrors(doc, "preprocessor-errors", errs); // NOI18N
 }
  /**
   * Locates AnnotateLine associated with given line. The line is translated to Element that is used
   * as map lookup key. The map is initially filled up with Elements sampled on annotate() method.
   *
   * <p>Key trick is that Element's identity is maintained until line removal (and is restored on
   * undo).
   *
   * @param line
   * @return found AnnotateLine or <code>null</code>
   */
  private AnnotateLine getAnnotateLine(int line) {
    StyledDocument sd = (StyledDocument) doc;
    int lineOffset = NbDocument.findLineOffset(sd, line);
    Element element = sd.getParagraphElement(lineOffset);
    AnnotateLine al = elementAnnotations.get(element);

    if (al != null) {
      int startOffset = element.getStartOffset();
      int endOffset = element.getEndOffset();
      try {
        int len = endOffset - startOffset;
        String text = doc.getText(startOffset, len - 1);
        String content = al.getContent();
        if (text.equals(content)) {
          return al;
        }
      } catch (BadLocationException e) {
        Mercurial.LOG.log(Level.INFO, "HG.AB: can not locate line annotation."); // NOI18N
      }
    }

    return null;
  }
 public void run() {
   if (lp == null || ec == null) return;
   StyledDocument doc;
   try {
     doc = ec.openDocument();
   } catch (IOException ex) {
     return;
   }
   JEditorPane ep = EditorContextDispatcher.getDefault().getCurrentEditor();
   if (ep == null) return;
   int offset;
   String expression =
       getIdentifier(
           doc,
           ep,
           offset = NbDocument.findLineOffset(doc, lp.getLine().getLineNumber()) + lp.getColumn());
   if (expression == null) return;
   DebuggerEngine currentEngine = DebuggerManager.getDebuggerManager().getCurrentEngine();
   if (currentEngine == null) return;
   JPDADebugger d = currentEngine.lookupFirst(null, JPDADebugger.class);
   if (d == null) return;
   JPDAThread t = d.getCurrentThread();
   if (t == null || !t.isSuspended()) return;
   String toolTipText = null;
   try {
     Variable v = null;
     List<Operation> operations = t.getLastOperations();
     if (operations != null) {
       for (Operation operation : operations) {
         if (!expression.endsWith(operation.getMethodName())) {
           continue;
         }
         if (operation.getMethodStartPosition().getOffset() <= offset
             && offset <= operation.getMethodEndPosition().getOffset()) {
           v = operation.getReturnValue();
         }
       }
     }
     if (v == null) {
       v = d.evaluate(expression);
     }
     String type = v.getType();
     if (v instanceof ObjectVariable)
       try {
         String toString = null;
         try {
           java.lang.reflect.Method toStringMethod =
               v.getClass()
                   .getMethod(
                       "getToStringValue", // NOI18N
                       new Class[] {Integer.TYPE});
           toStringMethod.setAccessible(true);
           toString = (String) toStringMethod.invoke(v, TO_STRING_LENGTH_LIMIT);
         } catch (Exception ex) {
           ex.printStackTrace();
         }
         if (toString == null) {
           toString = ((ObjectVariable) v).getToStringValue();
         }
         toolTipText =
             expression + " = " + (type.length() == 0 ? "" : "(" + type + ") ") + toString;
       } catch (InvalidExpressionException ex) {
         toolTipText =
             expression + " = " + (type.length() == 0 ? "" : "(" + type + ") ") + v.getValue();
       }
     else
       toolTipText =
           expression + " = " + (type.length() == 0 ? "" : "(" + type + ") ") + v.getValue();
   } catch (InvalidExpressionException e) {
     toolTipText = expression + " = >" + e.getMessage() + "<";
   }
   firePropertyChange(PROP_SHORT_DESCRIPTION, null, toolTipText);
 }
  // latestAnnotationTask business logic
  @Override
  public void run() {
    // get resource bundle
    ResourceBundle loc = NbBundle.getBundle(AnnotationBar.class);
    // give status bar "wait" indication // NOI18N
    StatusBar statusBar = editorUI.getStatusBar();
    recentStatusMessage = loc.getString("CTL_StatusBar_WaitFetchAnnotation"); // NOI18N
    statusBar.setText(StatusBar.CELL_MAIN, recentStatusMessage);

    // determine current line
    int line = -1;
    int offset = caret.getDot();
    try {
      line = Utilities.getLineOffset(doc, offset);
    } catch (BadLocationException ex) {
      Mercurial.LOG.log(Level.SEVERE, "Can not get line for caret at offset ", offset); // NOI18N
      clearRecentFeedback();
      return;
    }

    // handle locally modified lines
    AnnotateLine al = getAnnotateLine(line);
    if (al == null) {
      AnnotationMarkProvider amp = AnnotationMarkInstaller.getMarkProvider(textComponent);
      if (amp != null) {
        amp.setMarks(Collections.<AnnotationMark>emptyList());
      }
      clearRecentFeedback();
      if (recentRevision != null) {
        recentRevision = null;
        repaint();
      }
      return;
    }

    // handle unchanged lines
    String revision = al.getRevision();
    if (revision.equals(recentRevision) == false) {
      recentRevision = revision;
      repositoryRoot = Mercurial.getInstance().getRepositoryRoot(getCurrentFile());
      repaint();

      AnnotationMarkProvider amp = AnnotationMarkInstaller.getMarkProvider(textComponent);
      if (amp != null) {

        List<AnnotationMark> marks = new ArrayList<AnnotationMark>(elementAnnotations.size());
        // I cannot affort to lock elementAnnotations for long time
        // it's accessed from editor thread too
        Iterator<Map.Entry<Element, AnnotateLine>> it2;
        synchronized (elementAnnotations) {
          it2 =
              new HashSet<Map.Entry<Element, AnnotateLine>>(elementAnnotations.entrySet())
                  .iterator();
        }
        while (it2.hasNext()) {
          Map.Entry<Element, AnnotateLine> next = it2.next();
          AnnotateLine annotateLine = next.getValue();
          if (revision.equals(annotateLine.getRevision())) {
            Element element = next.getKey();
            if (elementAnnotations.containsKey(element) == false) {
              continue;
            }
            int elementOffset = element.getStartOffset();
            int lineNumber = NbDocument.findLineNumber((StyledDocument) doc, elementOffset);
            AnnotationMark mark = new AnnotationMark(lineNumber, revision);
            marks.add(mark);
          }

          if (Thread.interrupted()) {
            clearRecentFeedback();
            return;
          }
        }
        amp.setMarks(marks);
      }
    }

    if (al.getCommitMessage() != null) {
      recentStatusMessage = al.getCommitMessage();
      statusBar.setText(
          StatusBar.CELL_MAIN,
          al.getRevision()
              + ":"
              + al.getId()
              + " - "
              + al.getAuthor()
              + ": "
              + recentStatusMessage); // NOI18N
    } else {
      clearRecentFeedback();
    }
  }
  /*
   * Save document using encoding declared in XML prolog if possible otherwise
   * at UTF-8 (in such case it updates the prolog).
   */
  public void saveDocument() throws java.io.IOException {
    final javax.swing.text.StyledDocument doc = getDocument();
    String defaultEncoding = "UTF-8"; // NOI18N
    // dependency on xml/core
    String enc = EncodingUtil.detectEncoding(doc);
    boolean changeEncodingToDefault = false;
    if (enc == null) enc = defaultEncoding;

    // test encoding
    if (!isSupportedEncoding(enc)) {
      NotifyDescriptor nd =
          new NotifyDescriptor.Confirmation(
              NbBundle.getMessage(
                  StrutsConfigEditorSupport.class,
                  "MSG_BadEncodingDuringSave", // NOI18N
                  new Object[] {
                    getDataObject().getPrimaryFile().getNameExt(), enc, defaultEncoding
                  }),
              NotifyDescriptor.YES_NO_OPTION,
              NotifyDescriptor.WARNING_MESSAGE);
      nd.setValue(NotifyDescriptor.NO_OPTION);
      DialogDisplayer.getDefault().notify(nd);
      if (nd.getValue() != NotifyDescriptor.YES_OPTION) return;
      changeEncodingToDefault = true;
    }

    if (!changeEncodingToDefault) {
      // is it possible to save the document in the encoding?
      try {
        java.nio.charset.CharsetEncoder coder = java.nio.charset.Charset.forName(enc).newEncoder();
        if (!coder.canEncode(doc.getText(0, doc.getLength()))) {
          NotifyDescriptor nd =
              new NotifyDescriptor.Confirmation(
                  NbBundle.getMessage(
                      StrutsConfigEditorSupport.class,
                      "MSG_BadCharConversion", // NOI18N
                      new Object[] {getDataObject().getPrimaryFile().getNameExt(), enc}),
                  NotifyDescriptor.YES_NO_OPTION,
                  NotifyDescriptor.WARNING_MESSAGE);
          nd.setValue(NotifyDescriptor.NO_OPTION);
          DialogDisplayer.getDefault().notify(nd);
          if (nd.getValue() != NotifyDescriptor.YES_OPTION) return;
        }
      } catch (javax.swing.text.BadLocationException e) {
        Logger.getLogger("global").log(Level.INFO, null, e);
      }
      super.saveDocument();
      // moved from Env.save()
      getDataObject().setModified(false);
    } else {
      // update prolog to new valid encoding

      try {
        final int MAX_PROLOG = 1000;
        int maxPrologLen = Math.min(MAX_PROLOG, doc.getLength());
        final char prolog[] = doc.getText(0, maxPrologLen).toCharArray();
        int prologLen = 0; // actual prolog length

        // parse prolog and get prolog end
        if (prolog[0] == '<' && prolog[1] == '?' && prolog[2] == 'x') {

          // look for delimitting ?>
          for (int i = 3; i < maxPrologLen; i++) {
            if (prolog[i] == '?' && prolog[i + 1] == '>') {
              prologLen = i + 1;
              break;
            }
          }
        }

        final int passPrologLen = prologLen;

        Runnable edit =
            new Runnable() {
              public void run() {
                try {

                  doc.remove(0, passPrologLen + 1); // +1 it removes exclusive
                  doc.insertString(
                      0,
                      "<?xml version='1.0' encoding='UTF-8' ?> \n<!-- was: "
                          + new String(prolog, 0, passPrologLen + 1)
                          + " -->",
                      null); // NOI18N

                } catch (BadLocationException e) {
                  if (System.getProperty("netbeans.debug.exceptions") != null) // NOI18N
                  e.printStackTrace();
                }
              }
            };

        NbDocument.runAtomic(doc, edit);

        super.saveDocument();
        // moved from Env.save()
        getDataObject().setModified(false);
      } catch (javax.swing.text.BadLocationException e) {
        Logger.getLogger("global").log(Level.INFO, null, e);
      }
    }
  }
  private void doSubstitute(
      final JTextComponent component, final String toAdd, final int backOffset) {

    final StyledDocument doc = (StyledDocument) component.getDocument();

    class AtomicChange implements Runnable {

      public void run() {

        int caretOffset = component.getCaretPosition();
        String cname = component.getClass().getName();

        Boolean _isReplPanel = false;

        if (cname.equals("javax.swing.JEditorPane")) _isReplPanel = true;

        String value = getText();
        String javaList = "";

        if (toAdd != null) {
          value += toAdd;
        }

        try {

          String c = component.getText(caretOffset - 1, 1);

          if (!_isClojure && _isNamespaceOrPkg) // java package containing the Class at the end
          {
            value = setValueForClass(value, component);
            javaList = getJavaImportListStr(value);

            if ((javaList.contains("(")) && (!_isReplPanel)) {
              int messageret =
                  (JOptionPane.showConfirmDialog(
                      component,
                      "Do you want to add the import " + value + " to your ns imports?",
                      "add import ?",
                      0));

              if (messageret == 0) {
                PersistentArrayMap entry = addImportList(component, javaList);
                // component.setCaretPosition(caretOffset + javaList.length());
                value = getClassPart(value);

                if (entry != null) {
                  String origNS = (String) entry.get(Keyword.intern(Symbol.create("orignodestr")));
                  String newNS = (String) entry.get(Keyword.intern(Symbol.create("newnodestr")));

                  int insertOffset = newNS.length() - origNS.length();

                  _carretOffset = _carretOffset + insertOffset;
                  _dotOffset = _dotOffset + insertOffset;
                }
              }
            }
          }

          if (!c.equals("/") && (_layout != backSlashAfterParen) && (_layout != backSlashNoParen)) {

            switch (_layout) {
              case LowercaseAfterParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case UppercaseAfterParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case UppercaseAfterParenWithDot:
                if (_isMethodOrFunction && (!_isClojure)) // java method
                {
                  if (_isConstructor) {
                    value = "";
                  } else if (Character.isLetter(value.charAt(0))) {
                    {
                      doc.remove(_dotOffset, _carretOffset - _dotOffset);
                      value = "." + value;
                    }
                  }
                } else doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case LowercaseAfterParenWithDot:
                if (_isMethodOrFunction && (!_isClojure)) // java method
                {
                  if (_isConstructor) {
                    value = "";
                  } else if (Character.isLetter(value.charAt(0))) {
                    {
                      doc.remove(_dotOffset, _carretOffset - _dotOffset);
                      value = "." + value;
                    }
                  }
                } else doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case backSlashAfterParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case FirstDotAfterParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case FirstDotNoParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case UppercaseNoParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case UppercaseNoParenWithDot:
                if (_isMethodOrFunction && (!_isClojure)) // java method
                {
                  if (_isConstructor) {
                    value = "";
                  } else if (Character.isLetter(value.charAt(0))) {
                    {
                      doc.remove(_dotOffset, _carretOffset - _dotOffset);
                      value = "." + value;
                    }
                  }
                } else doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case LowercaseNoParenWithDot:
                if (_isMethodOrFunction && (!_isClojure)) // java method
                {
                  if (_isConstructor) {
                    value = "";
                  } else if (Character.isLetter(value.charAt(0))) {
                    {
                      doc.remove(_dotOffset, _carretOffset - _dotOffset);
                      value = "." + value;
                    }
                  }
                } else doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
              case LowercaseNoParen:
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                break;
            }

            doc.insertString(_dotOffset, value, null);
          } else {
            if (!c.equals("/")) {
              int backSlashOffset = indexOfBackSlash(component);
              if (backSlashOffset == -1) backSlashOffset = caretOffset;

              if (_isStatic || _layout == backSlashAfterParen || _layout == backSlashNoParen) {
                if (_isClojure && _isMethodOrFunction) {
                  if (isInCurrentNamespace(_fullclassname, component)) {
                    doc.remove(_dotOffset, _carretOffset - _dotOffset);
                    doc.insertString(_dotOffset, setValue(value), null);
                  } else {
                    doc.remove(backSlashOffset + 1, caretOffset - backSlashOffset - 1);
                    doc.insertString(backSlashOffset + 1, value, null);
                  }
                } else {
                  doc.remove(backSlashOffset + 1, caretOffset - backSlashOffset - 1);
                  doc.insertString(backSlashOffset + 1, value, null);
                }
              } else {
                doc.remove(_dotOffset, _carretOffset - _dotOffset);
                doc.insertString(_dotOffset, setValue(value), null);
              }

            } else if (_isStatic || _layout == backSlashAfterParen || _layout == backSlashNoParen)
              if (_isClojure && _isMethodOrFunction) {
                if (isInCurrentNamespace(_fullclassname, component)) {
                  doc.remove(_dotOffset, _carretOffset - _dotOffset);
                  doc.insertString(_dotOffset, setValue(value), null);
                } else doc.insertString(_carretOffset, value, null);
              } else doc.insertString(_carretOffset, value, null);
            else {
              doc.remove(_dotOffset, _carretOffset - _dotOffset);
              doc.insertString(_dotOffset, setValue(value), null);
            }
          }

          component.setCaretPosition(component.getCaretPosition() - backOffset);

        } catch (BadLocationException e) {
          LOG.log(Level.FINEST, e.getMessage());
        }
      }
    }

    AtomicChange change = new AtomicChange();
    try {
      NbDocument.runAtomicAsUser(doc, change);
    } catch (BadLocationException ex) {
      LOG.log(Level.FINEST, ex.getMessage());
    }
  }
  @Override
  public void saveDocument() throws IOException {
    final StyledDocument doc = getDocument();
    // Save document using encoding declared in XML prolog if possible,
    // otherwise use UTF-8 (in such case it updates the prolog).
    String enc = EncodingUtil.detectEncoding(doc);
    if (enc == null) {
      enc = "UTF8"; // NOI18N
    }
    try {
      // Test the encoding on a dummy stream.
      new OutputStreamWriter(new ByteArrayOutputStream(1), enc);
      if (!checkCharsetConversion(Convertors.java2iana(enc))) {
        return;
      }
      super.saveDocument();
      getDataObject().setModified(false);

    } catch (UnsupportedEncodingException uee) {
      NotifyDescriptor descriptor =
          new NotifyDescriptor.Confirmation(
              java.text.MessageFormat.format(
                  NbBundle.getMessage(WadlEditorSupport.class, "MSG_WadlEditorSupport_Use_UTF8"),
                  new Object[] {enc}));
      Object res = DialogDisplayer.getDefault().notify(descriptor);

      if (res.equals(NotifyDescriptor.YES_OPTION)) {
        // Update prolog to new valid encoding.
        try {
          final int MAX_PROLOG = 1000;
          int maxPrologLen = Math.min(MAX_PROLOG, doc.getLength());
          final char prolog[] = doc.getText(0, maxPrologLen).toCharArray();
          int prologLen = 0;
          if (prolog[0] == '<' && prolog[1] == '?' && prolog[2] == 'x') {
            for (int i = 3; i < maxPrologLen; i++) {
              if (prolog[i] == '?' && prolog[i + 1] == '>') {
                prologLen = i + 1;
                break;
              }
            }
          }

          final int passPrologLen = prologLen;
          Runnable edit =
              new Runnable() {
                public void run() {
                  try {
                    doc.remove(0, passPrologLen + 1);
                    doc.insertString(
                        0,
                        "<?xml version='1.0' encoding='UTF-8' ?>\n<!-- was: "
                            + new String(prolog, 0, passPrologLen + 1)
                            + " -->",
                        null); // NOI18N
                  } catch (BadLocationException ble) {
                    if (System.getProperty("netbeans.debug.exceptions") != null) // NOI18N
                    ble.printStackTrace();
                  }
                }
              };
          NbDocument.runAtomic(doc, edit);

          super.saveDocument();
          getDataObject().setModified(false);

        } catch (BadLocationException lex) {
          ErrorManager.getDefault().notify(lex);
        }
      }
    }
  }