1 /**
2  *  Copyright (c) 2017 Angelo ZERR.
3  *
4  *  This program and the accompanying materials
5  *  are made available under the terms of the Eclipse Public License 2.0
6  *  which accompanies this distribution, and is available at
7  *  https://www.eclipse.org/legal/epl-2.0/
8  *
9  *  SPDX-License-Identifier: EPL-2.0
10  *
11  *  Contributors:
12  *  Angelo Zerr <angelo.zerr@gmail.com> - [CodeMining] Provide inline annotations support - Bug 527675
13  */
14 package org.eclipse.jface.text.source.inlined;
15 
16 import org.eclipse.jface.text.BadLocationException;
17 import org.eclipse.jface.text.IDocument;
18 import org.eclipse.jface.text.Position;
19 
20 /**
21  * Utilities class to retrieve position.
22  *
23  * @since 3.13
24  */
25 public class Positions {
26 
27 	/**
28 	 * Returns the line position by taking care or not of of leading spaces.
29 	 *
30 	 * @param lineIndex the line index
31 	 * @param document the document
32 	 * @param leadingSpaces true if line spacing must take care of and not otherwise.
33 	 * @return the line position by taking care of leading spaces.
34 	 * @throws BadLocationException if the line number is invalid in this document
35 	 */
of(int lineIndex, IDocument document, boolean leadingSpaces)36 	public static Position of(int lineIndex, IDocument document, boolean leadingSpaces) throws BadLocationException {
37 		int offset= document.getLineOffset(lineIndex);
38 		int lineLength= document.getLineLength(lineIndex);
39 		String line= document.get(offset, lineLength);
40 		if (leadingSpaces) {
41 			offset+= getLeadingSpaces(line);
42 		}
43 		return new Position(offset, 1);
44 	}
45 
46 	/**
47 	 * Returns the leading spaces of the given line text.
48 	 *
49 	 * @param line the line text.
50 	 * @return the leading spaces of the given line text.
51 	 */
getLeadingSpaces(String line)52 	private static int getLeadingSpaces(String line) {
53 		int counter= 0;
54 		char[] chars= line.toCharArray();
55 		for (char c : chars) {
56 			if (c == '\t')
57 				counter++;
58 			else if (c == ' ')
59 				counter++;
60 			else
61 				break;
62 		}
63 		return counter;
64 	}
65 }
66