当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript TextDocuments.onDidChangeContent方法代码示例

本文整理汇总了TypeScript中vscode-languageserver.TextDocuments.onDidChangeContent方法的典型用法代码示例。如果您正苦于以下问题:TypeScript TextDocuments.onDidChangeContent方法的具体用法?TypeScript TextDocuments.onDidChangeContent怎么用?TypeScript TextDocuments.onDidChangeContent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在vscode-languageserver.TextDocuments的用法示例。


在下文中一共展示了TextDocuments.onDidChangeContent方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: constructor

	constructor() {
		this.documents = new TextDocuments();
		this.subject = new Subject<DocumentEvent>();

		this.documents.onDidOpen(this.emitDocumentEvent(DocumentEventKind.OPEN));
		this.documents.onDidChangeContent(this.emitDocumentEvent(DocumentEventKind.CHANGE_CONTENT));
		this.documents.onDidClose(this.emitDocumentEvent(DocumentEventKind.CLOSE));
	}
开发者ID:rubyide,项目名称:vscode-ruby,代码行数:8,代码来源:DocumentManager.ts

示例2: constructor

  constructor(
      connection: IConnection, documents: TextDocuments, baseDir: string,
      converter: AnalyzerLSPConverter, logger: Logger) {
    super();
    const fileLoader = new FsUrlLoader(baseDir);
    const inMemoryOverlayLoader = new InMemoryOverlayUrlLoader(fileLoader);
    this.inMemoryDocuments = inMemoryOverlayLoader.urlContentsMap;
    this.urlLoader = inMemoryOverlayLoader;

    const {fire, stream} = EventStream.create<FileEvent[]>();
    this.fileChanges = stream;
    documents.onDidOpen((change) => {
      logger.log(`Opened: ${change.document.uri}`);
    });
    this.disposables.push(documents.onDidChangeContent((change) => {
      logger.log(`Changed in memory: ${change.document.uri}`);
      // A document has changed in memory!
      const url = converter.getAnalyzerUrl(change.document);
      if (!url) {
        return;  // don't care
      }
      this.inMemoryDocuments.set(url, change.document.getText());

      // Publish document change so other parts of the system can react.
      fire([{type: FileChangeType.Changed, uri: change.document.uri}]);
    }));

    this.disposables.push(documents.onDidClose((event) => {
      logger.log(`Closed: ${event.document.uri}`);
      // The file is no longer managed in memory, so we should delete it from
      // the in-memory map.
      const url = converter.getAnalyzerUrl(event.document);
      if (url === undefined) {
        return;  // don't care
      }
      this.inMemoryDocuments.delete(url);
      fire([{type: FileChangeType.Changed, uri: event.document.uri}]);
    }));

    connection.onDidChangeWatchedFiles((req) => {
      for (const change of req.changes) {
        logger.log(`Changed on disk: ${change.uri}`);
      }
      const inMemoryURIs = new Set(documents.keys());
      // We will get documents.onDidChangeContent events for changes of
      // in-memory buffers, so we filter them out to avoid sending duplicate
      // events for those changes.
      const diskBackedChanges =
          req.changes.filter((ch) => !inMemoryURIs.has(ch.uri));
      fire(diskBackedChanges);
    });
  }
开发者ID:MehdiRaash,项目名称:tools,代码行数:52,代码来源:file-synchronizer.ts

示例3:

documents.onDidChangeContent((change) => {
    let diagnostics: Diagnostic[] = [];
    let input = change.document.getText();
    
    try{
        let output = toml.parse(input);
    }catch(e){
        // workaround for typescript limitation
        const ex : TomlSyntaxError = e;

        // content has invalid toml, send diagnostic to client

        // toml parser give position in one based, but languageserver used zero based
        // so we must convert it before send the position
        const startPosition = {line: ex.line - 1, character: ex.column};
        const endPosition = {line: ex.line - 1, character: ex.column + 1};

        diagnostics.push({
            severity: DiagnosticSeverity.Error,
            range: {
                start: startPosition,
                end: endPosition
            },
            message: ex.message,
            source: 'Toml Parser'
        });
    }

    // Send the computed diagnostics to VS Code.
    connection.sendDiagnostics({
        uri: change.document.uri,
        diagnostics
    });      

});
开发者ID:digitaltoad,项目名称:dotfiles,代码行数:35,代码来源:tomlServerMain.ts

示例4: if

			}
		} else if (formatterRegistration) {
			formatterRegistration.then(r => r.dispose());
			formatterRegistration = null;
		}
	}

});

let pendingValidationRequests: { [uri: string]: NodeJS.Timer } = {};
const validationDelayMs = 200;

// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent(change => {
	triggerValidation(change.document);
});

// a document has closed: clear all diagnostics
documents.onDidClose(event => {
	cleanPendingValidation(event.document);
	connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
});

function cleanPendingValidation(textDocument: TextDocument): void {
	let request = pendingValidationRequests[textDocument.uri];
	if (request) {
		clearTimeout(request);
		delete pendingValidationRequests[textDocument.uri];
	}
}
开发者ID:armanio123,项目名称:vscode,代码行数:31,代码来源:htmlServerMain.ts

示例5: trace

}

documents.onDidOpen(async (event) => {
    trace(`onDidOpen: ${event.document.uri}`);

    await validateTextDocument(event.document);
});

// The content of a text document has changed.
// This event is emitted when the text document is first opened or when its content has changed.
documents.onDidChangeContent(async (event) => {
    trace(`onDidChangeContent: ${event.document.uri}`);

    const settings = await settingsCache.get(event.document.uri);

    if (settings && settings.run === "onType") {
        await validateTextDocument(event.document);
    } else if (settings && settings.run === "onSave") {
        // Clear the diagnostics when validating on save and when the document is modified.
        connection.sendDiagnostics({uri: event.document.uri, diagnostics: []});
    }
});

documents.onDidSave(async (event) => {
    trace(`onDidSave: ${event.document.uri}`);

    const settings = await settingsCache.get(event.document.uri);

    if (settings && settings.run === "onSave") {
        await validateTextDocument(event.document);
    }
});
开发者ID:glen-84,项目名称:vscode-sass-lint,代码行数:32,代码来源:sass-lint-server.ts

示例6: debouncedValidateTextDocument

connection.onInitialize((params): InitializeResult => {
  workspaceRoot = params.rootPath;

  const capabilities: ServerCapabilities = {
    documentSymbolProvider: true,
    textDocumentSync: documents.syncKind,
  };

  return {
    capabilities,
  } as InitializeResult;

});

documents.onDidChangeContent((change) => {
  debouncedValidateTextDocument(change.document);
});

documents.onDidClose((event) => {
  connection.sendDiagnostics({ diagnostics: [], uri: event.document.uri });
});

let currentSettings: ApiElementsSettings;
let desideredSymbols = defaultRefractSymbolsTree;

connection.onDidChangeConfiguration((change) => {
  const apiElementsSettings: ApiElementsSettings = change.settings.apiElements;
  currentSettings = lodash.cloneDeep(apiElementsSettings);
  debouncedValidateTextDocument = lodash.debounce(validateTextDocument, apiElementsSettings.validation.debounce);

  const desideredSymbolNames =
开发者ID:XVincentX,项目名称:vscode-apielements,代码行数:31,代码来源:server.ts

示例7: run


//.........这里部分代码省略.........
            }
            lastDurationSelector = new Rx.Subject<number>();
            Rx.Observable.timer(activeSettings.spellCheckDelayMs || defaultDebounce).subscribe(lastDurationSelector);
            return lastDurationSelector;
        })
        .do(doc => log(`Validate: ${doc.uri}`))
        .do(() => lastDurationSelector = undefined)
        .subscribe(validateTextDocument);

    // Clear the diagnostics for documents we do not want to validate
    const disposableSkipValidationStream = validationRequestStream
        .filter(doc => !shouldValidateDocument(doc))
        .do(doc => log(`Skip Validate: ${doc.uri}`))
        .subscribe(doc => {
            connection.sendDiagnostics({ uri: doc.uri, diagnostics: [] });
        });

    const disposableTriggerUpdateConfigStream = triggerUpdateConfig
        .do(() => log('Trigger Update Config'))
        .do(() => activeSettingsNeedUpdating = true)
        .debounceTime(100)
        .subscribe(() => {
            updateActiveSettings();
        });

    const disposableTriggerValidateAll = triggerValidateAll
        .debounceTime(250)
        .subscribe(() => {
            log('Validate all documents');
            documents.all().forEach(doc => validationRequestStream.next(doc));
        });

    validationFinishedStream.next({ uri: 'start', version: 0 });

    function shouldValidateDocument(textDocument: TextDocument): boolean {
        const { uri, languageId } = textDocument;
        return !!getActiveSettings().enabled && isLanguageEnabled(languageId)
            && !isUriExcluded(uri);
    }

    function isLanguageEnabled(languageId: string) {
        const { enabledLanguageIds = []} = getActiveSettings();
        return enabledLanguageIds.indexOf(languageId) >= 0;
    }

    function isUriExcluded(uri: string) {
        return fnFileExclusionTest(uri);
    }

    function getBaseSettings() {
        return {...CSpell.mergeSettings(defaultSettings, getActiveSettings()), enabledLanguageIds: getActiveSettings().enabledLanguageIds};
    }

    function getSettingsToUseForDocument(doc: TextDocument) {
        return tds.constructSettingsForText(getBaseSettings(), doc.getText(), doc.languageId);
    }

    function validateTextDocument(textDocument: TextDocument): void {
        try {
            const settingsToUse = getSettingsToUseForDocument(textDocument);
            if (settingsToUse.enabled) {
                Validator.validateTextDocument(textDocument, settingsToUse).then(diagnostics => {
                    // Send the computed diagnostics to VSCode.
                    validationFinishedStream.next(textDocument);
                    connection.sendDiagnostics({ uri: textDocument.uri, diagnostics });
                });
            }
        } catch (e) {
            console.log(e);
        }
    }

    // Make the text document manager listen on the connection
    // for open, change and close text document events
    documents.listen(connection);

    // The content of a text document has changed. This event is emitted
    // when the text document first opened or when its content has changed.
    documents.onDidChangeContent((change) => {
        validationRequestStream.next(change.document);
    });

    documents.onDidClose((event) => {
        // A text document was closed we clear the diagnostics
        connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
    });

    connection.onCodeAction(onCodeActionHandler(documents, getBaseSettings));

    // Listen on the connection
    connection.listen();

    // Free up the validation streams on shutdown.
    connection.onShutdown(() => {
        disposableSkipValidationStream.unsubscribe();
        disposeValidationStream.unsubscribe();
        disposableTriggerUpdateConfigStream.unsubscribe();
        disposableTriggerValidateAll.unsubscribe();
    });
}
开发者ID:AlekSi,项目名称:vscode-spell-checker,代码行数:101,代码来源:server.ts

示例8: setParser

  return Files.resolveModule(workspaceRoot, 'drafter.js').then((value) => {
    setParser(value, 'Drafter.js');
    return { capabilities: capabilities };
  }, (error) => {
    return Files.resolveModule(workspaceRoot, 'protagonist').then((value) => {
      setParser(value, 'Protagonist');
      return { capabilities: capabilities };
  }, (error) => {
      setParser(require('drafter.js'), 'Ext Drafter.js');
      return { capabilities: capabilities };
    });
  });
});

documents.onDidChangeContent((change) => {
  validateTextDocument(change.document);
});

documents.onDidClose((event) => {
  connection.sendDiagnostics({ uri: event.document.uri, diagnostics: [] });
});

interface Settings {
  apiElements: ApiElementsSettings;
};

interface ApiElementsSettings {
  parser: ParserSettings;
};

interface ParserSettings {
开发者ID:smizell,项目名称:vscode-apielements,代码行数:31,代码来源:server.ts

示例9: run


//.........这里部分代码省略.........
    interface ValidationResult extends vscode.PublishDiagnosticsParams {}

    async function validateTextDocument(dsp: DocSettingPair): Promise<ValidationResult> {
        async function validate() {
            const { doc, settings } = dsp;
            const uri = doc.uri;
            try {
                if (!isUriAllowed(uri, settings.allowedSchemas)) {
                    const schema = uri.split(':')[0];
                    log(`Schema not allowed (${schema}), skipping:`, uri);
                    return { uri, diagnostics: [] };
                }
                const shouldCheck = await shouldValidateDocument(doc, settings);
                if (!shouldCheck) {
                    log('validateTextDocument skip:', uri);
                    return { uri, diagnostics: [] };
                }
                const settingsToUse = await getSettingsToUseForDocument(doc);
                if (settingsToUse.enabled) {
                    logInfo('Validate File', uri);
                    log('validateTextDocument start:', uri);
                    const diagnostics = await Validator.validateTextDocument(doc, settingsToUse);
                    log('validateTextDocument done:', uri);
                    return { uri, diagnostics };
                }
            } catch (e) {
                logError(`validateTextDocument: ${JSON.stringify(e)}`);
            }
            return { uri, diagnostics: [] };
        }

        isValidationBusy = true;
        const r = await validate();
        isValidationBusy = false;
        return r;
    }

    // Make the text document manager listen on the connection
    // for open, change and close text document events
    documents.listen(connection);

    // The content of a text document has changed. This event is emitted
    // when the text document first opened or when its content has changed.
    documents.onDidChangeContent((change) => {
        validationRequestStream.next(change.document);
    });

    documents.onDidClose((event) => {
        const uri = event.document.uri;
        const sub = validationByDoc.get(uri);
        if (sub) {
            validationByDoc.delete(uri);
            sub.unsubscribe();
        }
        // A text document was closed we clear the diagnostics
        connection.sendDiagnostics({ uri, diagnostics: [] });
    });

    connection.onCodeAction(
        onCodeActionHandler(documents, getBaseSettings, () => documentSettings.version, documentSettings)
    );

    // Listen on the connection
    connection.listen();

    // Free up the validation streams on shutdown.
    connection.onShutdown(() => {
        disposableValidate.unsubscribe();
        disposableTriggerUpdateConfigStream.unsubscribe();
        disposableTriggerValidateAll.unsubscribe();
        const toDispose = [...validationByDoc.values()];
        validationByDoc.clear();
        toDispose.forEach(sub => sub.unsubscribe());
    });

    function updateLogLevel() {
        connection.workspace.getConfiguration({ section: 'cSpell.logLevel' }).then(
            (result: string) => {
                fetchFolders();
                logger.level = result;
                logger.setConnection(connection);
            },
            (reject) => {
                fetchFolders();
                logger.level = LogLevel.DEBUG;
                logger.error(`Failed to get config: ${JSON.stringify(reject)}`);
                logger.setConnection(connection);
            }
        );
    }

    async function fetchFolders() {
        const folders = await connection.workspace.getWorkspaceFolders();
        if (folders) {
            setWorkspaceFolders(folders.map(f => f.uri));
        } else {
            setWorkspaceFolders([]);
        }
    }
}
开发者ID:Jason-Rev,项目名称:vscode-spell-checker,代码行数:101,代码来源:server.ts

示例10: log

      documentFormattingProvider: true
    }
  }
})

connection.onInitialized(() => {
  if (hasConfigurationCapability) {
    // Register for all configuration changes.
    connection.client.register(
      DidChangeConfigurationNotification.type,
      undefined
    )
  }
  if (hasWorkspaceFolderCapability) {
    connection.workspace.onDidChangeWorkspaceFolders(event => {
      log("Workspace folder change event received.")
    })
  }
})

connection.onCompletion(completion)
connection.onCompletionResolve((c: CompletionItem) => c)
connection.onDefinition(findDefinition)
connection.onReferences(findReferences)
connection.onDocumentSymbol(documentSymbols)
connection.onDocumentFormatting(formatDocument)
documents.onDidChangeContent(change => syntaxCheck(change.document))

documents.listen(connection)
connection.listen()
开发者ID:valdirmendesgt,项目名称:vscode_abap_remote_fs,代码行数:30,代码来源:server.ts


注:本文中的vscode-languageserver.TextDocuments.onDidChangeContent方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。