Skip to content

Commit

Permalink
Change TextDocument's getText to take an optional range
Browse files Browse the repository at this point in the history
TextDocument's getText() function has been changed to take an
optional range in the form of getText(range?: Range). This allows
clients to extract a substring within the document instead of the
entire document. Ranges that start at a position smaller than the
document will be adjusted to the beginning of the document. Likewise,
ranges that end beyond the length of the document will be adjusted to
end within the bounds of the document.

Signed-off-by: Remy Suen <remy.suen@gmail.com>
  • Loading branch information
rcjsuen committed Dec 25, 2017
1 parent fd152c3 commit aef70a7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
13 changes: 10 additions & 3 deletions types/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1460,11 +1460,13 @@ export interface TextDocument {
readonly version: number;

/**
* Get the text of this document.
* Get the text of this document. A substring can be retrieved by
* providing a range.
*
* @param range The interested range within the document to return.
* @return The text of this document.
*/
getText(): string;
getText(range?: Range): string;

/**
* Converts a zero-based offset to a position.
Expand Down Expand Up @@ -1607,7 +1609,12 @@ class FullTextDocument implements TextDocument {
return this._version;
}

public getText(): string {
public getText(range?: Range): string {
if (range) {
let start = this.offsetAt(range.start);
let end = this.offsetAt(range.end);
return this._content.substring(start, end);
}
return this._content;
}

Expand Down
13 changes: 12 additions & 1 deletion types/src/test/textdocument.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
'use strict';

import assert = require('assert');
import { TextDocument, Position } from '../main';
import { TextDocument, Range, Position } from '../main';

suite('Text Document Lines Model Validator', () => {
function newDocument(str: string) {
Expand Down Expand Up @@ -62,6 +62,17 @@ suite('Text Document Lines Model Validator', () => {
assert.equal(newDocument(str).lineCount, 3);
})

test('getText(Range)', () => {
var str = "12345\n12345\n12345";
var lm = newDocument(str);
assert.equal(lm.getText(), str);
assert.equal(lm.getText(Range.create(-1, 0, 0, 5)), "12345");
assert.equal(lm.getText(Range.create(0, 0, 0, 5)), "12345");
assert.equal(lm.getText(Range.create(0, 4, 1, 1)), "5\n1");
assert.equal(lm.getText(Range.create(0, 4, 2, 1)), "5\n12345\n1");
assert.equal(lm.getText(Range.create(0, 4, 3, 1)), "5\n12345\n12345");
assert.equal(lm.getText(Range.create(0, 0, 3, 5)), str);
});

test('Invalid inputs', () => {
var str = "Hello World";
Expand Down

0 comments on commit aef70a7

Please sign in to comment.