Center next/previous diff command

Created by jasonrudolph
Last updated about 1 year ago
atom.commands.add 'atom-text-editor',
  # Approximate Vim's "zz" motion: Scroll the view such that the line containing
  # the cursor is vertically centered in the view.
  'me:scroll-cursor-to-center': ->
    textEditor = atom.workspace.getActiveTextEditor()
    textEditorElement = atom.views.getView(textEditor)
    cursorPosition = textEditor.getCursorScreenPosition()
    pixelPositionForCursorPosition =
      textEditorElement.pixelPositionForScreenPosition(cursorPosition)
    halfScreenHeight = textEditorElement.getHeight() / 2
    scrollTop = pixelPositionForCursorPosition.top - halfScreenHeight
    textEditorElement.setScrollTop(scrollTop)

  # Move the cursor to the next diff in the editor, and then scroll the view
  # such that the line containing the cursor is vertically centered in the view.
  'me:center-next-diff': ->
    editor = atom.workspace.getActiveTextEditor()
    editorView = atom.views.getView(editor)
    atom.commands.dispatch editorView, "git-diff:move-to-next-diff"
    atom.commands.dispatch editorView, "me:scroll-cursor-to-center"

  # Move the cursor to the previous diff in the editor, and then scroll the view
  # such that the line containing the cursor is vertically centered in the view.
  'me:center-previous-diff': ->
    editor = atom.workspace.getActiveTextEditor()
    editorView = atom.views.getView(editor)
    atom.commands.dispatch editorView, "git-diff:move-to-previous-diff"
    atom.commands.dispatch editorView, "me:scroll-cursor-to-center"

################################################################################
# Example keybindings
# -------------------
# I find it handy to trigger these commands via the following keyboard shortcuts
# defined in my keymap.cson file.
################################################################################
# 'atom-workspace atom-text-editor:not(.mini)':
#   'ctrl-g j': 'me:center-next-diff'
#   'ctrl-g k': 'me:center-previous-diff'
#   'ctrl-. z': 'me:scroll-cursor-to-center'