Is it possible deleteTab command

Hello: I want delete tab when I use Shift-Tab shortcut. But I can’t find any StateCommand.

indentMore and indentLess command affects line. It doesn’t help me.

image

Commands are just functions. Writing one that deletes a tab before the cursor shouldn’t be hard.

1 Like

I was looking for similar functionality, so I build a command for this. Its working for me


import {  indentLess, insertTab, deleteCharBackward } from '@codemirror/commands'


const undoTab: Command = (view) => {
  const { state, dispatch } = view

  /* If there is some selected part in the text of the line, delete the tab  at the start of the line */
  if (state.selection.ranges.some((r) => !r.empty)) return indentLess({ state, dispatch })

  const { doc } = view.state

  let isPreviousCharTab = false

  state.changeByRange((range) => {
    const { from, to } = range
    const line = doc.lineAt(from)
    const { text: lineText, from: lineFrom } = line

    /*
      The actual line string index can be calculated by subtracting lineFrom from the actualFrom 
    */
    const actualTextIndex = from - lineFrom

    const previousChar = lineText?.[actualTextIndex - 1]

    /* 
      If the previous character is a tab, delete that tab otherwise
      trap the shift+tab by returning true which prevents the focus from being moved out of the editor
    */
    if (actualTextIndex > 0 && previousChar === '\t') {
      isPreviousCharTab = true
    }

    return { changes: { from, to }, range: EditorSelection.cursor(from) }
  })

  if (isPreviousCharTab) {
    return deleteCharBackward(view)
  }

  // Notify Codemirror that we are trapping shift+tab
  return true
}


/* 
  Modify the default tabbing behavior CodeMirror provides using its default extension.
  That extension inserts the Tab at the start of the line
  but we are inserting the tab at the cursor positions unless there is no text selected. 
  (In case of selected text, we Tab the whole line)
*/
const insertWithTab: KeyBinding = { key: 'Tab', run: insertTab, shift: undoTab }

4 Likes

Thanks for sharing solution. :clap:

Thanks for sharing solution :smiley:

Thank you for sharing!