- Настройка Atom от GitHub для работы с PHP, Python и некоторыми другими языками программирования
- Linter
- Пакет Script: запуск программ из Atom
- Python
- Swift
- Терминал
- Как настроить atom для lua
- Available Providers
- Configuration
- Type definitions
- Tables
- variants
- Named types
- Option providers
- priority and getPreviousOptions()
- dispose()
- getOptions(request, getPreviousOptions, utils, cache)
- utils.reviveOptions(options)
- utils.mergeOptions(previousOptions, newOptions)
- utils.mergeOptionsCached(previousOptions, newOptions, cache[, merger])
- util. New()
- util.tableSet(table, key, value)
- util.tableGet(table, key)
- util.tableSettable(table, table)
- util.tableGettable(table)
Настройка Atom от GitHub для работы с PHP, Python и некоторыми другими языками программирования
Изначально считаем что у Вас установлена поддерживаемая операционная система, Node.JS и Atom. В примерах мы работаем в OpenSUSE (13.1) в нём (и вообще в дистрибутивах *nix) уже «из коробки» обычно есть не только Python но PHP и другие языки программирования. Так же исправно работает на Ubuntu (>12.04). Если у Вас Windows 7 или 8, а раньше Вы с ними (языками) не работали то их предварительно необходимо скачать и установить.
Примечание: перед началом работы желательно запускать Atom под root.
опыт показывает — работает стабильнее
Linter
Идеология Atom к подсветке в том, что основным пакетом для работы с синтаксисом и его анализа будет Linter, который является верхним уровнем в API для других линтеров кода. Это сделано для прекращения «войны между плагинами» (The idea is to stop the linter plugins war, by providing a top level API for linters to parse and display errors in the Atom editor). Тем не менее, не все сторонние разработчики придерживаются этой идеологии и пишут свои плагины.
- linter-php , для PHP `php -l`
- linter-phpcs , для PHP, `phpc`
- linter-phpmd , для PHP, `phpmd`
- linter-pylint , для Python, `pylint`
- linter-pyflakes , для python, `pyflakes`
- linter-pep8, для python, `pep8`
- linter-flake8, для python, `flake8`
- linter-javac , для Java, `javac`
- linter-jshint , для JavaScript and JSON, `jshint`
- linter-jscs , для JavaScript, `jscs`
- linter-scss-lint , для SASS/SCSS, `scss-lint`
- linter-coffeelint , для CoffeeScript, `coffeelint`
- linter-csslint , для CSS, `csslint`
- linter-rubocop , для Ruby and Ruby on Rails, `rubocop`
- linter-tslint , для Typescript, `tslint`
- linter-xmllint , для XML, `xmllint`
- linter-shellcheck , для Bash, `shellcheck`
- linter-scalac , для Scala, `scalac`
- linter-clang , для C / C++, `clang`
- linter-ruby , для ruby, `ruby -wc`
- linter-lua , для Lua, `luac -p`
Пакет Script: запуск программ из Atom
Script — пакет для запуска кода в atom.
Установка пакета Script, возможна из командной строки:
или меню
Packages->Settings View->Install->Packages
Каждый язык работает, при наличии предварительно установленного компилятора / интерпритатора.
Пакет Script обновляется довольно часто. Например поддержка Swift появилась менее двух недель назад. Так что скорее всего в ближайшее время появится поддержка новых языков.
Для запуска программы необходимо выбрать
Packages—>Script—>Run
Дополнительные опции можно найти в документации либо на страницах Atom`а или проекта.
Для функционирования должен быть создан рабочий каталог.
Путь к нему нужно прописать здесь:
Packages—>Script—>Configure Script—>Current Working Directory
Заявку разработчикам на поддержку нового языка можно оставить здесь (отвечают быстро)
И немного юмора от разработчиков пакета Script,
у которых, судя по всему, спрашивают всё на свете:
первод: Атом не может найти Нод | Руби | Питон | Мои носки
Python
Поддержка подсветки этого языка идёт изначально. Пакеты для работы с синтаксисом и отладки:
Linter + Language Python + Linter Python Pep8 + Script
Script запускает код на Python, а Linter и Linter Python Pep8 покажут синтаксические ошибки.
Возможно Вам, для работы с Python также поможет Atom Python Debugger.
Подсветка ошибок и запуск после установки будут выглядеть так:
Swift
Терминал
Для запуска исполняемого кода С, C++, Java иногда проще использовать сторонний пакет (не пакет Atom, а пакет вашего дистрибутива), который запускается через терминал, поскольку сам Atom поддерживает большое количество языков. Если Atom выступает в качестве редактора кода, a терминал рядом запускает его — это очень удобно для нас, поскольку терминал не имеет такое преимущество редактирования, как Atom.
Для запуска терминала в окне Atom установите пакет Term. Для запуска терминала в окне Atom выбрать
Packages—>Command Palette—>Toggle и Term
с нужными параметрами.
В заключении ещё один интересный кликабельный анимационный gif от разработчиков script, ссылки.
Источник
Как настроить atom для lua
Atom Autocomplete+ provider for Lua.
This package aims to parse Lua files with oxyc/luaparse and generate scope and type-aware completions with syntactic analysis.
- Limited type inference mechanism
- Scope-aware variable name suggestions
- Table member completions on . and :
- Snippets for call arguments
- Aware of settable() and return types
- Completion for the Lua standard library
- .luacompleterc file to define additional globals
- Doc-strings in .luacompleterc
- Configuration service for other packages to programmatically define globals
- Autocomplete required modules
Available Providers
- Defold IDE — Adds hot reloading, autocompletion and in-line API docs for the Defold game engine.
- LÖVE Atom — Smart autocompletion for the LÖVE framework in Atom.
Configuration
Besides what you can configure in Atom preferences, atom-autocomplete-lua looks for a .luacompleterc file in the parent directories of the current file.
If you need to define additional global symbols for your specific Lua environment, place a .luacompleterc file in your project root. It’s a JSON file with roughly the following structure:
All options are optional. Here’s what each option does:
Option | Default | Description |
---|---|---|
global | < type: ‘table’, fields: <>> | The type definition of the global environment. Define additional fields on this table to declare globals available in your Lua environment. Read the Type definitions section for more . |
namedTypes | <> | To avoid deep nesting and allow multiple places to reference a type, you can define named types. Read the Named types section for more . |
luaVersion | «5.2» | The version of Lua your code is targeting. Valid values are «5.1», «5.2», «5.3» and «luajit-2.0». |
packagePath | «./?.lua» | The value of LUA_PATH used when resolving required modules. |
cwd | . | The current directory used to resolve relative paths in packagePath. If cwd is relative, it’s considered relative to the parent directory of .luacompleterc. |
Type definitions
The general format of a type definition is:
<
«type»: «type_name», // one of «», «table», «number», «boolean», «string» or «unknown», «ref»
«description»: «Optional short Markdown description of your symbol»,
«descriptionPlain»: «Optional short plain text description of your symbol (if you don’t want Markdown for some reason)»,
«»: «https://optional./to/full/api/docs»
>
Tables
Tables («type»: «table») have 2 more properties:
- fields: Required. An object mapping table fields to their corresponding type definition. Even though Lua allows indexing tables with any value, only string keys are supported for autocompletion purposes.
- table: Optional. The type definition of the table of this table, if it has one. autocomplete-lua is aware of keys like __index in this table and uses them for completion. If present, the type of the table must be «table».
s («type»: «») can have a few more optional properties:
- returnTypes: An array of type definitions describing the types of the ‘s return values.
- args: An array of argument name definitions (see below).
- argsDisplay: In case you want your arguments to be displayed in the autocomplete dropdown in a custom way, you can provide a string of the argument list here.
- argsDisplayOmitSelf: Same as above, but displayed when completing method calls with :. You should provide the same arg list string, but with the first argument removed. Defaults to argsDisplay.
- argTypes: An array of argument type definitions (or null when type is unknown).
Argument names are of the form < «name»: «arg_name», «displayName»: «display_name» >, where displayName is optional.
displayName will be displayed in the autocomplete dropdown, while name will be part of the inserted snippet. This is useful for things like optional arguments:
will produce f(arg1, [arg2]) in the dropdown and f(arg1, arg2) after being inserted.
In rare cases, displayName might be unsuitable for you. argsDisplay and argsDisplayOmitSelf can be used to manually specify the comma-separated list of arguments.
For example, you can use it to customize comma placement in relation to [:
This will produce f(self[, arg1[, arg2]]) in the dropdown and f(self, arg1, arg2) after being inserted.
variants
Somes, you may have polymorphic s which can be called with a number of different argument configurations. You might want to show all of these versions separately in the autocomplete dropdown.
You can provide multiple versions of the same by moving , description, args, argsDisplay and argsDisplayOmitSelf inside a variants array like so:
< // Type definition for a get(url_or_filename)
«type»: «»,
«variants»: [ <
«args»: [< name: «url» >],
«description»: «Fetches an URL and returns a string with the contents»
>, <
«args»: [< name: «filename» >],
«description»: «Read the file at filename and returns a string with the contents»
>]
>
The autocomplete dropdown will show both get(url) and get(filename) with their corresponding descriptions.
Named types
There are often cases where you want to use the same type definition in multiple places. In these situations, you can use named types in your .luacompleterc.
Just use < «type»: «ref», «name»: «my_named_type» >instead of your type definition and define my_named_type in namedTypes.
Option providers
All the options provided in a .luacompleterc can be programmatically provided by plugin packages (like Defold IDE).
Start by adding this to your package.json:
«providedServices»: <
«autocomplete-lua.options-provider»: <
«versions»: <
«1.0.0»: «getOptionProvider»
>
>
>
Then, in your package’s JS object:
getOptionProvider () <
return myProvider; // You can also return an array of providers if you have more
>
The provider is an object (or a class) with the following interface:
const myProvider = <
priority: 20,
getOptions (request, getPreviousOptions, utils, cache) <
// Just return the options from the previous provider
return getPreviousOptions().then(previousOptions => <
return < options: previousOptions >
>)
>
dispose () <
// Destroy stuff
>
>
priority and getPreviousOptions()
Each a completion is needed (roughly at each keystroke), autocomplete-lua sorts all the option providers by their priority and calls the getOptions() method of the highest priority option provider.
The option provider can choose to call the next-highest-in-priority provider by calling getPreviousOptions(). getPreviousOptions() returns a promise to the options object provided by the next-in-line provider.
There are 3 option providers that come with autocomplete-lua:
- StdLibProvider. Priority 100. Adds Lua’s standard library s to the options.
- LuaCompleteRcProvider. Priority 10. Adds the contents of .luacompleterc to the options.
- EmptyProvider. Priority 0. Just returns an empty options object. Acts as fallback for getPreviousOptions().
dispose()
Optional . dispose() is called when your provider is not needed anymore.
getOptions(request, getPreviousOptions, utils, cache)
This is called when your provider is expected to return a new set of options.
request comes directly from Autocomplete+, with the addition of request.filePath, the absolute path to the current file.
The return value is an object of the form < options >. The same object is passed to getOptions() as cache the next the is called on the same file, so you can store additional arbitrary properties on it that you’d like to receive in cache. Returning a promise to this object is also supported.
It’s strongly encouraged to always return the same options object if nothing changed from the last call. Read on utils.mergeOptionsCached() for a simple way to do this.
utils.reviveOptions(options)
Takes an options object and resolves all references to named types. (Replaces < type: ‘ref’, name: ‘myRef’ >with namedTypes.myRef). This should be called after you read the options object from permanent storage.
Returns the same options object.
utils.mergeOptions(previousOptions, newOptions)
Takes 2 options objects, merges them and returns the result.
Fields in newOptions overwrite fields in previousOptions. The global fields are deeply merged.
utils.mergeOptionsCached(previousOptions, newOptions, cache[, merger])
Uses mergeOptions() to merge previousOptions and newOptions if any of the two are different from cache.previousOptions and cache.newOptions, else returns cache.options.
If the merge takes place, merger(mergedOptions, previousOptions, newOptions) is called on the newly merged object to do additional custom merging work.
Returns an object < options, previousOptions, newOptions >suitable for returning as the cache object from getOptions().
A ed pattern is the following:
getOptions = async (request, getPreviousOptions, utils, cache) => <
if (providerIsNotApplicableToTheCurrentFile) <
return < options: await getPreviousOptions() >
>
const newOptions = conjureABunchOfNewOptions()
const previousOptions = await getPreviousOptions()
return utils.mergeOptionsCached(previousOptions, newOptions, cache, mergedOptions => <
mergedOptions.oneMoreThing = ‘this thing’
>)
>
util. New()
Creates a new type definition for a . Available s are: tableNew(), booleanNew(), New(), numberNew(), unknownNew(), nilNew()
util.tableSet(table, key, value)
Sets the field identified by key in the table type definition table to the type definition value.
util.tableGet(table, key)
Gets the type definition corresponding to the field identified by key in the table type definition table.
util.tableSettable(table, table)
Sets the table type definition in the table type definition table to the type definition table.
util.tableGettable(table)
Gets the type definition of the table of the table type definition table.
Источник