aboutsummaryrefslogtreecommitdiff
path: root/atom/packages/vim-mode/lib/operators/put-operator.coffee
blob: 611d6faad21eaf658fb28c4387c4076f27171313 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
_ = require 'underscore-plus'
{Operator} = require './general-operators'
settings = require '../settings'

module.exports =
#
# It pastes everything contained within the specifed register
#
class Put extends Operator
  register: null

  constructor: (@editor, @vimState, {@location}={}) ->
    @location ?= 'after'
    @complete = true
    @register = settings.defaultRegister()

  # Public: Pastes the text in the given register.
  #
  # count - The number of times to execute.
  #
  # Returns nothing.
  execute: (count=1) ->
    {text, type} = @vimState.getRegister(@register) or {}
    return unless text

    textToInsert = _.times(count, -> text).join('')

    selection = @editor.getSelectedBufferRange()
    if selection.isEmpty()
      # Clean up some corner cases on the last line of the file
      if type is 'linewise'
        textToInsert = textToInsert.replace(/\n$/, '')
        if @location is 'after' and @onLastRow()
          textToInsert = "\n#{textToInsert}"
        else
          textToInsert = "#{textToInsert}\n"

      if @location is 'after'
        if type is 'linewise'
          if @onLastRow()
            @editor.moveToEndOfLine()

            originalPosition = @editor.getCursorScreenPosition()
            originalPosition.row += 1
          else
            @editor.moveDown()
        else
          unless @onLastColumn()
            @editor.moveRight()

      if type is 'linewise' and not originalPosition?
        @editor.moveToBeginningOfLine()
        originalPosition = @editor.getCursorScreenPosition()

    @editor.insertText(textToInsert)

    if originalPosition?
      @editor.setCursorScreenPosition(originalPosition)
      @editor.moveToFirstCharacterOfLine()

    if type isnt 'linewise'
      @editor.moveLeft()
    @vimState.activateNormalMode()

  # Private: Helper to determine if the editor is currently on the last row.
  #
  # Returns true on the last row and false otherwise.
  onLastRow: ->
    {row, column} = @editor.getCursorBufferPosition()
    row is @editor.getBuffer().getLastRow()

  onLastColumn: ->
    @editor.getLastCursor().isAtEndOfLine()