author linhuiw
 *  desc import { TargetStr } from './define' ; import * as vscode from 'vscode' ; import { updateLangFiles } from './file' ; param arg param val param validateDuplicate export function replaceAndUpdate ( arg , val , validateDuplicate ) { let activeEditor = vscode . window . activeTextEditor ; const currentFilename = activeEditor . document . fileName ; const isHtmlFile = currentFilename . endsWith ( '.html' ) ; const isVueFile = currentFilename . endsWith ( '.vue' ) ; const edit = new vscode . WorkspaceEdit ( ) ; const { document } = vscode . window . activeTextEditor ; let finalReplaceText = arg . text ; if ( arg . isString ) { let startColPostion ; try { startColPostion = arg . range . start . translate ( 0 , - 2 ) ; } catch ( e ) { startColPostion = arg . range . start . translate ( 0 , 0 ) ; } const prevTextRange = new vscode . Range ( startColPostion , arg . range . start ) ; const [ last2Char , last1Char ] = document . getText ( prevTextRange ) . split ( '' ) ; let finalReplaceVal = val ; if ( last2Char === '=' ) { if ( isHtmlFile ) { finalReplaceVal = '{{' + val + '}}' ; } else if ( isVueFile ) { finalReplaceVal = '{{' + val + '}}' ; } else { finalReplaceVal = '{' + val + '}' ; } } if ( last1Char === '`' ) { const varInStr = arg . text . match ( /(\$\{[^\}]+?\})/g ) ; if ( varInStr ) { const kvPair = varInStr . map ( ( str , index ) => { return `val${ index + 1 }: ${ str . replace ( /^\${([^\}]+)\}$/ , '$1' ) }` ; } ) ; finalReplaceVal = `I18N.template(${ val }, { ${ kvPair . join ( ',\n' ) } })` ; varInStr . forEach ( ( str , index ) => { finalReplaceText = finalReplaceText . replace ( str , `{val${ index + 1 }}` ) ; } ) ; } } edit . replace ( document . uri , arg . range . with ( { start : arg . range . start . translate ( 0 , - 1 ) , end : arg . range . end . translate ( 0 , 1 ) } ) , finalReplaceVal ) ; } else { if ( isHtmlFile ) { edit . replace ( document . uri , arg . range , '{{' + val + '}}' ) ; } else if ( isVueFile ) { edit . replace ( document . uri , arg . range , '{{' + val + '}}' ) ; } else { edit . replace ( document . uri , arg . range , '{' + val + '}' ) ; } } try { updateLangFiles ( val , finalReplaceText , validateDuplicate ) ; return vscode . workspace . applyEdit ( edit ) ; } catch ( e ) { return Promise . reject ( e . message ) ; } }