Conditional keybinding behaviour


#1

I would like to be able to execute different commands depending if there is a selection or not. Like this:

  • When I have any text selected, ctrl+c copies that text.
  • When I have no selection, ctrl+c copies the entire line (including \n).

Another case is:

  • When I have a normal text copied to clipboard, ctrl+v paste that text whenever the cursor is.
  • When I used the second copy case and have a entire line copied, paste it before the line where the cursor is.

I’m not sure if this is the default behaviour on Sublime Text, but it’s what I use and it’s really useful.


#2

I did something similar.


#3

Thank you @AbeEstrada.

I took your code and extended it to behave more like Sublime does.
It’s my first atom code, I hope it isn’t that bad:

init.coffee:

atom.workspaceView.command 'custom:copyline', ->
  editor = atom.workspace.getActiveEditor()
  if not editor.getSelectedText()
    cursor = editor.getCursor()
    originalPosition = cursor.getScreenPosition()
    editor.selectLine()
    editor.copySelectedText()
    cursor.setScreenPosition(originalPosition)
  else
    editor.copySelectedText()
atom.workspaceView.command 'custom:cutline', ->
  editor = atom.workspace.getActiveEditor()
  if not editor.getSelectedText()
    cursor = editor.getCursor()
    originalPosition = cursor.getScreenPosition()
    editor.selectLine()
    editor.cutSelectedText()
    cursor.setScreenPosition(originalPosition)
  else
    editor.cutSelectedText()
atom.workspaceView.command 'custom:pasteline', ->
  editor = atom.workspace.getActiveEditor()
  clipboardText = atom.clipboard.read()
  if clipboardText.indexOf('\n') == clipboardText.length - 1 and not editor.getSelectedText()
    cursor = editor.getCursor()
    originalPosition = cursor.getScreenPosition()
    cursor.moveToBeginningOfLine()
    editor.pasteText()
    originalPosition.row += 1
    cursor.setScreenPosition(originalPosition)
  else
    editor.pasteText()

keymap.cson:

'body':
  'ctrl-c': 'custom:copyline'
  'ctrl-x': 'custom:cutline'
  'ctrl-v': 'custom:pasteline'

Possible to chain actions together somehow?
#4

nice work, really apreciated :blush: