Moving up and down through code blocks


#1

Emacs always had a cool way of navigating through code by moving up and down through code blocks. For example, ctrl-up would move you upwards to the next newline, very useful for working around some code. I didn’t find an out-of-the-box way to do this with atom, so I created two commands and bound them to keys for anyone that was interested.
atom.commands.add ‘atom-workspace’, ‘editor:go-down-a-block’, ->
editor = atom.workspace.getActiveTextEditor()#get editor
editor.moveDown()#move down and copy next line
editor.moveToBeginningOfLine()
editor.selectToEndOfLine()
timeout = 0;
text = editor.getLastSelection().getText()# get text and check if empty
loop
timeout++;
editor.moveToBeginningOfLine()
break if timeout > 500
break if text == ''
editor.moveDown()
editor.selectToEndOfLine()
text = editor.getLastSelection().getText()

atom.commands.add ‘atom-workspace’, ‘editor:go-up-a-block’, ->
editor = atom.workspace.getActiveTextEditor()#get editor
editor.moveUp()#move up and copy next line
editor.moveToBeginningOfLine()
editor.selectToEndOfLine()
text = editor.getLastSelection().getText()# get text and check if empty
timeout = 0;
loop
timeout++;
editor.moveToBeginningOfLine()
break if timeout > 500
break if text == ''
editor.moveUp()
editor.selectToEndOfLine()
text = editor.getLastSelection().getText()


#2

I’m not sure how to edit posts and I accidentally hit save by hitting space twice I think. Anyway, here is the code better formatted:

This isn’t very optimized (and probably buggy). Does anyone know a better way to do this?

atom.commands.add 'atom-workspace', 'editor:go-down-a-block', ->
  editor = atom.workspace.getActiveTextEditor()#get editor
  editor.moveDown()#move down and copy next line
  editor.moveToBeginningOfLine()
  editor.selectToEndOfLine()
  timeout = 0;
  text = editor.getLastSelection().getText()# get text and check if empty
  loop
    timeout++;
    editor.moveToBeginningOfLine()
    break if timeout > 500
    break if text == ''
    editor.moveDown()
    editor.selectToEndOfLine()
    text = editor.getLastSelection().getText()

atom.commands.add 'atom-workspace', 'editor:go-up-a-block', ->
    editor = atom.workspace.getActiveTextEditor()#get editor
    editor.moveUp()#move up and copy next line
    editor.moveToBeginningOfLine()
    editor.selectToEndOfLine()
    text = editor.getLastSelection().getText()# get text and check if empty
    timeout = 0;
    loop
      timeout++;
      editor.moveToBeginningOfLine()
      break if timeout > 500
      break if text == ''
      editor.moveUp()
      editor.selectToEndOfLine()
      text = editor.getLastSelection().getText()

#3

There is indeed a better way to do this. There’s a function that moves the cursor to the beginning of the next paragraph, and one to go back. You can make your commands with two lines each.


#4

Thanks! Much better than looping.