@@ -684,6 +684,49 @@ export function insertCommonmarkTableCommand(
684684 }
685685}
686686
687+ /**
688+ * Inserts a horizontal rule at the cursor
689+ * @param state The current editor state
690+ * @param dispatch the dispatch function used to dispatch the transaction, set to "null" if you don't want to dispatch
691+ */
692+ export function insertCommonmarkHorizontalRuleCommand (
693+ state : EditorState ,
694+ dispatch : ( tr : Transaction ) => void
695+ ) {
696+ // figure out how many leading newlines we need to add
697+ // adding only a single newline after text will result in the thematic break
698+ // being parsed as an setext heading; e.g. header1\n---
699+ const precedingText = state . doc . cut ( 0 , state . selection . from ) . textContent ;
700+ const lastNewlineIdx = precedingText . lastIndexOf ( "\n" ) ;
701+ const currentLine = precedingText . slice ( lastNewlineIdx + 1 ) ;
702+
703+ // check the previous line as well
704+ let prevLine : string = null ;
705+ if ( lastNewlineIdx > - 1 ) {
706+ const prevNewlineIdx = precedingText . lastIndexOf (
707+ "\n" ,
708+ lastNewlineIdx - 1
709+ ) ;
710+ // even if no additional newline is found, we can assume an index of (-1 + 1), which is the beginning of the text
711+ prevLine = precedingText . slice ( prevNewlineIdx + 1 , lastNewlineIdx ) ;
712+ }
713+
714+ let newlines : string ;
715+
716+ if ( ! precedingText || ( ! prevLine && ! currentLine ) ) {
717+ // beginning of doc or multiple empty lines - no newlines
718+ newlines = "" ;
719+ } else if ( ! currentLine ) {
720+ // no text in current line - one newline
721+ newlines = "\n" ;
722+ } else {
723+ // text in current line - two newlines
724+ newlines = "\n\n" ;
725+ }
726+
727+ return insertRawTextCommand ( newlines + "---\n" , 4 , 4 ) ( state , dispatch ) ;
728+ }
729+
687730//TODO
688731function indentBlockCommand ( ) : boolean {
689732 return false ;
@@ -740,8 +783,6 @@ export const strikethroughCommand = wrapInCommand("~~", null);
740783export const blockquoteCommand = setBlockTypeCommand ( ">" ) ;
741784export const orderedListCommand = setBlockTypeCommand ( "1." ) ;
742785export const unorderedListCommand = setBlockTypeCommand ( "-" ) ;
743- export const insertCommonmarkHorizontalRuleCommand =
744- insertRawTextCommand ( "\n---\n" ) ;
745786export const insertCodeblockCommand = blockWrapInCommand ( "```" ) ;
746787export const spoilerCommand = setBlockTypeCommand ( ">!" ) ;
747788export const supCommand = wrapInCommand ( "<sup>" , "</sup>" ) ;
0 commit comments