Sublime Forum

Add new listen item when pressing enter in markdown

#1

I would like to enter a new list item when I press enter, when I’m in a markdown list. The following code does this.

  // Insert new list item in markdown
  { "keys": ["enter"], "command": "insert_snippet", "args": {"contents": "\n* "}, "context":
    [
      { "key": "selector", "operator": "equal", "operand": "text.html.markdown markup.list.unnumbered.markdown meta.paragraph.list.markdown" },
      { "key": "following_text", "operator": "regex_contains", "operand": "^(?:\t| |\\)|]|;|\\}|$)", "match_all": true }
    ]
  },

However, I would like to end the list and delete the last line (which contains just *) if I press enter without writing anything down.

* List item
* |

After pressing enter:

* List item

|

How would I achieve this?

The only way I’ve thought of is if I can negate the following_text command with \n* as the argument, a new list item will not be created if I press enter when there is a blank line with * in it. However, I don’t know how to remove the last line.

0 Likes

#2

The easiest way to do something like that is via a macro that captures the steps you would manually take. The Default package ships with a macro that might suit:

  { "keys": ["enter"], "command": "run_macro_file", "args": {"file": "res://Packages/Default/Delete Line.sublime-macro"}, "context":
    [
      { "key": "selector", "operator": "equal", "operand": "text.html.markdown markup.list.unnumbered.markdown meta.paragraph.list.markdown" },
      { "key": "preceding_text", "operator": "regex_match", "operand": "^\\s*\\*\\s*$", "match_all": true }
    ]
  },

If enter is pressed while in an unordered list and the item is empty, run the macro to delete the current line.

To achieve what you outlined above, (the blank link between the last item and the cursor) you would need to have a more customized macro. For example, you could save the following in your User package as Delete Line then Newline.sublime-macro:

[
	{"command": "expand_selection", "args": {"to": "line"}},
	{"command": "add_to_kill_ring", "args": {"forward": true}},
	{"command": "left_delete"},
	{"command": "insert", "args": {"characters": "\n"}}
]

Then modify the key binding to use that macro instead:

  { "keys": ["enter"], "command": "run_macro_file", "args": {"file": "res://Packages/User/Delete Line then Newline.sublime-macro"}, "context":
    [
      { "key": "selector", "operator": "equal", "operand": "text.html.markdown markup.list.unnumbered.markdown meta.paragraph.list.markdown" },
      { "key": "preceding_text", "operator": "regex_match", "operand": "^\\s*\\*\\s*$", "match_all": true }
    ]
  },
3 Likes

#3

This is super sweet! Thanks a lot!

0 Likes