]> arthur.barton.de Git - atom-ax-pipe.git/blobdiff - lib/pipe.coffee
Don't use editor.{begin|commit}Transaction
[atom-ax-pipe.git] / lib / pipe.coffee
index 7a3b9658495fbd3394c2d62cff31bfbd28027dd4..7c97563e4eb1e2028090ad4a35a7b6e7fa1547ad 100644 (file)
@@ -2,42 +2,69 @@
 {spawn} = require 'child_process'
 CommandView = require './command-view'
 
+history = []
+
 module.exports =
   activate: ->
-    atom.workspaceView.command 'pipe:run', => @run()
+    atom.commands.add 'atom-workspace', "pipe:run", => @run()
 
   run: ->
     editor = atom.workspace.getActiveEditor()
     view = atom.workspaceView.getActiveView()
     return if not editor?
 
-    new CommandView (commandString) ->
+    new CommandView history, (commandString) ->
       if not commandString
         view.focus()
         return
 
-      range = editor.getSelectedBufferRange()
-      stdout = ''
-      stderr = ''
+      history.push commandString
+      if history.length > 300
+        history.shift()
 
-      proc = spawn process.env.SHELL, ["-l", "-c", commandString]
+      if atom.project.rootDirectory?
+        commandString = "cd '#{atom.project.rootDirectory.path}' && #{commandString}"
+      properties = { reversed: true, invalidate: 'never' }
 
-      proc.stdout.on 'data', (text) ->
-        stdout += text
+      ranges = editor.getSelectedBufferRanges()
+      wg = new WaitGroup ->
+        view.focus()
 
-      proc.stderr.on 'data', (text) ->
-        stderr += text
+      wg.add(ranges.length)
 
-      proc.on 'close', (code) ->
-        text = stderr || stdout
-        if not text then return
+      for range, i in ranges
+        marker = editor.markBufferRange range, properties
+        processRange marker, editor, commandString, wg
 
-        if text.slice(-1) is '\n'
-          text = text.slice(0, -1)
+processRange = (marker, editor, commandString, wg) ->
+  stdout = ''
+  stderr = ''
 
-        editor.setTextInBufferRange(range, text)
-        editor.setSelectedBufferRange(new Range(range.start, range.start))
-        view.focus()
+  proc = spawn process.env.SHELL, ["-l", "-c", commandString]
+
+  proc.stdout.on 'data', (text) ->
+    stdout += text
+
+  proc.stderr.on 'data', (text) ->
+    stderr += text
+
+  proc.on 'close', (code) ->
+    text = stderr || stdout
+    editor.setTextInBufferRange(marker.getBufferRange(), text)
+    wg.done()
+
+  proc.stdin.write(editor.getTextInBufferRange(marker.getBufferRange()))
+  proc.stdin.end()
+
+class WaitGroup
+  constructor: (cb) ->
+    @n = 0
+    @cb = cb
+
+  add: (n) ->
+    @n += n
 
-      proc.stdin.write(editor.getSelectedText())
-      proc.stdin.end()
+  done: ->
+    @n -= 1
+    if @n <= 0
+      @cb()