Sublime text 3 удалить пробелы
Sublime Text is brim-full of editing features. This topic just scratches the surface of what's possible.
Multiple selections let you make sweeping changes to your text efficiently. Any praise about multiple selections is an understatement. This is why:
Select some text and press Ctrl D to add more instances. If you want to skip the current instance, press Ctrl K , Ctrl D .
If you go too far, press Ctrl U to deselect the current instance.
You can copy multiple selected lines to a separate buffer, edit them there, select the content again as multiple lines and then paste them back into place in the first buffer.
You can select a rectangular area of a file. Column selection makes use of multiple selections.
It's possible to add blocks of text to or remove them from the selection.
Windows & Linux
Description | Shortcut |
---|---|
Select Block | ⇧ + Right Mouse Button |
Add to Selection | Ctrl ⇧ + Right Mouse Button |
Remove from Selection | Alt ⇧ + Right Mouse Button |
macOS
Description | Shortcut |
---|---|
Select Block | ⌥ + Left Mouse Button |
Add to Selection | ⌥ ⌘ + Left Mouse Button |
Remove from Selection | ⌥ ⇧ ⌘ + Left Mouse Button |
System | Shortcut |
---|---|
Windows | Ctrl Alt ↑ and Ctrl Alt ↓ |
Linux | Alt ⇧ ↑ and Alt ⇧ ↓ |
macOS | Ctrl ⇧ ↑ and Ctrl ⇧ ↓ |
The list is long; all available options can be found under Selection. To name a few:
- Select subwords ( Alt ⇧ ← and Alt ⇧ → )
- Expand selection to brackets ( Ctrl ⇧ M )
- Expand selection to indentation ( Ctrl ⇧ J )
- Expand selection to scope ( Ctrl ⇧ ␣ )
Need to swap two letters or, better yet, two words? Experiment with Ctrl T .
The Edit, Selection, Find and Goto menus are good places to look for handy editing tools. You might end up using just a few of them, but the rest will still be there for when you need them.
Я знаю, что Sublime Text 2 может удалить конечное пробел в файлах при сохранении.
при работе в команде и фиксации изменений в файле это приводит к огромным различиям, которые делают рецензирование кода более громоздким. По этой причине я предпочитаю делать очистку белого пространства только тогда, когда я фиксирую огромные изменения в файле в любом случае и оставляю пробелы как есть для незначительных изменений.
Я хотел бы знать, есть ли какая-либо команда для выполнения обрезки из белого пространства по требованию в файле, кроме "Activate trimming on save > Save file > Deactivate trimming" .
поиск в документации и на stackoverflow не показал ничего важного, все ссылки, похоже, говорят об автоматической обрезке при сохранении.
остерегайтесь: используя этот плагин делает Sublime Text значительно медленнее
я использую TrailingSpaces плагин для этого.
выделите конечные пробелы и удалите их в мгновение ока.
ST2 обеспечивает способ автоматического удаления конечных пробелов в файле спасать. В зависимости от ваших настроек, он может быть более удобно выделите их и / или удалите вручную. Этот плагин предоставляет только это!
использование: нажмите "Редактировать / конечные пробелы / удалить".
чтобы добавить привязку ключа, откройте "настройки / привязки ключа-Пользователь" и добавьте:
Я использую эти шаги для быстрого решения по требованию в Sublime Text:
- Найти > Заменить.
- Найти: [ \t]+\n
- Заменить На: \n
- Заменить Все
вы также можете сделать это для большого набора файлов через
- найти > найти в файлах.
- найти: [ \t]+\n
- где:
- заменить: \n
- заменить
вот супер простой способ, который не использует плагины или настройки и работает в большинстве ситуаций.
- Multi-Select и переместить курсор в конец каждой строки
- удерживайте CTRL-Shift, нажмите влево, вправо
пробелы и знаки табуляции в конце строк должно быть выбран. Нажмите Delete или Backspace
Примечание - специальные символы, такие как ( и + также могут быть выбраны в конце строки на это точка, а не просто пространство.
Как выбрать все строки:
один из способов-использовать среднюю клавишу мыши, чтобы выбрать вертикально, а затем нажать клавишу End, если это небольшой выбор.
- CTRL-A (выбрать все)
- CTRL-SHIFT-L (поместите курсор на все выбранные строки)
- конец (перейти к концу строк)
вы также можете использовать функцию find для поиска что-то, что будет в каждой строке, как символ пространства:
Как Sublime Text может показывать непечатаемые символы (меня интересуют пробелы и вкладки)?
для просмотра пробелов настройка:
Вы можете увидеть его, если вы перейдете в Настройки- > Настройки по умолчанию. Если вы измените настройки пользователя (настройки - >настройки-пользователь) и добавите строку, как показано ниже, вы должны получить то, что хотите:
помните, что настройки-JSON, поэтому никаких запятых.
в выделенном тексте пробел отображается как точка (.) и TAB как тире ( -).
Я использую Unicode Character Highlighter , может отображать пробелы и некоторые другие специальные символы.
добавьте это, управление пакетом
установить пакеты, unicode .
Если вы хотите иметь возможность переключать отображение пробелов и выключать, вы можете установить плагин HighlightWhitespaces
надеюсь помочь вам!
Я знаю, что это старый нить, но мне нравится мой собственный плагин, который может цикл через пробел режимы (нет, выбор и все) с помощью одного ярлыка. Он также предоставляет пункты меню в меню View | Whitespace.
надеюсь, люди найдут это полезным - он используется многими людьми:)
"быстрый и грязный" способ-использовать функцию find и активировать регулярные выражения.
тогда просто найдите : \ы для подсветки помещений \T для табуляции \N для новых строк так далее.
у меня есть несколько плагинов (включая Unicode Character Highlighter), но единственный, который нашел символ, который скрывался от меня сегодня, был маркер.
вы можете проверить, работает ли он, вставив текст из readme.
для справки, персонаж, вызывающий у меня проблемы, был .
для проверки вменяемости нажмите клавишу со стрелкой вправо над диапазоном текста, содержащего невидимый символ, и вам нужно вправо-стрелка дважды, чтобы пройти мимо персонажа.
Я также использую следующую пользовательскую строку регулярного выражения (которую я не полностью grok):
A Sublime Text plugin that allows you to…
highlight trailing spaces and delete them in a flash!
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.
It is available through Sublime Package Control and this is the recommended way of installation (brings configuration instructions, automatic updates with changelogs…).
Alternative installation methods
You can install from github if you want, although Package Control automates just that. Go to your Packages directory (find out where it is by running Preferences: Browse Packages from The Command Palette) and clone this repository:
Download the plugin as a zip. Copy the Trailing Spaces directory to its location (see prior section).
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:
With this setting, pressing Ctrl + Shift + t 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+shift+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".
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:
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" to add you custom settings.
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
You may change the highlighting color, providing a color scope name such as "error", "comment"… just like that:
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:
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:
Include Current Line
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:
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
When firing the deletion command, empty lines are matched as trailing regions, and end up being deleted. You can specifically ignore them:
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:
There is also a command to toggle this feature on and off. You may thus define a key binding:
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.
Save After Trim
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:
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:
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.
Default: ["text.find-in-files", "source.build_output", "source.diff", "text.html.markdown"]
With this option you can ignore lines being highlighted based on the scope of their trailing region.
If at least one scope in the configured list matches a scope in the trailing region of the line, it won't be highlighted.
By default, the scope under the mouse cursor is shown by pressing Option+Command+P (OS X) or Ctrl+Alt+Shift+P (Windows, Linux)
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:
The matching pattern
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:
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" to add the following:
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!):
and to ensure a newline is kept at end of file upon saving:
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.
Some commands take paths as parameters. Among these, some support snippet-like syntax, while others don't. A command of the first kind would take a parameter like $/SomeDir/SomeFile.ext whereas a command of the second kind would take a parameter like Packages/SomeDir/SomeFile.ext .
Generally, newer commands support the snippet-like syntax.
Commands expect UNIX-style paths if not otherwise noted, including on Windows (for example, /c/Program Files/Sublime Text 3/sublime_plugin.py ).
Often, relative paths in arguments to commands are assumed to start at the Data directory.
: Inserts a string at the end of the view.
- characters (String): String to be inserted.
- force (Bool):
- scroll_to_end (Bool):
: Opens the auto complete list.
: Runs a build system.
- variant (String): Optional. The name of the variant to be run.
: If no name argument, or the name "bookmarks" is specified, it removes all bookmarks set in the current file, but not the marks. If the name "mark" is specified as an argument, it removes all marks set in the current file, but not the bookmarks.
- name (String): e.g. "mark" , "bookmarks" .
: Breaks out of the active snippet field cycle.
: Deletes records of recently accessed files and folders.
: Deletes records of recently accessed projects.
: Clones the current view into the same tab group, both sharing the same buffer. That means you can drag one tab to another group and every update to one view will be visible in the other one too.
: Closes the active view and, under certain circumsances, the whole application.
: Removes all folders from the current project.
: Closes the current project.
: Surrounds the current inner text with the appropiate tags.
: Closes the active window.
: Closes the active view.
: Inserts into the buffer the item that's currently selected in the auto complete list.
: Shows the context menu.
: Sends the selected text to to the system clipboard.
: Removes the selected text and sends it to the system clipboard. Put differently, it cuts.
: Decreases the font size.
: Deletes the text that select_to_mark would select.
: Guesses the indentation from the current file.
: Duplicates the current line.
: Runs an external process asynchronously. On Windows, GUIs are supressed.
exec is the default command used by build systems, thus it provides similar functionality. However, a few options in build systems are taken care of by Sublime Text internally so they list below only contains parameters accepted by this command.
- cmd [(String)]
- shell_cmd (String): Shell command to use. If given overrides cmd and ignores shell .
- file_regex (String)
- line_regex (String)
- working_dir (String)
- encoding (String)
- env []
- quiet (Bool): If True no runtime information is printed if the command fails or has a non-zero exit code.
- kill (Bool): If True will simply terminate the current build process. This is invoked via Build: Cancel command from the Command Palette.
- update_phantoms_only (Bool)
- hide_phantoms_only (Bool)
- word_wrap (Bool): Whether to word-wrap the output in the build panel
- syntax (String): Syntax file used to colour output.
- path (String)
- shell (Bool)
(opens new window) Detailed documentation on all parameters of the exec command.
: Exits the whole application with all open windows.
: Extends the selection up to predefined limits.
: Finds all occurrences of the current selection or the current word.
: Finds the next occurrence of the current search term.
: Finds the previous occurrence of the current search term.
: Adds a new selection based on the current selection or expands the selection to the current word while removing the current selection.
: Adds a new selection based on the current selection or expands the selection to the current word.
: Finds the previous occurrence of the current selection or the current word.
: Finds the next occurrence of the current selection or the current word.
: Gives focus to the top-most file in the specified group.
- group (Int): The group index to focus. This is determined by the order of cells items from the current layout (see Window.set_layout ).
: Scans the whole file and folds everything with an indentation level of level or higher. This does not unfold already folded regions if you first fold by level 2 and then by 3, for example. Sections with cursors are not folded.
Folds all tag attributes in XML files, only leaving the tag's name and the closing bracket visible.
: Folds the current selection and displays … instead. Unfold arrows are added to the lines where a region has been folded.
: Hides the auto complete list.
: Hides the active overlay. Show the overlay using the show_overlay command.
: Hides the active panel.
- cancel (Bool): Notifies the panel to restore the selection to what it was when the panel was opened. (Only incremental find panel.)
: Increases the font size.
: Increments indentation of selection.
: Inserts the best completion that can be inferred from the current context.
- default (String): String to insert failing a best completion.
: Inserts a snippet from a string or .sublime-snippet file.
- contents (String): Snippet as a string to be inserted. Remember that backslashes \ have to be escaped, like in every other JSON string.
- name (String): Relative path to the .sublime-snippet file to be inserted.
Snippets Documentation on snippets and their variable features.
: Inserts a string.
- characters (String): String to be inserted.
: Joins the current line with the next one.
: Deletes the character right before the caret.
: Makes the selection lower case.
: Moves the current file to the specified group.
: Advances the caret to predefined locations.
- to (Enum): Values: bol, eol, bof, eof, brackets.
- extend (Bool): Whether to extend the selection. Defaults to false .
: Advances the caret by predefined units.
- by (Enum): Values: characters, words, word_ends, subwords, subword_ends, lines, pages, stops.
- forward (Bool): Whether to advance or reverse in the buffer.
- word_begin (Bool)
- empty_line (Bool)
- punct_begin (Bool)
- separators (Bool)
- extend (Bool): Whether to extend the selection. Defaults to false .
: Creates a new buffer and inserts a build system template.
: Creates a new buffer and inserts a plugin template (a text command).
: Creates a new buffer and inserts a snippet template.
: Opens a new window.
: Select the next bookmarked region.
: Advances the caret to the text snippet field in the current snippet field cycle.
: Advance to the next misspelling
: Advance to the next captured result.
: Switches to the most recently active view.
: Switches to the next view.
: Opens the specified directory with the default file manager.
- dir (String): The directory to open.
: Opens the syntax-specific user settings file for the current syntax.
: Opens the specified file. Will dynamically open resource files from sublime-package archives as read-only if the specified override file does not exist.
file (String): Absolute or relative path to the file to be opened. Relative paths will originate from the recently
Expands snippet-like variables, such as $platform and $packages .
contents (String): This string will be written to the new buffer if the file does not exist. accessed directory (e.g. the directory of the currently opened file).
.. XXX more variables?
: Opens a recently closed file.
: Opens a recently closed folder.
: Opens a recently closed project.
: Opens the specified url with the default browser.
: Inserts the clipboard contents after the caret and indents contextually.
: Inserts the clipboard contents after the caret.
- clipboard (String): May be selection. XXX what other values are allowed?
: Select the previous bookmarked region.
: Moves the caret to the previous snippet field in the current snippet field cycle.
: Move to the previous misspelling.
: Move to the previous captured result.
: Switches to the view that was active before the most recently active view.
: Switches to the previous view.
: Prompts for a folder to add to the current project.
: Prompts for a project file to open as a project.
: Prompts for a new file name and saves the active file.
: Opens a popup with recently accessed projects where you can fuzzy-search.
: Performs the latest action again.
: Reapplies the latest undone action.
: Reloads all folders in the current project and updates the side bar.
: Corrects indentation of the selection with regular expressions set in the syntax's preferences. The base indentation will be that of the line before the first selected line. Sometimes does not work as expected.
: Reopens the last closed file.
: Reopens the current file.
- encoding (String): The file encoding the file should be reopened with.
: Resets the font size to the default
Note: This essentially removes the entry from your User settings, there might be other places where this has been "changed".
: Undoes all unsaved changes to the file.
: Deletes the character right after the caret.
: Runs a .sublime-macro file.
- file (String): Relative path to the macro file.
: Runs the macro stored in the macro buffer.
: Saves all open files.
: Prompts for a file path to save the macro in the macro buffer to.
: Prompts for a new file name and saves the current project.
: Saves the active file.
- encoding (String): The file encoding to save as.
: Scrolls lines in the view.
amount [Float]: Positive values scroll lines down and negative values scroll lines up.
: Selects all bookmarked regions.
: Select the view's content.
: Selects a bookmarked region in the current file.
: Focuses a certain tab in the current group.
- index (Int): The tab index to focus.
: Adds a line to the current selection.
- forward (Bool): Whether to add the next or previous line. Defaults to true .
: Selects the text between the current position of each one of the current carets and the marked position. Each caret is matched with each mark in order of occurrence, and is moved to the beginning of its selection.
If any number of selections overlap, they are joined and, of all the carets corresponding to each one of the joined selections, only the one occurring first in the file is preserved.
If the number of current carets is less or equal to the number of marks, the remaining marks in order are ignored. Conversely, if currently there are more carets than marks, the first relevant selections are produced. Of all extra marks, those contained in the selections are removed, and the rest of them are left where they are, without triggering a selection from their position.
: Changes the current build system.
- file (String): Path to the build system. If empty, Sublime Text tries to automatically find an appropriate build systems from specified selectors.
- index (Int): Used in the Tools | Build System menu but otherwise probably not useful.
: Changes the group layout of the current window. This command uses the same pattern as Window.set_layout , see there for a list and explanation of parameters.
: Changes the line endings of the current file.
: Marks the position of each caret in the current file. If any marks have already been set in that file, they are removed.
: Set the value of a setting. This value is view-specific.
- setting (String): The name of the setting to changed.
- value (*): The value to set to.
: I think you know what this does.
: Scrolls the view to show the selected line in the middle of the view and adjusts the horizontal scrolling if necessary.
overlay (Enum): The type of overlay to show. Possible values:
- goto: Show the Goto Anything overlay.
- command_palette: Show the Command Palette.
show_files (Bool): If using the goto overlay, start by displaying files rather than an empty widget.
text (String): The initial contents to put in the overlay.
- panel (Enum): Values: incremental_find, find, replace, find_in_files, console or output. .
- reverse (Bool): Whether to search backwards in the buffer.
- toggle (Bool): Whether to hide the panel if it's already visible.
: Shows the name for the caret's scope in the status bar.
: Collapses multiple selections into a single selection.
: Copies the current selection or word into the "find" field of the find panel.
: Copies the current selection or word into the "replace" field of the find and replace panel.
: Redoes each action stepping through granular edits.
: Undoes each action stepping through granular edits.
- case_sensitive (Bool): Whether the sort should be case sensitive.
: Sorts lines in selection.
- case_sensitive (Bool): Whether the sort should be case sensitive.
: Splits the selection into multiple selections, one on each line.
: Swaps the case of each character in the selection.
: Swaps the current line with the line below.
: Swaps the current line with the line above.
: Marks all the current carets' positions, removes those carets, and sets new carets at the previously marked positions, if any.
: Switches between two files with the same name and different extensions.
- extensions (String): Extensions (without leading dot) for which switching will be enabled.
: Capitalizes the selection's first character and turns the rest into lower case.
: Sets or unsets a bookmark for the active region(s). (Bookmarks can be accessed via the regions API using "bookmarks" as the key.)
: Comments or uncomments the active lines, if available.
- block (Bool): Whether to insert a block comment.
: Toggles distraction free mode on or off.
: Toggles full screen mode on or off.
: Shows or hides the minimap.
: Toggles overwriting on or off.
: Starts or stops the macro recorder.
: Toggles whether all open files should be saved before starting the build.
: Toggles the value of a boolean setting. This value is view-specific.
- setting (String): The name of the setting to be toggled.
: Shows ot hides the open files in the sidebar.
: Shows or hides the sidebar.
: Shows or hides the status bar.
: Shows or hides the tab bar.
: Makes selections or characters swap places.
With selection: The contents of the selected regions are circulated. Without selection: Swaps adjacent characters and moves the caret forward by 1.
: Undoes the latest action.
: Unfolds all folded regions.
: Unfolds all folded regions in the selection or the current line if there is none.
: Makes the selection upper case.
: Wraps lines. By default, it wraps lines at the first ruler's column.
- width (Int): Specifies the column at which lines should be wrapped.
There are several ways to discover a command's name in order to use it as a key binding, in a macro, as a menu entry or in a plugin.
- Browsing the default key bindings at Preferences | Key Bindings - Default. If you know the key binding whose command you want to inspect, you can just search for it using the search panel. This, of course, also works in the opposite direction.
Running the above in the console will tell Sublime Text to print the command's name in the console whenever a command is run. You can practically just enter this, do whatever is needed to run the command you want to inspect and then look at the console. It will also print the passed arguments so you can basically get all the information you need from it. When you are done, just run the function again with False as parameter.
Inspecting .sublime-menu files. If your command is run by a menu item, browse the default menu file at Packages/Default/Main.sublime-menu . You will find them quick enough once you take a look at it, or see the menu documentation.
Читайте также: