@@ -118,17 +118,26 @@ export function removeAttachmentLinksFromMarkdown(text: string, fileUuid: string
118118 return text ;
119119}
120120
121- function handleClipboardText ( textarea : HTMLTextAreaElement , e : ClipboardEvent , text : string , isShiftDown : boolean ) {
121+ export function pasteAsMarkdownLink ( textarea : { value : string , selectionStart : number , selectionEnd : number } , pastedText : string ) : string | null {
122+ const { value, selectionStart, selectionEnd} = textarea ;
123+ const selectedText = value . substring ( selectionStart , selectionEnd ) ;
124+ const trimmedText = pastedText . trim ( ) ;
125+ const beforeSelection = value . substring ( 0 , selectionStart ) ;
126+ const afterSelection = value . substring ( selectionEnd ) ;
127+ const isInMarkdownLink = beforeSelection . endsWith ( '](' ) && afterSelection . startsWith ( ')' ) ;
128+ const asMarkdownLink = selectedText && isUrl ( trimmedText ) && ! isUrl ( selectedText ) && ! isInMarkdownLink ;
129+ return asMarkdownLink ? `[${ selectedText } ](${ trimmedText } )` : null ;
130+ }
131+
132+ function handleClipboardText ( textarea : HTMLTextAreaElement , e : ClipboardEvent , pastedText : string , isShiftDown : boolean ) {
122133 // pasting with "shift" means "paste as original content" in most applications
123134 if ( isShiftDown ) return ; // let the browser handle it
124135
125136 // when pasting links over selected text, turn it into [text](link)
126- const { value, selectionStart, selectionEnd} = textarea ;
127- const selectedText = value . substring ( selectionStart , selectionEnd ) ;
128- const trimmedText = text . trim ( ) ;
129- if ( selectedText && isUrl ( trimmedText ) && ! isUrl ( selectedText ) ) {
137+ const pastedAsMarkdown = pasteAsMarkdownLink ( textarea , pastedText ) ;
138+ if ( pastedText ) {
130139 e . preventDefault ( ) ;
131- replaceTextareaSelection ( textarea , `[ ${ selectedText } ]( ${ trimmedText } )` ) ;
140+ replaceTextareaSelection ( textarea , pastedAsMarkdown ) ;
132141 }
133142 // else, let the browser handle it
134143}
0 commit comments