Установка и настройка sublime text 3 и его плагинов

License

“None are so hopelessly enslaved as those who falsely believe they are free.” Johann Wolfgang von Goethe

Copyright 2014 Tito Bouzout tito.bouzout@gmail.com

This license apply to all the files inside this program unless noted different for some files or portions of code inside these files.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation. http://www.gnu.org/licenses/gpl.html

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/gpl.html

Горячие клавиши Sublime Text

Несколько часто используемых в Sublime Text 3 горячих клавиш:

Alt+Shift+f — выравнивание кода (reindent);Ctrl+f Alt+enter — выделить все найденные слова;Super+Alt+. — переход к выбранному классу в CSS в Sublime Text 3;Ctrl+/ — закомментировать / раскомментировать HTML;Ctrl+Shift + D — дублировать строку или выделение;Ctrl+K+U — преобразовать в прописные буквы (выделен фрагмент текста);Ctrl+K+L — преобразовать в строчные буквы (выделен фрагмент текста);Shift+Ctrl+g — обернуть выделение в div;Ctrl+ — передвигаем выделенный код влево или вправо;Ctrl+Shift+p — открываем меню команд;Ctrl+` — открывает в Sublime Text консоль.

Поделиться

Inspiring Generosity, Gittip Style

by wbond
at 3:00pm
on Friday, August 9th, 2013

As part of the new site launch and the expanded package detail pages, I
wanted to start an experiment with making supporting package developers
even easier. Now granted, the part I’m playing in the process is rather
small since I am just providing links for each author. The real work that
makes this possible is Gittip, founded
by Chad Whitacre.

I was excited a few weeks ago to see the attention Gittip received when
John Resig announced the Khan Academy has started giving their developers
$5 a week to say thank you to the open source developers who make their
work possible.

My hope is that through exposing the work of the over 1,000 developers
who maintain various packages for Sublime Text, we can encourage each other
to say “thank you!”

In case you’ve never checked it out, Gittip offers weekly donation amounts
as small as $0.25. This may seen inconsequential, however if only 100 users
tip $0.25 a week, the developer can recieve $25. Considering there are
tens of thousands of users of some of the more popular packages, it should
be possible for these small donations to make a big impact and encourage
future open source work.

In closing I wanted to highlight some of the work a few contributors to
Package Control have been doing over the past months. These developers have
spent their time reviewing and giving feedback to fellow package developers
as they merge pull requests into the default channel:

Usage

  • Run Black on the current file:

    Press Ctrl-Alt-B to format the entire file.
    You can also Ctrl-Shift-P (Mac: Cmd-Shift-P) and select Sublack: Format file.

  • Run Black with —diff:

    Press Ctrl-Alt-Shift-B will show diff in a new tab.
    You can also Ctrl-Shift-P (Mac: Cmd-Shift-P) and select Sublack: Diff file.

  • Toggle Black on save for current view :

    Press Ctrl-Shift-P (Mac: Cmd-Shift-P) and select Sublack: Toggle black on save for current view.

  • run Black Format All :

    Press Ctrl-Shift-P (Mac: Cmd-Shift-P) and select Sublack: Format All. Run black against each root folder in a standard way (without taking care of sublack options and configuration). Same thing as running black . being in the folder.

  • Start Blackd Server :

    Press Ctrl-Shift-P (Mac: Cmd-Shift-P) and select Sublack: Start BlackdServer.

  • Stop Blackd Server :

    Press Ctrl-Shift-P (Mac: Cmd-Shift-P) and select Sublack: Stop BlackdServer.

Issues

  • Linux requires the curl binary to be installed on your system (in one of:
    , , , , , or ).

  • Depending on the number of gists you have, there can be a considerable delay the first time your list of gists is fetched. Subsequent requests will be cached and should be a bit faster (although the GitHub API’s ETags are currently not correct; once they fix that, it should speed things up). In the meantime, if there are gists that you open frequently, open them on GitHub and “Star” them, then access them via the Open/Copy Starred Gist commands.

  • Setting the file type for syntax highlighting when opening a gist in the editor does not work in Linux. I could get it to work with significant effort, so if you desperately want it, open an issue.

Installing

With the Package Control plugin: The easiest way to install CodeFormatter is through Package Control, which can be found at this site: http://wbond.net/sublime_packages/package_control

Once you install Package Control, restart Sublime Text and bring up the Command Palette ( on OS X, on Linux/Windows). Select “Package Control: Install Package”, wait while Package Control fetches the latest package list, then select CodeFormatter when the list appears. The advantage of using this method is that Package Control will automatically keep CodeFormatter up to date with the latest version.

Without Git: Download the latest source from GitHub and copy the CodeFormatter folder to your Sublime Text “Packages” directory.

With Git: Clone the repository in your Sublime Text “Packages” directory:

git clone https://github.com/akalongman/sublimetext-codeformatter.git CodeFormatter

The “Packages” directory is located at:

  • OS X:

    ST2: ~/Library/Application Support/Sublime Text 2/Packages/
    ST3: ~/Library/Application Support/Sublime Text 3/Packages/
    
  • Linux:

    ST2: ~/.config/sublime-text-2/Packages/
    ST3: ~/.config/sublime-text-3/Packages/
    
  • Windows:

    ST2: %APPDATA%/Sublime Text 2/Packages/
    ST3: %APPDATA%/Sublime Text 3/Packages/
    

Notes on configuring the Open With menu:

Definitions file: (note the extra subfolder levels). To open it, right-click on any file in an open project and select

  • On OSX, the ‘application’ property simply takes the name of an application, to which the file at hand’s full path will be passed as if with , e.g.: “application”: “Google Chrome”
  • On OSX, invoking shell commands is NOT supported.
  • You should change Caption and id of the menu item to be unique.

    //application 1
    {
    “caption”: “Photoshop”,
    “id”: “side-bar-files-open-with-photoshop”,
    “command”: “side_bar_files_open_with”,
    “args”: {
    “paths”: ,
    “application”: “Adobe Photoshop CS5.app”, // OSX
    “extensions”:“psd|png|jpg|jpeg”, //any file with these extensions
    “args”:
    }
    },

Vars on “args” param

  • \$PATH — The full path to the current file, “C:\Files\Chapter1.txt”
  • \$PROJECT — The root directory of the current project.
  • \$DIRNAME — The directory of the current file, “C:\Files”
  • \$NAME — The name portion of the current file, “Chapter1.txt”
  • \$NAME_NO_EXTENSION — The name portion of the current file without the extension, “Chapter1”
  • \$EXTENSION — The extension portion of the current file, “txt”

Features

The below features are available via the keyboard shortcuts shown, or via the Command Palette (^ means the key):

Feature Shortcut
Rename
Find references
Next reference
Prev reference
Format document
Format selection
Format line
Format braces
Navigate to symbol
Go to definition or
Trigger completion
Trigger signature help
See previous signature in the tooltip
See next signature in the tooltip
Paste and format or
Quick info
Build (Win) or , (OSX) or
Error list (via Command Palette)

The “format on key” feature is disabled by default, which formats the current line after typing , or .
To enable it, go to -> -> -> , and add to the json file.

For further information about the keyboard shortcuts, please refer to the file for common shortcuts and
.sublime-keymap),
.sublime-keymap),
.sublime-keymap)
for OS-specific shortcuts.

Other settings

These settings can be overridden in , which you can open by going to -> -> -> .

  • : the color of the lines drawn underneath/around type errors; either an empty string for the default color, or one of , , , , , ,
  • : specifies a gutter icon, defaults to nothing can be set to , , or any other value accepted by Sublime Text
  • : will draw type errors with a solid outline instead of the default which is a squiggly line underneath
  • : the max width of the quick info popup, default 1024
  • : array of command line arguments sent to the tsserver Node.js process before the tsserver script path (useful for e.g. changing max heap size or attaching debugger to the tsserver process)
  • : array of command line arguments sent to tsserver Node.js process after the tsserver script path (useful for e.g. overriding tsserver error message locale)
  • : environment variables to set for the tsserver Node.js process (useful for e.g. setting ). These variables are merged with the environment variables available to Sublime.
  • : boolean to make the autocompletion only provides typescript suggestions and hides the standard completions (aka, all the words of the page). (Default value: ).

Description

Provides enhancements to the operations on Sidebar of Files and Folders for Sublime Text. http://www.sublimetext.com/

Notably provides delete as “move to trash”, open with.. and a clipboard.

Close, move, open and restore buffers affected by a rename/move command. (even on folders)

New file/folder, edit, open/run, reveal, find in selected/parent/project, cut, copy, paste, paste in parent, rename, move, delete, refresh….

Copy paths as URIs, URLs, content as UTF8, content as data:uri base64 ( nice for embedding into CSS! ), copy as tags img/a/script/style, duplicate

Preference to control if a buffer should be closed when affected by a deletion operation.

Allows to display “file modified date” and “file size” on statusbar (may be a bit buggy).

Плагины Sublime text 3

Нажмите ctrl+shift+P и снова напишите слово “install” и выберите графу Package Control: Install Package.

Выбор графы Package Control: Install Package открывает список доступных пакетов или plugins Sublime Text 3.

Emmet

Самый первый плагин для Sublime Text 3 — Emmet (с двумя m). Начните вписывать его название и увидите подсказку. В названии не должно быть никаких дополнительных слов. Нам нужно скачать Emmet к Sublime Text 3.

Кликаем по нему и дожидаемся открытия вкладки с сообщением о завершении установки, и просьбой перезапустить редактор Sublime text.

Как работает Emmet можно продемонстрировать на простом примере.

Создайте новый файл с расширением html в Sublime Text 3. Сделать это быстро можно тапнув два раза в строке вкладок, что откроет новую вкладку. Далее жмем сtrl+shift+S и сохраняем наш файл с любым именем и расширением — html.

Теперь emmet будет знать с каким языком мы хотим работать.

Для того, чтобы открыть начальный шаблон любой html страницы, будет достаточно поставить — ! и нажать tab.

Этот прием работает и с тегами. Достаточно набрать имя тега и нажать tab и он развернется в открывающий и закрывающий тег. И это еще не все. Подробный список доступных сокращений и возможных комбинаций можно увидеть на официальной странице Emmet.

All Autocomplete

Продолжим установку плагинов в Sublime Text.

Снова нажмите ctrl+shift+P и выберите “Package Control: Install” и введите название следующего плагина — All Autocomplete.

Это дополнение дает подсказки, когда мы начинаем набирать текст. Подсказки он берет из текста текущего файла.

AutoFileName

Следующий плагин называется AutoFileName. Он позволит нам подгружать имена файлов, которые находятся в папке с нашим сайтом, чтобы нам не приходилось вручную набирать пути к файлам или копировать их названия.

BracketHighlighter

Устанавливаем в Sublime Text еще одно дополнение, которое называется BracketHighlighter.

Снова нажмите ctrl+shift+P, введите install-package и название плагина BracketHighlighter. Он будет подсвечивать открывающие и закрывающие теги, открывающие скобки и закрывающие скобки и так далее.

Подсветка цвета

Очень помогает в разработке подсветка цвета в Sublime Text 3. Установите плагин в Sublime Text — Color Highlighter и вы будете видеть, а не только догадываться какой цвет означает например код — #fe9c10. Для установки в Sublime Text 3 — Color Highlighter, используйте тот же подход — через install package.

Плагины для Python

Для разработчиков на языке Python в Sublime Text 3 рекомендую установить плагин Anaconda. Его возможности:

  • Автодополнение кода Python;
  • Python linting (подчеркивание как синтаксических ошибок, так и нарушения PEP8);
  • Документация Python;
  • McCabe — проверка сложности;
  • и много чего еще.

Установка выглядит аналогично.

Нажмите ctrl+shift+P, пишем слово “install” и выбираем графу “Package Control: Install Package”. Далее пишем — Anaconda и выбираем для установки этот пакет.

В завершении установки Sublime Text откроет вкладку с приветствием.

Еще один плагин для Python в Sublime Text 3 — Djaneiro. Установка по старой схеме.

Roadmap and wish list

  • Better Markdown syntax highlighting, including Multimarkdown and Pandoc extras like footnotes, tables, and citations.
  • Create commands for Pandoc conversion from R Markdown to other formats? (or maybe just use actual Pandoc packages for that).

Manual patch for LaTeXTools

If you want to use the LaTeXTools plugin, you need to patch three files to make the standard LaTeXTools build system knit and typest the file. Make these three changes (huge thanks to Heberto del Rio for this!):

Important: Copying and pasting code from GitHub can do unexpected things to indentation (replacing tabs with spaces) and can temporarily break LaTeXTools. Make sure the indentation is correct after pasting.

File 1:

Add to the list of accepted LaTeX file types, like so:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>fileTypes</key>
    <array>
        <string>tex</string>
        <string>Rnw</string>
    </array>

Instructions for Sublime Text 3: In ST3, default packages are hidden deep within ST itself and are difficult to access, let alone edit. However, you can still get to relatively easily if you install the PackageResourceViewer plugin. After installing it, run the “PackageResourceViewer: Open Resource:” command through the command pallete (command/ctrl + shift + p) and navigate to LaTeX.tmLanguage. After making changes, ST will save a copy of the file in a more accessible location (), overriding the default built-in file.

File 2:

Find this:

if self.tex_ext.upper() != ".TEX":
    sublime.error_message("%s is not a TeX source file: cannot compile." % (os.path.basename(view.file_name()),))
    return

And replace with this:

if (self.tex_ext.upper() != ".TEX") and (self.tex_ext.upper() != ".RNW"):
    sublime.error_message("%s is not a TeX or Rnw source file: cannot compile." % (os.path.basename(view.file_name()),))
    return

Then find this:

# We should now be able to construct the builder object
self.builder = builder_class(self.file_name, self.output, builder_settings, platform_settings)

And replace with this:

if self.tex_ext.upper() == ".RNW":
    # Run Rscript -e "library(knitr); knit('" + self.file_name + "')"
    os.system("Rscript -e \"library(knitr); knit('"+ self.file_name +"')\"")
    self.file_name = self.tex_base + ".tex"
    self.tex_ext = ".tex"

# We should now be able to construct the builder object
self.builder = builder_class(self.file_name, self.output, builder_settings, platform_settings)

(If you want to use instead of , change the command accordingly.)

File 3:

Find this:

if texExt.upper() != ".TEX":
    sublime.error_message("%s is not a TeX source file: cannot jump." % (os.path.basename(view.fileName()),))
    return

And replace with this:

if (texExt.upper() != ".TEX") and (texExt.upper() != ".RNW"):
    sublime.error_message("%s is not a TeX or Rnw source file: cannot jump." % (os.path.basename(view.fileName()),))
    return

File 4:

Find this:

if texExt.upper() != ".TEX":
    sublime.error_message("%s is not a TeX source file: cannot view." % (os.path.basename(view.fileName()),))
    return

And replace with this:

if (texExt.upper() != ".TEX") and (texExt.upper() != ".RNW"):
    sublime.error_message("%s is not a TeX or Rnw source file: cannot view." % (os.path.basename(view.fileName()),))
    return

If you want to be able to use multiple files and to find your bib file, you’ll also need to change the following files:

File 5:

Find this:

mroot = re.match(r"%\s*!TEX\s+root *= *(.*(tex|TEX))\s*$",line)

And replace with this:

mroot = re.match(r"%\s*!TEX\s+root *= *(.*(tex|rnw))\s*$",line, flags=re.IGNORECASE)

What is improved?

Most of C Improved features tend to facilitate everyday C development experience. This varies from enabling highlighting of operators to more complex enhancements listed below.

Preprocessor issues

C preprocessor directives are relatively simple to parse (even with regular expressions, to some extent). And so related issues were addressed first of all.

Macro highlighting and error handling

Macro parameters (including variadic arguments) and argument stringification now have proper highlighting with handling of some common syntax errors.

Here is an example of two more or less complex multi-line macros.

Standard C C Improved

And below is a result of commenting out a vararg (but missing a preceding comma outside the comment) and accidentally putting tabs after some line continuation backslashes.

Standard C C Improved

Both errors are ignored by the standard package, while C Improved highlights a premature closing paren in the first case as an error, and warns about trailing whitespaces after the backslashes (the second one is immediately followed by an error complaining about an unexpected EOL within macro parameters). See an issue about highlighting.

Macro innards

A macro body (with proper line continuations, if needed) is not able to contribute to the symbol index anymore, nor it can interfere with a code surrounding the macro, or anyhow break syntax highlighting.

Standard C C Improved

In this example the standard C package recognizes inside a macro as a function definition though it is actually a function call.
This leads to incorrect highlighting and also adds a bogus symbol into the symbol list.
Moreover, a function declaration which follows the macro () is not recognized at all.

Scopes for preprocessor directives

All preprocessor directives provide a proper scope now (), which means that you can select a whole macro with ctrl+shift+space or ++space. It also allows, for instance, the whole macro body to be styled differently (this is up to a color scheme though).

Support for significant projects

The standard C package provides a special support for functions from C standard library and POSIX. For example, a function is highlighted differently.

However, most of major software projects implemented in C have their own internal libraries/frameworks and use some established patterns and idioms all across their sources. This includes not only a set of commonly used functions and types; there could be a handful macro for defining some object, a special kind of function attribute/annotation, etc.

If you use Sublime Text for developing some of the following projects, you should find these improvements rather useful.

Linux kernel source

This adds a special handling of some common macros widely used across the kernel source code, like , or ,
which would otherwise be recognized as functions thus polluting a symbol index and an outline.

Standard C C Improved

CPython interpreter source

This includes:

  • Highlighing of Python-related constants (like or ) and main data structures (, , , etc.)
  • Widely used , and function annotation. This sanitizes higlighting of annotated functions and the symbol index
  • Special highlighting of interned static string literals defined with macro
  • Well-marked highlighting of macros involving transfer of control (like ).
Standard C C Improved

Customizable indexing of types/functions/macros

You can adjust which symbols are available for navigation and visible in a symbol index or in an outline.

The following scopes and default preferences are provided:

Scope name Description Outlinectrl+R Index (ST3) F12ctrl+shift+R
compound type visible visible
forward declaration of a type visible hidden
type alias () visible visible
function definition visible visible
function declaration visible hidden
function-like macro visible visible
object-like macro visible visible

These settings can be changed through files, see .

New Package Control Website

by wbond
at 2:32pm
on Friday, August 9th, 2013

The old Community Packages list that was hosted on my website was admittedly
a quick and dirty hack to make it easier for users to try and find packages.
I have always known there were many usability issues and tons of room for
improvement.

When the first alpha of Sublime Text 3 was announced, I knew there was
quite a bit of work ahead of me to adapt the architecture to support
multiple versions of Sublime Text. I also saw this as the opportunity to
converge the codebase from python (for Package Control) and PHP (for the
old Community Packages list) to a single re-usable library.

Along the way of pursuing that goal, I vastly expanded the information that
can be provided by the channel system. This information helps greatly
enhance the new Package Control site to include in-depth information about
every package.

I am sure many of you have already poked around a bit, but here are some
highlights of the new site:

Generating Your Own Access Token

If you feel uncomfortable giving your GitHub username and password to the plugin, you can generate a GitHub API access token yourself. Just open up a Terminal window/shell (on OS X, Linux or Cygwin), and run:

curl -u username -d '{"scopes":, "note": "sublime-github"}' https://api.github.com/authorizations

where is your GitHub username. You’ll be prompt for your password first. Then you’ll get back a response that includes a 40-digit “token” value (e.g. ). Go to Sublime Text 2 -> Preferences -> Package Settings -> GitHub -> Settings — User, and insert the token there. It should look like:

{
    "github_token": "6423ba8429a152ff4a7279d1e8f4674029d3ef87"
}

Restart Sublime.

That’s it!

Работа с темой оформления

После того как необходимые расширения установлены можно перейти к работе.

Но внесем еще несколько штрихов в тему оформления. Не всем нравится тема установленная по умолчанию в Sublime Text 3, поэтому установим другую. Для этого снова нажмите ctrl+shift+P, перейдите в раздел Install-Package, как будто хотите установить новый плагин, но впишите название темы которая называется «Afterglow».

Теперь необходимо перейти в раздел “Preference Color — Scheme“.

Выбираем цветовую схему, которая теперь называется “Afterglow-monokai”.

Цветовая схема Sublime Text немного изменилась.

Но вкладки выглядят по-прежнему. Поэтому сменим еще и саму тему. Не цветовую схему для нашего кода, а тему. Для этого выбираем Theme и выбираю здесь Afterglow Orange.

Это оранжевая тема. Вкладки изменились, внешний вид в целом изменился, но размер вкладок великоват, поэтому настроим еще тоньше. Переходим в Sublime Text 3 раздел Preference и выбираем Settings.

У нас появляется два вкладки. Это вкладка со стандартными настройками Sublime Text и вкладка с нестандартными — нашими настройками.

Пропишем сюда еще кое-что, что относится к размеру табов. Для того чтобы это сделать необходимо найти тему Afterglow в интернете.

Скопируйте название темы Sublime Text 3 из настроек или просто напишите слово Afterglow в поиске. Откройте страницу на GitHub.

Воспользуемся поиском по странице, чтобы найти информацию по табам. Нажмем Ctrl+F и введем в поиске “tab”.

Как видим, можно использовать средний размер табов — medium или маленький — small. Возьмем средний размер табов, скопировав строчку, содержащую “tabs_medium” и перейдем обратно во вкладку с кодом. После последней строчки настроек поставьте запятую, перейдите на новую строчку и вставьте скопированный код.

Сохраните внесенные изменения через ctrl+S и вы увидите, что размеры табов Sublime Text изменились.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector