Skip to content

Commit

Permalink
fix #25, fix #24, Added "enable_keymap" option to the plugin settings…
Browse files Browse the repository at this point in the history
… in order to allow quick enabling/disabling of the default plugin keymaps
  • Loading branch information
pichillilorenzo committed Jan 25, 2018
1 parent f0fa07b commit bf6b3fc
Show file tree
Hide file tree
Showing 15 changed files with 206 additions and 48 deletions.
3 changes: 3 additions & 0 deletions JavaScript Enhancements.sublime-settings
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@
"angularv1_custom_path": "yo",
"angularv2_custom_path": "ng",
"react_custom_path": "create-react-app",
"react_native_custom_path": "create-react-native-app",
"express_custom_path": "express",
"yeoman_custom_path": "yo",

"enable_keymap": true,

"enable_can_i_use_menu_option": true,
"enable_unused_variables_feature": true
}
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ If all is going in the right way, you will see `JavaScript Enhancements - instal

### Fixing node.js and npm custom path

If the plugin gives to you message errors like `Error during installation: "node.js" seems not installed on your system...` but instead you have installed node.js and npm (for example using [nvm](https://github.com/creationix/nvm)), then you could try to set your custom path in the [Global settings](https://github.com/pichillilorenzo/JavaScriptEnhancements/wiki/Global-settings) of the plugin and then restart Sublime Text.
If the plugin gives to you message errors like `Error during installation: "node.js" seems not installed on your system...` but instead you have installed node.js and npm (for example using [nvm](https://github.com/creationix/nvm)), then you could try to set your custom path in the [Global settings](https://github.com/pichillilorenzo/JavaScriptEnhancements/wiki/Global-settings) of the plugin and then restart Sublime Text.

If you don't know the path of them, use `which node`/`which npm` (for Linux-based OS) or `where node.exe`/`where npm` (for Windows OS) to get it.

If this doesn't work too, then you could try to add the custom path that contains binaries of node.js and npm in the **`PATH`** key-value on the same JavaScript Enhancements settings file. This variable will be **appended** to the **$PATH** environment variable, so you could use the same syntax in it. After this you need to restart Sublime Text. Example of a global setting for `Linux` that uses `nvm`:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from shutil import copyfile
from threading import Timer

PLUGIN_VERSION = "0.13.14"
PLUGIN_VERSION = "0.13.15"

PACKAGE_PATH = os.path.abspath(os.path.dirname(__file__))
PACKAGE_NAME = os.path.basename(PACKAGE_PATH)
Expand Down Expand Up @@ -887,7 +887,7 @@ def execute(command, command_args, chdir="", wait_terminate=True, func_stdout=No

env = os.environ.copy()
env["PATH"] = env["PATH"] + javascriptCompletions.get("PATH")
shell = os.getenv('SHELL')
shell = None if sublime.platform() == 'windows' else '/bin/bash'

with subprocess.Popen(args, shell=True, executable=shell, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=(None if not chdir else chdir)) as p:

Expand Down Expand Up @@ -917,7 +917,7 @@ def _wrapper_func_stdout(args, func_stdout, args_func_stdout=[], chdir=""):

env = os.environ.copy()
env["PATH"] = env["PATH"] + javascriptCompletions.get("PATH")
shell = os.getenv('SHELL')
shell = None if sublime.platform() == 'windows' else '/bin/bash'

with subprocess.Popen(args, shell=True, executable=shell, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, preexec_fn=os.setsid, cwd=(None if not chdir else chdir)) as p:

Expand Down Expand Up @@ -1277,6 +1277,12 @@ def close(self) :
self.socket = None


KEYMAP_COMMANDS = []
keymaps = Util.open_json(os.path.join(PACKAGE_PATH, 'Default.sublime-keymap'))
for keymap in keymaps:
if keymap["command"] != "window_view_keypress":
KEYMAP_COMMANDS += [keymap["command"]]

def sublime_executable_path():
executable_path = sublime.executable_path()

Expand Down Expand Up @@ -1329,11 +1335,17 @@ def init(self):
node_modules_path = os.path.join(PACKAGE_PATH, "node_modules")
npm = NPM()
if not os.path.exists(node_modules_path):
sublime.active_window().status_message("JavaScript Enhancements - installing npm dependencies...")
animation_npm_installer = AnimationLoader(["[= ]", "[ = ]", "[ = ]", "[ = ]", "[ =]", "[ = ]", "[ = ]", "[ = ]"], 0.067, "JavaScript Enhancements - installing npm dependencies ")
interval_animation = RepeatedTimer(animation_npm_installer.sec, animation_npm_installer.animate)
# sublime.active_window().status_message("JavaScript Enhancements - installing npm dependencies...")
result = npm.install_all()
if result[0]:
animation_npm_installer.on_complete()
interval_animation.stop()
sublime.active_window().status_message("JavaScript Enhancements - npm dependencies installed correctly.")
else:
animation_npm_installer.on_complete()
interval_animation.stop()
print(result)
if os.path.exists(node_modules_path):
shutil.rmtree(node_modules_path)
Expand Down Expand Up @@ -1666,10 +1678,11 @@ def run(self, **kwargs):
self.command = ["$(which "+shlex.quote(self.path_cli)+")"]
self.path_cli = self.settings["project_settings"]["node_js_custom_path"] or javascriptCompletions.get("node_js_custom_path")

if not self.command:
self.command = kwargs.get("command")
else:
self.command += [kwargs.get("command")]
if kwargs.get("command"):
if not self.command:
self.command = kwargs.get("command")
else:
self.command += kwargs.get("command")

self.prepare_command(**kwargs)

Expand All @@ -1694,11 +1707,11 @@ def run(self, **kwargs):
self.command = ["$(which "+shlex.quote(self.path_cli)+")"]
self.path_cli = javascriptCompletions.get("node_js_custom_path")


if not self.command:
self.command = kwargs.get("command")
else:
self.command += [kwargs.get("command")]
if kwargs.get("command"):
if not self.command:
self.command = kwargs.get("command")
else:
self.command += kwargs.get("command")

self.prepare_command(**kwargs)

Expand Down Expand Up @@ -3362,6 +3375,8 @@ def find_prev(self, regions):
return previous_regions[len(previous_regions)-1] if len(previous_regions) > 0 else None


import sublime, sublime_plugin

class wait_modified_asyncViewEventListener():
last_change = time.time()
waiting = False
Expand All @@ -3381,9 +3396,7 @@ def wait(self):
self.waiting = True
else :
return
self.last_change = time.time()
while time.time() - self.last_change <= self.wait_time:
time.sleep(.1)
sublime.set_timeout(self.wait_time)
self.waiting = False

def on_modified_async_with_thread(self, *args, **kwargs):
Expand All @@ -3392,6 +3405,15 @@ def on_modified_async_with_thread(self, *args, **kwargs):

import sublime, sublime_plugin

class enableKeymap(sublime_plugin.EventListener):

def on_text_command(self, view, command_name, args):

if command_name in KEYMAP_COMMANDS and not javascriptCompletions.get("enable_keymap"):
return ("noop", {})

import sublime, sublime_plugin

class surround_withCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
view = self.view
Expand Down Expand Up @@ -4030,7 +4052,7 @@ def load_default_autocomplete(view, comps_to_campare, prefix, location, isHover

scope = view.scope_name(location-(len(prefix)+1)).strip()

if scope.endswith(" punctuation.accessor.js") :
if scope.endswith(" punctuation.accessor.js") or scope.endswith(" keyword.operator.accessor.js") :
return []

prefix = prefix.lower()
Expand Down Expand Up @@ -5603,7 +5625,7 @@ def on_modified_async_with_thread(self, recheck=True):

repetitions[variableName] = [variableRegion]

items = Util.nested_lookup("type", ["VariableDeclarator", "MemberExpression", "CallExpression", "BinaryExpression", "ExpressionStatement", "Property", "ArrayExpression", "ObjectPattern", "AssignmentExpression", "IfStatement", "ForStatement", "WhileStatement", "ForInStatement", "ForOfStatement", "LogicalExpression", "UpdateExpression", "ArrowFunctionExpression", "ConditionalExpression", "JSXIdentifier", "ExportDefaultDeclaration", "JSXExpressionContainer", "NewExpression", "ReturnStatement"], body)
items = Util.nested_lookup("type", ["VariableDeclarator", "MemberExpression", "CallExpression", "BinaryExpression", "ExpressionStatement", "Property", "ArrayExpression", "ObjectPattern", "AssignmentExpression", "IfStatement", "ForStatement", "WhileStatement", "ForInStatement", "ForOfStatement", "LogicalExpression", "UpdateExpression", "ArrowFunctionExpression", "ConditionalExpression", "JSXIdentifier", "ExportDefaultDeclaration", "JSXExpressionContainer", "NewExpression", "ReturnStatement", "SpreadProperty", "TemplateLiteral"], body)
for item in items:

if "exportKind" in item and "declaration" in item and isinstance(item["declaration"],dict) and "name" in item["declaration"] and item["declaration"]["type"] == "Identifier":
Expand All @@ -5629,6 +5651,12 @@ def on_modified_async_with_thread(self, recheck=True):

item = item["callee"]

elif "expressions" in item and item["expressions"]:
for expression in item["expressions"]:
if isinstance(expression,dict) and "name" in expression and expression["type"] == "Identifier":
items += [expression]
continue

elif "left" in item or "right" in item:

if "left" in item and isinstance(item["left"],dict) and "name" in item["left"] and item["left"]["type"] == "Identifier":
Expand Down Expand Up @@ -5935,7 +5963,7 @@ def start():
print("node.js version: " + str(node.getCurrentNodeJSVersion()))
except Exception as err:
print(err)
response = sublime.yes_no_cancel_dialog("Error during installation: \"node.js\" seems not installed on your system. Node.js and npm are required to be able to use JavaScript Enhancements plugin.\n\nIf you are using \"nvm\" or you have a different path for node.js and npm, please then change the path on:\n\nPreferences > Package Settings > JavaScript Enhancements > Settings\n\nand restart Sublime Text.\n\nIf this doesn't work then try also to add the path of their binaries in the PATH key-value on the same JavaScript Enhancements settings file. This variable will be used to add them in the $PATH environment variable, so put the symbol \":\" (instead \";\" for Windows) in front of your path.\n\nDo you want open the website of node.js?", "Yes, open it", "Or use nvm")
response = sublime.yes_no_cancel_dialog("Error during installation: \"node.js\" seems not installed on your system. Node.js and npm are required to be able to use JavaScript Enhancements plugin.\n\nIf you are using \"nvm\" or you have a different path for node.js and npm, please then change the path on:\n\nPreferences > Package Settings > JavaScript Enhancements > Settings\n\nand restart Sublime Text. If you don't know the path of it, use \"which node\" (for Linux-based OS) or \"where node.exe\" (for Windows OS) to get it.\n\nIf this doesn't work then try also to add the path of their binaries in the PATH key-value on the same JavaScript Enhancements settings file. This variable will be used to add them in the $PATH environment variable, so put the symbol \":\" (instead \";\" for Windows) in front of your path.\n\nDo you want open the website of node.js?", "Yes, open it", "Or use nvm")
if response == sublime.DIALOG_YES:
sublime.active_window().run_command("open_url", args={"url": "https://nodejs.org"})
elif response == sublime.DIALOG_NO:
Expand All @@ -5947,7 +5975,7 @@ def start():
print("npm version: " + str(npm.getCurrentNPMVersion()))
except Exception as err:
print(err)
response = sublime.yes_no_cancel_dialog("Error during installation: \"npm\" seems not installed on your system. Node.js and npm are required to be able to use JavaScript Enhancements plugin.\n\nIf you are using \"nvm\" or you have a different path for node.js and npm, please change their custom path on:\n\nPreferences > Package Settings > JavaScript Enhancements > Settings\n\nand restart Sublime Text.\n\nIf this doesn't work then try also to add the path of their binaries in the PATH key-value on the same JavaScript Enhancements settings file. This variable will be used to add them in the $PATH environment variable, so put the symbol \":\" (instead \";\" for Windows) in front of your path.\n\nDo you want open the website of node.js?", "Yes, open it", "Or use nvm")
response = sublime.yes_no_cancel_dialog("Error during installation: \"npm\" seems not installed on your system. Node.js and npm are required to be able to use JavaScript Enhancements plugin.\n\nIf you are using \"nvm\" or you have a different path for node.js and npm, please change their custom path on:\n\nPreferences > Package Settings > JavaScript Enhancements > Settings\n\nand restart Sublime Text. If you don't know the path of it, use \"which npm\" (for Linux-based OS) or \"where npm\" (for Windows OS) to get it.\n\nIf this doesn't work then try also to add the path of their binaries in the PATH key-value on the same JavaScript Enhancements settings file. This variable will be used to add them in the $PATH environment variable, so put the symbol \":\" (instead \";\" for Windows) in front of your path.\n\nDo you want open the website of node.js?", "Yes, open it", "Or use nvm")
if response == sublime.DIALOG_YES:
sublime.active_window().run_command("open_url", args={"url": "https://nodejs.org"})
elif response == sublime.DIALOG_NO:
Expand Down
95 changes: 95 additions & 0 deletions changelog/0.13.15.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
v0.13.15

## Fixes

- Fixed "zsh shell doesn't recognize node.js" #25, using "/bin/bash" shell instead
- Fixed other issues with Unused variable feature #24

## Improvements

- Added "enable_keymap" option to the plugin settings in order to allow quick enabling/disabling of the default plugin keymaps.



=================================================================
** THIS PLUGIN IS IN BETA! Thanks for your support in advance! **
=================================================================

If you like it, remember to star it ⭐ on GitHub: https://github.com/pichillilorenzo/JavaScriptEnhancements

** USAGE **
===========

See how it works on the Wiki: 👉👉 https://github.com/pichillilorenzo/JavaScriptEnhancements/wiki 👈👈


** WHAT IS THIS? **
===================

This plugin uses Flow (javascript static type checker from Facebook) under the hood.

It offers better javascript autocomplete and a lot of features about creating,
developing and managing javascript projects, such as:

- Cordova projects (run cordova emulate, build, compile, serve, etc. directly from Sublime Text!)
- Ionic v1 and v2 projects (same as Cordova projects!)
- Angular v1 and v2 projects
- React projects (only about the creation at this moment)
- React Native projects (only about the creation at this moment. I will add also NativeScript support)
- Express projects (only about the creation at this moment)
- Yeoman generators
- Local bookmarks project
- JavaScript real-time errors
- etc.

You could use it also in existing projects (see the Wiki - https://github.com/pichillilorenzo/JavaScriptEnhancements/wiki/Using-it-with-an-existing-project)!

It turns Sublime Text into a JavaScript IDE like!

This project is based on my other Sublime Text plugin JavaScript Completions (https://github.com/pichillilorenzo/JavaScript-Completions)

** NOTE **
If you want use this plugin, you may want uninstall/disable the JavaScript Completions plugin, if installed.

** OS SUPPORTED NOW **
======================

👉 Linux (64-bit)
👉 Mac OS X
👉 Windows (64-bit): released without the use of TerminalView plugin. For each feature (like also creating a project) will be used the cmd.exe shell (so during the creation of a project don't close it until it finishes!). Unfortunately the TerminalView plugin supports only Linux-based OS 😞. Has someone any advice or idea about that? Is there something similar to the TerminalView plugin for Windows?? Thanks!

❗❗ Dependencies ❗❗
=======================

In order to work properly, this plugin has some dependencies:

👉 Sublime Text 3 (build 3124 or newer)
👉 Node.js and npm (https://nodejs.org or nvm (https://github.com/creationix/nvm))
👉 TerminalView (only for Linux and Mac OS X) sublime text plugin (https://github.com/Wramberg/TerminalView)

Not required, but useful for typescript files (Flow wont work on this type of files):

👉 TypeScript sublime text plugin (https://github.com/Microsoft/TypeScript-Sublime-Plugin)

** Flow Requirements **
=======================

It use [Flow](https://github.com/facebook/flow) for type checking and auto-completions.

👉 Mac OS X
👉 Linux (64-bit)
👉 Windows (64-bit)

Email me for any questions or doubts about this new project on: [email protected]

** Donation **
==============

If this project help you reduce time to develop and also you like it, please support it with a donation 😄👍. Thanks!

Open Collective: https://opencollective.com/javascriptenhancements/donate
PayPal: https://www.paypal.me/LorenzoPichilli

Thanks anyway for your support! 😄😄

MIT License
8 changes: 8 additions & 0 deletions helper/enable_keymap_event_listener.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import sublime, sublime_plugin

class enableKeymap(sublime_plugin.EventListener):

def on_text_command(self, view, command_name, args):

if command_name in KEYMAP_COMMANDS and not javascriptCompletions.get("enable_keymap"):
return ("noop", {})
2 changes: 1 addition & 1 deletion helper/javascript_completions/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def load_default_autocomplete(view, comps_to_campare, prefix, location, isHover

scope = view.scope_name(location-(len(prefix)+1)).strip()

if scope.endswith(" punctuation.accessor.js") :
if scope.endswith(" punctuation.accessor.js") or scope.endswith(" keyword.operator.accessor.js") :
return []

prefix = prefix.lower()
Expand Down
2 changes: 2 additions & 0 deletions helper/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

${include wait_modified_async_view_event_listener.py}

${include enable_keymap_event_listener.py}

${include surround_with_command.py}

${include delete_surrounded_command.py}
Expand Down
8 changes: 7 additions & 1 deletion helper/unused_variables_view_event_listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def on_modified_async_with_thread(self, recheck=True):

repetitions[variableName] = [variableRegion]

items = Util.nested_lookup("type", ["VariableDeclarator", "MemberExpression", "CallExpression", "BinaryExpression", "ExpressionStatement", "Property", "ArrayExpression", "ObjectPattern", "AssignmentExpression", "IfStatement", "ForStatement", "WhileStatement", "ForInStatement", "ForOfStatement", "LogicalExpression", "UpdateExpression", "ArrowFunctionExpression", "ConditionalExpression", "JSXIdentifier", "ExportDefaultDeclaration", "JSXExpressionContainer", "NewExpression", "ReturnStatement"], body)
items = Util.nested_lookup("type", ["VariableDeclarator", "MemberExpression", "CallExpression", "BinaryExpression", "ExpressionStatement", "Property", "ArrayExpression", "ObjectPattern", "AssignmentExpression", "IfStatement", "ForStatement", "WhileStatement", "ForInStatement", "ForOfStatement", "LogicalExpression", "UpdateExpression", "ArrowFunctionExpression", "ConditionalExpression", "JSXIdentifier", "ExportDefaultDeclaration", "JSXExpressionContainer", "NewExpression", "ReturnStatement", "SpreadProperty", "TemplateLiteral"], body)
for item in items:

if "exportKind" in item and "declaration" in item and isinstance(item["declaration"],dict) and "name" in item["declaration"] and item["declaration"]["type"] == "Identifier":
Expand All @@ -177,6 +177,12 @@ def on_modified_async_with_thread(self, recheck=True):

item = item["callee"]

elif "expressions" in item and item["expressions"]:
for expression in item["expressions"]:
if isinstance(expression,dict) and "name" in expression and expression["type"] == "Identifier":
items += [expression]
continue

elif "left" in item or "right" in item:

if "left" in item and isinstance(item["left"],dict) and "name" in item["left"] and item["left"]["type"] == "Identifier":
Expand Down
Loading

0 comments on commit bf6b3fc

Please sign in to comment.