feat(SublimeText2.EditorPackages): cache packages

This commit is contained in:
Iristyle
2013-04-04 08:55:15 -04:00
parent d65666cdfc
commit c3efdad2c2
274 changed files with 26863 additions and 0 deletions

View File

@@ -0,0 +1 @@
TODO.md

View File

@@ -0,0 +1,10 @@
[
{
"caption": "Trailing Spaces: Toggle Trailing Spaces Highlighting",
"command": "toggle_trailing_spaces"
},
{
"caption": "Trailing Spaces: Delete Trailing Spaces",
"command": "delete_trailing_spaces"
}
]

View File

@@ -0,0 +1,20 @@
Copyright 2010 Jean-Denis Vauguet
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,123 @@
[
{
"id": "edit",
"children":
[
{
"caption": "Trailing Spaces",
"id": "trailing-spaces",
"children":
[
{
"command": "delete_trailing_spaces",
"caption": "Delete"
},
{ "caption": "-" },
{
"command": "toggle_trailing_spaces_modified_lines_only",
"caption": "Modified Lines Only",
"checkbox": true
},
{
"command": "toggle_trailing_spaces",
"caption": "Highlight Regions",
"checkbox": true
}
]
}
]
},
{
"id": "preferences",
"children":
[
{
"caption": "Package Settings",
"mnemonic": "P",
"id": "package-settings",
"children":
[
{
"caption": "Trailing Spaces",
"children":
[
{
"command": "open_file",
"args": {
"file": "${packages}/TrailingSpaces/README.md",
"platform": "Windows"
},
"caption": "Help"
},
{
"command": "open_file",
"args": {
"file": "${packages}/TrailingSpaces/README.md",
"platform": "OSX"
},
"caption": "Help"
},
{
"command": "open_file",
"args": {
"file": "${packages}/TrailingSpaces/README.md",
"platform": "Linux"
},
"caption": "Help"
},
{ "caption": "-" },
{
"command": "open_file",
"args": {
"file": "${packages}/TrailingSpaces/trailing_spaces.sublime-settings",
"platform": "Windows"
},
"caption": "Settings - Default"
},
{
"command": "open_file",
"args": {
"file": "${packages}/TrailingSpaces/trailing_spaces.sublime-settings",
"platform": "OSX"
},
"caption": "Settings - Default"
},
{
"command": "open_file",
"args": {
"file": "${packages}/TrailingSpaces/trailing_spaces.sublime-settings",
"platform": "Linux"
},
"caption": "Settings - Default"
},
{
"command": "open_file",
"args": {
"file": "${packages}/User/trailing_spaces.sublime-settings",
"platform": "Windows"
},
"caption": "Settings - User"
},
{
"command": "open_file",
"args": {
"file": "${packages}/User/trailing_spaces.sublime-settings",
"platform": "OSX"
},
"caption": "Settings - User"
},
{
"command": "open_file",
"args": {
"file": "${packages}/User/trailing_spaces.sublime-settings",
"platform": "Linux"
},
"caption": "Settings - User"
}
]
}
]
}
]
}
]

View File

@@ -0,0 +1,313 @@
Trailing Spaces
===============
A [Sublime Text 2](http://www.sublimetext.com/2) and
[3](http://www.sublimetext.com/3) plugin that allows you to…
**highlight trailing spaces and delete them in a flash!**
Synopsis
--------
Sublime Text provides a way to automate deletion of trailing spaces *upon file
saving* (more on this at the end of this file). Depending on your settings, it
may be more handy to just highlight them and/or delete them by hand, at any
time. This plugin provides just that, and a *lot* of options to fine-tune the
way you want to decimate trailing spaces.
Installation
------------
It is available through
[Sublime Package Contol](http://wbond.net/sublime_packages/package_control) and
this is the recommended way of installation (brings configuration instructions,
automatic updates with changelogs…).
### Alternative installation methods
#### From github
You can install from github if you want, although Package Control automates
just that. Go to your `Packages` subdirectory under ST2's data directory:
* Windows: `%APPDATA%\Sublime Text 2`
* OS X: `~/Library/Application Support/Sublime Text 2`
* Linux: `~/.config/sublime-text-2`
* Portable Installation: `Sublime Text 2/Data`
Then clone this repository:
git clone git://github.com/SublimeText/TrailingSpaces.git
#### Manually
[Download](https://github.com/SublimeText/TrailingSpaces/archive/master.zip)
the plugin as a zip. Copy the *Trailing Spaces* directory to its location
(see prior section).
Usage
-----
### Deletion
The main feature you gain from using this plugin is that of deleting all
trailing spaces in the currently edited document. In order to use this
deletion feature, you may either:
* click on "Edit / Trailing Spaces / Delete";
* bind the deletion command to a keyboard shortcut:
To add a key binding, open "Preferences / Key Bindings - User" and add:
``` js
{ "keys": ["ctrl+shift+t"], "command": "delete_trailing_spaces" }
```
With this setting, pressing <kbd>Ctrl + Shift + t</kbd> will delete all
trailing spaces at once in the current file! For OSX users, quoting wbond:
"When porting a key binding across OSes, it is common for the ctrl key on
Windows and Linux to be swapped out for super on OS X"
(eg. use "super+ctrl+t" instead).
*Beware*: the binding from this example overrides the default ST's mapping
for reopening last closed file. You can look at the default bindings in
"Preferences / Key Bindings - Default".
### Toggling highlighting
At any time, you can toggle highlighting on and off. You may either:
- click on "Edit / Trailing Spaces / Highlight Regions"
- bind the toggling command to a keyboard shortcut:
``` js
// I like "d", as in "detect" (overrides a default binding, though).
{ "keys": ["ctrl+shift+d"], "command": "toggle_trailing_spaces" }
```
Options
-------
Several options are available to customize the plugin's behavior. Those
settings are stored in a configuration file, as JSON. You must use a specific
file: Go to "Preferences / Package Settings / Trailing Spaces / Settings
- User" to add you custom settings. You can look at the default values in
"Settings - Default", in the same menu.
A few of them are also accessible through the "Edit / Trailing Spaces" menu.
Sometimes, editing a setting will require a fresh Sublime Text to be applied
properly, so try relaunching ST before reporting an issue ;)
All settings are global (ie. applied to all opened documents).
### Changing the highlighting color
*Default: "invalid"*
You may change the highlighting color, providing a color scope name such as
"error", "comment"… just like that:
``` js
{ "trailing_spaces_highlight_color": "comment" }
```
The scope should be defined in your current theme file. Here is a dummy,
fully-fledged example (feel free to cut irrelevant pieces for your settings)
of such a custom color scope:
``` xml
<dict>
<key>name</key>
<string>Invalid - Illegal</string>
<key>scope</key>
<string>invalid.illegal</string>
<key>settings</key>
<dict>
<key>background</key>
<string>#F93232</string>
<key>fontStyle</key>
<string></string>
<key>foreground</key>
<string>#F9F2CE</string>
</dict>
</dict>
```
You would then use the value of "invalid.illegal".
### Keeping trailing spaces invisible
You can make trailing spaces "invisible" yet still rely on the deletion
command. To do that, set the highlight scope to an empty string:
``` js
{ "trailing_spaces_highlight_color": "" }
```
Beware: this is **not** the same as *disabling* the highlighting (see "On-
Demand Matching" below). With this setting, the plugin still runs when opening
a file, and in the background afterwards; you just won't see the trailing
spaces (they are being highlighted with a "transparent" color).
### Include Current Line
*Default: true*
Highlighting of trailing spaces in the currently edited line can be annoying:
each time you are about to start a new word, the space you type is matched as
a trailing spaces. Currently edited line can thus be ignored:
``` js
{ "trailing_spaces_include_current_line": false }
```
Even though the trailing spaces are not highlighted on this line, they are
still internally matched and will be delete when firing the deletion command.
### Include Empty Lines
*Default: true*
When firing the deletion command, empty lines are matched as trailing regions,
and end up being deleted. You can specifically ignore them:
``` js
{ "trailing_spaces_include_empty_lines": false }
```
They will not be highlighted either.
### Modified Lines Only
*Default: false (reopen ST to update)*
When firing the deletion command, trailing regions *in the entire document* are
deleted. There are some use-cases when deleting trailing spaces *only on lines
you edited* is smarter; for instance when commiting changes to some third-party
source code.
At any time, you can change which area is covered when deleting trailing
regions. You may either:
- click on "Edit / Trailing Spaces / Modified Lines Only"
- specify as a setting:
``` js
{ "trailing_spaces_modified_lines_only": true }
```
There is also a command to toggle this feature on and off. You may thus define
a key binding:
``` js
{ "keys": ["pick+a+shortcut"], "command": "toggle_trailing_spaces_modified_lines_only" }
```
### Trim On Save
*Default: false*
Setting this to `true` will ensure trailing spaces are deleted when you save
your document. It abides by the other settings, such as *Modified Lines Only*.
``` js
{ "trailing_spaces_trim_on_save": true }
```
### Save After Trim
*Default: false*
You may not want to always trim trailing spaces on save, but the other way
around could prove useful. Setting this to `true` will automatically save your
document after you fire the deletion command:
``` js
{ "trailing_spaces_save_after_trim": true }
```
It is obviously ignored if *Trim On Save* is on.
### Live Matching vs On-demand Matching
*Default: true (reopen ST to update)*
By default, trailing regions are matched every time you edit the document, and
when you open it.
This feature is entirely optional and you may set it off: firing the deletion
command will cause the trailing spaces to be deleted as expected even though
they were not matched prior to your request. If you are afraid of the plugin
to cause slowness (for instance, you already installed several *heavy*
plugins), you can disable live matching:
``` js
{ "trailing_spaces_enabled": false }
```
In this case, for no trailing regions are matched until you request them to be
deleted, no highlighting occurs—it is in fact disabled, regardless of your
"scope" setting. If you want to check the trailing spaces regions, you can
toggle highlighting on and off. In this case, it may come in handy to define
a binding for the toggling command. When "On-demand Matching" is on and some
trailing spaces are highlighted, added ones will obviously not be. Toggling
highlight off and on will refresh them.
### For power-users only!
#### Disabled for large files
The plugin is disabled altogether for large files, for it may cause slowness.
The default threshold is around 1 million of characters. This is
configurable (in "File Settings - User") and the unit is number of chars:
``` js
{ "trailing_spaces_file_max_size": 1000}
```
#### The matching pattern
*Default: [ \t]+*
Trailing spaces are line-ending regions containing at least one simple space,
tabs, or both. This pattern should be all you ever need, but if you *do* want
to abide by another definition to cover edge-cases, go ahead:
``` js
// *danger* will match newline chars and many other folks
"trailing_spaces_regexp": "[\\s]+"
```
About Sublime Text's built-in features
--------------------------------------
Trailing Spaces is designed to be a drop-in replacement of the limited
*Trim Whitespace On Save* built-in feature. ST is indeed able to delete
trailing spaces upon saving files, and maybe that's all you need!
In order to enable this behavior, edit "Preferences / Settings - User"
to add the following:
``` js
{ "trim_trailing_white_space_on_save": true }
```
As Trailing Spaces bypasses this setting, you will have to uninstall it to
benefit from this setting.
Made a little less obvious in the documentation are settings to showcase
whitespaces (*not only trailing ones!*):
``` js
{ "draw_white_space": "all" }
```
and to ensure a newline is kept at end of file upon saving:
``` js
{ "ensure_newline_at_eof_on_save": true }
```
The former will display *all* whitespaces in your files. There is another value
of "selection" which display whitespaces under (you got it) your current text
selection.

View File

@@ -0,0 +1,4 @@
{
"install": "messages/install.txt",
"v1.0.0": "messages/v1.0.0.txt"
}

View File

@@ -0,0 +1,40 @@
Thank you for installing Trailing Spaces
----------------------------------------
You're now ready to give trailing spaces *a hard time*!
Wait… I guess Package Control just introduced some of them :(
Why don't you try clicking "Edit / Trailing Spaces / Delete"?
Documentation
=============
Although the usage of this plugin is dead simple, it comes with several options. All
details are available in the documentation, and you can read it by clicking on
"Preferences / Package Settings / Trailing Spaces / Help", or in a prettier form, by
browsing https://github.com/SublimeText/TrailingSpaces.
Key Binding
===========
This plugin does not come with a default key binding for the deletion command. You can
pick your own key binding and define it in "Preferences / Key Bindings - User", or just
stick to using the menu entry under "Edit". Check the help for advice on this.
Upgrades & Issues
=================
Package Control will automatically update all packages every time the editor is started,
so there is nothing for you to worry about. If you however do find the plugin not to work
as it used to, head to the issues tracker (see links below) to report the problem.
Useful Links
============
* Documentation & Code: https://github.com/SublimeText/TrailingSpaces
* Report issues / Request New Features / Roadmap: https://github.com/SublimeText/TrailingSpaces/issues
* Follow me on twitter: @jdvauguet

View File

@@ -0,0 +1,65 @@
Trailing Spaces update [v1.0.0]
-------------------------------
Hope you've been happy gaving trailin' a hard time so far.
I added several features to help you in this honorable quest…
All details accessible through:
"Preferences / Package Settings / Trailing Spaces / Help"
New feature: Modified Lines Only
================================
As proposed by a fellow user, it is now possible to target only the lines
modified by You and You Only when deleting trailing spaces.
This feature will certainly please coders who edit third-party code filled
with trailing spaces but do not want to commit giant diffs, just their little
fix, while keeping it clean.
New feature: Trim On Save
=========================
This option allows for automatic deletion upon saving. No more lost trailing
spaces! A perfect combo to the "Modified Lines Only" setting I guess.
New feature: Save After Trim
============================
A different kind of automation: many users just want those trailings out and
forget 'bout them. It is now made even easier with this auto-saving hook. Fire
the deletion command, and your document is clean on the hard drive!
At the current time, "Trim On Save" and "Save After Trim" cannot be both
enabled (the former wins), but this is on the roadmap.
New Menu
========
Some of the settings seemed a bit more important than the others. Along the
deletion command, the toggling command/state and the "Modified Lines Only"
setting have been elected first-class citizens of the new "Edit / Trailing
Spaces" menu. Any change made by click here is live, persistent and reflected
in the JSON settings file. Settings are global to all open documents.
Improvements & Misc.
====================
- Support for custom matching patterns (danger!).
- Performance improvements (reduced overhead, with some room for further
improvements).
- Better documentation (both code & user doc).
- Lazy "On-demand" matching improved.
Useful Links
============
* Documentation & Code: https://github.com/SublimeText/TrailingSpaces
* Report issues / Request New Features / Roadmap: https://github.com/SublimeText/TrailingSpaces/issues
* Follow me on twitter: @jdvauguet

View File

@@ -0,0 +1 @@
{"url": "https://github.com/SublimeText/TrailingSpaces", "version": "2013.03.07.20.09.52", "description": "Highlight trailing spaces and delete them in a flash."}

View File

@@ -0,0 +1,20 @@
{
"schema_version": "1.2",
"packages": [
{
"name": "TrailingSpaces",
"description": "Highlight trailing spaces and delete them in a flash.",
"author": "Jean-Denis Vauguet",
"homepage": "https://github.com/SublimeText/TrailingSpaces/",
"last_modified": "2013-03-08 01:00:00",
"platforms": {
"*": [
{
"version": "1.0.0",
"url": "https://nodeload.github.com/SublimeText/TrailingSpaces/zip/v1.0.0"
}
]
}
}
]
}

View File

@@ -0,0 +1,453 @@
'''
Provides both a trailing spaces highlighter and a deletion command.
See README.md for details.
@author: Jean-Denis Vauguet <jd@vauguet.fr>, Oktay Acikalin <ok@ryotic.de>
@license: MIT (http://www.opensource.org/licenses/mit-license.php)
@since: 2011-02-25
'''
import sublime
import sublime_plugin
import difflib
import codecs
DEFAULT_MAX_FILE_SIZE = 1048576
DEFAULT_IS_ENABLED = True
DEFAULT_MODIFIED_LINES_ONLY = False
# Global settings object and flags.
# Flags duplicate some of the (core) JSON settings, in case the settings file has
# been corrupted or is empty (ST2 really dislikes that!)
ts_settings_filename = "trailing_spaces.sublime-settings"
ts_settings = None
trailing_spaces_live_matching = DEFAULT_IS_ENABLED
trim_modified_lines_only = DEFAULT_MODIFIED_LINES_ONLY
startup_queue = []
on_disk = None
# Private: Loads settings and sets whether the plugin (live matching) is enabled.
#
# Returns nothing.
def plugin_loaded():
global ts_settings_filename, ts_settings, trailing_spaces_live_matching
global current_highlighting_scope, trim_modified_lines_only, startup_queue
global DEFAULT_COLOR_SCOPE_NAME, on_disk
ts_settings = sublime.load_settings(ts_settings_filename)
trailing_spaces_live_matching = bool(ts_settings.get("trailing_spaces_enabled",
DEFAULT_IS_ENABLED))
current_highlighting_scope = ts_settings.get("trailing_spaces_highlight_color",
"invalid")
DEFAULT_COLOR_SCOPE_NAME = current_highlighting_scope
trim_modified_lines_only = bool(ts_settings.get("trailing_spaces_modified_lines_only",
DEFAULT_MODIFIED_LINES_ONLY))
if trailing_spaces_live_matching:
for view in startup_queue:
match_trailing_spaces(view)
else:
current_highlighting_scope = ""
if ts_settings.get("trailing_spaces_highlight_color") != current_highlighting_scope:
persist_settings()
# Private: Updates user's settings with in-memory values.
#
# Allows for persistent settings from the menu.
#
# Returns nothing.
def persist_settings():
sublime.save_settings(ts_settings_filename)
# Private: Determine if the view is a "Find results" view.
#
# view - the view, you know
#
# Returns True or False.
def is_find_results(view):
return view.settings().get('syntax') and "Find Results" in view.settings().get('syntax')
# Private: Get the regions matching trailing spaces.
#
# As the core regexp matches lines, the regions are, well, "per lines".
#
# view - the view, you know
#
# Returns both the list of regions which map to trailing spaces and the list of
# regions which are to be highlighted, as a list [matched, highlightable].
def find_trailing_spaces(view):
sel = view.sel()[0]
line = view.line(sel.b)
include_empty_lines = bool(ts_settings.get("trailing_spaces_include_empty_lines",
DEFAULT_IS_ENABLED))
include_current_line = bool(ts_settings.get("trailing_spaces_include_current_line",
DEFAULT_IS_ENABLED))
regexp = ts_settings.get("trailing_spaces_regexp") + "$"
no_empty_lines_regexp = "(?<=\S)%s$" % regexp
offending_lines = view.find_all(regexp if include_empty_lines else no_empty_lines_regexp)
if include_current_line:
return [offending_lines, offending_lines]
else:
current_offender = view.find(regexp if include_empty_lines else no_empty_lines_regexp, line.a)
removal = False if current_offender == None else line.intersects(current_offender)
highlightable = [i for i in offending_lines if i != current_offender] if removal else offending_lines
return [offending_lines, highlightable]
# Private: Find the fraking trailing spaces in the view and flags them as such!
#
# It will refresh highlighted regions as well. Does not execute if the
# document's size exceeds the file_max_size setting, or if the fired in a view
# which is not a legacy document (helper/build views and so on).
#
# view - the view, you know
#
# Returns nothing.
def match_trailing_spaces(view):
if ts_settings is None:
startup_queue.append(view)
return
# Silently pass if file is too big.
if max_size_exceeded(view):
return
if not is_find_results(view):
(matched, highlightable) = find_trailing_spaces(view)
add_trailing_spaces_regions(view, matched)
highlight_trailing_spaces_regions(view, highlightable)
# Private: Checks whether the document is bigger than the max_size setting.
#
# view - the view, you know
#
# Returns True or False.
def max_size_exceeded(view):
return view.size() > ts_settings.get('trailing_spaces_file_max_size',
DEFAULT_MAX_FILE_SIZE)
# Private: Marks specified regions as trailing spaces.
#
# view - the view, you know
# regions - regions qualified as trailing spaces
#
# Returns nothing.
def add_trailing_spaces_regions(view, regions):
view.erase_regions('TrailingSpacesMatchedRegions')
view.add_regions('TrailingSpacesMatchedRegions',
regions,
"",
"",
sublime.HIDE_ON_MINIMAP)
# Private: Highlights specified regions as trailing spaces.
#
# It will use the scope enforced by the state of the toggable highlighting.
#
# view - the view, you know
# regions - regions qualified as trailing spaces
#
# Returns nothing.
def highlight_trailing_spaces_regions(view, regions):
view.erase_regions("TrailingSpacesHighlightedRegions")
view.add_regions('TrailingSpacesHighlightedRegions',
regions,
current_highlighting_scope or "",
"",
sublime.HIDE_ON_MINIMAP)
# Private: Toggles highlighting of all trailing spaces in the view.
#
# It has no effect is the plugin is disabled.
#
# view - the view, you know
#
# Returns True (highlighting was turned on) or False (turned off).
def toggle_highlighting(view):
global current_highlighting_scope
# If the scope is that of an invisible, there is nothing to toggle.
if DEFAULT_COLOR_SCOPE_NAME == "":
return "disabled!"
# If performing live, highlighted trailing regions must be updated
# internally.
if not trailing_spaces_live_matching:
(matched, highlightable) = find_trailing_spaces(view)
highlight_trailing_spaces_regions(view, highlightable)
scope = DEFAULT_COLOR_SCOPE_NAME if current_highlighting_scope == "" else ""
current_highlighting_scope = scope
highlight_trailing_spaces_regions(view, view.get_regions('TrailingSpacesHighlightedRegions'))
return "off" if current_highlighting_scope == "" else "on"
# Clear all the highlighted regions in all views.
#
# FIXME: this is not used! Delete?
#
# window - the window, you know
#
# Returns nothing.
def clear_trailing_spaces_highlight(window):
for view in window.views():
view.erase_regions('TrailingSpacesMatchedRegions')
# Find edited lines since last save, as line numbers, based on diff.
#
# It uses a Differ object to compute the diff between the file as red on the
# disk, and the current buffer (which may differ from the disk's state). See
# http://docs.python.org/2/library/difflib.html for details about diff codes.
#
# It relies on a full diff, so it may be expensive computation for very large
# files (diff generation + looping through all lines).
#
# old - a buffer of lines, as in "old version"
# new - a buffer of lines, as in "new version"
#
# Returns the list of edited line numbers.
def modified_lines_as_numbers(old, new):
d = difflib.Differ()
diffs = d.compare(old, new)
# Pretty Naive Algorithm (tm):
# - split off the "Differ code", to check whether:
# - the line is in either in both files or just b: increment the line number
# - the line is only in b: it qualifies as an edited line!
# Starting from -1 as ST2 is internally 0-based for lines.
lineNum = -1
edited_lines = []
for line in diffs:
code = line[:2]
# those lines with "? " are not real! watch out!
if code in (" ", "+ "):
lineNum += 1
if code == "+ ":
edited_lines.append(lineNum)
return False if not edited_lines else edited_lines
# Private: Find the dirty lines.
#
# view - the view, you know
#
# Returns the list of regions matching dirty lines.
def get_modified_lines(view):
try:
on_disk
on_buffer = view.substr(sublime.Region(0, view.size())).splitlines()
except UnicodeDecodeError:
sublime.status_message("File format incompatible with this feature (UTF-8 files only)")
return
lines = []
line_numbers = modified_lines_as_numbers(on_disk, on_buffer)
if line_numbers:
lines = [view.full_line(view.text_point(number,0)) for number in line_numbers]
return lines
# Private: Finds the trailing spaces regions to be deleted.
#
# It abides by the user settings: while in mode "Only Modified Lines", it returns
# the subset of trailing spaces regions which are within dirty lines; otherwise, it
# returns all trailing spaces regions for the document.
#
# view - the view, you know
#
# Returns a list of regions to be deleted.
def find_regions_to_delete(view):
# If the plugin has been running in the background, regions have been matched.
# Otherwise, we must find trailing spaces right now!
if trailing_spaces_live_matching:
regions = view.get_regions('TrailingSpacesMatchedRegions')
else:
(regions, highlightable) = find_trailing_spaces(view)
# Filtering is required in case triming is restricted to dirty regions only.
if trim_modified_lines_only:
modified_lines = get_modified_lines(view)
# If there are no dirty lines, don't do nothing.
if not modified_lines:
return
# Super-private: filters trailing spaces regions to dirty lines only.
#
# As one cannot perform a smart find_all within arbitrary boundaries, we must do some
# extra work:
# - we want to loop through the modified lines set, not the whole trailing regions
# - but we need a way to match modified lines with trailings to those very regions
#
# Hence the reversed dict on regions: keys are the text_point of the begining of
# each region, values are the region's actual boundaries. As a Region is unhashable,
# trailing regions are being recreated later on from those two values.
#
# We loop then loop through the modified lines: for each line, we get its begining
# text_point, and check whether it matches a line with trailing spaces in the
# reversed dict. If so, this is a match (a modified line with trailing spaces), so
# we can re-create and store a Region for the relevant trailing spaces boundaries.
#
# Returns the filtered list of trailing spaces regions for the modified lines set.
def only_those_with_trailing_spaces():
regions_by_begin = {}
matches = []
for region in regions:
begin = view.line(region).begin()
regions_by_begin[begin] = (region.begin(), region.end())
for line in modified_lines:
text_point = line.begin()
if text_point in regions_by_begin:
matches.append(sublime.Region(regions_by_begin[text_point][0], regions_by_begin[text_point][1]))
return matches
regions = only_those_with_trailing_spaces()
return regions
# Private: Deletes the trailing spaces regions.
#
# view - the view, you know
# edit - the Edit object spawned by the deletion command
#
# Returns the number of deleted regions.
def delete_trailing_regions(view, edit):
regions = find_regions_to_delete(view)
if regions:
# Trick: reversing the regions takes care of the growing offset while
# deleting the successive regions.
regions.reverse()
for r in regions:
view.erase(edit, r)
return len(regions)
else:
return 0
# Public: Toggles the highlighting on or off.
class ToggleTrailingSpacesCommand(sublime_plugin.WindowCommand):
def run(self):
view = self.window.active_view()
if max_size_exceeded(view):
sublime.status_message("File is too big, trailing spaces handling disabled.")
return
state = toggle_highlighting(view)
ts_settings.set("trailing_spaces_highlight_color", current_highlighting_scope)
persist_settings()
sublime.status_message('Highlighting of trailing spaces is %s' % state)
def is_checked(self):
return current_highlighting_scope != ""
# Public: Toggles "Modified Lines Only" mode on or off.
class ToggleTrailingSpacesModifiedLinesOnlyCommand(sublime_plugin.WindowCommand):
def run(self):
global trim_modified_lines_only
was_on = ts_settings.get("trailing_spaces_modified_lines_only")
ts_settings.set("trailing_spaces_modified_lines_only", not was_on)
persist_settings()
# TODO: use ts_settings.add_on_change() when it lands in ST3
trim_modified_lines_only = ts_settings.get('trailing_spaces_modified_lines_only')
message = "Let's trim trailing spaces everywhere" if was_on \
else "Let's trim trailing spaces only on modified lines"
sublime.status_message(message)
def is_checked(self):
return ts_settings.get("trailing_spaces_modified_lines_only")
# Public: Matches and highlights trailing spaces on key events, according to the
# current settings.
class TrailingSpacesListener(sublime_plugin.EventListener):
def on_modified(self, view):
if trailing_spaces_live_matching:
match_trailing_spaces(view)
def on_activated(self, view):
if trailing_spaces_live_matching:
match_trailing_spaces(view)
def on_selection_modified(self, view):
if trailing_spaces_live_matching:
match_trailing_spaces(view)
def on_activated(self, view):
self.freeze_last_version(view)
if trailing_spaces_live_matching:
match_trailing_spaces(view)
def on_pre_save(self, view):
self.freeze_last_version(view)
if ts_settings.get("trailing_spaces_trim_on_save"):
view.run_command("delete_trailing_spaces")
# Toggling messes with what is red from the disk, and it breaks the diff
# used when modified_lines_only is true. Honestly, I don't know why (yet).
# Anyway, let's cache the persisted version of the document's buffer for
# later use on specific event, so that we always have a decent version of
# "what's on the disk" to work with.
def freeze_last_version(self, view):
global on_disk
file_name = view.file_name()
# For some reasons, the on_activated hook gets fired on a ghost document
# from time to time.
if file_name:
on_disk = codecs.open(file_name, "r", "utf-8").read().splitlines()
# Public: Deletes the trailing spaces.
class DeleteTrailingSpacesCommand(sublime_plugin.TextCommand):
def run(self, edit):
if max_size_exceeded(self.view):
sublime.status_message("File is too big, trailing spaces handling disabled.")
return
deleted = delete_trailing_regions(self.view, edit)
if deleted:
if ts_settings.get("trailing_spaces_save_after_trim") \
and not ts_settings.get("trailing_spaces_trim_on_save"):
sublime.set_timeout(lambda: self.save(self.view), 10)
msg_parts = {"nbRegions": deleted,
"plural": 's' if deleted > 1 else ''}
message = "Deleted %(nbRegions)s trailing spaces region%(plural)s" % msg_parts
else:
message = "No trailing spaces to delete!"
sublime.status_message(message)
def save(self, view):
if view.file_name() is None:
view.run_command('prompt_save_as')
else:
view.run_command('save')
# ST3 features a plugin_loaded hook which is called when ST's API is ready.
#
# We must therefore call our init callback manually on ST2. It must be the last
# thing in this plugin (thanks, beloved contributors!).
if not int(sublime.version()) > 3000:
plugin_loaded()

View File

@@ -0,0 +1,56 @@
// Trailing Spaces' default settings.
//
// In order to tweak the settings, you should NOT edit this file, but instead
// the user-specific, empty-by-default version under "Preferences / Package
// Settings / Trailing Spaces / Settings - User".
//
// See Trailing Spaces' README for detailled instructions.
{
// By default, Trailing Spaces is "live". It means the trailing spaces
// regions will be matched in the background, and highlighted if a color
// scope is defined, when the document is opened and edited.
// Set to false to disable live matching and highlighting (the deletion
// command remains available, so-called "lazy matching").
"trailing_spaces_enabled" : true,
// Highlight color is specified as a scope. You may define and use a custom
// scope to better fit your colorscheme.
"trailing_spaces_highlight_color" : "invalid",
// By default, empty lines are cleared as well when calling the deletion
// command.
// Set to false to ignore empty lines upon deletion.
"trailing_spaces_include_empty_lines" : true,
// By default, the line being currently edited will have its trailing
// spaces highlighted.
// Set to false to ignore trailing spaces on the edited line.
"trailing_spaces_include_current_line" : true,
// By default, trailing spaces are deleted within the whole document.
// Set to true to affect only the lines you edited since last save.
// Trailing spaces will still be searched for and highlighted in the whole
// document.
"trailing_spaces_modified_lines_only": false,
// By default, nothing happens on save.
// Set to true to trim trailing spaces before saving, with respect to the
// other settings.
"trailing_spaces_trim_on_save": false,
// By default, deleting trailing spaces does not cause the document to be
// saved.
// Set to true to force saving after trailing spaces have been deleted.
// This setting is irrelevant and will be ignored if trim_on_save is true.
"trailing_spaces_save_after_trim": false,
// ---- NEXT SETTINGS ARE FOR POWER USERS ONLY! ----
// Highlighting will be disabled if the edited file's size is larger than
// this.
// Adjust the value (in number of chars) to whatever fits your performance.
"trailing_spaces_file_max_size" : 1048576,
// By default, only simple spaces and tabs are matched as "trailing spaces".
"trailing_spaces_regexp": "[ \t]+"
}