import { window , commands , TextEditor , Range , TextDocument , TextLine , Position } from 'vscode' ; import { formatVar } from '..' ; const { activeTextEditor , onDidChangeActiveTextEditor } = window ; let currentEditor ; export const insertVariable = context => { currentEditor = activeTextEditor ; onDidChangeActiveTextEditor ( editor => ( currentEditor = editor ) ) ; context . subscriptions . push ( commands . registerTextEditorCommand ( 'consoleLog.insertVariable' , ( ) => handleCursorInsert ( ) ) ) ; } ; interface WrapData { txt : string ; item : string ; sel : Selection ; doc : TextDocument ; ran : Range ; ind : string ; idx : number ; line : number ; isLastLine : boolean ; } export const handleCursorInsert = ( ) => { new Promise ( ( resolve , reject ) => { const doc = currentEditor . document ; const sel = currentEditor . selection ; const ran = doc . getWordRangeAtPosition ( sel . anchor ) || new Range ( sel . start , sel . end ) ; const lineNumber = ran . start . line ; const item = doc . getText ( ran ) ; const idx = doc . lineAt ( lineNumber ) . firstNonWhitespaceCharacterIndex ; const ind = doc . lineAt ( lineNumber ) . text . substring ( 0 , idx ) ; const logText = formatVar ( item , lineNumber + 2 ) ; const wrapData = { txt : logText , item : item , doc : doc , ran : ran , ind : ind , line : lineNumber , sel : sel , isLastLine : doc . lineCount - 1 === lineNumber } ; resolve ( wrapData ) ; } ) . then ( ( wrap ) => { let nxtLine ; let nxtLineIndex ; if ( ! wrap . isLastLine ) { nxtLine = wrap . doc . lineAt ( wrap . line + 1 ) ; nxtLineIndex = nxtLine . text . substring ( 0 , nxtLine . firstNonWhitespaceCharacterIndex ) ; } currentEditor . edit ( e => { e . insert ( new Position ( wrap . line , wrap . doc . lineAt ( wrap . line ) . range . end . character ) , '\n' . concat ( nxtLineIndex > wrap . ind ? nxtLineIndex : wrap . ind , wrap . txt ) ) ; } ) ; } ) ; } ;