Brackets проверка на ошибки

Linguistics Brackets Extension

Linguistics adds a very powerful spell checking system to the Brackets editor. It offers the following features right out of the box:

  • Off-line spell checking
  • Support for multiple dictionaries
  • Custom user dictionary profiles
  • Integrated user interface
  • Intelligent built in support for common file extensions
  • Intelligent support for uppercased words
  • Spell check within camelCasedWords
  • Spell check available within your code files

How to Make it Work

For a detailed walkthrough, check out the guide on the Stillat website at https://stillat.com/blog/2017/10/31/installing-linguistics-for-adobe-brackets

Download both of the following repositories into your Brackets extensions folder. If you don’t know where that it is, simply go to Help > Show Extensions Folder in Brackets.

  • brackets/spellcheck
  • brackets-spellcheck-dictionaries

You will have to restart Brackets after you do this.

Assuming everything has gone to plan, you will see a new item in the lower right hand corner of the status bar. By default it says something like English (United States). This is the main UI component that lets you change dictionaries, disable/enable the spell checker and configure the default languages.

This looks like this:

Clicking on any of the dictionaries will reload them in real-time, no need to restart Brackets. Additionally, the plugin will not load a dictionary unless it actually needs to be used. A good example is if both the American and British English dictionaries are specified to load in a user profile, the extension will check the first dictionary, and if the word is spelled correctly it won’t consult the second dictionary. Only when a word is flagged as misspelled by one dictionary will the extension start checking in other dictionaries.

The following image shows what it looks like when there are spelling errors. You can also right click on incorrect word to view suggestions and replace the word. There is currently no feature to add to dictionaries through the UI.

it is important to note that the spell checker will attempt to spell check your source code. It will even spell check the various words that make up a camelCased variable name. Give it a try, and if it is too much in your code you can disable it from the UI when working on source code.

Getting Brackets

Downloads Brackets here for Mac, Windows and Linux (Debian/Ubuntu). Brackets is built with HTML, CSS and JS, but currently runs as a desktop application in a thin native shell that can access your local files.

Updates are released about once a month.

The Basics

Initially, Brackets opens a default «Getting Started» project. Follow the instructions in the HTML code for a quick walkthrough of Brackets features.

You can open a different folder in the file tree on the left using File > Open Folder. Brackets considers this folder your «project»: it acts as the scope for various search operations, and some settings are tied to the folder you have open. You can easily switch back to previous projects by clicking on root folder name in the file tree. You can also drag a folder from the OS onto the Brackets window to open it in the file tree, and drag files onto the Brackets window to open them.

Unlike other editors that show open files in tabs, Brackets has a «Working Files» list, which is displayed above the file tree. Clicking a file in the file tree just views it, but doesn’t add it to the Working Files list — so you can quickly browse through different files without cluttering the list. If you make an edit, the file is automatically added to Working Files. To add a file without editing it, double-click it in the file tree.

Split View

Initially Brackets will show just one editor in the main view but you can split the main view so that 2 editors can be shown in whichever orientation you prefer (vertical or horizontal).

You can do this by selecting View > Horizontal Split or View > Vertical Split. This splits the main view into 2 panes so that 2 files can be shown at the same time. Splitting the main view also creates a second «Working Files» list, which shows which files are open in which pane. You can drag a file between the two «Working Files» lists to move it to the opposite pane.

Brackets will remember the view layout for each project so switching to another project will show the layout you had chosen when the project was closed. And, if you’d prefer to go back to just a single view, you can select View > No Split to go back to a single view. Doing so does not close the files currently opened. Brackets will just merge the two «Working Files» lists and keep your changes in memory until you’re ready to save them.

Brackets doesn’t support opening a file in both panes but we are planning to ship that in a future release.

Extensions

In addition to the core features built into Brackets, there is a large and growing community of developers building extensions that add all sorts of useful functionality. You can search for and install/uninstall extensions using File > Extension Manager… (or click the «plugin block» icon on the toolbar). You can even temporarily disable extensions and re-enable them later from the Extension Manager.

You can also browse the available extensions online without installing Brackets first.

Themes

You can change the color scheme of the editor by downloading a theme from via the Extension Manager (search for «theme» in the Extension Manager to find them). You can even create your own custom theme to get editor colors that suit your personal taste.

Brackets Highlights

Quick Edit

Instead of cluttering up your coding environment with lots of panels and icons, the Quick Edit UI in Brackets puts context-specific code and tools inline.

You open Quick Edit’s inline editors by pressing Ctrl/Cmd-E when your cursor is on certain pieces of code. For example:

  • In an HTML file with the cursor inside a class or id attribute (name or value) or on the tag name — Quick Edit will show you all the CSS, SCSS and LESS rules in your project that match. You can edit these rules directly inline, without ever leaving the context of the HTML file.
    • When multiple rules match, navigate among them using the list on the right side (or use Alt-Up/Down).
    • To create a new CSS rule directly from the inline editor, click the New Rule button (or press Ctrl-Alt-N/Cmd-Opt-N).
  • In any file with a hex color or rgb/rgba/hsl/hsla color — Quick Edit opens an inline color picker for previewing and adjusting the color. The color picker also lists the top most-used colors from other parts of the file for quick access.
  • In a JavaScript file with the cursor on a function name — Quick Edit will show you the function’s body (even if it’s in a different file).
  • In a CSS/LESS/SCSS file with the cursor on a cubic-bezier() or steps() transition timing function — Quick Edit opens a graphical transition curve editor. Pre-defined timing functions ease, ease-in, ease-out, ease-in-out, step-start, and step-end are also valid starting points.

Quick Docs is a related feature that displays relevant documentation inline. Use Ctrl/Cmd-K to open Quick Docs:

  • In a CSS/LESS/SCSS file with the cursor on a CSS property/value — Quick Docs opens documentation from the Web Platform Docs project.

You can open multiple inline editors and docs viewers simultaneously. To close a single inline editor or docs viewer, click the «X» in the upper-left or press Escape while it has focus. To close all inline editors & docs at once, place your cursor back in the main enclosing code editor and press Escape.

Live Preview

Brackets works directly with your browser to push code edits instantly, so your browser preview is always up to date while you’re coding — no page reloads needed. In order to keep your current web browsing unaffected, Brackets Live Preview opens an additional copy of Chrome using a separate Chrome profile.

There are two different ways to use Live Preview:

With no backend (i.e. server-side) logic — Open an HTML file and select File > Live Preview (or click the «lightning bolt» icon). Brackets will launch Chrome and open your file in a new tab. The content is served statically from a built-in server that Brackets runs — it doesn’t contain any of your app’s backend logic.

This mode offers the full range of Live Preview functionality:

  • Browser preview updates in real time as you type in HTML and CSS files (without reloading)
  • File extensions recognized for HTML files are: htm, html, and xhtml.
  • If you edit any other type of file, the page is auto-reloaded when you save
  • When you move the cursor around an HTML file, the corresponding element is highlighted in the browser
  • When you move the cursor around a CSS/LESS/SCSS file, all elements matching the current rule are highlighted in the browser
  • (All cursor-driven highlighting can be disabled by unchecking View > Live Preview Highlight)

All the CSS features above also work when you’re in an inline Quick Edit CSS editor.

Using your own backend — Make sure your local server is already running, serving files from the same folder Brackets is editing. Choose File > Project Settings and enter whatever URL corresponds to the root folder that’s open in Brackets (typically a localhost URL). Then open a file for one of your webpages (e.g. an HTML, PHP, or ASP file) and launch Live Preview. Brackets will launch Chrome with the correct URL to load that page from your local server.

However, Live Preview has the following limitations when using your own backend:

  • The browser won’t update immediately as you type in server-processed files (such as HTML or PHP) — only changes to CSS files will be reflected in real time. For server-processed files, Brackets will automatically reload the page on save to update the browser preview.
  • «Live Highlighting» is disabled for server-processed files. It will still work when your cursor is in a CSS file, however.

Why do these limitations exist? To enable HTML live editing, Brackets needs to inject some annotations into your HTML code before the browser loads it. Normally, the built-in Brackets server does this. When using your own server instead, Brackets can’t inject those annotations. Without the annotations, Brackets can’t map edits and cursor positions from your source file onto the corresponding DOM nodes in the browser.

Note: The «Experimental Live Preview» mode (aka multi-browser Live Preview) does not support using a custom server. The reasons are similar to the explanation above (additional detail here).

Live Preview with SCSS/LESS

Live Preview won’t update in real time as you type in LESS/SCSS files. However, if you use a third-party «file watcher» to automatically recompile your CSS on save, Live Preview will automatically update on save to reflect the changed CSS file (without reloading). You can also use a Brackets extension such as Brackets SASS or LESS AutoCompile for this. However — if you’re using less.js to dynamically compile your LESS at runtime, Live Preview won’t be able to update the page; you’ll need to reload to see changes.

Other limitations

Live Preview currently has a few other important limitations:

  • It only works with desktop Chrome as the target browser.
  • Opening the Developer Tools in Chrome will close the live development connection.
  • Files must be inside your «project» (the root folder you currently have open in Brackets).
  • Only one HTML file can be previewed at a time. If you switch to a different HTML file in Brackets, the browser preview will switch to that new page as well.
  • Updating pauses when the HTML is syntactically invalid (e.g. after you type ‘<‘ for a new tag but before you type the closing ‘>’). The line number and Live Preview icon turn red in this case. Brackets will resume pushing changes to the browser when syntax becomes valid again.

See Live Preview troubleshooting for additional help.

Experimental Live Preview

Experimental multi-browser live preview can be enabled/disabled Under File > Enable Experimental Live Preview menu. This addresses some of the limitations of current Live Preview.

  • Target multiple browsers and preview on them simultaniously.
  • Developer Tools in chrome can be opened without interrupting the Live Preview workflow.

Quick View

Quick View makes it easy to visualize assets and colors in your code. Just hover your
mouse over a color, gradient, or image reference, and a popover will appear showing
a preview. You can disable this feature in the View menu.

Other Features

Command Line Integration

Brackets can be launched from command line- using brackets <file/folder/nothing> on Windows and Mac. On Windows, you can even right-click on a file/folder from Windows Explorer and select «Open With Brackets»/»Open as Brackets Project» respectively to launch Brackets.

Code Folding

With Brackets, you can expand/collapse blocks of code using indicators next to the line numbers, or via keyboard shortcuts.

Multiple Selections

Brackets supports multiple cursors, multiple selections, and rectangular selections, as well as Undo Selection and useful commands like Add Next Match to Selection. See Working with Multiple Selections for more information.

Settings

  • Indentation and tabs — To change the default indentation for the editor, use the controls on the right end of the status bar at the bottom of the window. Click the word «Spaces» or «Tab Size» to switch whether you’re using spaces or tabs, and change the indentation size by clicking on the number to the right. Note that Brackets uses «soft tabs», so even if spaces are inserted, the cursor moves as if tabs are present.
  • Editor font and colors — There are no official preferences for these yet. However, there are unofficial ways to Customize your code font, and several extensions add the ability to choose different themes.

See also the Preferences section below.

Quick Open

To quickly jump to a file, press Ctrl/Cmd-Shift-O and type part of the filename. You can type abbreviations or other non-contiguous parts of the name, and Quick Open will intelligently find the best matching file.

Quick Find Definition

To quickly jump around within a file, press Ctrl/Cmd-T to see an outline view — functions in a JS file, selectors in a CSS/LESS/SCSS file, etc. Similar to Quick Open, you can type parts of a name to filter the list.

Instant Find in Files

The updated Find In Files feature- Instant Search shows results as you type. To start a search, press Ctrl/Cmd + Shift + F and start entering your query string. You see the matches almost instantly in the results panel as you type in the search bar. You can refine the search in files using case-sensitive and regex searches. You could even make the search in a specific folder(right click a folder in the file tree and select Find in) or exclude files based on exclusion sets(Press ctrl/cmd + shift + fand click on the exclusion set dropdown).

Code Hints

Code hints generally pop up automatically while you’re typing, but you can also manually display them with Ctrl-Space (note that this shortcut uses Ctrl even on Mac).

Code hints are provided by default in a number of places:

  • HTML — tag names, attribute names, attribute values, and & entities.
  • CSS, LESS, SCSS — all property names, and enumerated property values (those where the value is a discrete list of keywords).
    • Code hints don’t yet work for shorthand properties (e.g. background), only for individual properties (e.g. background-repeat).
  • JS — variables and functions, using the Tern code intelligence engine.
    • Tern makes intelligent inferences about what properties and methods a given object contains, based on an analysis of your code. In addition to the current file, Brackets looks at other files in the same folder and any files referenced by a require() statement.
    • In cases where Brackets can’t determine exactly what hints should be available, it will fall back to a list of heuristic guesses. These guesses are shown in italics.
    • JS code hints use smart matching — so you can type camel-case initials and other shorthand to filter the hint list more quickly (e.g. type «gsp» for getScrollPos).
    • You also get argument hints — while you’re typing arguments to a function, an indicator above the cursor lists the expected types of the arguments. Normally this appears automatically, but you can also display it manually by pressing Ctrl-Shift-Space. (Nothing is shown if Tern is unsure where the function is defined, however).

ESLint

By default, Brackets runs ESLint on JavaScript files when you initially open them and whenever you save changes. If ESLint finds problems, the results are shown in a panel at the bottom. If your file is clean, you’ll see a green checkmark in the status bar instead.

See all the configuration options available at [https://eslint.org/docs/user-guide/configuring](https://eslint.org/docs/user-guide/configuring]. You can hide the ESLint results panel by clicking the close box at the top (the status bar icon will still indicate if ESLint has found problems with either a green checkmark or yellow warning symbol), or you can turn off ESLint completely by unchecking View > Lint Files on Save.

Brackets Health Report

Anonymous data to help improve Brackets. You can preview the data that will be sent, or opt-out if desired. We’ve gone to great lengths to protect your privacy and maintain transparency — see Help > Health Report for details.

Keyboard Shortcut Cheat Sheet

Here are some keyboard shortcuts that are worth knowing. Also see the
Brackets Shortcut wiki page
for a more complete list of shortcuts and the User Key Bindings Wiki to learn how to setup Brackets to use your preferred keyboard shortcuts.

Windows Mac Description
Ctrl-E Cmd-E Open/close the inline editor (Quick Edit)
Alt-Up/Down Alt-Up/Down Switch between rules in the inline editor
Ctrl-K Cmd-K Open Quick Docs
Ctrl-Space Ctrl-Space Bring up code hints, if applicable
Ctrl-Shift-O Cmd-Shift-O Bring up the Quick Open prompt
Ctrl-G Cmd-L Go to a line in the current file
Ctrl-T Cmd-T Go to a method/selector in the current file (Quick Find)
Ctrl-Shift-H Cmd-Shift-H Show/hide the sidebar
Ctrl-Alt-P Cmd-Alt-P Live preview

Preferences

There is not yet a global user interface for all preferences (so the required «Preferences» menu item on Mac is disabled). You can change a few preferences from the Brackets user interface — such as word wrap or the current color theme. But many more preferences are available via JSON configuration files. To modify these preferences, first choose how globally you want to set the preference:

Scope of preferences

  • User-global preferences — your default settings. To edit, choose Debug > Open Preferences File.
  • Project-level preferences — override any number of preferences on a project-specific basis. Create a .brackets.json file in the root of your project.

Choosing Debug > Open Preferences File opens the global preferences file «brackets.json» along with the default preferences in left panel in split view. You can refer to the available settings in the left panel and change the preferences in the right. Code hints is available for the settings of this file.
Changing a preference using the Brackets UI modifies the project’s .brackets.json file if the preference is already set there; otherwise it modifies the user-global setting.

Within either file, there are three levels of specificity at which you can set a preference:

  • default — global (user-level file) or project-global (project-level file)
  • "path" layer — overrides in effect for files that match the given path/filename wildcard
  • "language" layer — overrides in effect for files that Brackets detects as the given programming language (this is also filename/extension based, but it’s easier to work with since Brackets already understands many file extensions out of the box, and additional languages supported by Brackets extensions can automatically be used here too).

See the sample .json file below for examples of how to use the path/language-specific preferences.

List of supported preferences

These are all the settings that are currently supported:

Setting Default Description
closeBrackets false Automatically close braces, brackets and parentheses
closeOthers.above,
closeOthers.below,
closeOthers.others
all true False to remove the Close Others, Close Others Above, Close Others Below items from the Working Files context menu
closeTags {"whenOpening": true, "whenClosing": true, "indentTags": []} Sets the tag closing options. See the CodeMirror documentation.
code-folding.alwaysUseIndentFold false Since 1.3. Always generate collapsible section markers when indent level changes (for > minFoldSize lines), including in plain text files
code-folding.enabled true Since 1.3. True to show collapsible section indicators in the gutter. Disabling code folding also hides its View menu items
code-folding.hideUntilMouseover false Since 1.3 Section-collapsing markers are only visible when you move the mouse over the gutter. May improve performance
code-folding.maxFoldLevel 2 Since 1.3. Limits how many levels deep Collapse All applies
code-folding.minFoldSize 2 Since 1.3. Blocks must be > minFoldSize lines long (including opening and closing lines) before a collapsible section icon appears
code-folding.saveFoldStates true Since 1.3. Remember collapsed sections if you close and reopen a file or project
codehint.AttrHints true Enable/disable HTML attribute hints
codehint.CssPropHints true Enable/disable CSS/LESS/SCSS property hints
codehint.JSHints true Enable/disable JavaScript code hints
codehint.SpecialCharHints true Enable/disable HTML entity hints
codehint.SVGHints true Enable/disable SVG code hints
codehint.TagHints true Enable/disable HTML tag hints
codehint.UrlCodeHints true Enable/disable URL hints in HTML & CSS/LESS/SCSS
dragDropText false Enable/disable Drag & Drop functionality
healthData.healthDataTracking true Since 1.3. Enable the Health Data Tracking
highlightMatches false Enables automatic highlighting of matching strings throughout the document:

  • true — highlight all strings that match the current selection (nothing is highlighted when no selection)
  • {"showToken": true} — highlight all strings that match the token the cursor is currently in (no selection needed)
  • {"wordsOnly": true} — highlight only when selection is a complete token
insertHintOnTab false True to insert the currently selected code hint on tab
jscodehints.noHintsOnDot false If true, do not automatically show JS code hints when . is typed.
language.fileExtensions undefined Additional mappings from file extension to language name (see Language Support#Preferences)
language.fileNames undefined Additional mappings from file name to language name (see Language Support#Preferences)
linting.enabled true Determines if Code Inspection is on
linting.prefer undefined Since 1.1. Array of linters (CodeInspection providers) to run first. For example: ["ESLint", "SassLint"]. If provider on the list is not installed, it will be silently ignored. By default, all the linters will be run.
livedev.enableReverseInspect true False to disable live preview reverse inspect.
livedev.multibrowser false True to enable experimental Live Preview.
linting.usePreferredOnly false Since 1.1. If set to true, then only providers specified in linting.prefer will be run (if installed).
maxCodeHints 50 Maximum code hints displayed at once
proxy undefined The URL of the proxy server used for extension installation (general syntax: «http://username:password​@server:port/»)
scrollPastEnd false True to be able to scroll beyond the end of the document
showCodeHints true If false, all code hints are disabled
showCursorWhenSelecting false Keeps the blinking cursor visible when you have a text selection
showLineNumbers true Show line numbers in a «gutter» to the left of the code
smartIndent true Automatically indent when creating a new block
softTabs true False to turn off soft tabs behaviour
sortDirectoriesFirst false for Mac, true otherwise True to sort the directories first in the project tree
spaceUnits 4 Number of spaces to use for space-based indentation
staticserver.port Port number that the built-in server should use for Live Preview
styleActiveLine false Highlight background color of the line the cursor is on
tabSize 4 Number of spaces to display for tabs
useTabChar false True to use tabs instead of spaces
uppercaseColors false Generate uppercase hex colors in Inline Color Editor
wordWrap true Wrap lines that exceed the viewport width

A Sample preferences JSON file:-

{
    "spaceUnits": 4,
    "closeTags": {
        "whenOpening": false,
        "whenClosing": true
    },
    "proxy": "http://username:password@proxy.com:8080",
    "path": {
        "src/thirdparty/someLibrary.js": {
            "useTabChar": true,
            "tabSize": 4,
            "linting.enabled": false
        },
        "**.js": {
            "insertHintOnTab": true,
            "scrollPastEnd": true
        }
    },
    "language": {
        "javascript": {
            "linting.prefer": ["ESLint"],
            "linting.usePreferredOnly": true
        }
    },
    "language.fileExtensions": {
        "foo": "javascript"
    },
    "language.fileNames": {
        "pavement": "python"
    }
}

With this .brackets.json file at the top of your project, your files will all default to 4 space indentation. However, src/thirdparty/someLibrary.js will be set to use tabs with 4 spaces for the tabs and linting will be turned off. Note that values for paths match fileglob rules. So for example, *.js will only match JS files in the root of the project whereas **.js will match files with the JS extension anywhere in the project.

What’s Next?

For more info on Brackets, check out these resources:

  • How to contribute to the Brackets project, including filing bugs and editing the source code
  • How to write an extension
  • Join the community!
    • @brackets on Twitter
    • Discord
  • Brackets blog
  • Troubleshooting for common issues
  • Watch our GitHub activity stream or latest release notes to see what’s in the works for the next update!

Содержание

  1. ТОП-3 расширений для Brackets
  2. Расширение beautify
  3. Расширение autosave
  4. Расширение emmet

Если ты встал на скользкую дорожку веб-разработки, то стартом твоей карьеры будет покупка большой упаковки кофе и установка редактора кода. Первую проблему, мы уверены, ты решишь самостоятельно, а со второй попробуем помочь. Многие в качестве редактора выбирают именно Brackets от компании Adobe, который, вполне заслужено, считается одним из лучших инструментов для редактирования кода. А еще это бесплатно!

Вебдев, как ты понимаешь, не заканчивается написанием кода и версткой шаблонов — это только вершина айсберга. Для полноценного сайта необходим полный спектр работ по продвижению, айдентике, контексту. Посмотри на спектр услуг казахстанской диджитал студии Globalm — именно так должен создаваться проект с нуля. Комплексный подход обеспечивает целостность сайта от и до: общий концепт, программирование, брендинг, проверка работы в тестовой среде, деплой в продакшн и последующее сопровождение.

Редактор кода Brackets: ТОП-3 плагина, которые нужно установить, чтобы начать работать

В данном редакторе реализовано огромное количество плагинов, чтобы облегчить процесс написания кода. Мы выбрали три самых-самых необходимых для новичков. Чтобы установить что-либо в Brackets нужно нажать на менеджер расширений в правом верхнем углу

Редактор кода Brackets: ТОП-3 плагина, которые нужно установить, чтобы начать работать

Далее в поисковой строке набираем нужные нам расширения. А нужны нам следующие:

Расширение beautify

Редактор кода Brackets: ТОП-3 плагина, которые нужно установить, чтобы начать работать

Приводит говнокод в приличный вид. Выравнивает элементы, тэги, проводит автоматическое «причёсывание» кода. Редактировать можно через горячие клавиши CTRL+SHIFT+L, либо через меню «Правка» -> «beautify». Для примера:

Редактор кода Brackets: ТОП-3 плагина, которые нужно установить, чтобы начать работать

Расширение autosave

Редактор кода Brackets: ТОП-3 плагина, которые нужно установить, чтобы начать работать

Позволяет не парится насчет постоянных CTRL+S (сохранение). Ведь в суматохе и забыть можно, да и от зависания операционной системы никто не застрахован. Чтобы не потерять наработки, плагин будет автосейвить твой прогресс, а ты больше не будешь нервничать.

Расширение emmet

Редактор кода Brackets: ТОП-3 плагина, которые нужно установить, чтобы начать работать

Одним махом (если точнее, то хоткеями: сначала «!» , а затем нажать TAB) создает тебе в новом файле «скелет» HTML-файла, чтобы каждый раз не прописывать одно и тоже в каждом новом файле. Естественно, это не все возможности плагина. Важно! Некоторые функции (в т.ч. которая описана выше) будет работать, только после того, как вы сохраните редактируемый файл в формате HTML (т.е. создали новый и сразу сохранили). Пример того, как работает !+TAB:

Редактор кода Brackets: ТОП-3 плагина, которые нужно установить, чтобы начать работать

Как вам статья?

СД: НЧ

Без плагинов Brackets не лучше других редакторов, но с ними его стоит хотя бы попробовать.

Введение

Не так давно на Хабре было опубликовано множество статей, касающихся тем или иным образом редактора Brackets. У многих людей сразу же появились вполне справедливые вопросы:

  1. Чем он лучше используемого мной %EDITOR_NAME%?
  2. Много ли под него плагинов?
  3. Стоит ли связываться или лучше использовать какую-нибудь известную IDE или текстовый редактор?

Надеюсь, после чтения этой статьи каждый сможет найти для себя ответы на эти вопросы.

Функционал «из коробки»

Хоть Brackets и позиционируется как текстовый редактор, по факту он всё больше напоминает полноценную IDE. Тем не менее, следует сказать о том, что мы получаем при базовой установке этого редактора:

  • плагин для Live Preview — работает только с Google Chrome. Вносим какие-либо изменения в код в редакторе — в окне браузера автоматически отображаются изменения
  • подсветка синтаксиса
  • подсказки при редактировании CSS, JS и HTML-файлов
  • корявое отображение кириллического текста. Обещают исправить в одном из следующих релизов. Сейчас есть несколько обходных путей, об этом ниже.

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

Brackets из коробки

Brackets для сомневающихся и новичков

Общего назначения

Extensions Rating

Новичкам советую ставить это дополнение самым первым. Оно позволяет упорядочивать другие дополнения в каталоге по различным критериям, также отображает различную дополнительную информацию: количество загрузок, звезд и форков на GitHub, что позволяет хотя бы примерно оценить полезность данного расширения.

До и после

Brackets для сомневающихся и новичков

Brackets для сомневающихся и новичков

Brackets Git

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

Git в Brackets

Brackets для сомневающихся и новичков

Code Folding

Без этого плагина в Brackets нет такой нужной функциональности, как сворачивание блоков кода. После установки слева, рядом с номерами строк, появятся треугольники, которые позволяют сворачивать те фрагменты, которые сейчас не нужны.

Сворачивание кода

Brackets для сомневающихся и новичков

Emmet

В представлении не нуждается, но для новичков будет интересно о нём узнать. Этот плагин позволяет существенно ускорить ввод текста при редактировании LESS, CSS и HTML.
Например, вводим такую конструкцию:

button.btn.btn-primary{Кнопка}

После нажатия клавиши Tab она будет развёрнута в такую:

<button class="btn btn-primary">Кнопка</button>

Идём дальше:

div.btn-toolbar>(button.btn.btn-default{Кнопка})*3

по нажатию развернётся в

<div class="btn-toolbar">
    <button class="btn btn-default">Кнопка</button>
    <button class="btn btn-default">Кнопка</button>
    <button class="btn btn-default">Кнопка</button>
</div>

Не буду делать дальнейших спойлеров, лучше почитайте уже имеющиеся на Хабре обзоры:
Прощай, Zen Coding. Привет, Emmet!
Вышел Emmet v1.0
Также рекомендую официальную инструкцию (на английском).

Codeoverview

Включает небольшую панель в правой части окна редактора, где отображается весь код «с высоты птичьего полёта». Можно быстро перейти к любому интересному участку.
Помимо плагина CodeOverview есть также BluePrint в стадии Beta. Какой лучше — решайте сами.

Обзор кода

Brackets для сомневающихся и новичков

Documents Toolbar

Для тех, кто привык к вкладочному интерфейсу и не хочет от него отвыкать (взамен Brackets предлагает список открытых файлов над деревом).

Brackets Fonts

Позволяет выбрать из списка шрифт, которым будет выводиться текст в редакторе. Обратите внимание на то, как стали отображаться кириллические символы. Кроме этого есть ещё несколько плагинов с таким же функционалом. Имеется возможность открыть в меню пункт Вид/Themes, где вручную прописать, какие шрифты следует использовать.

Шрифты

Brackets для сомневающихся и новичков

Http Server for Brackets

Запускает локальный HTTP-сервер для отладки вашего проекта. В чём отличие от встроенного Live Preview?

  1. Это не LivePreview, т.е. страницу надо обновлять вручную.
  2. Обратиться к данному серверу можно из любого браузера, установленного в системе. Разработчики под IE и Firefox ликуют.

Также в каталоге расширений есть плагин Static Preview, подобный LivePreview, но позволяющий делать «живую» правку в других браузерах, однако на текущий момент (8 ноября 2014 года) он «вешает» Brackets. Если быть более точным, он не даёт редактору возможности нормально завершить свою работу — сохранить настройки и список открытых файлов. Возможно, эту ошибку скоро исправят, но имеющиеся проблемы лично меня уже оттолкнули от этого плагина.

Grunt for Brackets

Brackets может предложить плагин для Grunt’а. Его настройка — отдельная тема, некоторые даже целые книги написали об этом. От себя замечу лишь, что сейчас, в 2014 году, не использовать Grunt или Gulp — признак дурного тона и несерьёзности разработчика.

Beautify, Beautifer

Простым нажатием комбинации клавиш Ctrl+L или Ctrl+B плохо оформленный JS- или HTML-код превращается в оформленный вполне приемлемо. На картинках global_main.js Хабра до и после применения данного плагина. Не используйте эти плагины для LESS! Они вставляют пробелы после двоеточий, что делает LESS-файл некомпилируемым.

Ассистент, всё в мясорубку!

Brackets для сомневающихся и новичков

Brackets для сомневающихся и новичков

QuickSearch

При двойном клике на выражение подсвечивает все его вхождения в документ. Автор расширения вдохновлён Notepad++, чего не скрывает.

Notepad++? Нет.

Brackets для сомневающихся и новичков

SFtpUpload, FTP-Sync

Позволяют выгружать файлы проекта на сервер через (S)FTP. Умеют в авторизацию по ключу.

FTP Sync, SFtpUpload

Brackets для сомневающихся и новичков

Brackets для сомневающихся и новичков

Верстальщику

LESS Autocompile

Для тех, кто не хочет головной боли от правки CSS давно придуман LESS. Данный плагин позволяет автоматически компилировать ваши .less-файлы при сохранении. В текущем состоянии требует небольшой настройки.

  • В заголовке .less-файла нужно написать что-то вроде:
    	// out: ../css/login.css
    

    если нужно переопределить каталог вывода .css. В противном случае .css-файл будет создан там же, где и .less, а это не очень хорошо. Все остальные настройки LESS для файла прописываются здесь же.

  • В настройках проекта нужно явно указать, какие файлы LESS должен обрабатывать. Для этого нужно добавить в .brackets.json или compile.json (оба лежат в корневом каталоге проекта, первый автоматически создаётся Brackets) следующее:
    	{
    	    "less": [
    	        "static/login/less/login.less",
    	        "static/desktop/less/index.less"
    	       //И все остальные LESS-файлы
    	    ]
    	}
    
Brackets Autoprefixer

Думаю, этот плагин не нуждается в представлении. Он вставляет в имеющийся CSS-файл необходимые дополнения для поддержки вендорных префиксов и старых браузеров. В зависимости от настроек можно получить самые разные результаты. Имеет довольно простое окно параметров. Полный список можно посмотреть на странице проекта на GitHub.

Минимализм настроек Autoperefixer

Brackets для сомневающихся и новичков

CSSLint, LESSLint, LESS StyleSheets Formatter

Три плагина, призванные помочь в улучшении вашего LESS- и CSS-кода. Будут указывать на типичные и не очень ошибки. Пример на картинке.

Ошибки в CSS

Brackets для сомневающихся и новичков

HTMLHint, More CSS Code Hints, More HTML5 Code Hints

Плагины просто дают больше подсказок при правке HTML и CSS. Учитывая, с какой скоростью базовую поставку Brackets добавляются различные улучшения и дополнения, следует ждать интеграции функционала этих плагинов в ядро.

ColorHints, Brackets Color Picker

Первый выводит подсказку при наведении курсора на код или название цвета в редакторе, умеет также показывать градиенты. Второй выводит окошко с палитрой для выбора нужного цвета. При редактировании LESS-файлов окошко для выбора цвета следует вызывать по Ctrl+Alt+K, если оно не появилось автоматически после ввода слова color.

Подсказки при вводе градиентов и цвета

Brackets для сомневающихся и новичков

Brackets для сомневающихся и новичков

JavaScript-разработчику

JSHint, JSLint, JSHint Configurator, JSLint Configurator

Крайне полезные плагины для разработчиков, которые не только верстают, но и пишут код на JavaScript. На выбор JSHint и JSLint, хотя можно использовать оба (второй куда более предвзято отнесётся к вашему коду). Конфигураторы, как видно из названия, позволяют настроить разные параметры проверки кода, например, игнорировать использование функции requirejs до её объявления.

Все и так знают, для чего нужен каждый из параметров

Brackets для сомневающихся и новичков

FuncDocr

Плагин позволяет быстро документировать функции JS.
Например, имеется следующий код:

Desktop.prototype.addResizeHandler = function(handler) {
    if ($.isFunction(handler)) {
        this.resizeActions.push(handler);
    }
};

Становимся перед объявлением функции и вводим /**. После нажатия клавиши Enter FuncDocr развернёт этот комментарий, подставив заготовки, куда надо лишь вписать нужное:

/**
 * [[Description]]
 * @param {[[Type]]} handler [[Description]]
 */
Desktop.prototype.addResizeHandler = function(handler) {
    if ($.isFunction(handler)) {
        this.resizeActions.push(handler);
    }
};
AngularJS Code Hints, AngularJS for Brackets

Добавляют подсказки при вводе Angular-директив. Я плохо знаком с этим фреймворком, но надеюсь, указанные два плагина оправдают надежды специалистов.

Rename JavaScript Identifier

Становимся на идентификатор, нажимаем Ctrl+R, вводим новое имя — все вхождения переменной в скрипт автоматически переименовываются.

Ложка дёгтя

При всём многообразии настроек и параметров, есть некоторые претензии к Brackets. Первая и самая важная — скорость работы. При наличии большого количества плагинов и множестве подключенных к документу CSS начинает довольно заметно подтормаживать появление подсказок при редактировании документов. Иногда довольно долго приходится ждать реакции редактора при правке JS-скриптов. Второе — довольно неудобное дерево навигации. Третье — некоторые плагины способны «повесить» редактор, не давая ему нормально закрыться и сохранить настройки.

Автор: dunmaksim

Источник

Задать вопрос

Sergei Zharov

@srgazh

SA

  • boch112

brackets

  • Brackets

Есть ли расширение с поддержкой Русского языка.


  • Вопрос задан

    более трёх лет назад

  • 436 просмотров



3

комментария

Подписаться

2



Простой


3

комментария

  • boch112

    Vkok

    @boch112

    по ходу нет

    Написано

    более трёх лет назад

  • Matyushko

    @Matyushko

    Vkok, Нашли ли вы решение?

    Написано

    более двух лет назад

  • boch112

    Vkok

    @boch112

    Matyushko, нет, так и не нашел)

    Написано

    более двух лет назад


Решения вопроса 0

Пригласить эксперта


Ответы на вопрос 0


Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации


Похожие вопросы

  • html

    • HTML

    • +2 ещё




    Простой

    Не подключается .CSS к html?


    • 2 подписчика
    • 26 июн. 2022


    • 281 просмотр

    2

    ответа

  • brackets

    • Brackets




    Простой

    Я поламала Brackets. В какой папке в Brackets на Windows размещены плагины?


    • 1 подписчик
    • более года назад


    • 123 просмотра

    1

    ответ

  • текстовые-редакторы

    • Текстовые редакторы

    • +1 ещё




    Средний

    Как называется данная цветовая тема для Brackets (скрин)?


    • 2 подписчика
    • более года назад


    • 92 просмотра

    0

    ответов

  • brackets

    • Brackets

    • +1 ещё




    Сложный

    Не работает emmet в редакторе brackets?


    • 1 подписчик
    • более года назад


    • 188 просмотров

    0

    ответов

  • css

    • CSS

    • +1 ещё




    Простой

    В brackets не дает в css сделать несколько функций?


    • 1 подписчик
    • более года назад


    • 46 просмотров

    1

    ответ

  • linux

    • Linux

    • +2 ещё




    Средний

    Некорректно отображается левая боковая панель в brackets?


    • 1 подписчик
    • более года назад


    • 38 просмотров

    0

    ответов

  • ubuntu

    • Ubuntu

    • +1 ещё




    Средний

    Не работает боковая панель в brackets, как исправить?


    • 1 подписчик
    • более года назад


    • 30 просмотров

    0

    ответов

  • linux

    • Linux

    • +2 ещё




    Сложный

    Не работает боковая панель в brackets, как исправить?


    • 1 подписчик
    • более года назад


    • 67 просмотров

    0

    ответов

  • brackets

    • Brackets




    Простой

    Как исправить ошибку в Brackets?


    • 1 подписчик
    • более года назад


    • 2232 просмотра

    2

    ответа

  • html

    • HTML

    • +2 ещё




    Простой

    Про brackets и автозаполнение?


    • 1 подписчик
    • более года назад


    • 225 просмотров

    1

    ответ


  • Показать ещё
    Загружается…

Вакансии с Хабр Карьеры

Senior Laravel разработчик (удаленно)

2V Modules

от 2 100 до 3 200 $

Инженер по данным

Флексибейс

от 100 000 ₽

Разработчик C++

Сбер

Москва

от 190 000 до 240 000 ₽

Ещё вакансии

Заказы с Хабр Фриланса

Собрать описания товаров с сайта

21 июн. 2023, в 19:05

2000 руб./за проект

Доработка и обновление B2B агрегатора

21 июн. 2023, в 19:05

1000 руб./в час

Собрать описания товаров с сайта

21 июн. 2023, в 19:04

2000 руб./за проект

Ещё заказы

Минуточку внимания

Присоединяйтесь к сообществу, чтобы узнавать новое и делиться знаниями

Зарегистрироваться

Войдите на сайт

Чтобы задать вопрос и получить на него квалифицированный ответ.

Войти через центр авторизации

Description

CodeHintManager Overview:

The CodeHintManager mediates the interaction between the editor and a
collection of hint providers. If hints are requested explicitly by the
user, then the providers registered for the current language are queried
for their ability to provide hints in order of descending priority by
way their hasHints methods. Character insertions may also constitute an
implicit request for hints; consequently, providers for the current
language are also queried on character insertion for both their ability to
provide hints and also for the suitability of providing implicit hints
in the given editor context.

Once a provider responds affirmatively to a request for hints, the
manager begins a hinting session with that provider, begins to query
that provider for hints by way of its getHints method, and opens the
hint list window. The hint list is kept open for the duration of the
current session. The manager maintains the session until either:

  1. the provider gives a null response to a request for hints;
  2. a deferred response to getHints fails to resolve;
  3. the user explicitly dismisses the hint list window;
  4. the editor is closed or becomes inactive; or
  5. the editor undergoes a «complex» change, e.g., a multi-character
    insertion, deletion or navigation.

Single-character insertions, deletions or navigations may not
invalidate the current session; in which case, each such change
precipitates a successive call to getHints.

If the user selects a hint from the rendered hint list then the
provider is responsible for inserting the hint into the editor context
for the current session by way of its insertHint method. The provider
may use the return value of insertHint to request that an additional
explicit hint request be triggered, potentially beginning a new
session.

CodeHintProvider Overview:

A code hint provider should implement the following three functions:

  • CodeHintProvider.hasHints(editor, implicitChar)
  • CodeHintProvider.getHints(implicitChar)
  • CodeHintProvider.insertHint(hint)

The behavior of these three functions is described in detail below.

CodeHintProvider.hasHints(editor, implicitChar)

The method by which a provider indicates intent to provide hints for a
given editor. The manager calls this method both when hints are
explicitly requested (via, e.g., Ctrl-Space) and when they may be
implicitly requested as a result of character insertion in the editor.
If the provider responds negatively then the manager may query other
providers for hints. Otherwise, a new hinting session begins with this
provider, during which the manager may repeatedly query the provider
for hints via the getHints method. Note that no other providers will be
queried until the hinting session ends.

The implicitChar parameter is used to determine whether the hinting
request is explicit or implicit. If the string is null then hints were
explicitly requested and the provider should reply based on whether it
is possible to return hints for the given editor context. Otherwise,
the string contains just the last character inserted into the editor’s
document and the request for hints is implicit. In this case, the
provider should determine whether it is both possible and appropriate
to show hints. Because implicit hints can be triggered by every
character insertion, hasHints may be called frequently; consequently,
the provider should endeavor to return a value as quickly as possible.

Because calls to hasHints imply that a hinting session is about to
begin, a provider may wish to clean up cached data from previous
sessions in this method. Similarly, if the provider returns true, it
may wish to prepare to cache data suitable for the current session. In
particular, it should keep a reference to the editor object so that it
can access the editor in future calls to getHints and insertHints.

param {Editor} editor
A non-null editor object for the active window.

param {string} implicitChar
Either null, if the hinting request was explicit, or a single character
that represents the last insertion and that indicates an implicit
hinting request.

return {boolean}
Determines whether the current provider is able to provide hints for
the given editor context and, in case implicitChar is non- null,
whether it is appropriate to do so.

CodeHintProvider.getHints(implicitChar)

The method by which a provider provides hints for the editor context
associated with the current session. The getHints method is called only
if the provider asserted its willingness to provide hints in an earlier
call to hasHints. The provider may return null or false, which indicates
that the manager should end the current hinting session and close the hint
list window; or true, which indicates that the manager should end the
current hinting session but immediately attempt to begin a new hinting
session by querying registered providers. Otherwise, the provider should
return a response object that contains the following properties:

  1. hints, a sorted array hints that the provider could later insert
    into the editor;
  2. match, a string that the manager may use to emphasize substrings of
    hints in the hint list (case-insensitive); and
  3. selectInitial, a boolean that indicates whether or not the
    first hint in the list should be selected by default.
  4. handleWideResults, a boolean (or undefined) that indicates whether
    to allow result string to stretch width of display.

If the array of
hints is empty, then the manager will render an empty list, but the
hinting session will remain open and the value of the selectInitial
property is irrelevant.

Alternatively, the provider may return a jQuery.Deferred object
that resolves with an object with the structure described above. In
this case, the manager will initially render the hint list window with
a throbber and will render the actual list once the deferred object
resolves to a response object. If a hint list has already been rendered
(from an earlier call to getHints), then the old list will continue
to be displayed until the new deferred has resolved.

Both the manager and the provider can reject the deferred object. The
manager will reject the deferred if the editor changes state (e.g., the
user types a character) or if the hinting session ends (e.g., the user
explicitly closes the hints by pressing escape). The provider can use
this event to, e.g., abort an expensive computation. Consequently, the
provider may assume that getHints will not be called again until the
deferred object from the current call has resolved or been rejected. If
the provider rejects the deferred, the manager will end the hinting
session.

The getHints method may be called by the manager repeatedly during a
hinting session. Providers may wish to cache information for efficiency
that may be useful throughout these sessions. The same editor context
will be used throughout a session, and will only change during the
session as a result of single-character insertions, deletions and
cursor navigations. The provider may assume that, throughout the
lifetime of the session, the getHints method will be called exactly
once for each such editor change. Consequently, the provider may also
assume that the document will not be changed outside of the editor
during a session.

param {string} implicitChar
Either null, if the request to update the hint list was a result of
navigation, or a single character that represents the last insertion.

return {jQuery.Deferred|{
     hints: Array.<string|jQueryObject>,
     match: string,
     selectInitial: boolean,
     handleWideResults: boolean}}

Null if the provider wishes to end the hinting session. Otherwise, a
response object, possibly deferred, that provides 1. a sorted array
hints that consists either of strings or jQuery objects; 2. a string
match, possibly null, that is used by the manager to emphasize
matching substrings when rendering the hint list; and 3. a boolean that
indicates whether the first result, if one exists, should be selected
by default in the hint list window. If match is non-null, then the
hints should be strings.

If the match is null, the manager will not
attempt to emphasize any parts of the hints when rendering the hint
list; instead the provider may return strings or jQuery objects for
which emphasis is self-contained. For example, the strings may contain
substrings that wrapped in bold tags. In this way, the provider can
choose to let the manager handle emphasis for the simple and common case
of prefix matching, or can provide its own emphasis if it wishes to use
a more sophisticated matching algorithm.

CodeHintProvider.insertHint(hint)

The method by which a provider inserts a hint into the editor context
associated with the current session. The provider may assume that the
given hint was returned by the provider in some previous call in the
current session to getHints, but not necessarily the most recent call.
After the insertion has been performed, the current hinting session is
closed. The provider should return a boolean value to indicate whether
or not the end of the session should be immediately followed by a new
explicit hinting request, which may result in a new hinting session
being opened with some provider, but not necessarily the current one.

param {string} hint
The hint to be inserted into the editor context for the current session.

return {boolean}
Indicates whether the manager should follow hint insertion with an
explicit hint request.

CodeHintProvider.insertHintOnTab

type {?boolean} insertHintOnTab
Indicates whether the CodeHintManager should request that the provider of
the current session insert the currently selected hint on tab key events,
or if instead a tab character should be inserted into the editor. If omitted,
the fallback behavior is determined by the CodeHintManager. The default
behavior is to insert a tab character, but this can be changed with the
insertHintOnTab Preference.

Dependencies

  • CodeHintList
  • CommandManager
  • Commands
  • EditorManager
  • KeyEvent
  • PreferencesManager
  • strings

Functions

Show Private Members


Private

_endSession

End the current hinting session

    function _endSession() {
        if (!hintList) {
            return;
        }
        hintList.close();
        hintList = null;
        codeHintOpened = false;
        keyDownEditor = null;
        sessionProvider = null;
        sessionEditor = null;
        if (deferredHints) {
            deferredHints.reject();
            deferredHints = null;
        }
    }


Private
Public API

_getCodeHintList

Expose CodeHintList for unit testing

    function _getCodeHintList() {
        return hintList;
    }

    function activeEditorChangeHandler(event, current, previous) {
        if (current) {
            current.on("editorChange", _handleChange);
            current.on("keydown",  _handleKeydownEvent);
            current.on("keypress", _handleKeypressEvent);
            current.on("keyup",    _handleKeyupEvent);
            current.on("cursorActivity", _handleCursorActivity);
        }

        if (previous) {
            //Removing all old Handlers
            previous.off("editorChange", _handleChange);
            previous.off("keydown",  _handleKeydownEvent);
            previous.off("keypress", _handleKeypressEvent);
            previous.off("keyup",    _handleKeyupEvent);
            previous.off("cursorActivity", _handleCursorActivity);
        }
    }

    activeEditorChangeHandler(null, EditorManager.getActiveEditor(), null);

    EditorManager.on("activeEditorChange", activeEditorChangeHandler);
 
    // Dismiss code hints before executing any command other than showing code hints since the command
    // may make the current hinting session irrevalent after execution.
    // For example, when the user hits Ctrl+K to open Quick Doc, it is
    // pointless to keep the hint list since the user wants to view the Quick Doc
    CommandManager.on("beforeExecuteCommand", function (event, commandId) {
        if (commandId !== Commands.SHOW_CODE_HINTS) {
            _endSession();
        }
    });

    CommandManager.register(Strings.CMD_SHOW_CODE_HINTS, Commands.SHOW_CODE_HINTS, _startNewSession);

    exports._getCodeHintList        = _getCodeHintList;
    exports._removeHintProvider     = _removeHintProvider;

    // Define public API
    exports.isOpen                  = isOpen;
    exports.registerHintProvider    = registerHintProvider;
    exports.hasValidExclusion       = hasValidExclusion;
});


Private

_getProvidersForLanguageId

Return the array of hint providers for the given language id.
This gets called (potentially) on every keypress. So, it should be fast.

languageId
non-nullable
string
Returns: ?Array.<{provider: Object,priority: number}>
    function _getProvidersForLanguageId(languageId) {
        var providers = hintProviders[languageId] || hintProviders.all;

        // Exclude providers that are explicitly disabled in the preferences.
        // All code hint providers that do not have their constructor
        // names listed in the preferences are enabled by default.
        return providers.filter(function (provider) {
            var prefKey = "codehint." + provider.provider.constructor.name;
            return PreferencesManager.get(prefKey) !== false;
        });
    }

    var _beginSession;


Private

_handleChange

Start a new implicit hinting session, or update the existing hint list.
Called by the editor after handleKeyEvent, which is responsible for setting
the lastChar.

event
Event
editor
Editor
changeList
{from: Pos,to: Pos,text: Array,origin: string}
    function _handleChange(event, editor, changeList) {
        if (lastChar && editor === keyDownEditor) {
            keyDownEditor = null;
            if (_inSession(editor)) {
                var charToRetest = lastChar;
                _updateHintList();

                // _updateHintList() may end a hinting session and clear lastChar, but a
                // different provider may want to start a new session with the same character.
                // So check whether current provider terminates the current hinting
                // session. If so, then restore lastChar and restart a new session.
                if (!_inSession(editor)) {
                    lastChar = charToRetest;
                    _beginSession(editor);
                }
            } else {
                _beginSession(editor);
            }

            // Pending Text is used in hintList._keydownHook()
            if (hintList && changeList[0] && changeList[0].text.length && changeList[0].text[0].length) {
                var expectedLength = editor.getCursorPos().ch - changeList[0].from.ch,
                    newText = changeList[0].text[0];
                // We may get extra text in newText since some features like auto
                // close braces can append some text automatically.
                // See https://github.com/adobe/brackets/issues/6345#issuecomment-32548064
                // as an example of this scenario.
                if (newText.length > expectedLength) {
                    // Strip off the extra text before calling removePendingText.
                    newText = newText.substr(0, expectedLength);
                }
                hintList.removePendingText(newText);
            }
        }
    }


Private

_handleCursorActivity

Handle a selection change event in the editor. If the selection becomes a
multiple selection, end our current session.

event
BracketsEvent
editor
Editor
    function _handleCursorActivity(event, editor) {
        if (_inSession(editor)) {
            if (editor.getSelections().length > 1) {
                _endSession();
            }
        }
    }


Private

_handleKeydownEvent

Handles keys related to displaying, searching, and navigating the hint list.
This gets called before handleChange.

TODO: Ideally, we’d get a more semantic event from the editor that told us
what changed so that we could do all of this logic without looking at
key events. Then, the purposes of handleKeyEvent and handleChange could be
combined. Doing this well requires changing CodeMirror.

jqEvent
Event
editor
Editor
event
KeyboardEvent
    function _handleKeydownEvent(jqEvent, editor, event) {
        keyDownEditor = editor;
        if (!(event.ctrlKey || event.altKey || event.metaKey) &&
                (event.keyCode === KeyEvent.DOM_VK_ENTER ||
                 event.keyCode === KeyEvent.DOM_VK_RETURN ||
                 event.keyCode === KeyEvent.DOM_VK_TAB)) {
            lastChar = String.fromCharCode(event.keyCode);
        }
    }
    function _handleKeypressEvent(jqEvent, editor, event) {
        keyDownEditor = editor;

        // Last inserted character, used later by handleChange
        lastChar = String.fromCharCode(event.charCode);

        // Pending Text is used in hintList._keydownHook()
        if (hintList) {
            hintList.addPendingText(lastChar);
        }
    }
    function _handleKeyupEvent(jqEvent, editor, event) {
        keyDownEditor = editor;
        if (_inSession(editor)) {
          if (event.keyCode === KeyEvent.DOM_VK_HOME || 
                  event.keyCode === KeyEvent.DOM_VK_END) {
                _endSession();
            } else if (event.keyCode === KeyEvent.DOM_VK_LEFT ||
                       event.keyCode === KeyEvent.DOM_VK_RIGHT ||
                       event.keyCode === KeyEvent.DOM_VK_BACK_SPACE) {
                // Update the list after a simple navigation.
                // We do this in "keyup" because we want the cursor position to be updated before
                // we redraw the list.
                _updateHintList();
            } else if (event.ctrlKey && event.keyCode === KeyEvent.DOM_VK_SPACE) {
                _updateHintList(event);
            }
        }
    }


Private

_inSession

Is there a hinting session active for a given editor?

NOTE: the sessionEditor, sessionProvider and hintList objects are
only guaranteed to be initialized during an active session.

editor
Editor
Returns: boolean
    function _inSession(editor) {
        if (sessionEditor) {
            if (sessionEditor === editor &&
                    (hintList.isOpen() ||
                     (deferredHints && deferredHints.state() === "pending"))) {
                return true;
            } else {
                // the editor has changed
                _endSession();
            }
        }
        return false;
    }


Private

_providerSort

Comparator to sort providers from high to low priority

    function _providerSort(a, b) {
        return b.priority - a.priority;
    }


Private
Public API

_removeHintProvider

provider
non-nullable
CodeHintProvider
Code hint provider to remove
targetLanguageId
optional
(string, Array.<string>)
Optional set of language IDs for languages to remove the provider for. Defaults to all languages.
    function _removeHintProvider(provider, targetLanguageId) {
        var index,
            providers,
            targetLanguageIdArr;

        if (Array.isArray(targetLanguageId)) {
            targetLanguageIdArr = targetLanguageId;
        } else if (targetLanguageId) {
            targetLanguageIdArr = [targetLanguageId];
        } else {
            targetLanguageIdArr = Object.keys(hintProviders);
        }

        targetLanguageIdArr.forEach(function (languageId) {
            providers = hintProviders[languageId];

            for (index = 0; index < providers.length; index++) {
                if (providers[index].provider === provider) {
                    providers.splice(index, 1);
                    break;
                }
            }
        });
    }


Private

_startNewSession

Explicitly start a new session. If we have an existing session,
then close the current one and restart a new one.

editor
Editor
    function _startNewSession(editor) {
        if (isOpen()) {
            return;
        }

        if (!editor) {
            editor = EditorManager.getFocusedEditor();
        }
        if (editor) {
            lastChar = null;
            if (_inSession(editor)) {
                _endSession();
            }

            // Begin a new explicit session
            _beginSession(editor);
        }
    }


Private

_updateHintList

From an active hinting session, get hints from the current provider and
render the hint list window.

Assumes that it is called when a session is active (i.e. sessionProvider is not null).

    function _updateHintList(callMoveUpEvent) {

        callMoveUpEvent = typeof callMoveUpEvent === "undefined" ? false : callMoveUpEvent;

        if (deferredHints) {
            deferredHints.reject();
            deferredHints = null;
        }

        if (callMoveUpEvent) {
            return hintList.callMoveUp(callMoveUpEvent);
        }

        var response = sessionProvider.getHints(lastChar);
        lastChar = null;

        if (!response) {
            // the provider wishes to close the session
            _endSession();
        } else {
            // if the response is true, end the session and begin another
            if (response === true) {
                var previousEditor = sessionEditor;

                _endSession();
                _beginSession(previousEditor);
            } else if (response.hasOwnProperty("hints")) { // a synchronous response
                if (hintList.isOpen()) {
                    // the session is open
                    hintList.update(response);
                } else {
                    hintList.open(response);
                }
            } else { // response is a deferred
                deferredHints = response;
                response.done(function (hints) {
                    // Guard against timing issues where the session ends before the
                    // response gets a chance to execute the callback.  If the session
                    // ends first while still waiting on the response, then hintList
                    // will get cleared up.
                    if (!hintList) {
                        return;
                    }

                    if (hintList.isOpen()) {
                        // the session is open
                        hintList.update(hints);
                    } else {
                        hintList.open(hints);
                    }
                });
            }
        }
    }

Public API

hasValidExclusion

Test whether the provider has an exclusion that is still the same as text after the cursor.

exclusion
string
Text not to be overwritten when the provider inserts the selected hint.
textAfterCursor
string
Text that is immediately after the cursor position.
Returns: boolean
true if the exclusion is not null and is exactly the same as textAfterCursor, false otherwise.
    function hasValidExclusion(exclusion, textAfterCursor) {
        return (exclusion && exclusion === textAfterCursor);
    }

Public API

isOpen

Test if a hint popup is open.

Returns: boolean
— true if the hints are open, false otherwise.
    function isOpen() {
        return (hintList && hintList.isOpen());
    }

Public API

registerHintProvider

The method by which a CodeHintProvider registers its willingness to
providing hints for editors in a given language.

provider
non-nullable
CodeHintProvider
The hint provider to be registered, described below.
languageIds
non-nullable
Array.<string>
The set of language ids for which the provider is capable of providing hints. If the special language id name «all» is included then the provider may be called for any language.
priority
nullable
number
Used to break ties among hint providers for a particular language. Providers with a higher number will be asked for hints before those with a lower priority value. Defaults to zero.
    function registerHintProvider(providerInfo, languageIds, priority) {
        var providerObj = { provider: providerInfo,
                            priority: priority || 0 };

        if (languageIds.indexOf("all") !== -1) {
            // Ignore anything else in languageIds and just register for every language. This includes
            // the special "all" language since its key is in the hintProviders map from the beginning.
            var languageId;
            for (languageId in hintProviders) {
                if (hintProviders.hasOwnProperty(languageId)) {
                    hintProviders[languageId].push(providerObj);
                    hintProviders[languageId].sort(_providerSort);
                }
            }
        } else {
            languageIds.forEach(function (languageId) {
                if (!hintProviders[languageId]) {
                    // Initialize provider list with any existing all-language providers
                    hintProviders[languageId] = Array.prototype.concat(hintProviders.all);
                }
                hintProviders[languageId].push(providerObj);
                hintProviders[languageId].sort(_providerSort);
            });
        }
    }

Форум JScourse

Загрузка…

Возможно, вам также будет интересно:

  • Bq tank power 2430 ошибка зарядки
  • Bq 2817 ошибка зарядки
  • Bpwin ошибка shw32 dll
  • Bplab суточный монитор ошибки e099
  • Bplab суточный монитор ошибки e083

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии