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 Jan 9, 2018
1 parent 020764e commit f9ece22
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
16 changes: 12 additions & 4 deletions types/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1460,11 +1460,14 @@ 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.
*
* @return The text of this document.
* @param range The interested range within the document to return.
* @return The text of this document or a substring of the text if a
* range is provided.
*/
getText(): string;
getText(range?: Range): string;

/**
* Converts a zero-based offset to a position.
Expand Down Expand Up @@ -1607,7 +1610,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 f9ece22

Please sign in to comment.