Skip to content

Instantly share code, notes, and snippets.

@lucascosti
Last active December 21, 2020 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lucascosti/ed14f857a63a1088cefa5fcf6aee68e6 to your computer and use it in GitHub Desktop.
Save lucascosti/ed14f857a63a1088cefa5fcf6aee68e6 to your computer and use it in GitHub Desktop.
Atom function & command to wrap text in something (markdown link)
# Put this in to your Atom's init.coffee file
# Generic function to wrap text in something (original from https://discuss.atom.io/t/wrap-selection-in-html-tag-command/22318/7)
# set multiLine to false to split selections into single line
# You can set a cursor position in `before` or `after` using `$1`
wrapSelections = (editor, before, after, multiLine = true) ->
editor.transact ->
editor.splitSelectionsIntoLines() unless multiLine
cursorPositions = for selection in editor.getSelections()
# check if the before/after contains a cursor position
if before.indexOf("$1") != -1
# position is in before
cursorOffset = before.indexOf('$1')
else if after.indexOf("$1") != -1
# position is in after
cursorOffset = before.length+selection.getText().length+after.indexOf('$1')
else
# else put the cursor at the end of the selection
cursorOffset = before.length+selection.getText().length+after.length
cursorPosition = selection.getBufferRange().start.translate [0, cursorOffset]
#replace the selection text
selection.insertText("#{before.replace '$1', ''}#{selection.getText()}#{after.replace '$1', ''}")
cursorPosition
for cursorPosition, i in cursorPositions
if i == 0
editor.setCursorBufferPosition cursorPosition
else
editor.addCursorAtBufferPosition cursorPosition
# Add command to wrap selected text in markdown link
atom.commands.add 'atom-text-editor', 'custom:markdown-link', ->
wrapSelections @getModel(), '[', ']($1)', false
@lucascosti
Copy link
Author

To create a keymapping for the above command, and scope that keymapping just to markdown files, you can add something like the following to your Atom's keymap.cson file:

"atom-text-editor[data-grammar='source gfm']":
  'cmd-shift-K': 'custom:markdown-link'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment