@@ -448,13 +448,7 @@ class Resolver {
448448 return parsedNamespaces ;
449449 }
450450
451- sortImports ( ) {
452- let [ useStatements , ] = this . getDeclarations ( ) ;
453-
454- if ( useStatements . length <= 1 ) {
455- throw new Error ( '$(issue-opened) Nothing to sort.' ) ;
456- }
457-
451+ getSortFunction ( ) {
458452 let sortFunction = ( a , b ) => {
459453 if ( this . config ( 'sortAlphabetically' ) ) {
460454 if ( a . text . toLowerCase ( ) < b . text . toLowerCase ( ) ) return - 1 ;
@@ -481,7 +475,21 @@ class Resolver {
481475 } ;
482476 }
483477
484- let sorted = useStatements . slice ( ) . sort ( sortFunction ) ;
478+ return sortFunction ;
479+ }
480+
481+ sortImports ( ) {
482+ const sortFunction = this . getSortFunction ( ) ;
483+
484+ const [ useStatements , sorted ] = ( ( ) => {
485+ if ( this . config ( 'sortBlockWise' ) ) {
486+ const useStatements = this . getUseStatementsArray ( true ) ;
487+ return [ useStatements . flat ( ) , useStatements . map ( block => block . slice ( ) . sort ( sortFunction ) ) . flat ( ) ] ;
488+ }
489+
490+ const useStatements = this . getDeclarations ( ) ;
491+ return [ useStatements , useStatements . slice ( ) . sort ( sortFunction ) ] ;
492+ } ) ( ) ;
485493
486494 this . activeEditor ( ) . edit ( textEdit => {
487495 for ( let i = 0 ; i < sorted . length ; i ++ ) {
@@ -507,21 +515,28 @@ class Resolver {
507515 return false ;
508516 }
509517
510- getUseStatementsArray ( ) {
511- let useStatements = [ ] ;
518+ getUseStatementsArray ( blocked = false ) {
519+ const useStatements = [ ] ;
520+ const matchRegex = new RegExp ( / ^ ( u s e \s [ \w \\ ] + ; ) / , 'g' ) ;
512521
513522 for ( let line = 0 ; line < this . activeEditor ( ) . document . lineCount ; line ++ ) {
514- let text = this . activeEditor ( ) . document . lineAt ( line ) . text ;
515-
516- if ( text . startsWith ( 'use ' ) ) {
517- useStatements . push (
518- text . match ( / ( \w + ?) ; / ) [ 1 ]
519- ) ;
523+ const text = this . activeEditor ( ) . document . lineAt ( line ) . text ;
524+ const matchRes = text . match ( matchRegex ) ;
525+
526+ if ( matchRes != null ) {
527+ const prevLine = this . activeEditor ( ) . document . lineAt ( Math . max ( 0 , line - 1 ) ) . text ;
528+ if ( prevLine === '' || ! prevLine . match ( matchRegex ) || useStatements . length === 0 )
529+ useStatements . push ( [ { text : matchRes [ 0 ] , line } ] ) ;
530+ else
531+ useStatements [ useStatements . length - 1 ] . push ( { text : matchRes [ 0 ] , line } ) ;
520532 } else if ( / ( c l a s s | t r a i t | i n t e r f a c e ) \s + \w + / . test ( text ) ) {
521533 break ;
522534 }
523535 }
524536
537+ if ( ! blocked )
538+ return useStatements . flat ( ) ;
539+
525540 return useStatements ;
526541 }
527542
0 commit comments