vscode#TextDocumentChangeEvent TypeScript Examples

The following examples show how to use vscode#TextDocumentChangeEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: spFileHandlers.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
/**
 * Handle the changes in a document by creating a new FileItem object and parsing the file, even if it wasn't saved.
 * @param  {ItemsRepository} itemsRepo      The itemsRepository object constructed in the activation event.
 * @param  {TextDocumentChangeEvent} event  The document change event triggered by the file change.
 * @returns void
 */
export function handleDocumentChange(
  itemsRepo: ItemsRepository,
  event: TextDocumentChangeEvent
) {
  const fileUri = event.document.uri.toString();
  const filePath: string = event.document.uri.fsPath.replace(".git", "");

  let fileItems = new FileItems(fileUri);
  itemsRepo.documents.add(fileUri);
  // We use parseText here, otherwise, if the user didn't save the file, the changes wouldn't be registered.
  try {
    parseText(
      event.document.getText(),
      filePath,
      fileItems,
      itemsRepo,
      false,
      false
    );
  } catch (error) {
    console.log(error);
  }
  readUnscannedImports(itemsRepo, fileItems.includes);
  itemsRepo.fileItems.set(fileUri, fileItems);
  parseText(
    event.document.getText(),
    filePath,
    fileItems,
    itemsRepo,
    true,
    false
  );
}
Example #2
Source File: WorkspaceWatcher.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
/** This version of `onDidChangeTextDocument` is debounced for a shorter time, and is useful for UI updates that should happen quickly. */
  async quickOnDidChangeTextDocument(event: TextDocumentChangeEvent) {
    try {
      // `workspace.onDidChangeTextDocument` fires 2 events for every change
      // the second one changing the dirty state of the page from `true` to `false`
      if (event.document.isDirty === false) {
        return;
      }

      const ctx = {
        ctx: "WorkspaceWatcher:quickOnDidChangeTextDocument",
        uri: event.document.uri.fsPath,
      };
      Logger.debug({ ...ctx, state: "enter" });
      this._quickDebouncedOnDidChangeTextDocument.cancel();
      const uri = event.document.uri;
      const { wsRoot, vaults } = this._extension.getDWorkspace();
      if (
        !WorkspaceUtils.isPathInWorkspace({
          wsRoot,
          vaults,
          fpath: uri.fsPath,
        })
      ) {
        Logger.debug({ ...ctx, state: "uri not in workspace" });
        return;
      }
      Logger.debug({ ...ctx, state: "trigger change handlers" });
      const activeEditor = window.activeTextEditor;
      if (activeEditor?.document.uri.fsPath === event.document.uri.fsPath) {
        this._windowWatcher.triggerUpdateDecorations(activeEditor);
      }
      Logger.debug({ ...ctx, state: "exit" });
      return;
    } catch (error) {
      Sentry.captureException(error);
      throw error;
    }
  }
Example #3
Source File: listener.ts    From vscode-discord with MIT License 6 votes vote down vote up
public listen() {
		// just make sure that no double registration happens
		this.dispose();

		const fileSwitch = window.onDidChangeActiveTextEditor,
			fileEdit = workspace.onDidChangeTextDocument,
			debugStart = debug.onDidStartDebugSession,
			debugEnd = debug.onDidTerminateDebugSession,
			diagnostictsChange = languages.onDidChangeDiagnostics;

		if (this.config.get("showFile"))
			this.disposables.push(
				fileSwitch((e: TextEditor) => this.parser.fileSwitch(e)),
				fileEdit((e: TextDocumentChangeEvent) =>
					this.parser.fileEdit(e)
				)
			);

		if (this.config.get("showDebugging"))
			this.disposables.push(
				debugStart(() => this.parser.toggleDebug()),
				debugEnd(() => this.parser.toggleDebug())
			);

		if (this.config.get("showProblems"))
			this.disposables.push(
				diagnostictsChange(() => this.parser.diagnosticsChange())
			);
	}
Example #4
Source File: parser.ts    From vscode-discord with MIT License 6 votes vote down vote up
public fileEdit({ document }: TextDocumentChangeEvent) {
    if (document.fileName.endsWith(".git") || document.languageId == "scminput")
      return;

    const info = new PathInfo(document);
    this.presence.largeImageKey = info.icon;
    this.presence.details = this.makeDetails(activity.editing, info);
    this.presence.state = this.makeState({ info });
    if (this.config.get("showFileInfo"))
      this.presence.largeImageText = this.makeFileInfo(document);
    this.update();
  }
Example #5
Source File: events.ts    From vscode-todo-md with MIT License 6 votes vote down vote up
/**
 * Called when active text document changes (typing in it, for instance)
 */
export function onChangeTextDocument(e: TextDocumentChangeEvent) {
	const activeTextEditor = window.activeTextEditor;
	if (activeTextEditor && $state.theRightFileOpened) {
		updateEverything(activeTextEditor);
	}
}
Example #6
Source File: DoUpdateCache.ts    From vscode-alxmldocumentation with MIT License 5 votes vote down vote up
constructor() {
        const subscriptions: Disposable[] = []; 
        var changeTimeout: NodeJS.Timeout | null;
        var cancellation: { cancel: (reason?: any) => void, token: CancellationToken } | null = null;
        
        workspace.onDidDeleteFiles(async (event: FileDeleteEvent) => {
            event.files.forEach(fileUri => {
                ALObjectCache.ALObjects.filter(alObject => (alObject.Uri === fileUri)).forEach(alObject => {
                    ALObjectCache.ALObjects.splice(ALObjectCache.ALObjects.indexOf(alObject), 1); // remove object from cache
                });
            });
        });

        workspace.onDidChangeTextDocument(async (event: TextDocumentChangeEvent) => {
            if ((!event.document) || (event.document.languageId !== 'al')) {
                return;
            }

            if (event.contentChanges.length === 0) {
                return;
            }

            // clear timer to avoid update AL object cache while typing
            if (changeTimeout !== null) {
                clearTimeout(changeTimeout);
            }

            // send cancellation request to previously started process
            if (cancellation !== null) {
                cancellation.cancel();
            }
    
            // create cancellation token
            cancellation = CancellationToken.create();

            // avoid starting update AL object cache while typing
            changeTimeout = setInterval(function(token: CancellationToken) {
                if (changeTimeout !== null) {
                    clearTimeout(changeTimeout);
                }
                changeTimeout = null;

                ALSyntaxUtil.ClearALObjectFromCache(event.document);
                ALSyntaxUtil.GetALObject(event.document, token);
            }, 500, cancellation.token);
        }, this, subscriptions);
        
        this.disposable = Disposable.from(...subscriptions);
    }
Example #7
Source File: spItemsRepository.ts    From sourcepawn-vscode with MIT License 5 votes vote down vote up
public handleDocumentChange(event: TextDocumentChangeEvent) {
    refreshDiagnostics(event.document);
    refreshCfgDiagnostics(event.document);
    handleDocumentChange(this, event);
    updateDecorations(this);
  }
Example #8
Source File: activator.ts    From plugin-vscode with Apache License 2.0 5 votes vote down vote up
function showDiagramEditor(context: ExtensionContext, langClient: ExtendedLangClient): void {
	const didChangeDisposable = workspace.onDidChangeTextDocument(
		_.debounce((e: TextDocumentChangeEvent) => {
			if (activeEditor && (e.document === activeEditor.document) &&
				e.document.fileName.endsWith('.bal')) {
				if (preventDiagramUpdate) {
					return;
				}
				updateWebView(e.document.uri);
			}
		}, DEBOUNCE_WAIT));

	const changeActiveEditorDisposable = window.onDidChangeActiveTextEditor(
		(activatedEditor: TextEditor | undefined) => {
			if (window.activeTextEditor && activatedEditor
				&& (activatedEditor.document === window.activeTextEditor.document)
				&& activatedEditor.document.fileName.endsWith('.bal')) {
				activeEditor = window.activeTextEditor;
				updateWebView(activatedEditor.document.uri);
			}
		});

	if (diagramViewPanel) {
		diagramViewPanel.reveal(ViewColumn.Two, true);
		return;
	}
	// Create and show a new webview
	diagramViewPanel = window.createWebviewPanel(
		'ballerinaDiagram',
		"Ballerina Diagram",
		{ viewColumn: ViewColumn.Two, preserveFocus: true },
		getCommonWebViewOptions()
	);

	diagramViewPanel.iconPath = {
		light: Uri.file(join(context.extensionPath, 'resources/images/icons/design-view.svg')),
		dark: Uri.file(join(context.extensionPath, 'resources/images/icons/design-view-inverse.svg'))
	};

	const editor = window.activeTextEditor;
	if (!editor) {
		return;
	}
	activeEditor = editor;
	rpcHandler = WebViewRPCHandler.create(diagramViewPanel, langClient);
	const html = render(editor.document.uri);
	if (diagramViewPanel && html) {
		diagramViewPanel.webview.html = html;
	}

	diagramViewPanel.onDidDispose(() => {
		diagramViewPanel = undefined;
		didChangeDisposable.dispose();
		changeActiveEditorDisposable.dispose();
	});
}
Example #9
Source File: split-provider.ts    From plugin-vscode with Apache License 2.0 5 votes vote down vote up
public updateDocument(event: TextDocumentChangeEvent) {
        const editor = window.activeTextEditor;
        if (!editor || !editor.document.fileName.endsWith('.bal') || event.contentChanges.length === 0) {
            return;
        }

        let documentChange: TextDocumentContentChangeEvent | undefined;
        event.contentChanges.forEach(change => {
            if (change.text.startsWith(newLine)) {
                documentChange = change;
            }
        });

        if (!documentChange) {
            return;
        }

        const range: Range = documentChange!.range;
        if (this instanceof BallerinaExtension) {
            if (!this.langClient) {
                return;
            }
            const extension: BallerinaExtension = this;
            this.langClient.getSyntaxTreeNode({
                documentIdentifier: {
                    uri: editor.document.uri.toString()
                },
                range: {
                    start: {
                        line: range.start.line,
                        character: range.start.character
                    },
                    end: {
                        line: range.end.line,
                        character: range.end.character
                    }
                }
            }).then((response) => {
                if (!response.kind) {
                    return;
                }
                if (response.kind === STRING_LITERAL) {
                    sendTelemetryEvent(extension, TM_EVENT_STRING_SPLIT, CMP_STRING_SPLIT);
                    editor.edit(editBuilder => {
                        const startPosition = new Position(range.start.line, range.start.character);
                        const nextLinePosition = new Position(range.start.line + 1, documentChange!.text.length - 1);
                        const endPosition = new Position(range.end.line + 1, documentChange!.text.indexOf('\n'));
                        editBuilder.insert(startPosition, `\" +${newLine}`);
                        editBuilder.insert(nextLinePosition, `\"`);
                        editBuilder.delete(new Range(startPosition, endPosition));
                    });
                }
            });
        }
    }
Example #10
Source File: extension.ts    From utopia with MIT License 5 votes vote down vote up
function didChangeTextChange(path: string, event: TextDocumentChangeEvent): DidChangeTextChange {
  return {
    type: 'DID_CHANGE_TEXT',
    path: path,
    event: event,
  }
}
Example #11
Source File: WorkspaceWatcher.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
private _quickDebouncedOnDidChangeTextDocument: DebouncedFunc<
    (event: TextDocumentChangeEvent) => Promise<void>
  >;
Example #12
Source File: TextDocumentService.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
   * See {@link ITextDocumentService.processTextDocumentChangeEvent}
   */
  public async processTextDocumentChangeEvent(event: TextDocumentChangeEvent) {
    if (event.document.isDirty === false) {
      return;
    }

    const document = event.document;
    const contentChanges = event.contentChanges;

    const ctx = "TextDocumentService:processTextDocumentChangeEvent";
    const uri = document.uri;
    const fname = path.basename(uri.fsPath, ".md");

    const { wsRoot, vaults } = this._extension.getDWorkspace();
    if (
      !WorkspaceUtils.isPathInWorkspace({ wsRoot, vaults, fpath: uri.fsPath })
    ) {
      this.L.debug({ ctx, uri: uri.fsPath, msg: "not in workspace, ignoring" });
      return;
    }

    const maybePos = await this.getFrontmatterPosition(document);
    let fmChangeOnly = false;
    if (!maybePos) {
      this.L.debug({ ctx, uri: uri.fsPath, msg: "no frontmatter found" });
      return;
    }
    if (contentChanges) {
      const allChangesInFM = _.every(contentChanges, (contentChange) => {
        const endPosition = contentChange.range.end;
        return endPosition.isBefore(maybePos);
      });
      if (allChangesInFM) {
        this.L.debug({ ctx, uri: uri.fsPath, msg: "frontmatter change only" });
        fmChangeOnly = true;
      }
    }

    this.L.debug({ ctx, uri: uri.fsPath });
    const engine = this._extension.getEngine();
    const vault = VaultUtils.getVaultByFilePath({
      vaults: engine.vaults,
      wsRoot: this._extension.getEngine().wsRoot,
      fsPath: uri.fsPath,
    });
    const noteHydrated = NoteUtils.getNoteByFnameFromEngine({
      fname,
      vault,
      engine,
    });
    if (_.isUndefined(noteHydrated)) {
      return;
    }

    const content = document.getText();
    if (!WorkspaceUtils.noteContentChanged({ content, note: noteHydrated })) {
      this.L.debug({
        ctx,
        uri: uri.fsPath,
        msg: "note content unchanged, ignoring",
      });
      return noteHydrated;
    }

    return this.updateNoteContents({
      oldNote: noteHydrated,
      content,
      fmChangeOnly,
      fname,
      vault,
    });
  }