ace приложение для запуска скрипта
Ace Script от Ace Stream
User Script Manager, с поддержкой технологий Ace Stream.
Метаданные расширения
Используется
Позволяет настроить способ отображения или поведения веб-страницы с помощью UserScript, по аналогии с Greasemonkey.
Поддерживает работу скриптов для Greasemonkey и Tampermonkey, а также позволяет создавать скриптовые сценарии с возможностью удобной интеграции функциональных возможностей ПО Ace Stream (www.acestream.org), для улучшения ваших любимых сайтов.
Вы можете написать свои собственные скрипты или воспользоваться существующими. Готовые скрипты вы можете найти по следующим адресам:
— http://awe.acestream.me (использующие функциональные возможности Ace Stream)
— https://openuserjs.org (разные)
— https://greasyfork.org (разные)
Внимание! Данное расширение не содержит никакой рекламы и самостоятельно не модифицирует страницы сайтов. Любые изменения и модификации на сайтах могут осуществляются только отдельно установленными вами скриптами. Поэтому устанавливайте только те скрипты, в работе которых вы уверены, а в случае выявления некорректной работы добавленных вами скриптов, немедленно их удаляйте.
Сообщить о нарушении правил этим дополнением
Если вы считаете, что это дополнение нарушает политики Mozilla в отношении дополнений, или имеет проблемы с безопасностью или приватностью, сообщите об этих проблемах в Mozilla, используя эту форму.
Не используйте эту форму, чтобы сообщать об ошибках или запрашивать новые функции в дополнении; это сообщение будет отправлено в Mozilla, а не разработчику дополнения.
Этому дополнению нужно:
Ace Script от Ace Stream
User Script Manager, с поддержкой технологий Ace Stream.
Метаданные расширения
Используется
Позволяет настроить способ отображения или поведения веб-страницы с помощью UserScript, по аналогии с Greasemonkey.
Поддерживает работу скриптов для Greasemonkey и Tampermonkey, а также позволяет создавать скриптовые сценарии с возможностью удобной интеграции функциональных возможностей ПО Ace Stream (www.acestream.org), для улучшения ваших любимых сайтов.
Вы можете написать свои собственные скрипты или воспользоваться существующими. Готовые скрипты вы можете найти по следующим адресам:
— http://awe.acestream.me (использующие функциональные возможности Ace Stream)
— https://openuserjs.org (разные)
— https://greasyfork.org (разные)
Внимание! Данное расширение не содержит никакой рекламы и самостоятельно не модифицирует страницы сайтов. Любые изменения и модификации на сайтах могут осуществляются только отдельно установленными вами скриптами. Поэтому устанавливайте только те скрипты, в работе которых вы уверены, а в случае выявления некорректной работы добавленных вами скриптов, немедленно их удаляйте.
Сообщить о нарушении правил этим дополнением
Если вы считаете, что это дополнение нарушает политики Mozilla в отношении дополнений, или имеет проблемы с безопасностью или приватностью, сообщите об этих проблемах в Mozilla, используя эту форму.
Не используйте эту форму, чтобы сообщать об ошибках или запрашивать новые функции в дополнении; это сообщение будет отправлено в Mozilla, а не разработчику дополнения.
Этому дополнению нужно:
ACE: самый функциональный редактор кода
Я был достаточно приятно удивлен, когда узнал, что проект Ajax.org, именуемый Ace почти ни разу не упоминался на хабре. Ace — это веб-редактор исходного кода нового поколения. Он поддерживает уйму различных функций, среди которых: наличие режимов подсветки синтаксиса для более чем 60 языков программирования, поддержка сумашедшего количества цветовых схем из различных популярных IDE, функций, среди которых: широкая кастомизация, проверка синтаксиса для нескольких скриптовых языков. Так уж получилось, что эта статья скорее всего будет разносторонняя, т.е. содержать материал для веб-разработчиков и С++ программистов, которых я так успешно агитирую в сторону Qt. Итак, что вы можете прочитать в этой статье?
Что такое Ace?
Ace (англ. Ajax.org Cloud9 Editor) — онлайн-редактор исходного кода с подсветкой синтаксиса, темами, и горячими клавишами, написанный на Javascript, распространяющийся по лицензиям MPL/LGPL/GPL и легко встраиваемый в любую веб-страницу. Ace разработан в качестве основного редактора Cloud9 IDE является продолжением проекта Mozilla Skywriter (Bespin). Сейчас проект хостится на GitHub и активно развивается.
Ace может заинтересовать того, кому необходимо установить красивый и главное — удобный редактор исходного кода на сайт или встроить в свое приложение. Из преимуществ редактора можно выделить:
API и документации
Присутствие документации определяет ее отсутствие. Короче говоря, нормальной документации у Ace’a нету. На сайте таковое есть, но назвать его API Reference — это слишком громко сказать. Сейчас, давайте как-то интеративненько настроим этот редактор. Step-by-step, так сказать.
Шаг 1. Элементарная настройка
Начнем с создания предполагаемой страницы с редактором. Создадим шаблон:
Отлично! Теперь у нас есть простая страничка с простым редактором кода. Это уже что-то. Кстати, можно использовать другие источники ace.js. Не говоря о том, что вам понадобятся другие файлы, лучше вообще собирать его самостоятельно (node-ом) или собирать по-кусочкам из built-файлов с различным функционалом.
Шаг 2. Больше красок!
Сейчас настало время добавить красок нашему предполагаемому JavaScript коду. Это можно легко сделать путем нескольких нехитрых call-ов. Ну что, давайте допишем пару строчек:
Что же мы сделали? Тема редактора задается строкой, содержащей путь формата ace/theme/
Шаг 3. Управляем текстом на API-level
Писать код — хорошо, но еще лучше уметь что-то с ним делать на программном уровне. На этом шаге я постараюсь разобраться в основных функциях редактора и их API. Как сказал Гагарин, Поехали!
Получаем и задаем содержимое:
Немного работы с выделением:
А теперь немного поиграемся с курсором:
Что насчет расширенного управления кодингом?
Кстати, если вдруг вам захочется поменять размер div#editor, не меняя размеров самого окна, то нужно выполнить
Шаг 4. Поиск и события (events)
К сожалению, о поиске я скажу только пару слов, так как почему-то нет желания сейчас здесь описывать его работу. Вкратце, поддерживает регулярные выражения, чувствительность к регистру, и много других параметров. API сводится к
Слушаем различные события:
А теперь очень классное — «горячие» клавиши и сочетания:
В теории, обладая этими знаниями (+ специфика из полного api reference) можно написать редактор, аналогичный редактору Cloud9 IDE. Конечно нужно очень сильно его расширять, но оно того стоит.
Novile Component for Qt
Сейчас речь пойдет о проекте Novile, проекте над которым я работал последнюю неделю. Смелые продолжат читать, а те, кому не особо оно-то и колышется, могут пролистать к Заключению. А джедаев я попрошу остаться. Я собираюсь рассказать о том, как использовать Novile, зачем он нужен, и главное, расскажу,
Кому оно надо?
Когда я начинал работу над Novile, я в первую очередь думал о том, какое она сможет найти применение. По отзывам знакомых программистов, я решил, что использовать Novile можно в различных десктопных (и не только) приложениях, где нужно редактировать код или как минимум, конфигурационные файлы. Таких приложений есть достаточно много, а с Novile их должно стать больше.
Novile, в частности, created with Qt, created for Qt. Кто не знает, Qt — это фреймворк для разработки кросс-платформенного ПО на C++ (еще можно на Python, Java, но это не тот случай). Погуглив, можно понять что Qt — это нечто, что Qt — это Linux Mac Window Symbian Android iOS Embedded. Novile — это мост между низкоуровневым API редактора на JavaScript к высокоуровневому коду на С++ через QtWebKit.
Сборочная система
Несмотря на то, что Qt очень активно пропагандирует QMake, а уже скоро начнется QBS-мания, я считаю, что для библиотек самый лучший вариант, однозначно CMake. Он дает тот уровень кастомизации сборки, который действительно нужен.
Сейчас для сборки и установки Novile с документацией, debug output и примером нужно выполнить (Linux):
Удобно, не так-ли? Сегодня я попробую научить вас делать такие библиотеки (в данном случае для Qt 5). Кстати, я не буду рассказывать, как работает СMake, и как с ним работать, так как на хабре уже есть такая статья. Она отнимет у вас буквально пару минут. А сейчас, если вам неинтересен CMake, вы можете пролистать следующую статью.
Qt 5 в CMake 2.8.8+
Как же заставить CMake собирать Qt 5 проекты? Да очень просто. Читаем код и комментарии (кстати, приятно, что на хабре есть хайлайтер для CMake):
Import/Export свитчеры
При работе с библиотекой, некоторые символы должны уйти в экспорт, а потом, на этапе использования либы, быть импортированными из нее, поэтому удобно использовать такую конструкцию:
Как пользоваться Novile?
Но тут я готов привести маленький пример того, как же удобно это все делается из плюсов (С++11 + Qt 5)
C++11, мощный Qt и дописанная Novile позволяют построить быструю и кросс-платформенную IDE со всем необходимым функционалом.
Заключение
Я надеюсь что эта статья действительно помогла и веб-разработчикам, и программистам. Представить не могу, насколько удачно я сагитировал народ на Qt, но я старался. Честно. Хотелось бы сказать пару слов в сторону Novile. Признаться, сейчас Novile не совсем хороший продукт, чтобы я про него не говорил. Сейчас она покрывает от силы 50% функционала Ace. Если есть кто-то заинтересованный, вы всегда можете помочь проекту на GitHub. Даже самый маленький pull request будет кстати.
Built for Code
Ace is an embeddable code editor written in JavaScript. It matches the features and performance of native editors such as Sublime, Vim and TextMate. It can be easily embedded in any web page and JavaScript application. Ace is maintained as the primary editor for Cloud9 IDE and is the successor of the Mozilla Skywriter (Bespin) project.
Looking for a more full-featured demo? Check out the kitchen sink.
Features
Get the Open-Source Code
Ace is a community project. We actively encourage and support contributions! The Ace source code is hosted on GitHub and released under the BSD license ‐ very simple and friendly to all kinds of projects, whether open-source or not. Take charge of your editor and add your favorite language highlighting and keybindings!
History
Skywriter/Bespin and Ace started as two independent projects both aiming to build a no compromise code editor component for the web. Bespin started as part of Mozilla Labs and was based on the tag, while Ace is the editor component of Cloud9 IDE and uses the DOM for rendering. After the release of Ace at JSConf.eu 2010 in Berlin the Skywriter team decided to merge Ace with a simplified version of Skywriter’s plugin system and some of Skywriter’s extensibility points. All these changes have been merged back to Ace now, which supersedes Skywriter. Both Cloud9 IDE and Mozilla are actively developing and maintaining Ace.
Related Projects
Embedding Ace in Your Site
Ace can be easily embedded into a web page. Get prebuilt version of ace from ace-builds repository and use the code below:
Now check out the How-To Guide for instructions on common operations, such as setting a different language mode or getting the contents from the editor.
Loading Ace from a Local URL
If you want to clone and host Ace locally you can use one of the pre-packaged versions. Just copy one of src* subdirectories somewhere into your project, or use RequireJS to load the contents of lib/ace folder as ace :
Loading Ace from a CDN
The packaged version can also be loaded from CDN’s such as PageCDN, jsDelivr or cdnjs.
Working with Ace
In all of these examples Ace has been invoked as shown in the embedding guide.
Configuring the editor
there are several ways to pass configuration to Ace
See Configuring-Ace wiki page for a more detailed list of options.
Changing the size of the editor
Ace only checks for changes of the size of it’s container when window is resized. If you resize the editor div in another manner, and need Ace to resize, use the following:
if you want editor to change it’s size based on contents, use maxLines option as shown in https://ace.c9.io/demo/autoresize.html
Setting Themes
Themes are loaded on demand; all you have to do is pass the string name:
Setting the Programming Language Mode
By default, the editor supports plain text mode. All other language modes are available as separate modules, loaded on demand like this:
One Editor, Multiple Sessions
You might accomplish this like so:
Common Operations
Set and get content:
Insert at cursor, emulating user input:
Replace text in range:
Get the current cursor line and column:
Get total number of lines:
Set the default tab size:
Toggle word wrapping:
Set line highlighting:
Set the print margin visibility:
Set the editor to read-only:
Using undo manager
To group undo delta of the next edit with the previous one set `mergeUndoDeltas` to true
To start new undo group use `markUndoGroup` method
To disable undo of a an edit in a collaborative editor
Searching
The following options are available to you for your search parameters:
Here’s how you can perform a replace:
And here’s a replace all:
Listening to Events
To listen for an onchange :
To listen for an selection change:
To listen for a cursor change:
Adding New Commands and Keybindings
To assign key bindings to a custom function:
Configure dynamic loading of modes and themes
By default ace detcts the url for dynamic loading by finding the script node for ace.js. This doesn’t work if ace.js is not loaded with a separate script tag, and in this case it is required to set url explicitely
Path for one module alone can be configured with:
When using ace with webpack, it is possible to configure paths for all submodules using
Creating a Syntax Highlighter for Ace
Creating a new syntax highlighter for Ace is extremely simple. You’ll need to define two pieces of code: a new mode, and a new set of highlighting rules.
We recommend using the Ace Mode Creator when defining your highlighter. This allows you to inspect your code’s tokens, as well as providing a live preview of the syntax highlighter in action.
Every language needs a mode. A mode contains the paths to a language’s syntax highlighting rules, indentation rules, and code folding rules. Without defining a mode, Ace won’t know anything about the finer aspects of your language.
Here is the starter template we’ll use to create a new mode:
What’s going on here? First, you’re defining the path to TextMode (more on this later). Then you’re pointing the mode to your definitions for the highlighting rules, as well as your rules for code folding. Finally, you’re setting everything up to find those rules, and exporting the Mode so that it can be consumed. That’s it!
All Ace modes can be found in the lib/ace/mode folder.
The Ace highlighter can be considered to be a state machine. Regular expressions define the tokens for the current state, as well as the transitions into another state. Let’s define mynew_highlight_rules.js, which our mode above uses.
All syntax highlighters start off looking something like this:
Once again, we’re inheriting from TextHighlightRules here. We could choose to make this any other language set we want, if our new language requires previously defined syntaxes. For more information on extending languages, see «extending Highlighters» below.
The Ace highlighting system is heavily inspired by the TextMate language grammar. Most tokens will follow the conventions of TextMate when naming grammars. A thorough (albeit incomplete) list of tokens can be found on the Ace Wiki.
For the complete list of tokens, see tool/tmtheme.js. It is possible to add new token names, but the scope of that knowledge is outside of this document.
Multiple tokens can be applied to the same text by adding dots in the token, e.g. token: support.function wraps the text in a tag.
Regular expressions can either be a RegExp or String definition
If you’re using a regular expression, remember to start and end the line with the / character, like this:
A caveat of using stringed regular expressions is that any \ character must be escaped. That means that even an innocuous regular expression like this:
Must actually be written like this:
For flat regular expression matches, token can be a String, or a Function that takes a single argument (the match) and returns a string token. For example, using a function might look like this:
If token is a function,it should take the same number of arguments as there are groups, and return an array of tokens.
For grouped regular expressions, token can be a String, in which case all matched groups are given that same token, like this:
More commonly, though, token is an Array (of the same length as the number of groups), whereby matches are given the token of the same alignment as in the match. For a complicated regular expression, like defining a function, that might look something like this:
In this extremely short sample, we’re defining some highlighting rules for when Ace detects a tag. When one is encountered, the tokenizer moves from start into the cdata state. It remains there, applying the text token to any string it encounters. Finally, when it hits a closing ]> symbol, it returns to the start state and continues to tokenize anything else.
Using the TMLanguage Tool
There is a tool that will take an existing tmlanguage file and do its best to convert it into Javascript for Ace to consume. Here’s what you need to get started:
Two files are created and placed in lib/ace/mode: one for the language mode, and one for the set of highlight rules. You will still need to add the code into ace/ext/modelist.js, and add a sample file for testing.
Your .tmlanguage file will then be converted to the best of the converter’s ability. It is an understatement to say that the tool is imperfect. Probably, language mode creation will never be able to be fully autogenerated. There’s a list of non-determinable items; for example:
However, the tool is an excellent way to get a quick start, if you already possess a tmlanguage file for you language.
Extending Highlighters
To get the existing syntax highlighting rules for a particular language, use the getRules() function. For example:
The addRules method does one thing, and it does one thing well: it adds new rules to an existing rule set, and prefixes any state with a given tag. For example, let’s say you’ve got two sets of rules, defined like this:
To explain this visually, let’s take a look at the syntax highlighter for Lua pages, which combines all of these concepts:
Code Folding
Adding new folding rules to your mode can be a little tricky. First, insert the following lines of code into your mode definition:
You’ll be defining your code folding rules into the lib/ace/mode/folding folder. Here’s a template that you can use to get started:
Just like with TextMode for syntax highlighting, BaseFoldMode contains the starting point for code folding logic. foldingStartMarker defines your opening folding point, while foldingStopMarker defines the stopping point. For example, for a C-style folding system, these values might look like this:
Again, for a C-style folding mechanism, a range to return for the starting fold might look like this:
Testing Your Highlighter
The best way to test your tokenizer is to see it live, right? To do that, you’ll want to modify the live Ace demo to preview your changes. You can find this file in the root Ace directory with the name kitchen-sink.html.
add a sample file to demo/kitchen-sink/docs/ with same name as the mode file
Once you set this up, you should be able to witness a live demonstration of your new highlighter.
Adding automated tests for a highlighter is trivial so you are not required to do it, but it can help during development.
In lib/ace/mode/_test create a file named with some example code. (You can skip this if the document you have added in demo/docs both looks good and covers various edge cases in your language syntax).
Плагин Ace Stream для Firefox
Ace Stream для Mozilla Firefox – это три отдельных скрипта, так или иначе связанных с воспроизведением медиаконтента (музыки и видео) в браузере «Огненная лисица». И их запуск возможен только при наличии установленного плагина. Рассмотрим все это чуть более детально.
Подробная информация
Сначала разберем существующие скрипты. Как и упоминалось ранее, всего их три штуки:
Чтобы воспользоваться любым из них, для начала нужно в интернет-обозреватель установить расширение Ace Script – это исполнитель пользовательских скриптов. Процедура здесь следующая:
Теперь сам плагин установлен, остается добавить желаемые скрипты. Делается это так:
Хотелось бы отметить, что у последних двух скриптов (P2P Search и Ace Cast) и плагина для их работы в Мозилле Фаерфокс довольно низкие отзывы. То есть пользователи считают, что только Magic Player достоин внимания. Разберемся с его использованием.
Нюансы использования Magic Player
Суть этого скрипта в том, что он запускает потоковое воспроизведение видео из торрент-файла (или magnet-ссылки), а значит, не нужно дожидаться полной загрузки и сразу же смотреть фильм, сериал, аниме и т. д. Но сам браузер не станет плеером, нужно установить отдельную программу на компьютер:
В результате в браузере откроется страница http://info.acestream.org/#/welcome. Она предназначается для проверки. В будущем торрент-ссылку воспроизвести выйдет, если кликнуть по ней ПКМ и выбрать пункт Watch Online.