@@ -3,7 +3,7 @@ import React from 'react';
33import CodeMirror from 'codemirror' ;
44import emmet from '@emmetio/codemirror-plugin' ;
55import prettier from 'prettier' ;
6- import parserBabel from 'prettier/parser-babel' ;
6+ import babelParser from 'prettier/parser-babel' ;
77import htmlParser from 'prettier/parser-html' ;
88import cssParser from 'prettier/parser-postcss' ;
99import { withTranslation } from 'react-i18next' ;
@@ -335,36 +335,31 @@ class Editor extends React.Component {
335335 this . _cm . execCommand ( 'replace' ) ;
336336 }
337337
338+ prettierFormatWithCursor ( parser , plugins ) {
339+ const { formatted, cursorOffset } = prettier . formatWithCursor (
340+ this . _cm . doc . getValue ( ) ,
341+ {
342+ cursorOffset : this . _cm . doc . indexFromPos ( this . _cm . doc . getCursor ( ) ) ,
343+ parser,
344+ plugins
345+ }
346+ ) ;
347+ this . _cm . doc . setValue ( formatted ) ;
348+ return cursorOffset ;
349+ }
350+
338351 tidyCode ( ) {
339352 const mode = this . _cm . getOption ( 'mode' ) ;
340- const currentPosition = this . _cm . doc . getCursor ( ) ;
353+ let cursorOffset ;
341354 if ( mode === 'javascript' ) {
342- this . _cm . doc . setValue (
343- prettier . format ( this . _cm . doc . getValue ( ) , {
344- parser : 'babel' ,
345- plugins : [ parserBabel ]
346- } )
347- ) ;
355+ cursorOffset = this . prettierFormatWithCursor ( 'babel' , [ babelParser ] ) ;
348356 } else if ( mode === 'css' ) {
349- this . _cm . doc . setValue (
350- prettier . format ( this . _cm . doc . getValue ( ) , {
351- parser : 'css' ,
352- plugins : [ cssParser ]
353- } )
354- ) ;
357+ cursorOffset = this . prettierFormatWithCursor ( 'css' , [ cssParser ] ) ;
355358 } else if ( mode === 'htmlmixed' ) {
356- this . _cm . doc . setValue (
357- prettier . format ( this . _cm . doc . getValue ( ) , {
358- parser : 'html' ,
359- plugins : [ htmlParser ]
360- } )
361- ) ;
359+ cursorOffset = this . prettierFormatWithCursor ( 'html' , [ htmlParser ] ) ;
362360 }
363361 this . _cm . focus ( ) ;
364- this . _cm . doc . setCursor ( {
365- line : currentPosition . line ,
366- ch : currentPosition . ch
367- } ) ;
362+ this . _cm . doc . setCursor ( this . _cm . doc . posFromIndex ( cursorOffset ) ) ;
368363 }
369364
370365 initializeDocuments ( files ) {
0 commit comments