import { TextRange } from '../commands' ; export interface TextSection { text : string ; selection : TextRange ; } export function selectWord ( { text , selection } ) { if ( text && text . length && selection . start === selection . end ) { return getSurroundingWord ( text , selection . start ) ; } return selection ; } /**
 *  Gets the number of line-breaks that would have to be inserted before the given 'startPosition'
 *  to make sure there's an empty line between 'startPosition' and the previous text
 */ export function getBreaksNeededForEmptyLineBefore ( text = '' , startPosition ) { if ( startPosition === 0 ) return 0 ; let neededBreaks = 2 ; let isInFirstLine = true ; for ( let i = startPosition - 1 ; i >= 0 && neededBreaks >= 0 ; i -- ) { switch ( text . charCodeAt ( i ) ) { case 32 : continue ; case 10 : neededBreaks -- ; isInFirstLine = false ; break ; default : return neededBreaks ; } } return isInFirstLine ? 0 : neededBreaks ; } /**
 *  Gets the number of line-breaks that would have to be inserted after the given 'startPosition'
 *  to make sure there's an empty line between 'startPosition' and the next text
 */ export function getBreaksNeededForEmptyLineAfter ( text = '' , startPosition ) { if ( startPosition === text . length - 1 ) return 0 ; let neededBreaks = 2 ; let isInLastLine = true ; for ( let i = startPosition ; i < text . length && neededBreaks >= 0 ; i ++ ) { switch ( text . charCodeAt ( i ) ) { case 32 : continue ; case 10 : { neededBreaks -- ; isInLastLine = false ; break ; } default : return neededBreaks ; } } return isInLastLine ? 0 : neededBreaks ; } export function getSurroundingWord ( text , position ) { if ( ! text ) throw Error ( "Argument 'text' should be truthy" ) ; const isWordDelimiter = ( c ) => c === ' ' || c . charCodeAt ( 0 ) === 10 ; let start = 0 ; let end = text . length ; for ( let i = position ; i - 1 > - 1 ; i -- ) { if ( isWordDelimiter ( text [ i - 1 ] ) ) { start = i ; break ; } } for ( let i = position ; i < text . length ; i ++ ) { if ( isWordDelimiter ( text [ i ] ) ) { end = i ; break ; } } return { start , end } ; }