Git Product home page Git Product logo

sublime-hooks's Introduction

sublime-hooks

Run Sublime commands on common event hooks (e.g. on_new, on_post_save).

This was designed to give event level bindings to other Sublime plugins.

My use case was to make a request (via sublime-request to a server when a save occurs. The result was:

"on_post_save_user": [
  {
    "command": "request",
    "args": {
      "open_args": ["http://localhost:7060/"]
    },
    "scope": "window"
  }
]

Getting started

Installation

This package is available under hooks inside of Package Control, a Sublime Text plugin that allows for easy management of other plugins.

If you prefer the manual route, you can install the script via the following command in the Sublime Text terminal (ctrl+` ) which utilizes git clone.

import os; path=sublime.packages_path(); (os.makedirs(path) if not os.path.exists(path) else None); window.run_command('exec', {'cmd': ['git', 'clone', 'https://github.com/twolfson/sublime-hooks', 'hooks'], 'working_dir': path})

Packages can be uninstalled via "Package Control: Remove Package" via the command pallete, ctrl+shift+p on Windows/Linux, command+shift+p on Mac.

Creating a new hook

For this exercise, we will be creating a binding that selects all text after a save occurs.

A hook can be added at the User, Project, or Language level. We will add a User level hook.

To edit User settings, open the command pallete, and select "Preferences: Settings - User".

In the opened preferences, create a new key/value pair for on_post_save_user with the following:

"on_post_save_user": [
  {
    "command": "select_all"
  }
]

Then, save twice (once to save settings, another to trigger the plugin).

At this step, all text will be selected, demonstrating the hook and command were run.

Examples of user, project, and language hooks can be found below.

Documentation

Hooks are stored in the User, Project, or Language settings. Each of these expects a list of dictionaries. Each of those dictionaries satisfies the following:

  • command (required), Command for Sublime to run via run_command at the listed scope.
  • args (optional), Dictionary of arguments to be passed to . Comparable to args in "Key Bindings".
  • scope (optional), String indicating where to run command. By default, commands are run in the view. Other options are window and app which run at the window and sublime levels respectively.
"on_post_save_user": [
  {
    // Runs `request` command
    "command": "request",

    // Invokes `request` with `open_args=["http://...:7060/"]`
    "args": {
      "open_args": ["http://localhost:7060/"]
    },

    // Runs `request` via `window.run_command`
    "scope": "window"
  }
]

Accessing settings

User settings are accessed via "Preferences: Settings - User" in the command pallete.

Project settings are accessed via "Project -> Edit Project" from the menu bar. You must be in a saved project for this option to be accessible.

Language settings are accessed via "Preferences -> Settings - More -> Syntax Specific - User". This will open settings specifically for the language in the open file.

Namespacing

Hooks are required to be namespaced at the User, Project, or Language level. The key will be the event_name followed by its _level.

The namespaces are _user, _project, and _language.

For demonstration:

  • An on_new hook at the Project level will be on_new_project
  • An on_load at the Language level will be on_load_language

Events

For both Sublime Text 2 and 3, you will have access to the following events:

  • on_new
  • on_clone
  • on_load
  • on_close
  • on_pre_save
  • on_post_save
  • on_activated
  • on_deactivated

For Sublime Text 3, you gain access to:

  • on_new_async
  • on_clone_async
  • on_load_async
  • on_pre_close
  • on_pre_save_async
  • on_post_save_async
  • on_activated_async
  • on_deactivated_async

Documentation on each hook can be found in the Sublime Text documentation:

Sublime Text 2 - http://www.sublimetext.com/docs/2/api_reference.html#sublime_plugin.EventListener

Sublime Text 3 - http://www.sublimetext.com/docs/3/api_reference.html#sublime_plugin.EventListener

The events not on these lists were excluded due to potential performance issues (e.g. on_modified, on_text_command).

Examples

User

User settings should be defined at the top level in your user's .sublime-settings. This can be accessed either via the Preferences: Settings - User command palette or Preferences -> Settings - User in the menu.

// Inside Packages/User/Preferences.sublime-settings
{
  "ignored_packages": [
  // ...
  ],
  "on_post_save_user": [
    {
      "command": "select_all"
    }
  ]
}

Project

Project settings should be defined under a settings in your current .sublime-project. This can be accessed either via the Project: Edit command palette or Project -> Edit in the menu.

// Inside my-project.sublime-project
{
  "folders": [
  // ...
  ],
  "settings": {
    "on_post_save_project": [
      {
        "command": "select_all"
      }
    ]
  }
}

Language

Language settings should be defined at the top level in your language's .sublime-settings. This can be accessed via Preferences -> Settings - More -> Syntax Specific - User in the menu.

// Inside my-language.sublime-settings
{
  "extensions": [
  // ...
  ],
  "on_post_save_language": [
    {
      "command": "select_all"
    }
  ]
}

Donating

Support this project and others by twolfson via gittip.

Support via Gittip

Unlicense

As of Sep 04 2013, Todd Wolfson has released this repository and its contents to the public domain.

It has been released under the UNLICENSE.

sublime-hooks's People

Contributors

karlhorky avatar olivierblanvillain avatar twolfson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

sublime-hooks's Issues

Getting the file path being saved?

I want to run an external command when a certain file type is saved. I know how to handle the file type part, as well as the external command part. What I'm unsure of, however, is how to get the path of the file in the view being saved, so that I may pass it to that external command.

Am I missing something obvious?

Two errors on sublime text4

On sublime text4 with python3.3 as default compiler, there're two errors:

  1. NameError: global name 're' is not defined
    solution:
    insert
import re

2.FileNotFoundError: [Errno 2] No such file or directory: 'rsync ...'
solution:
insert

import shlex

then replace

 process = subprocess.Popen(command,
                        stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

by

 process = subprocess.Popen(shlex.split(command),
                        stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

Hooks on the project level do not work

Hello,
can you provide a working example of a project-level hook that works on ST3?
I created a project and added this to the .sublime-project:

"on_post_save_project": 
[
    {
        "command": "select_all"
    }
]

This did not work, whereas the same code with _user instead of _project in Settings-User does work. Maybe I am not understanding how to set project-level hooks.

Running build command many times on_pre_save

I have these in my project setting:

{
  "settings":{
    "on_pre_save_project": [
      {
        "command": "build",
        "scope": "window"
      }
    ]
  }, 
  "build_systems": [
    {
      "name": "my_script",
      "cmd": "node script.js $file",
      "working_dir": "c:\\workspace\\app",
      "selector": "source.js"
    }
  ]
}

The script is a dead simple node script

console.log(process.argv);

The build system works when I press F7 on .js file. The console would immediately appear. But when I save the file, my computer would go busy for a while and finally finish the job, showing the console.

If I check the dev console, I would found:

Running node script.js c:\workspace\app\src\app.js
Running node script.js c:\workspace\app\src\app.js
Running node script.js c:\workspace\app\src\app.js
Running node script.js c:\workspace\app\src\app.js
....(repeated for so many times)

I don't know if there is any thing required to return from the on_pre_save hook?

Error on plugin load

Linux - Build 3054, the console says:

Traceback (most recent call last):
  File "/opt/sublime_text/sublime_plugin.py", line 327, in on_deactivated_async
    callback.on_deactivated_async(v)
  File "hooks in /home/olivier/.config/sublime-text-3/Installed Packages/Hooks.sublime-package", line 84, in run_hook_namespace
  File "hooks in /home/olivier/.config/sublime-text-3/Installed Packages/Hooks.sublime-package", line 21, in run_hooks
  File "hooks in /home/olivier/.config/sublime-text-3/Installed Packages/Hooks.sublime-package", line 12, in get_hooks
TypeError: 'NoneType' object is not iterable

Any idea?

Documentation on command scope.

Based on documentation it seems to indicate that a command is in fact a sublime text command and not a command for the command line to be executed. Can this be clarified and also is there a way to trigger a command line execution via the hooks? Ex: /bin/bash --login -c "foobar" by using the hooks plugin?

Syntax in Scope.

can i add specific syntax like (html,css,etc..) in the scope so the command only runs when the currently active file is any of those in the scope?

Post-save hook not running in project scope

I have a command which I would like to run whenever a file is saved in my project. I believe I got it set up and working… but it's not working now. I've tried replacing my command with select_all, to simplify matters, but that didn't help. Here's the contents of the file ./Just.sublime-project in the root of my project:

{
	"folders":
	[
		{
			"path": "."
		}
	],
	"settings": {
		"on_post_save_project": [
			  {
			    "command": "select_all"
			  }
		]
	}
}

Reopening the project and restarting Sublime doesn't help.

I know Hooks is installed and working because when I put this in my user settings, select_all is run as soon as a file is saved, regardless of project:

~/Library/Application Support/Sublime Text/Packages/User/Preferences.sublime-settings

{
// other settings...
  "on_post_save_user": [
    {
      "command": "select_all"
    }
  ]
}

Versions:

  • Sublime Text: 4143
  • Hooks: 0.3.2

Is there a Hooks debug flag I can set to get some idea of what's going on?

File typ matching

Sometimes there is only value to change certain types. Lets say *.js files.
Would be very useful

Add ability to run shell commands

A simple change that would be awesome would be the ability to run shell commands. An example use case would be for files to be pushed remotely on any save.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.