Last active
December 21, 2020 06:57
-
-
Save lucascosti/ed14f857a63a1088cefa5fcf6aee68e6 to your computer and use it in GitHub Desktop.
Atom function & command to wrap text in something (markdown link)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: