Error unexpected tab character

Русские Блоги Решение об ошибке под Vue Eslint Vue CLI 3 создает проект Vue, который будет иметь ESLINT для обнаружения спецификации кода, поэтому вы часто встретите некоторые подсказки Eslint, поэтому есть некоторые решения для ошибки во время использования. Последующий будет продлен и увеличен в глубине. 2、Newline required at end of file but not found […]

Содержание

  1. Русские Блоги
  2. Решение об ошибке под Vue Eslint
  3. Интеллектуальная рекомендация
  4. IView CDN Загрузка значка шрифта нормальная, а значок шрифта не может быть загружен при локальной загрузке JS и CSS
  5. Критическое: ошибка настройки прослушивателя приложения класса org.springframework.web.context.ContextLoaderLis
  6. 1086 Не скажу (15 баллов)
  7. Pandas применяют параллельный процесс приложения, многоядерная скорость очистки данных
  8. PureMVC Learning (Tucao) Примечания
  9. [no-tabs] allow exceptions #12438
  10. Comments
  11. This comment was marked as off-topic.
  12. Eslint expected indentation of 1 tab but found 4 spaces error
  13. 14 Answers 14
  14. If you are using VSCODE follow the next steps.
  15. [Solved] SyntaxError: unexpected character after line continuation character
  16. ❌ Problem: you accidentally put something after the backslash
  17. ✅ Fix: just remove the stuff after the backslash or put it on a new line
  18. ❌ Problem: you didn’t put a string containing a special character in quotes
  19. ✅ Fix: add the missing quote(s)
  20. ☝️ Tip: use syntax hilighting!
  21. ❌ Problem: you’re using a backslash for division (why?)
  22. ✅ Fix: use a forward slash for division 🤦‍♂️
  23. Conclusion

Русские Блоги

Решение об ошибке под Vue Eslint

Vue CLI 3 создает проект Vue, который будет иметь ESLINT для обнаружения спецификации кода, поэтому вы часто встретите некоторые подсказки Eslint, поэтому есть некоторые решения для ошибки во время использования. Последующий будет продлен и увеличен в глубине.

2、Newline required at end of file but not found

3、Extra semicolon semi

4、Unexpected tab character. (no-tabs)

5, последующее обновление. Отказ Отказ

Интеллектуальная рекомендация

IView CDN Загрузка значка шрифта нормальная, а значок шрифта не может быть загружен при локальной загрузке JS и CSS

Используйте iview, чтобы сделать небольшой инструмент. Чтобы не затронуть другие платформы, загрузите JS и CSS CDN на локальные ссылки. В результате значок шрифта не может быть загружен. Просмо.

Критическое: ошибка настройки прослушивателя приложения класса org.springframework.web.context.ContextLoaderLis

1 Обзор Серверная программа, которая обычно запускалась раньше, открылась сегодня, и неожиданно появилась эта ошибка. Интуитивно понятно, что не хватает связанных с Spring пакетов, но после удаления п.

1086 Не скажу (15 баллов)

При выполнении домашнего задания друг, сидящий рядом с ним, спросил вас: «Сколько будет пять умножить на семь?» Вы должны вежливо улыбнуться и сказать ему: «Пятьдесят три». Это.

Pandas применяют параллельный процесс приложения, многоядерная скорость очистки данных

В конкурсе Algorith Algorith Algorith Algorith Algorith 2019 года используется многофункциональная уборка номера ускорения. Будет использовать панды. Но сама панда, кажется, не имеет механизма для мно.

PureMVC Learning (Tucao) Примечания

Справочная статья:Введение подробного PrueMVC Использованная литература:Дело UnityPureMvc Основная цель этой статьи состоит в том, чтобы организовать соответствующие ресурсы о PureMVC. Что касается Pu.

Источник

[no-tabs] allow exceptions #12438

What rule do you want to change?

no-tabs (currently on eslint 6.5.1)

Does this change cause the rule to produce more or fewer warnings?

How will the change be implemented?

Please provide some example code that this change will affect:

What does the rule currently do for this code?

It complains about Unexpected tab character inside the commented-out code and in the string string literal, which is too strict imo.

What will the rule do after it’s changed?

I would propose to add some configuration options that either

  • could allow lines matching a certain regex
  • could allow lines in a certain AST context, e.g. string literals or comments

so that the rule would accept above code examples but still complain about tabulator characters elsewhere.

The text was updated successfully, but these errors were encountered:

Hi @ab-pm, thanks for this issue.

Have you looked at the indent rule? That should allow you to enforce spaces for indentation and is probably what you need.

I agree this rule is pretty strict, but before we enhance it, I just want to see if indent gives you what you need.

If you believe the no-tabs rule still needs to be enhanced, could you please use the rule enhancement issue template to show what you would particularly like to see? Thanks!

Hi @ab-pm, thanks for the issue. It looks like there’s not enough information for us to know how to help you.

Requesting a rule change? Please see Proposing a Rule Change for instructions.

@platinumazure Yes, I am using the indent rule, and prefer tabs for indentation — that’s why they are still to be found in the commented-out code. Updated with the template, sorry if it’s been unclear.

What do you think should an extra option look like that is easy to use and still flexible? Something like allowIndentationTabsInCommentedCode and allowTabsInTemplateStrings ?

Is there a reason you want to enable no-tabs if you want to allow tabs in strings and comments?

@kaicataldo I don’t want to have any tabs in the rest of the code, e.g. as whitespace between keywords or between elements in inline array/object literals.

Understood, thank you. I think it would make sense to make the configuration option also accept an object with the following signature:

We could do this in a backwards compatible way and eventually remove the current string option in a future major release.

I second this request (so it does not expire like the older ones) as I also use tabs for indenting and I don’t want no-tabs to error or warn on commented-out lines of code (tab indented).
I still want to use no-tabs to warn me about tabs used for anything else than indenting.

I already have this config:

In fact I was quite surprised when that didn’t already cover tabs in comments.

and it has worked! But I guess all I’ve really done is turn off no-tabs for the whole codebase. Which I definitely don’t want to do.

So, @mdjermanovic, this eslint tool is also really that much anti-tabs?
When using tabs for indentation, it’s normal to comment lines out with // preceeding tabs.
So we need the allowInComments for sure!

Someone took the time and effort to fix that with PR #16224 but it was closed by you. :-C

New options: We will not add any new options to stylistic rules unless an option is the only way to fix a bug

I don’t understand how this policy doesn’t apply here, it’s a bug to detect tab indented commented out lines are errors.

Or if the policy means there is no evolutions?
What does it mean?
Eslint is dead?

@jesus2099 Hey, I personally use Prettier now for code styling and it does its thing. But I never found a good workaround for this sorry.

Still deal with this, just ignore it now, but it is quite annoying.

The solution proposed in #16224 adds 4 options, which is a bit excessive.

I don’t think Eslint is dead, nor do the maintainers hate tabs. Eslint is a massive project, and sometimes you have to prioritize essential issues. @nzakas explained the reason for this policy very clearly in this blog post

This issue suggests adding a configuration option for no-tabs rule, which would be considered a Minor change and it goes against No new options for stylistic rules. My suggestion – this should be considered a bug and tabs in comments should always be ignored. Since the fix would reduce the number of errors ESLint reports, it could be released as a Patch. PR for this should be definitely made by the community, not core team members.

Источник

Eslint expected indentation of 1 tab but found 4 spaces error

I am using VScode with latest version of Eslint. It is my first time using a linter.

I keep getting this linting error when using a tab as indentation:

severity: ‘Error’ message: ‘Expected indentation of 1 tab but found 4 spaces. (indent)’ at: ‘4,5’ source: ‘eslint’

Here is my config file

I don’t understand why this error is being thrown as I indicated tabs for indentation. It is obviously calculating my 1 tab as 4 spaced but I don’t understand why it is doing that when I am pressing tab for indentation.

update: The reason is because in VScode using ctrl + shift + i to beautify code will actually use spaces and not tabs. That is the reason.

14 Answers 14

Try to disable indent inside .eslintrc.js file

this works fine for me

In VSCODE, go to menu:

File / Preferences / Settings then Text Editor (or just search for ‘tab’ in the search settings box)

Then remove the tick from the following settings:

  • Insert Spaces
  • Detect Indentation

Also to auto format the document with the default VSCode keyboard shortcut use:

If you use both eslint and prettier , don’t disable indent by using <‘indent’: ‘off’>in rules object. To ensure the consistency of your code style, you have to use this rule.

Solution:

This issue is probably happened because of eslint & prettier conflict. Try to play with different options of eslint in .eslintrc file.

If you hover the error lines in vsCode, at the end of error description you can click on that link to see eslint docs.

For example, in case of indent docs is in this link:

For me, error resolved by adding this line (for ternary expressions):

You can also try flatTernaryExpressions or offsetTernaryExpressions for ternary expressions.

You can automaticaly fix the problems with

I used VScode to solve this problem. All you have to do is hold the mouse over the part where there is an error.

and.

Wee, that exactly what it says. You have in your config «indent»: [ «error», «tab» ], So it expects tab as indent. But found in your file 4 spaces. Remove spaces and put tab in you file

I had a similar problem and solved with this code:

change «editor.tabSize»: 4 to «editor.tabSize»: 2 in VS Code Settings

If you are using VSCODE follow the next steps.

  1. Access the settings by clicking: code > preferences > settings, as shown in the following image.

  1. In the settings, click: Text Editor after that, uncheck the Insert Space option and the Detect Indentation option as shown in the following image.

  1. Restart VSCODE and your dev server.

I was having the same problem and I solved my problem with documentation. Instead of disabling eslint indent, you can add it as shown in the documentation.

remove this line if have:

eslint conflict with prettier

There was a conflict between plugins in my example. I’m using eslint version 8.24.0 . To fix, i just removed the rule plugin:prettier/recommended and added prettier at last position from extends as explained in eslint-config-prettier documentation. See: https://github.com/prettier/eslint-config-prettier#arrow-body-style-and-prefer-arrow-callback

It worked for me, if error is coming then just solve it line by line simply in your code, like : 1.)Expected indentation of 2 spaces but found 8 -> then put only 2 spaces from the starting of the line 2.)Unexpected tab character -> don’t use tabs, use spaces 3.)Trailing spaces not allowed -> don’t give any spaces after lines end. 4.)Missing space before value for key ‘name’ -> put 1 space after «:» in object value 5.)A space is required after ‘,’ -> put 1 space after «,» in parameter of the function 6.)Opening curly brace does not appear on the same line as controlling statement -> just put the opening curly brace where function starts in the same line 7.)Closing curly brace should be on the same line as opening curly brace or on the line after the previous block -> put the closing curly brace just below where the function starts.

Please add the below comment at the first line of the JS file that you are customizing.

Источник

[Solved] SyntaxError: unexpected character after line continuation character

This Python error occurs when you accidentally put a character right after a backslash ( ) that isn’t inside a string. This can happen for many reasons, for example, if you forget to put a newline ( n ) in quotes or if you’re mistakenly using a backslash for division. Fix this easily by making sure nothing follows a that is outside of a string.

Sometimes lines get a little too long in your Python code. The old rule of thumb is to not let your lines get longer than 80 characters. But that was before widescreen monitors. Nowadays, it’s more like 120 characters. Really, it comes down to personal preference or whatever your team decides is the style to go with.

Either way, there’s only one way to break up a long line, and that’s with the line continuation character:

Though this might look a little funky if you’ve never seen it done before, the above code is perfectly valid. The backslash simply tells the Python interpreter “hey, this line continues below, so pretend the next line is also on this line”.

If you don’t use the continuation character correctly, however, you can end up with “SyntaxError: unexpected character after line continuation character”. Let’s look at some ways this can occur!

❌ Problem: you accidentally put something after the backslash

We’ll start with the most obvious one: you did just make a mistake. I know, I know. You don’t make mistakes. I don’t either. It was probably someone else. But now it’s your problem, because it’s 4:58 on a Friday afternoon and your branch won’t merge because of a syntax error.

Here’s an example of some code that will cause this problem:

This is the same example from above, except there’s a stray n after the . If you run this code, you’ll get the following stack trace:

As you can see, the Python interpreter is pointing right at the problem. It’s easy to make this particular mistake, because you were already putting n s in your string, so you may have slipped up and accidentally put one after the continuation character as well. Or someone else did. But we both know it was you. Don’t worry, I’m no snitch.

This can also happen if you didn’t actually put the second line on a new line:

✅ Fix: just remove the stuff after the backslash or put it on a new line

This one is easy to fix: just delete the extra stuff or put it on a new line like so:

Now we’re back in business!

❌ Problem: you didn’t put a string containing a special character in quotes

You can also easily have this problem if you forget one or more quotes in a string that contains a special character, such as t or n :

As you can see here, all we wanted to do was have a string containing the word “foo” that is tabbed over once (like this: » foo» ). But, instead, we get the following error message:

✅ Fix: add the missing quote(s)

This one’s an easy fix too. All we have to do is add the missing quotation marks and it should work as expected:

That’s all there is to it!

☝️ Tip: use syntax hilighting!

This should come as no surprise, but you can avoid mistakes like this by using a text editor or integrated development environment (IDE) that has syntax highlighting like the code blocks you see above do. If you’re stuck on a system that has vanilla vi installed or something, then I guess you’re out of luck. But, if you have the ability to do so, try:

  • vim – this might already be installed on the system you’re editing Python code on – try it and see! You can save yourself a lot of hassle. If you’re on a Debian based Linux disto such as Ubuntu, and you’re in the sudoers list, you can install it with sudo apt-get install vim .
  • PyCharm – this is a great, full-featured Python IDE by JetBrains. Don’t let the price tag scare you, there’s a free version called “Community Edition” or “CE”. Install that one and it won’t harass you for a license key when you go to install it
  • Atom – this one’s a personal favorite. It’s an all-purpose text editor with tons of plugins, similar to Notepad++ on Windows systems, or Sublime Text on Mac. But, this one’s cross-platform and best of all, it’s free. Which is my favorite price!

❌ Problem: you’re using a backslash for division (why?)

This is a weird one, but I’ve seen it happen before. Not me of course, I would never do this. But someone has. For the sake of completeness, here’s what the wrong thing looks like:

This, as you can imagine, isn’t going to give you 0.5 . It’s going to give you a stack trace. And that stack trace is going to look like this:

No surprises here. Let’s fix this.

✅ Fix: use a forward slash for division 🤦‍♂️

Alright kids, gather ’round. Grandpa Bill is going to lay down a life lesson for you: you divide with a forward slash. Like this:

And there you have it.

Conclusion

In this article, we covered what causes the Python error “SyntaxError: unexpected character after line continuation character”. It’s always caused by something coming after a backslash that’s not within a string. Inside a string, the character is used to denote a special character, like n . Outside a string, like in your regular Python code, it’s a continuation character, which means it tells the Python interpreter that the current line is continued on the next one. It can’t have anything after it, or you’ll get this error.

We also discussed why you should use a text editor (or IDE) with syntax highlighting. This will save you a lot of trouble in the long run.

That’s all for now, happy coding!

About the Author

Bill is a senior software engineer with 23 years of experience. He specializes in Python, Javascript, C/C++, DevOps, test driven development, and making sure your code isn’t terrible.

Источник

Я использую ESLint с плагин Airbnb (eslint-config-airbnb) и варительный синтаксический анализатор. Я добавил дополнительное правило использования Tab символов для отступов вместо пробелов.

Вот мой .eslintrc:

{
    "parser": "babel-eslint",
    "extends": "airbnb",
    "plugins": [
        "react",
        "jsx-a11y",
        "import"
    ],
    "rules":{
        "indent": [2, "tab"]
    }
}

Теперь я получаю эту ошибку при каждом отступе:

Error: Unexpected tab character

На всякий случай это помогает, я использую Atom IDE с плагинами автолинкета linter и linter-eslint.

30 нояб. 2016, в 18:16

Поделиться

Источник

1 ответ

Я отвечаю сам, потому что Airbnb установил правило no-tabs равным 2 или ошибке, я просто отключил его.

{
    "parser": "babel-eslint",
    "extends": "airbnb",
    "plugins": [
        "react",
        "jsx-a11y",
        "import"
    ],
    "rules":{
        "indent": [2, "tab"],
        "no-tabs": 0
    }
}

R01010010
04 дек. 2016, в 21:31

Поделиться

Ещё вопросы

  • 0Извлечение контента из HTML с помощью PHP
  • 0утверждать указатель на функцию, совместимую с std :: function
  • 1Сравните атрибут для WPF?
  • 1Чтение текстового файла (разделение, сортировка, поиск между числами с помощью ArrayList)
  • 1InputStream и производитель байтового массива?
  • 1Есть ли способ добавить локальную базу данных в пакет Java-проекта NetBeans?
  • 0Как проверить флажок установлен или нет? [Дубликат]
  • 0Выберите все идентификаторы в одной таблице, которые соответствуют как минимум столько же идентификаторов в другой таблице
  • 0Предупреждение: mysql_result () [function.mysql-result]: невозможно перейти к строке -1
  • 0Переключение между массивами с помощью ng-repeat
  • 1Эффект стекла формы
  • 0Карта Google AngularJS не обновляет свой контент при первом просмотре
  • 1как получить предложения nmea на Android, когда метод API не работает
  • 0Дублирующая запись ‘1’ для ключа ‘PRIMARY’ при обновлении таблицы
  • 1знать о вставке удалить и обновить данные в gridview в C #
  • 0angularjs data-ui-sref перезагрузка не работает?
  • 0.htaccess — Как добавить http: // www. на нескольких условиях
  • 0Разъяснение соответствия регулярных выражений для логических AND и OR с Boost
  • 1getLastNonConfigurationInstance ()
  • 1Конвертировать строку в pandas dataframe
  • 0Невозможно отобразить растровое изображение и текст на CMfcButton: отображается только изображение
  • 0ASP.net MVC4 Скрыть исходный код HTML, код Javascript
  • 0Как отключить кнопку с синхронизированным циклом?
  • 1Настройка цвета фона элемента списка теряет подсветку
  • 0jquery slideToggle не работает
  • 1InstancePerApiControllerType не работает
  • 1Google Cloud Datastore Индексы для запросов количества
  • 1Сокращение времени расчета и требований к большой ковариационной матрице
  • 1Highcharts Синхронизированные графики с отсутствующими точками данных
  • 1Как заменить функцию в Python?
  • 1Добавить многострочную labelString в yAxes Chart.js
  • 1Функция Javascript не получает целое значение
  • 0мне нужно использовать проценты или фиксированные значения в начальной загрузке 3?
  • 0Как мне добавить два внешних ключа?
  • 0Дамп ядра при создании вектора из диапазона векторов
  • 1Алфавитная сортировка массива синхронно с другим массивом
  • 0POST работает с использованием JQuery, но не Angularjs
  • 0Копирование статического массива в динамический массив в C ++
  • 0Необработанное исключение в (адрес памяти) (msvcr110.dll)
  • 0Как отсортировать элементы на основе целочисленных значений в элементах?
  • 1Android — как улучшить HorizontalScrollView, который имеет много просмотров / изображений внутри
  • 1C # универсальный с аналогичными классами
  • 0На сетке xeditable, где курсор перемещается в тот же столбец, когда пользователь нажимает клавишу Tab
  • 0Показать последнее изображение из папки динамически
  • 0Как отправить значение кнопки в textBox?
  • 1Как изменить имена файлов путем замены символов?
  • 0Вы рассматриваете определенные флажки как переключатели?
  • 1Добавить собственный стиль карты в Mapbox.js
  • 1Изменение значения узла раздела связанного списка в Python
  • 0Пустая проверка объекта JSON

Сообщество Overcoder

This topic has been deleted. Only users with topic management privileges can see it.

  • I use atom and the eslint atom package for other work. I keep an eslintrc.js file in my home directory for all projects.
    https://github.com/AtomLinter/linter-eslint

    I’m just now getting back to messing with quasar and when running quasar dev or lint on the default template I get errors that keep it from building related to spaces vs tabs (I use tabs). As there is a .eslintrc.js file in the project directory the atom package should use it rather then my “global” one but this seems not the case. I also get errors in atom itself from the eslint plugin

    Can someone using atom eslinter give some advice how to resolve this.

    /mnt/AllData/hacking/eval-repos/645light/src/main.js
      16:2  error  Unexpected tab character                           no-tabs
      17:2  error  Unexpected tab character                           no-tabs
      17:2  error  Expected indentation of 2 spaces but found 1 tab   indent
    ...
    Errors:
      6  http://eslint.org/docs/rules/no-tabs
      5  http://eslint.org/docs/rules/indent
    
     @ multi ./build/hot-reload ./src/main.js
    
  • I believe you need to either remove the eslintrc.js file from your app (the one Quasar offers) or edit it to fit your rules.

    Scott

  • Turns out somehow the no-tabs is being set (how I have not clue, maybe in html plugin??)

    If one adds
    "no-tabs": 0,
    the errors go away

    It’s enough of a “bug” that the maintainers should add this to the template’s .eslintrc.js. That way for those of us liking tabs errors are not thrown but otherwise spaces are accepted by default
    @rstoenescu

    See this post this stackoverflow post
    https://stackoverflow.com/questions/40893518/eslint-unexpected-tab-character-when-indent-rule-set-to-tab

  • maybe you should try editorconfig

  • @dgk said in [solved] eslint no-tabs errors:

    It’s enough of a “bug” that the maintainers should add this to the template’s .eslintrc.js. That way for those of us liking tabs errors are not thrown but otherwise spaces are accepted by default
    @rstoenescu

    The linting rules Quasar follows are from StandardJS, with a couple of exceptions.

    http://beta.quasar-framework.org/guide/app-linter-configuration.html
    https://github.com/standard/standard/blob/master/RULES.md

    As you can see from the rules of StandardJS, spaces should be used for indentation.

    It’s not a bug. It’s how it should be (since we are following that linting standard). You’ve found the correct solution though. Just modify the linting config, as you have.

    Scott

  • Понравилась статья? Поделить с друзьями:
  • Error unexpected rcode refused
  • Error unexpected matlab operator
  • Error unexpected matlab expression
  • Error unexpected local declaration in procedure body
  • Error unexpected junk after else statement at 1