Java Code Examples for org.eclipse.jface.text.BadLocationException#printStackTrace()

The following examples show how to use org.eclipse.jface.text.BadLocationException#printStackTrace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StyleRangesCollector.java    From tm4e with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void colorize(TextPresentation presentation, Throwable error) {
	add(presentation);
	if (waitForToLineNumber != null) {
		int offset = presentation.getExtent().getOffset() + presentation.getExtent().getLength();
		try {
			if (waitForToLineNumber != document.getLineOfOffset(offset)) {
				return;
			} else {
				waitForToLineNumber = null;
			}
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}
	((Command) command).setStyleRanges("[" + currentRanges.toString() + "]");
	synchronized (lock) {
		lock.notifyAll();
	}
}
 
Example 2
Source File: XMLPartitioner.java    From http4e with Apache License 2.0 6 votes vote down vote up
public void printPartitions( IDocument document){
   StringBuilder buffer = new StringBuilder();

   ITypedRegion[] partitions = computePartitioning(0, document.getLength());
   for (int i = 0; i < partitions.length; i++) {
      try {
         buffer.append("Partition type: " + partitions[i].getType() + ", offset: " + partitions[i].getOffset() + ", length: " + partitions[i].getLength());
         buffer.append("\n");
         buffer.append("Text:\n");
         buffer.append(document.get(partitions[i].getOffset(), partitions[i].getLength()));
         buffer.append("\n---------------------------\n\n\n");
      } catch (BadLocationException e) {
         e.printStackTrace();
      }
   }
   System.out.print(buffer);
}
 
Example 3
Source File: CoverageInformation.java    From tlaplus with MIT License 6 votes vote down vote up
public void add(final CoverageInformationItem item) {
	try {
		final String filename = item.getModuleLocation().source() + TLAConstants.Files.TLA_EXTENSION;
		if (nameToDocument.containsKey(filename)) {
			final IDocument document = nameToDocument.get(filename);
			final IRegion region = AdapterFactory.locationToRegion(document , item.getModuleLocation());
			item.setRegion(region);
		}
	} catch (BadLocationException notExpectedToHappen) {
		notExpectedToHappen.printStackTrace();
	}
	
	synchronized (items) {
		this.items.add(item);
	}
}
 
Example 4
Source File: GamlEditor.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @see msi.gama.lang.gaml.ui.editor.IGamlEditor#applyTemplate(org.eclipse.jface.text.templates.Template)
 */

public void applyTemplateAtTheEnd(final Template t) {

	try {
		final IDocument doc = getDocument();
		int offset = doc.getLineOffset(doc.getNumberOfLines() - 1);
		doc.replace(offset, 0, "\n\n");
		offset += 2;
		final int length = 0;
		final Position pos = new Position(offset, length);
		final XtextTemplateContextType ct = new XtextTemplateContextType();
		final DocumentTemplateContext dtc = new DocumentTemplateContext(ct, doc, pos);
		final IRegion r = new Region(offset, length);
		final TemplateProposal tp = new TemplateProposal(t, dtc, r, null);
		tp.apply(getInternalSourceViewer(), (char) 0, 0, offset);
	} catch (final BadLocationException e) {
		e.printStackTrace();
	}
}
 
Example 5
Source File: AdapterFactory.java    From tlaplus with MIT License 5 votes vote down vote up
/**
   * Returns the line number (in Java coordinates/zero based) of the line containing the first
   * "--algorithm" or "--fair algorithm" token(s) that begin(s) a PlusCal algorithm. 
   * Returns -1 if there is none.
   * 
   * @param document
   * @return
   */
  public static int GetLineOfPCalAlgorithm(IDocument document) {
try {
	final String moduleAsString = document.get();
	return LocationToLine(document,
			TLAtoPCalMapping.GetLineOfPCalAlgorithm(moduleAsString));
} catch (BadLocationException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
return -1;
  }
 
Example 6
Source File: PresentationRepairer.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds style information to the given text presentation.
 * @param presentation
 *            the text presentation to be extended
 * @param offset
 *            the offset of the range to be styled
 * @param length
 *            the length of the range to be styled
 * @param textStyle
 *            the style of the range to be styled
 */
protected void addRange(TextPresentation presentation, int offset, int length, TextStyle textStyle) {
	if (textStyle != null) {

		if (textStyle.metrics != null && length >= 1) {
			for (int i = offset; i < offset + length; i++) {
				try {
					StyleRange styleRange = new StyleRange(textStyle);
					String placeHolder = fDocument.get(i, 1);
					InnerTag innerTag = InnerTagUtil.getInnerTag(fViewer.getInnerTagCacheList(), placeHolder);
					if (innerTag != null) {
						Point rect = innerTag.computeSize(SWT.DEFAULT, SWT.DEFAULT);
						// int ascent = 4 * rect.height / 5 + SEGMENT_LINE_SPACING / 2;
						// int descent = rect.height - ascent + SEGMENT_LINE_SPACING;
						styleRange.metrics = new GlyphMetrics(rect.y, 0, rect.x + SEGMENT_LINE_SPACING * 2);
					}
					styleRange.start = i;
					styleRange.length = 1;
					presentation.addStyleRange(styleRange);
				} catch (BadLocationException e) {
					e.printStackTrace();
				}
			}
		} /*
		 * else { StyleRange styleRange = new StyleRange(textStyle); styleRange.start = offset; styleRange.length =
		 * length; presentation.addStyleRange(styleRange); }
		 */
	}
}
 
Example 7
Source File: ASTReader.java    From JDeodorant with MIT License 5 votes vote down vote up
private List<CommentObject> processComments(IFile iFile, IDocument iDocument,
		AbstractTypeDeclaration typeDeclaration, List<Comment> comments) {
	List<CommentObject> commentList = new ArrayList<CommentObject>();
	int typeDeclarationStartPosition = typeDeclaration.getStartPosition();
	int typeDeclarationEndPosition = typeDeclarationStartPosition + typeDeclaration.getLength();
	for(Comment comment : comments) {
		int commentStartPosition = comment.getStartPosition();
		int commentEndPosition = commentStartPosition + comment.getLength();
		int commentStartLine = 0;
		int commentEndLine = 0;
		String text = null;
		try {
			commentStartLine = iDocument.getLineOfOffset(commentStartPosition);
			commentEndLine = iDocument.getLineOfOffset(commentEndPosition);
			text = iDocument.get(commentStartPosition, comment.getLength());
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
		CommentType type = null;
		if(comment.isLineComment()) {
			type = CommentType.LINE;
		}
		else if(comment.isBlockComment()) {
			type = CommentType.BLOCK;
		}
		else if(comment.isDocComment()) {
			type = CommentType.JAVADOC;
		}
		CommentObject commentObject = new CommentObject(text, type, commentStartLine, commentEndLine);
		commentObject.setComment(comment);
		String fileExtension = iFile.getFileExtension() != null ? "." + iFile.getFileExtension() : "";
		if(typeDeclarationStartPosition <= commentStartPosition && typeDeclarationEndPosition >= commentEndPosition) {
			commentList.add(commentObject);
		}
		else if(iFile.getName().equals(typeDeclaration.getName().getIdentifier() + fileExtension)) {
			commentList.add(commentObject);
		}
	}
	return commentList;
}
 
Example 8
Source File: TLAPartitionScanner.java    From tlaplus with MIT License 5 votes vote down vote up
/**
 * If the scanner starts inside of the multi-line partition, the depth of comment nesting need to be determined. This is performed by this method.
 * @param document the document
 * @param offset start of the partition
 * @param length number of characters between the start of partition and the offset from which the scanner will continue
 * @return comment depth
 */
private int getCommentDepth(IDocument document, int offset, int length)
{
    try
    {
        String partitionText = document.get(offset, length);
        // regex for (* and *) needs escaping
        return partitionText.split("\\(\\*").length - partitionText.split("\\*\\)").length;
        
    } catch (BadLocationException e)
    {
        e.printStackTrace();
        return 1;
    }
}
 
Example 9
Source File: ScriptConsoleDocumentListener.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
protected PromptContext removeUserInput() {
    if (!promptReady) {
        return new PromptContext(false, -1, "");
    }

    PromptContext pc = new PromptContext(true, -1, "");
    try {
        int lastLine = doc.getNumberOfLines() - 1;
        int lastLineLength = doc.getLineLength(lastLine);
        int end = doc.getLength();
        int start = end - lastLineLength;
        // There may be read-only content before the current input. so last line
        // may look like:
        // Out[10]: >>> some_user_command
        // The content before the prompt should be treated as read-only.
        int promptOffset = doc.get(start, lastLineLength).indexOf(prompt.toString());
        start += promptOffset;
        lastLineLength -= promptOffset;

        pc.userInput = doc.get(start, lastLineLength);
        pc.cursorOffset = end - viewer.getCaretOffset();
        doc.replace(start, lastLineLength, "");

        pc.userInput = pc.userInput.replace(prompt.toString(), "");

    } catch (BadLocationException e) {
        e.printStackTrace();
    }
    return pc;
}
 
Example 10
Source File: TLAEditor.java    From tlaplus with MIT License 5 votes vote down vote up
public void gotoMarker(final IMarker marker) {
	// if the given marker happens to be of instance TLAtoPCalMarker, it
	// indicates that the user wants to go to the PCal equivalent of the
	// current TLA+ marker
	if (marker instanceof TLAtoPCalMarker) {
		final TLAtoPCalMarker tlaToPCalMarker = (TLAtoPCalMarker) marker;
		try {
			final pcal.Region region = tlaToPCalMarker.getRegion();
			if (region != null) {
				selectAndReveal(region);
				return;
			} else {
				UIHelper.setStatusLineMessage("No valid TLA to PCal mapping found for current selection");
			}
		} catch (BadLocationException e) {
			// not expected to happen
			e.printStackTrace();
		}
	}
	
	// fall back to original marker if the TLAtoPCalMarker didn't work or no TLAtoPCalMarker
	//  N.B even though this is marked deprecated, the recommended replacement of: 
	//					((IGotoMarker)getAdapter(IGotoMarker.class)).gotoMarker(marker);
	//	causes a stack overflow.
	//		See: https://github.com/tlaplus/tlaplus/commit/28f6e2cf6328b84027762e828fb2f741b1a25377#r35904992
	super.gotoMarker(marker);
}
 
Example 11
Source File: PostfixTemplateProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean validate(IDocument document, int offset, DocumentEvent event) {
	if (getContext() instanceof JavaStatementPostfixContext) {
		JavaStatementPostfixContext c = (JavaStatementPostfixContext) getContext();
		try {
			int start = c.getStart() + c.getAffectedSourceRegion().getLength() + 1;
			String content = document.get(start, offset - start);
			return this.getTemplate().getName().toLowerCase().startsWith(content.toLowerCase());
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
	}
	return super.validate(document, offset, event);
}
 
Example 12
Source File: GamlEditor.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public String getSelectedText() {
	final ITextSelection sel = (ITextSelection) getSelectionProvider().getSelection();
	final int length = sel.getLength();
	if (length == 0) { return ""; }
	final IDocument doc = getDocument();
	try {
		return doc.get(sel.getOffset(), length);
	} catch (final BadLocationException e) {
		e.printStackTrace();
		return "";
	}
}
 
Example 13
Source File: DefaultFoldingStructureProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @since 2.17
 */
protected int getLineNumber(int offset) {
	IDocument document = viewer.getDocument();
	int lineNumber = -1;
	try {
		lineNumber = document.getLineOfOffset(offset);
	} catch (BadLocationException e) {
		e.printStackTrace();
	}
	return lineNumber;
}
 
Example 14
Source File: Ch5CompletionEditor.java    From http4e with Apache License 2.0 5 votes vote down vote up
protected String findMostRecentWord( int startSearchOffset){
   int currOffset = startSearchOffset;
   char currChar;
   String word = "";
   try {
      while (currOffset > 0 && !Character.isWhitespace(currChar = textViewer.getDocument().getChar(currOffset))) {
         word = currChar + word;
         currOffset--;
      }
      return word;
   } catch (BadLocationException e) {
      e.printStackTrace();
      return null;
   }
}
 
Example 15
Source File: DocumentReplaceCommand.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void doExecute() {
	try {
		document.replace(pos, length, text);
	} catch (BadLocationException e) {
		e.printStackTrace();
	}
}
 
Example 16
Source File: DocumentLineList.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void documentAboutToBeChanged(DocumentEvent event) {
	try {
		if (!DocumentHelper.isInsert(event)) {
			// Remove or Replace (Remove + Insert)
			removeLine(event);
		}
	} catch (BadLocationException e) {
		e.printStackTrace();
	}
}
 
Example 17
Source File: TexSpellingEngine.java    From texlipse with Eclipse Public License 1.0 4 votes vote down vote up
public void check(IDocument document, IRegion[] regions, SpellingContext context, 
        ISpellingProblemCollector collector, IProgressMonitor monitor) {
    
    if (ignore == null) {
        ignore = new HashSet<String>();
    }

    IProject project = getProject(document);

    String lang = DEFAULT_LANG;
    if (project != null) {
        lang = TexlipseProperties.getProjectProperty(project, TexlipseProperties.LANGUAGE_PROPERTY);
    }
    //Get spellchecker for the correct language
    SpellChecker spellCheck = getSpellChecker(lang);
    if (spellCheck == null) return;
    
    if (collector instanceof TeXSpellingProblemCollector) {
        ((TeXSpellingProblemCollector) collector).setRegions(regions);
    }
    
    try {
        spellCheck.addSpellCheckListener(this);
        for (final IRegion r : regions) {
            errors = new LinkedList<SpellCheckEvent>();
            int roffset = r.getOffset();
            
            //Create a new wordfinder and initialize it
            TexlipseWordFinder wf = new TexlipseWordFinder();
            wf.setIgnoreComments(TexlipsePlugin.getDefault().getPreferenceStore().getBoolean(TexlipseProperties.SPELLCHECKER_IGNORE_COMMENTS));
            wf.setIgnoreMath(TexlipsePlugin.getDefault().getPreferenceStore().getBoolean(TexlipseProperties.SPELLCHECKER_IGNORE_MATH));
            
            spellCheck.checkSpelling(new StringWordTokenizer(
                    document.get(roffset, r.getLength()), wf));
            
            for (SpellCheckEvent error : errors) {
                SpellingProblem p = new TexSpellingProblem(error, roffset, lang);
                collector.accept(p);
            }
        }
        spellCheck.removeSpellCheckListener(this);                
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}
 
Example 18
Source File: ExampleEditorAction.java    From tlaplus with MIT License 4 votes vote down vote up
/**
 * Listens for the first key to be pressed. If it is a digit, it
 * finds the word currently containing the caret and repeats that word
 * the number of times equal to the digit pressed.
 */
public void verifyKey(VerifyEvent event)
{
    // no other listeners should respond to this event
    event.doit = false;

    // the state mask indicates what modifier keys (such as CTRL) were being
    // pressed when the character was pressed
    if (event.stateMask == SWT.NONE && Character.isDigit(event.character))
    {
        // get the digit input
        int input = Character.getNumericValue(event.character);

        // get the text selection
        ISelection selection = getTextEditor().getSelectionProvider().getSelection();
        if (selection != null && selection instanceof ITextSelection)
        {
            ITextSelection textSelection = (ITextSelection) selection;

            IDocument document = getTextEditor().getDocumentProvider()
                    .getDocument(getTextEditor().getEditorInput());

            // if one or more characters are selected, do nothing
            if (textSelection.getLength() == 0 && document != null)
            {

                // retrieve the region describing the word containing
                // the caret
                try
                {
                	IRegion region = DocumentHelper.getRegionExpandedBoth(document, textSelection.getOffset());

                    // generate the insertion string
                    String insertionText = " " + document.get(region.getOffset(), region.getLength());
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < input; i++)
                    {
                        sb.append(insertionText);
                    }
                    document.replace(region.getOffset() + region.getLength(), 0, sb.toString());
                } catch (BadLocationException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    // do not listen to any other key strokes
    ((TLAEditor) getTextEditor()).getViewer().removeVerifyKeyListener(this);

    statusLine.setMessage("");
}
 
Example 19
Source File: ExampleEditCommandHandler.java    From tlaplus with MIT License 4 votes vote down vote up
/**
 * Listens for the first key to be pressed. If it is a digit, it
 * finds the word currently containing the caret and repeats that word
 * the number of times equal to the digit pressed. If the key pressed
 * is not a digit, this does nothing to the document and
 * removes itself from subsequent key events.
 */
public void verifyKey(VerifyEvent event)
{
    try
    {
        // no other listeners should respond to this event
        event.doit = false;

        // the state mask indicates what modifier keys (such as CTRL) were being
        // pressed when the character was pressed

        // the digit should be pressed without any modifier keys
        if (event.stateMask == SWT.NONE && Character.isDigit(event.character))
        {
            // get the digit input
            int input = Character.getNumericValue(event.character);

            // get the text selection
            ISelection selection = editor.getSelectionProvider().getSelection();

            if (selection != null && selection instanceof ITextSelection)
            {
                ITextSelection textSelection = (ITextSelection) selection;

                IDocument document = editor.getDocumentProvider().getDocument(editor.getEditorInput());

                // if one or more characters are highlighted, do nothing
                if (textSelection.getLength() == 0 && document != null)
                {

                    // retrieve the region describing the word containing
                    // the caret
                    try
                    {
                    	IRegion region = DocumentHelper.getRegionExpandedBoth(document, textSelection.getOffset());

                        // generate the insertion string
                        String insertionText = " " + document.get(region.getOffset(), region.getLength());
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < input; i++)
                        {
                            sb.append(insertionText);
                        }

                        // insert the string
                        document.replace(region.getOffset() + region.getLength(), 0, sb.toString());
                    } catch (BadLocationException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    } finally
    {

        uninstall();
    }
}
 
Example 20
Source File: CompletionProposalPopup.java    From APICloud-Studio with GNU General Public License v3.0 4 votes vote down vote up
private ICompletionProposal[] filterProposals1(ICompletionProposal[] proposals, IDocument document, int offset,
			DocumentEvent event, String per)
	{
	        String type = "";
		try
		{
			if ("__html_tag".equals(document.getPartition(offset).getType()))
				type = "html";
			if ("__css___dftl_partition_content_type".equals(document.getPartition(offset).getType()))
				type = "css";
			if ("__js__dftl_partition_content_type".equals(document.getPartition(offset).getType()))
				type = "js";
			if ("__dftl_partition_content_type".equals(document.getPartition(offset).getType()))
				type = "default";
		}
		
		catch (BadLocationException e1)
		{
			e1.printStackTrace();
		}
		if(per.equals("bs")) {
			header = filterPrefix1(proposals, document, offset, type);
			header += bufferString;

			if(header.length() == 1 ) {
//				header = "";
			}else if(header.length() == 0) {
				System.out.println("hhaha");
				hide();
				return null;
			}	
		}else {
			header = filterPrefix1(proposals, document, offset, type);
			header += bufferString;
		}
	

		List<ICompletionProposal> list = new ArrayList<ICompletionProposal>();
		
		for(ICompletionProposal p : proposals) {

			if(p.getDisplayString().toLowerCase().startsWith(header.toLowerCase())) {
				list.add(p);
			}
		}
		Collections.sort(list, new Comparator<ICompletionProposal>()
		{

			public int compare(ICompletionProposal o1, ICompletionProposal o2)
			{
				return o1.getDisplayString().compareTo(o2.getDisplayString());
			}
			
		});
		return list.toArray(new ICompletionProposal[list.size()]);
	}