|
| 1 | +{Motion} = require './general-motions' |
| 2 | +path = require 'path' |
| 3 | +{Directory} = require 'atom' |
| 4 | +shell = require 'shell' |
| 5 | +{exec} = require 'child_process' |
| 6 | + |
| 7 | +class OpenFileUnderCursor extends Motion |
| 8 | + execute: (count) -> |
| 9 | + ### |
| 10 | + /usr/bin/test |
| 11 | + ../../.travis.yml |
| 12 | + ./search-motion |
| 13 | + ./index |
| 14 | + http://github.com |
| 15 | + https://thing.com/item%20test |
| 16 | + //github.com |
| 17 | + ### |
| 18 | + wordRegex = /[a-z0-9\.\-_\/\\%:]+/i |
| 19 | + for cursor in @editor.getCursors() |
| 20 | + range = cursor.getCurrentWordBufferRange wordRegex: wordRegex |
| 21 | + selectedPath = @editor.getTextInRange range |
| 22 | + |
| 23 | + # exit early for url match |
| 24 | + if /^https?:/i.test(selectedPath) |
| 25 | + return @openUrl selectedPath |
| 26 | + if /^\/\//i.test(selectedPath) |
| 27 | + return @openUrl "http:#{selectedPath}" |
| 28 | + |
| 29 | + if selectedPath[0] isnt '/' and selectedPath[0] isnt '\\' |
| 30 | + selectedPath = path.join path.dirname(@editor.buffer.file.path), selectedPath |
| 31 | + |
| 32 | + pathDir = path.dirname selectedPath |
| 33 | + dir = new Directory pathDir |
| 34 | + ext = path.extname @editor.buffer.file.path |
| 35 | + dir.getEntries (err, entries) => |
| 36 | + # find any paths that contain the selected path |
| 37 | + matches = entries.filter (entry) -> entry.path.indexOf(selectedPath) > -1 |
| 38 | + return @loadFile matches[0].path if matches.length is 1 |
| 39 | + |
| 40 | + # if there are other possible matches, try to match on extension |
| 41 | + extMatches = matches.filter (entry) -> path.extname(entry.path) is ext |
| 42 | + return @loadFile extMatches[0].path if extMatches.length is 1 |
| 43 | + |
| 44 | + loadFile: (path) -> atom.workspace.open path |
| 45 | + |
| 46 | + openUrl: (url) -> |
| 47 | + # pulled from https://github.com/magbicaleman/open-in-browser/blob/master/lib/open-in-browser.coffee |
| 48 | + process_architecture = process.platform |
| 49 | + switch process_architecture |
| 50 | + when 'darwin' then exec "open '#{url}'" |
| 51 | + when 'linux' then exec "xdg-open '#{url}'" |
| 52 | + when 'win32' then shell.openExternal url |
| 53 | + |
| 54 | +module.exports = OpenFileUnderCursor |
0 commit comments