@@ -3,7 +3,7 @@ import React from 'react';
3
3
import CodeMirror from 'codemirror' ;
4
4
import emmet from '@emmetio/codemirror-plugin' ;
5
5
import prettier from 'prettier' ;
6
- import parserBabel from 'prettier/parser-babel' ;
6
+ import babelParser from 'prettier/parser-babel' ;
7
7
import htmlParser from 'prettier/parser-html' ;
8
8
import cssParser from 'prettier/parser-postcss' ;
9
9
import { withTranslation } from 'react-i18next' ;
@@ -335,36 +335,31 @@ class Editor extends React.Component {
335
335
this . _cm . execCommand ( 'replace' ) ;
336
336
}
337
337
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
+
338
351
tidyCode ( ) {
339
352
const mode = this . _cm . getOption ( 'mode' ) ;
340
- const currentPosition = this . _cm . doc . getCursor ( ) ;
353
+ let cursorOffset ;
341
354
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 ] ) ;
348
356
} 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 ] ) ;
355
358
} 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 ] ) ;
362
360
}
363
361
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 ) ) ;
368
363
}
369
364
370
365
initializeDocuments ( files ) {
0 commit comments