Skip to content
This repository has been archived by the owner on Apr 24, 2024. It is now read-only.

Latest commit

 

History

History
283 lines (234 loc) · 9.33 KB

README.ru.md

File metadata and controls

283 lines (234 loc) · 9.33 KB

yaspeller

NPM version NPM Downloads Coverage Status Dependency Status

Проект закрыт, используйте CSpell или другую альтернативу. Пример использования CSpell

Средство поиска опечаток в тексте, в файлах и на сайтах.

Используется API Yandex.Speller.

yaspeller

Установка

npm install yaspeller -g

Командная строка

yaspeller [options] <file-or-directory-or-link...>

Используйте с pre-commit

Добавте в ваш .pre-commit-config.yaml:

- repo: https://github.com/hcodes/yaspeller.git
  rev: '' # Use the sha / tag you want to point at
  hooks:
    - id: yaspeller

Примеры

  • yaspeller README.md — поиск опечаток в файле.
  • yaspeller -e ".md,.html" ./texts/ — поиск опечаток в файлах в папке.
  • yaspeller https://ru.wikipedia.org/wiki/%D0%9E%D0%BF%D0%B5%D1%87%D0%B0%D1%82%D0%BA%D0%B0 — поиск опечаток на странице сайта.
  • yaspeller http:https://bem.info/sitemap.xml — поиск опечаток в адресах, перечисленных в sitemap.xml.
  • echo "Hello, world!" | yaspeller

Опции

-f, --format <value>

Форматы: plain, html, markdown или auto.
По умолчанию: plain.

-l, --lang <value>

Языки: en, ru or uk.
По умолчанию: en,ru.

-c, --config <path>

Конфигурационный файл.

-e, --file-extensions <value>

Поиск файлов в папке по расширениям.
Пример: .md,.htm,.txt.

--dictionary <file>

JSON-файл собственного словаря.

[
    "someword1", // someword1 = someword1 and Someword1
    "Someword2", // Someword2 = Someword2
    "someword3"
]

Поддерживаются регулярные выражения:

[
    "unknownword",
    "unknown(W|w)ord[12]?", // unknown(W|w)ord[12]? = unknown(W|w)ord[12]? and Unknown(W|w)ord[12]?
    "Unknown(W|w)ord[34]?" // Unknown(W|w)ord[34]? = Unknown(W|w)ord[34]?
]

Примеры использования:
yaspeller --dictionary my_dict.json .
yaspeller --dictionary my_dict.json:my_dict2.json .

Если у вас много md-файлов, и вы заносите линтер, то, возможно, вам пригодится yaspeller-dictionary-builder. Так вы сможете сгенерировать начальный словарь, где каждая строка будет объединять все словоформы.

--report <type>

Задать вид отчёта: console, html, markdown, junit или json.
По умолчанию: console
Пример: console,html,custom_report.js

--check-yo

Проверять корректность использования буквы «ё» в русских текстах.

--find-repeat-words

Находить повторы слов, идущие подряд. Например, я полетел на на Кипр.

--ignore-tags <tags>

Игнорировать HTML-теги.
По умолчанию: code,kbd,object,samp,script,style,var
Опция для форматов html и markdown.

--ignore-text <regexp>

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

--ignore-capitalization

Игнорировать неверное употребление ПРОПИСНЫХ/строчных букв, например, в слове москва.

--ignore-digits

Пропускать слова с цифрами, например, авп17х4534.

--ignore-urls

Пропускать интернет-адреса, почтовые адреса и имена файлов.

--max-requests <value>

Одновременное количество запросов к API Yandex.Speller.
По умолчанию: 2.

--no-color

Консольный вывод без цвета.

--only-errors

Выводить только ошибки.

--stdin

Обработка файлов через <STDIN>. По умолчанию: false

--stdin-filename <file>

Имя файла, отправленного на <STDIN>, используется в отчётах.

--debug

Режим отладки.

Установка в проект

npm install yaspeller --save-dev

Необходимо добавить в package.json / scripts:
"yaspeller": "yaspeller .",

Для запуска в качестве линтера:
npm run yaspeller

yaspeller настраивается, используя JSON-файл, расположенный в корне проекта:

  • .yaspellerrc
  • .yaspellerrc.js
  • .yaspellerrc.json
  • .yaspeller.json
  • package.json, поле yaspeller
{
  "excludeFiles": [
    ".git",
    "yaspeller",
    "node_modules",
    "libs"
  ],
  "lang": "ru",
  "fileExtensions": [
    ".md",
    ".txt"
  ],
  "dictionary": [
    "someword1"
  ]
}

Расширенный пример:

{
  "excludeFiles": [
    ".git",
    "yaspeller",
    "node_modules",
    "libs"
  ],
  "format": "html",
  "lang": "en",
  "fileExtensions": [
    ".md",
    ".txt"
  ],
  "report": ["console", "html"],
  "dictionary": [
    // JSON comments
    "someword1", // someword1 = someword1 and Someword1
    "Someword2", // Someword2 = Someword2
    "some(w|W)ord[23]", // some(w|W)ord[23] = some(w|W)ord[23] and Some(w|W)ord[23]
    "Some(w|W)ord" // Some(w|W)ord = Some(w|W)ord
  ],
  "ignoreTags": ["code", "script"],
  "ignoreText": [
    "<php\?[^]*?\?>", // Короткая запись
    ["<php\?[^]*?\?>", "g"] // Длинная запись
  ],
  "ignoreUrls": true,
  "findRepeatWords": true,
  "maxRequests": 5
}
Свойство  Тип Подробности
format String --format
lang String --lang
excludeFiles Array
fileExtensions Array --file-extension
dictionary Array --dictionary
report Array --report
checkYo Boolean --check-yo
findRepeatWords Boolean --find-repeat-words
ignoreTags Array --ignore-tags
ignoreText Array --ignore-text
ignoreCapitalization Boolean --ignore-capitalization
ignoreDigits Boolean --ignore-digits
ignoreUrls Boolean --ignore-urls
maxRequests Number --max-requests

Исключение части текста из проверки

Исключить строку

var re = /А-ЯЁ/; // yaspeller ignore
var re = /А-ЯЁ/; /* yaspeller ignore */
<span>А-ЯЁ</span> <!-- yaspeller ignore -->

Исключить блок

/* yaspeller ignore:start */
const reUpper = /А-ЯЁ/;
const reLower = /а-яё/;
/* yaspeller ignore:end */
<!-- yaspeller ignore:start -->
<span>А-ЯЁ</span>
<div>а-яё</div>
<!-- yaspeller ignore:end -->

Плагин для Gulp

const gulp = require('gulp');
const run = require('gulp-run'); // npm install gulp-run --save-dev

gulp.task('yaspeller', function (cb) {
    run('./node_modules/.bin/yaspeller ./').exec()
        .on('error', function (err) {
            console.error(err.message);
            cb();
        })
        .on('finish', cb);
});

Плагин для Grunt

module.exports = function(grunt) {
    grunt.loadNpmTasks('grunt-shell'); // npm install grunt-shell --save-dev
    grunt.initConfig({
        shell: {
            yaspeller: {
                options: {stderr: false},
                command: './node_modules/.bin/yaspeller .'
            }
        }
    });
    grunt.registerTask('lint', ['shell:yaspeller']);
};

Ссылки

MIT License