public async provideHover(document: TextDocument, position: Position, token: CancellationToken): Promise<Hover> {
        if (!VariableUtility.isVariableReference(document, position)) {
            return;
        }

        let wordRange = document.getWordRangeAtPosition(position);
        let selectedVariableName = document.getText(wordRange);

        if (await FileVariableProvider.Instance.has(document, selectedVariableName)) {
            const { name, value, error, warning } = await FileVariableProvider.Instance.get(document, selectedVariableName);
            if (!warning && !error) {
                const contents: MarkedString[] = [value as string, new MarkdownString(`*File Variable* \`${name}\``)];
                return new Hover(contents, wordRange);
            }

            return;
        }

        if (await EnvironmentVariableProvider.Instance.has(document, selectedVariableName)) {
            const { name, value, error, warning } = await EnvironmentVariableProvider.Instance.get(document, selectedVariableName);
            if (!warning && !error) {
                const contents: MarkedString[] = [value as string, new MarkdownString(`*Environment Variable* \`${name}\``)];
                return new Hover(contents, wordRange);
            }

            return;
        }

        return;
    }
Example #2
0
	constructor(
		public position: Position,
		public document: TextDocument,
		entry: CompletionEntry,
		enableDotCompletions: boolean,
		enableCallCompletions: boolean
	) {
		super(entry.name);
		this.sortText = entry.sortText;
		this.kind = MyCompletionItem.convertKind(entry.kind);
		this.position = position;
		this.commitCharacters = MyCompletionItem.getCommitCharacters(enableDotCompletions, enableCallCompletions, entry.kind);
		if (entry.replacementSpan) {
			let span: protocol.TextSpan = entry.replacementSpan;
			// The indexing for the range returned by the server uses 1-based indexing.
			// We convert to 0-based indexing.
			this.textEdit = TextEdit.replace(new Range(span.start.line - 1, span.start.offset - 1, span.end.line - 1, span.end.offset - 1), entry.name);
		} else {
			// Try getting longer, prefix based range for completions that span words
			const wordRange = document.getWordRangeAtPosition(position);
			const text = document.getText(new Range(position.line, Math.max(0, position.character - entry.name.length), position.line, position.character)).toLowerCase();
			const entryName = entry.name.toLowerCase();
			for (let i = entryName.length; i >= 0; --i) {
				if (text.endsWith(entryName.substr(0, i)) && (!wordRange || wordRange.start.character > position.character - i)) {
					this.range = new Range(position.line, Math.max(0, position.character - i), position.line, position.character);
					break;
				}
			}
		}
	}
Example #3
0
export function getWindowsLineEndingCount(document: TextDocument, offset: Number) {
    const eolPattern = new RegExp('\r\n', 'g');
    const readBlock = 1024;
    let count = 0;
    let offsetDiff = offset.valueOf();

    // In order to prevent the one-time loading of large files from taking up too much memory
    for (let pos = 0; pos < offset; pos += readBlock) {
        let startAt = document.positionAt(pos);
        let endAt = null;

        if (offsetDiff >= readBlock) {
            endAt = document.positionAt(pos + readBlock);
            offsetDiff = offsetDiff - readBlock;
        } else {
            endAt = document.positionAt(pos + offsetDiff);
        }

        let text = document.getText(new Range(startAt, endAt));
        let cr = text.match(eolPattern);

        count += cr ? cr.length : 0;
    }
    return count;
}
  provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken) : CompletionItem[] {
    const start = new Position(position.line, 0);
    const range = new Range(start, position);
    const currentWord = document.getText(range).trim();
    const text = document.getText();
    const value = isValue(cssSchema, currentWord);
    const config = workspace.getConfiguration('languageStylus');

    let symbols = [],
        atRules = [],
        properties = [],
        values = [];

    if (value) {
      values = getValues(cssSchema, currentWord);
      symbols = compact(getAllSymbols(text, currentWord)).filter(item =>
        item.kind === CompletionItemKind.Variable
      );
    } else {
      atRules = getAtRules(cssSchema, currentWord);
      properties = getProperties(cssSchema, currentWord, config.get('useSeparator', true));
      symbols = compact(getAllSymbols(text, currentWord));
    }

    const completions = [].concat(
      symbols,
      atRules,
      properties,
      values,
      config.get('useBuiltinFunctions', true) ? builtIn : []
    );

    return completions;
  }
Example #5
0
export function applyLineChanges(original: TextDocument, modified: TextDocument, diffs: LineChange[]): string {
	const result: string[] = [];
	let currentLine = 0;

	for (let diff of diffs) {
		const isInsertion = diff.originalEndLineNumber === 0;
		const isDeletion = diff.modifiedEndLineNumber === 0;

		result.push(original.getText(new Range(currentLine, 0, isInsertion ? diff.originalStartLineNumber : diff.originalStartLineNumber - 1, 0)));

		if (!isDeletion) {
			let fromLine = diff.modifiedStartLineNumber - 1;
			let fromCharacter = 0;

			// if this is an insertion at the very end of the document,
			// then we must start the next range after the last character of the
			// previous line, in order to take the correct eol
			if (isInsertion && diff.originalStartLineNumber === original.lineCount) {
				fromLine -= 1;
				fromCharacter = modified.lineAt(fromLine).range.end.character;
			}

			result.push(modified.getText(new Range(fromLine, fromCharacter, diff.modifiedEndLineNumber, 0)));
		}

		currentLine = isInsertion ? diff.originalStartLineNumber : diff.originalEndLineNumber;
	}

	result.push(original.getText(new Range(currentLine, 0, original.lineCount, 0)));

	return result.join('');
}
Example #6
0
function getDiagnostic(document: TextDocument, report: NpmListReport, moduleName: string, ranges: SourceRanges): Diagnostic {
	let diagnostic = null;

	// npm list only reports errors against 'dependencies' and not against 'devDependencies'
	if (report.dependencies && report.dependencies[moduleName]) {
		if (report.dependencies[moduleName]['missing'] === true) {
			if (ranges.dependencies[moduleName]) {
				const source = ranges.dependencies[moduleName].name;
				const range = new Range(document.positionAt(source.offset), document.positionAt(source.offset + source.length));
				diagnostic = new Diagnostic(range, `Module '${moduleName}' is not installed`, DiagnosticSeverity.Warning);
			} else {
				console.log(`[npm-script] Could not locate "missing" dependency '${moduleName}' in package.json`);
			}
		}
		else if (report.dependencies[moduleName]['invalid'] === true) {
			if (ranges.dependencies[moduleName]) {
				const source = ranges.dependencies[moduleName].version;
				const installedVersion = report.dependencies[moduleName]['version'];
				const range = new Range(document.positionAt(source.offset), document.positionAt(source.offset + source.length));
				const message = installedVersion ?
					`Module '${moduleName}' the installed version '${installedVersion}' is invalid` :
					`Module '${moduleName}' the installed version is invalid or has errors`;
				diagnostic = new Diagnostic(range, message, DiagnosticSeverity.Warning);
			} else {
				console.log(`[npm-script] Could not locate "invalid" dependency '${moduleName}' in package.json`);
			}
		}
		else if (report.dependencies[moduleName]['extraneous'] === true) {
			const source = findAttributeRange(ranges);
			const range = new Range(document.positionAt(source.offset), document.positionAt(source.offset + source.length));
			diagnostic = new Diagnostic(range, `Module '${moduleName}' is extraneous`, DiagnosticSeverity.Warning);
		}
	}
	return diagnostic;
}
        return new Promise<Command[]>((resolve, reject) => {
            let commands: Command[] = [
                {
                    command: 'python.sortImports',
                    title: 'Sort Imports'
                }
            ];

            if (vscode.window.activeTextEditor.document === document && !vscode.window.activeTextEditor.selection.isEmpty) {
                let wordRange = document.getWordRangeAtPosition(range.start);
                // If no word has been selected by the user, then don't display rename
                // If something has been selected, then ensure we have selected a word (i.e. end and start matches the word range) 
                if (wordRange && !wordRange.isEmpty && wordRange.isEqual(vscode.window.activeTextEditor.selection)) {
                    let word = document.getText(wordRange).trim();
                    if (word.length > 0) {
                        commands.push({ command: 'editor.action.rename', title: 'Rename Symbol' });
                    }
                }
            }

            if (!range.isEmpty) {
                let word = document.getText(range).trim();
                if (word.trim().length > 0) {
                    commands.push({ command: 'python.refactorExtractVariable', title: 'Extract Variable', arguments: [range] });
                    commands.push({ command: 'python.refactorExtractMethod', title: 'Extract Method', arguments: [range] });
                }
            }
            resolve(commands);
        });
    public static getTodos(doc: TextDocument): model.TodoItem[] {
        let docContent = doc.getText();
        let regex = new rg.RegexFactory(doc.languageId).get();
        /* For no reason, vscode returns duplicates matches sometimes.
        To avoid that, check if a new item exists in the set */
        let set = new collections.Set<model.TodoItem>();
        let results: model.TodoItem[] = [];
        if (docContent != "") {
            let match, indices = [];
            while (match = regex.exec(docContent)) {
                indices.push(match.index);

                let matched_text = (match[1]) ? match[1] : match[0];
                let filter_result = this.filter(this.cleanString(matched_text));
                matched_text = filter_result[0];
                if(!matched_text) { // there is no todo
                    continue;
                }
                let skipped = filter_result[1];
                let id = match.index + skipped;
                let range = new Range(doc.positionAt(id), doc.positionAt(id + matched_text.length));
                let new_item = new model.TodoItem(range, matched_text, doc.fileName);
                
                if (!set.contains(new_item)) {
                    results.push(new_item);
                    set.add(new_item);
                }
            }
        }

        return results;
    }
export function buildDiagnostic(componentFailure): Diagnostic {
    let lineNumber: number = 0;
    let columnNumber: number = 0;

    if(componentFailure.lineNumber){
        lineNumber = componentFailure.lineNumber - 1;
    }
    if(componentFailure.columnNumber){
        columnNumber = componentFailure.columnNumber - 1;
    }

    let start = new Position(lineNumber, columnNumber);
    let end = new Position(lineNumber+1, 0);
    let range = new Range(start, end);

    if(componentFailure.document){
        let document: TextDocument = componentFailure.document;
        let wordRange = document.getWordRangeAtPosition(start); 
        if(wordRange){
            range = wordRange;
        }
    }

    let newDiagnostic = new Diagnostic(range, componentFailure.problem);

    return newDiagnostic;
}
Example #10
0
 public toDecorationRange(start: number, document: TextDocument): Range {
     const pos = document.positionAt(start);
     const line = pos.line;
     const documentLine = document.lineAt(line);
     const lineRange = documentLine.range;
     return new Range(lineRange.end.line, lineRange.end.character, lineRange.end.line, lineRange.end.character);
 }
Example #11
0
export function applyChanges(original: TextDocument, modified: TextDocument, diffs: LineChange[]): string {
	const result: string[] = [];
	let currentLine = 0;

	for (let diff of diffs) {
		const isInsertion = diff.originalEndLineNumber === 0;
		const isDeletion = diff.modifiedEndLineNumber === 0;

		result.push(original.getText(new Range(currentLine, 0, isInsertion ? diff.originalStartLineNumber : diff.originalStartLineNumber - 1, 0)));

		if (!isDeletion) {
			let fromLine = diff.modifiedStartLineNumber - 1;
			let fromCharacter = 0;

			if (isInsertion && diff.originalStartLineNumber === original.lineCount) {
				fromLine = original.lineCount - 1;
				fromCharacter = original.lineAt(fromLine).range.end.character;
			}

			result.push(modified.getText(new Range(fromLine, fromCharacter, diff.modifiedEndLineNumber, 0)));
		}

		currentLine = isInsertion ? diff.originalStartLineNumber : diff.originalEndLineNumber;
	}

	result.push(original.getText(new Range(currentLine, 0, original.lineCount, 0)));

	return result.join('');
}
Example #12
0
	public provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken): Thenable<CompletionList> {

		let fileName = basename(document.fileName);

		let currentWord = this.getCurrentWord(document, position);
		let overwriteRange : Range;

		let items: CompletionItem[] = [];
		let isIncomplete = false;

		let offset = document.offsetAt(position);
		let location = getLocation(document.getText(), offset);

		let node = location.previousNode;
		if (node && node.offset <= offset && offset <= node.offset + node.length && (node.type === 'property' || node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
			overwriteRange = new Range(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
		} else {
			overwriteRange = new Range(document.positionAt(offset - currentWord.length), position);
		}
		let filterText = document.getText(new Range(overwriteRange.start, position));

		let proposed: { [key: string]: boolean } = {};
		let collector: ISuggestionsCollector = {
			add: (suggestion: CompletionItem) => {
				if (!proposed[suggestion.label]) {
					proposed[suggestion.label] = true;
					suggestion.textEdit = TextEdit.replace(overwriteRange, suggestion.insertText);
					suggestion.filterText = filterText;

					items.push(suggestion);
				}
			},
			setAsIncomplete: () => isIncomplete = true,
			error: (message: string) => console.error(message),
			log: (message: string) => console.log(message)
		};

		let collectPromise : Thenable<any> = null;

		if (location.isAtPropertyKey) {
			let addValue = !location.previousNode || !location.previousNode.columnOffset;
			let isLast = this.isLast(document, position);
			collectPromise = this.jsonContribution.collectPropertySuggestions(fileName, location, currentWord, addValue, isLast, collector);
		} else {
			if (location.path.length === 0) {
				collectPromise = this.jsonContribution.collectDefaultSuggestions(fileName, collector);
			} else {
				collectPromise = this.jsonContribution.collectValueSuggestions(fileName, location, collector);
			}
		}
		if (collectPromise) {
			return collectPromise.then(() => {
				if (items.length > 0) {
					return new CompletionList(items, isIncomplete);
				}
				return null;
			});
		}
		return null;
	}
Example #13
0
    public static getCells(document: TextDocument): Cell[] {
        const cells: Cell[] = [];
        for (let index = 0; index < document.lineCount; index++) {
            const line = document.lineAt(index);
            if (CellIdentifier.test(line.text)) {
                const results = CellIdentifier.exec(line.text);
                if (cells.length > 0) {
                    const previousCell = cells[cells.length - 1];
                    previousCell.range = new Range(previousCell.range.start, document.lineAt(index - 1).range.end);
                }
                cells.push({
                    range: line.range,
                    title: results.length > 1 ? results[2].trim() : ''
                });
            }

        }

        if (cells.length >= 1) {
            const line = document.lineAt(document.lineCount - 1);
            const previousCell = cells[cells.length - 1];
            previousCell.range = new Range(previousCell.range.start, line.range.end);
        }
        return cells;
    }
	private buildOccurrences(
		highlights: DocumentHighlight[], document: TextDocument, position: number, occurrences: as.Occurrences
	) {
		let element = occurrences.element;
		let offsets: number[] = occurrences.offsets;
		let length: number = occurrences.length;

		for (let i = 0; i < offsets.length; i++) {
			let offset = offsets[i];

			// Look for a match in any of the occurance ranges.
			if ((offset <= position) && (position < (offset + length))) {
				// If we get a match, then create highlights for all the items in the matching occurance.
				for (let i = 0; i < offsets.length; i++) {
					let offset = offsets[i];
					let range = new Range(
						document.positionAt(offset),
						document.positionAt(offset + length)
					);
					highlights.push(new DocumentHighlight(range));
				}

				return;
			}
		}
	}
	public provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken): Promise<CompletionItem[]> {

		let wordToComplete = '';
		let range = document.getWordRangeAtPosition(position);
		if (range) {
			wordToComplete = document.getText(new Range(range.start, position));
		}

		let req = createRequest<protocol.AutoCompleteRequest>(document, position);
		req.WordToComplete = wordToComplete;
		req.WantDocumentationForEveryCompletionResult = true;
		req.WantKind = true;

		return serverUtils.autoComplete(this._server, req).then(values => {

			if (!values) {
				return;
			}

			let result: CompletionItem[] = [];
			let completions: { [c: string]: CompletionItem[] } = Object.create(null);

			// transform AutoCompleteResponse to CompletionItem and
			// group by code snippet
			for (let value of values) {
				let completion = new CompletionItem(value.CompletionText.replace(/\(|\)|<|>/g, ''));
				completion.detail = value.DisplayText;
				completion.documentation = plain(value.Description);
				completion.kind = _kinds[value.Kind] || CompletionItemKind.Property;

				let array = completions[completion.label];
				if (!array) {
					completions[completion.label] = [completion];
				} else {
					array.push(completion);
				}
			}

			// per suggestion group, select on and indicate overloads
			for (let key in completions) {

				let suggestion = completions[key][0],
					overloadCount = completions[key].length - 1;

				if (overloadCount === 0) {
					// remove non overloaded items
					delete completions[key];

				} else {
					// indicate that there is more
					suggestion.detail = `${suggestion.detail} (+ ${overloadCount} overload(s))`;
				}
				result.push(suggestion);
			}

			return result;
		});
	}
    public async provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken): Promise<CompletionItem[]> {
        if (!VariableUtility.isPartialRequestVariableReference(document, position)) {
            return [];
        }


        const wordRange = document.getWordRangeAtPosition(position, /\{\{(\w+)\.(.*?)?\}\}/);
        let lineRange = document.lineAt(position);

        let fullPath = this.getRequestVariableCompletionPath(wordRange, lineRange, position);

        if (!fullPath) {
            return undefined;
        }

        const match = fullPath.match(/(\w+)\.(.*?)?/);
        if (!match || !this.checkIfRequestVariableDefined(document, match[1])) {
            return [];
        }

        if (firstPartRegex.test(fullPath)) {
            return [
                new CompletionItem("request", CompletionItemKind.Field),
                new CompletionItem("response", CompletionItemKind.Field),
            ];
        } else if (secondPartRegex.test(fullPath)) {
            return [
                new CompletionItem("body", CompletionItemKind.Field),
                new CompletionItem("headers", CompletionItemKind.Field),
            ];
        }

        const requestVariables = await RequestVariableProvider.Instance.getAll(document);
        for (const { name, value } of requestVariables) {
            // Only add completion items for headers
            const regex = new RegExp(`^(${name})\.(?:request|response)\.headers\.$`);
            if (regex.test(fullPath)) {
                // Remove last dot if present
                fullPath = fullPath.replace(/\.$/, '');

                const result = RequestVariableCacheValueProcessor.resolveRequestVariable(value as RequestVariableCacheValue, fullPath);
                if (result.state === ResolveState.Warning && result.message === ResolveWarningMessage.MissingHeaderName) {
                    const {value} = result;
                    return Object.keys(value).map(p => {
                        let item = new CompletionItem(p);
                        item.detail = `HTTP ${ElementType[ElementType.RequestCustomVariable]}`;
                        item.documentation = new MarkdownString(`Value: \`${value[p]}\``);
                        item.insertText = p;
                        item.kind = CompletionItemKind.Field;
                        return item;
                    });
                }
            }
        }

        return;
    }
 return bat.errors.filter(x => x.node).map(error => {
   var startPos = doc.positionAt(error.node.startPosition);
   var endPos = doc.positionAt(error.node.endPosition);
   var decoration = {
     range: new Range(startPos, endPos),
     hoverMessage: error.toString()
   };
   return decoration;
 });
Example #18
0
	private isLast(document: TextDocument, position: Position): boolean {
		const scanner = createScanner(document.getText(), true);
		scanner.setPosition(document.offsetAt(position));
		let nextToken = scanner.scan();
		if (nextToken === SyntaxKind.StringLiteral && scanner.getTokenError() === ScanError.UnexpectedEndOfString) {
			nextToken = scanner.scan();
		}
		return nextToken === SyntaxKind.CloseBraceToken || nextToken === SyntaxKind.EOF;
	}
Example #19
0
export function byteOffsetAt(document: TextDocument, position: Position): number {
	let offset = document.offsetAt(position);
	let text = document.getText();
	let byteOffset = 0;
	for (let i = 0; i < offset; i++) {
		let clen = Buffer.byteLength(text[i]);
		byteOffset += clen;
	}
	return byteOffset;
}
Example #20
0
export function getModifiedRange(textDocument: TextDocument, diff: LineChange): Range {
	if (diff.modifiedEndLineNumber === 0) {
		if (diff.modifiedStartLineNumber === 0) {
			return new Range(textDocument.lineAt(diff.modifiedStartLineNumber).range.end, textDocument.lineAt(diff.modifiedStartLineNumber).range.start);
		} else {
			return new Range(textDocument.lineAt(diff.modifiedStartLineNumber - 1).range.end, textDocument.lineAt(diff.modifiedStartLineNumber).range.start);
		}
	} else {
		return new Range(textDocument.lineAt(diff.modifiedStartLineNumber - 1).range.start, textDocument.lineAt(diff.modifiedEndLineNumber - 1).range.end);
	}
}
	private getRange(document: TextDocument, outline: as.Outline): Range {
		// The outline's location includes whitespace before the block but the elements
		// location only includes the small range declaring the element. To give the best
		// experience to the user (perfectly highlight the range) we take the start point
		// from the element but the end point from the outline.

		let startPos = document.positionAt(outline.element.location.offset);
		let endPos = document.positionAt(outline.offset + outline.length);

		return new Range(startPos, endPos);
	}
 provideDocumentRangeFormattingEdits(
     document: TextDocument,
     range: Range,
     options: FormattingOptions,
     token: CancellationToken
 ): Promise<TextEdit[]> {
     return this._provideEdits(document, {
         rangeStart: document.offsetAt(range.start),
         rangeEnd: document.offsetAt(range.end),
     });
 }
    public static isVariableDefinition(document: TextDocument, position: Position): boolean {
        let wordRange = document.getWordRangeAtPosition(position);
        let lineRange = document.lineAt(position);
        if (!wordRange
            || wordRange.start.character < 1
            || lineRange.text[wordRange.start.character - 1] !== '@') {
            // not a custom variable definition syntax
            return false;
        }

        return true;
    }
    public async provideDefinition(document: TextDocument, position: Position, token: CancellationToken): Promise<Definition> {
        if (!VariableUtility.isVariableReference(document, position)) {
            return;
        }

        let documentLines = document.getText().split(Constants.LineSplitterRegex);

        let wordRange = document.getWordRangeAtPosition(position);
        let selectedVariableName = document.getText(wordRange);

        let locations = VariableUtility.getDefinitionRanges(documentLines, selectedVariableName);
        return locations.map(location => new Location(document.uri, location));
    }
    return new Promise<Definition>((resolve, reject) => {
      let wordRange = document.getWordRangeAtPosition(position);
      let symbol = document.getText(wordRange);
      // TODO Maybe change this to use the System temp dir instead of one under ~/.lein
      let command = `(do (require 'clojure.repl)
                        (require 'clojure.java.shell)
                        (require 'clojure.java.io)
                        (let [var-sym '${symbol}
                              the-var (or (some->> (or (get (ns-aliases *ns*) var-sym) (find-ns var-sym))
                                                  clojure.repl/dir-fn
                                                  first
                                                  name
                                                  (str (name var-sym) "/")
                                                  symbol)
                                          var-sym)
                              {:keys [file line]} (meta (eval \`(var ~the-var)))
                              file-path (.getPath (.getResource (clojure.lang.RT/baseLoader) file))]
                          (if-let [[_
                                    jar-path
                                    partial-jar-path
                                    within-file-path] (re-find #"file:(.+/\\.m2/repository/(.+\\.jar))!/(.+)" file-path)]
                            (let [decompressed-path (str (System/getProperty "user.home")
                                                        "/.lein/tmp-atom-jars/"
                                                        partial-jar-path)
                                  decompressed-file-path (str decompressed-path "/" within-file-path)
                                  decompressed-path-dir (clojure.java.io/file decompressed-path)]
                              (when-not (.exists decompressed-path-dir)
                                (println "decompressing" jar-path "to" decompressed-path)
                                (.mkdirs decompressed-path-dir)
                                (clojure.java.shell/sh "unzip" jar-path "-d" decompressed-path))
                              [decompressed-file-path line])
                            [file-path line])))`;
      // Use the REPL to find the definition point
      self.connection.eval(command, (cErr: any, cResult: any) => {
        if (cResult && cResult.length > 0) {
          var def: Location[] = [];
          let results = cResult[0]["value"];
          if (results != null) {
            let res = edn.parse(results);
            let uri = Uri.file(res.at(0));
            let line = res.at(1);
            let pos = new Position(line, 0);
            def = [new Location(uri, pos)];
          }

          resolve(def);
        } else {
          reject(cErr);
        }
      });
    });
Example #26
0
	public provideHover(document: TextDocument, position: Position, token: CancellationToken): Hover {
		let wordRange = document.getWordRangeAtPosition(position);
		if (!wordRange) {
			return;
		}

		let name = document.getText(wordRange);

		var entry = phpGlobals.globalfunctions[name] || phpGlobals.compiletimeconstants[name] || phpGlobals.globalvariables[name] || phpGlobals.keywords[name];
		if (entry && entry.description) {
			let signature = name + (entry.signature || '');
			let contents: MarkedString[] = [entry.description, { language: 'php', value: signature }];
			return new Hover(contents, wordRange);
		}
	}
Example #27
0
 return new Promise( (resolve, reject) => {
     
     let wordRange = document.getWordRangeAtPosition( position );
     let word = document.getText( wordRange )
     
     var finder = new VariableFinder();
     var results = finder.findDefinitionInText( document.getText(), word );
     
     if( results.length > 0 ) {
         let hover = new Hover( {language: 'cm', value: `${results[0].type} ${word}` } );
         resolve( hover ); 
     } else {
         resolve();
     }
 });
Example #28
0
async function doValidate(document: TextDocument) {
	let report = null;

	let documentWasClosed = false; // track whether the document was closed while getInstalledModules/'npm ls' runs
	const listener = workspace.onDidCloseTextDocument(doc => {
		if (doc.uri === document.uri) {
			documentWasClosed = true;
		}
	});

	try {
		report = await getInstalledModules(path.dirname(document.fileName));
	} catch (e) {
		listener.dispose();
		return;
	}
	try {
		diagnosticCollection.clear();

		if (report.invalid && report.invalid === true) {
			return;
		}
		if (!anyModuleErrors(report)) {
			return;
		}
		if (documentWasClosed || !document.getText()) {
			return;
		}
		const sourceRanges = parseSourceRanges(document.getText());
		const dependencies = report.dependencies;
		const diagnostics: Diagnostic[] = [];

		for (var moduleName in dependencies) {
			if (dependencies.hasOwnProperty(moduleName)) {
				const diagnostic = getDiagnostic(document, report, moduleName, sourceRanges);
				if (diagnostic) {
					diagnostic.source = 'npm';
					diagnostics.push(diagnostic);
				}
			}
		}
		//console.log("diagnostic count ", diagnostics.length, " ", document.uri.fsPath);
		diagnosticCollection.set(document.uri, diagnostics);
	} catch (e) {
		window.showInformationMessage(`[npm-script-runner] Cannot validate the package.json ` + e);
		console.log(`npm-script-runner: 'error while validating package.json stacktrace: ${e.stack}`);
	}
}
Example #29
0
			return this.client.execute('formatonkey', args, token).then((response): TextEdit[] => {
				let edits = response.body;
				let result: TextEdit[] = [];
				if (!edits) {
					return result;
				}
				for (let edit of edits) {
					let textEdit = this.codeEdit2SingleEditOperation(edit);
					let range = textEdit.range;
					// Work around for https://github.com/Microsoft/TypeScript/issues/6700.
					// Check if we have an edit at the beginning of the line which only removes white spaces and leaves
					// an empty line. Drop those edits
					if (range.start.character === 0 && range.start.line === range.end.line && textEdit.newText === '') {
						let lText = document.lineAt(range.start.line).text;
						// If the edit leaves something on the line keep the edit (note that the end character is exclusive).
						// Keep it also if it removes something else than whitespace
						if (lText.trim().length > 0 || lText.length > range.end.character) {
							result.push(textEdit);
						}
					} else {
						result.push(textEdit);
					}
				}
				return result;
			}, (err: any) => {
	public run(doc: TextDocument, pos: Position, state: MotionState): Position {
		let lineContent = doc.lineAt(pos.line).text;

		if (pos.character >= lineContent.length - 1) {
			// cursor at end of line
			return ((pos.line + 1 < doc.lineCount) ? new Position(pos.line + 1, 0) : pos);
		}

		let nextWord = Words.findNextWord(doc, pos, state.wordCharacterClass);

		if (!nextWord) {
			// return end of the line
			return Motions.EndOfLine.run(doc, pos, state);
		}

		if (nextWord.start <= pos.character && pos.character < nextWord.end) {
			// Sitting on a word
			let nextNextWord = Words.findNextWord(doc, new Position(pos.line, nextWord.end), state.wordCharacterClass);
			if (nextNextWord) {
				// return start of the next next word
				return new Position(pos.line, nextNextWord.start);
			} else {
				// return end of line
				return Motions.EndOfLine.run(doc, pos, state);
			}
		} else {
			// return start of the next word
			return new Position(pos.line, nextWord.start);
		}
	}