@@ -788,34 +788,48 @@ export class Yasqe extends CodeMirror {
788788 var min = Math . min ( startLine , endLine ) ;
789789 var max = Math . max ( startLine , endLine ) ;
790790
791- // if all lines start with #, remove this char . Otherwise add this char
791+ // if all lines start with # (after whitespace) , remove the comment . Otherwise add comment
792792 var linesAreCommented = true ;
793793 for ( var i = min ; i <= max ; i ++ ) {
794794 var line = this . getDoc ( ) . getLine ( i ) ;
795- if ( line . length == 0 || line . substring ( 0 , 1 ) != "#" ) {
795+ var trimmedLine = line . trimStart ( ) ;
796+ if ( line . length > 0 && ( trimmedLine . length === 0 || trimmedLine . substring ( 0 , 1 ) !== "#" ) ) {
796797 linesAreCommented = false ;
797798 break ;
798799 }
799800 }
800801 for ( var i = min ; i <= max ; i ++ ) {
801- if ( linesAreCommented ) {
802- // lines are commented, so remove comments
803- this . getDoc ( ) . replaceRange (
804- "" ,
805- {
806- line : i ,
807- ch : 0 ,
808- } ,
809- {
810- line : i ,
811- ch : 1 ,
812- } ,
813- ) ;
814- } else {
802+ var line = this . getDoc ( ) . getLine ( i ) ;
803+ var trimmedLine = line . trimStart ( ) ;
804+ var leadingWhitespace = line . length - trimmedLine . length ;
805+
806+ if ( linesAreCommented && trimmedLine . length > 0 ) {
807+ // lines are commented, so remove the # character (and following space if present)
808+ var commentIndex = line . indexOf ( "#" ) ;
809+ if ( commentIndex >= 0 ) {
810+ var removeLength = 1 ;
811+ // Also remove the space after # if present (e.g., " # code" -> " code")
812+ if ( commentIndex + 1 < line . length && line . charAt ( commentIndex + 1 ) === " " ) {
813+ removeLength = 2 ;
814+ }
815+ this . getDoc ( ) . replaceRange (
816+ "" ,
817+ {
818+ line : i ,
819+ ch : commentIndex ,
820+ } ,
821+ {
822+ line : i ,
823+ ch : commentIndex + removeLength ,
824+ } ,
825+ ) ;
826+ }
827+ } else if ( ! linesAreCommented && line . length > 0 ) {
815828 // Not all lines are commented, so add comments
816- this . getDoc ( ) . replaceRange ( "#" , {
829+ // Insert "# " after the leading whitespace
830+ this . getDoc ( ) . replaceRange ( "# " , {
817831 line : i ,
818- ch : 0 ,
832+ ch : leadingWhitespace ,
819833 } ) ;
820834 }
821835 }
0 commit comments