Skip to content
Johan West edited this page May 30, 2017 · 4 revisions

Recipes

A collection of "recipes" that can be applied to your Init file to get extended functionality.

NOTE

Code snippets below use adviseBefore from the underscore-plus library. You may want to insert it manually into your Init file:

adviseBefore = (object, methodName, advice) ->
  original = object[methodName]
  object[methodName] = (args...) ->
    unless advice.apply(this, args) == false
      original.apply(this, args)

Pad selection

Created by phyllisstein.

{|foo|} + Space yields {| foo |}

| indicates selection range

atom.workspace.observeTextEditors (editor) ->
  PAIR_REGEXP = /^([\{\[\(])(.*?)([\}\]\)])$/

  wrapSelectionWithPadding = (text) ->
    return true unless text is ' '

    didMutate = false

    editor.mutateSelectedText (selection) ->
      return if selection.isEmpty() or !selection.isSingleScreenLine()

      selectedRange = selection.getBufferRange()
      selectedRange.end.column += 1
      selectedRange.start.column -= 1

      toPad = editor.getTextInBufferRange(selectedRange)

      if toPad = PAIR_REGEXP.exec(toPad)
        padded = " #{toPad[2]} "
        selection.insertText(padded, { select: true })
        didMutate = true

    return !didMutate

  adviseBefore(editor, 'insertText', wrapSelectionWithPadding)

Automatically pad brackets

{ yields { | }

| indicates cursor position

atom.workspace.observeTextEditors (editor) ->
  paddableCharacters =
    '(': ')'
    '[': ']'
    '{': '}'

  autoPadCharacters = (text) ->
    closingCharacter = paddableCharacters[text]
    return true unless closingCharacter

    editor.insertText("#{text}  #{closingCharacter}")
    editor.moveLeft(2)

    false

  adviseBefore(editor, 'insertText', autoPadCharacters)
Clone this wiki locally