How do I fix the perl syntax error "missing right curly or square bracket" using VIM? - perl

Compiling (or executing) a perl program with unmatched array braces ("[ ]") or scope brackets ("{ }") causes the "missing right curly or square bracket" syntax error. Perl often reports the source as your last code line ("at EOF"), which could be far removed from the actual missing piece.
Example perl error message:
Missing right curly or square bracket at ./foo.pl line 100, at end of line
syntax error at ./foo.pl line 100, at EOF
Execution of ./foo.pl aborted due to compilation errors.
How do vi or Vi IMproved (VIM) users troubleshoot this error message? I've added an answer with some VIM enhancements. Please add your own ideas, practices, or vi plugins.
NOTE: Original question posted with VIM version that didn't highlight perl braces and brackets. Many newer versions do this; see vim.org for more info.

How to troubleshoot this error right now:
In VIM, pick an opening {, [, or ( symbol. The % command jumps between matching { }, [ ], and ( ) pairs. Mismatches will jump to an unexpected location.
Install perltidy, run it, and look for oddly indented code blocks.
How to prevent future errors:
StackOverflow question 719476 shows how to modify VIM brace/bracket syntax coloring for braces/brackets. (Some versions don't do this by default.)
Karl Guertin's AutoClose plugin auto-matches [, (, {, ", ' symbols when typed.
perltidy script reformats perl for readability, which can expose mismatched symbols.
User a paid nerd said: "Use perltidy within VIM editor with nmap."
nmap \g mt:%!perltidy<CR>'t
Use consistent {} matching indentation (general tip, not specific to this perl error).
 
sub foo {
...
}
or
sub bar
{
...
}

You can use the % command to match braces/brackets/parentheses in vim. So use that to search for unmatched characters.

I constantly use perltidy to reformat my code. When I reformat code that's missing a terminator, further code indents strangely and I can quickly trace upward to locate the problem.
Bonus: I use this mapping to instantly reformat the file and not lose the cursor position:
nmap \g mt:%!perltidy<CR>'t

Use padre. Click Perl->Find Unmatched Brace. It moves your cursor right to the problem.
I came to this page with the same problem. Using perltidy and vim were of no help, the indenting looked fine after perltidy. I had an extra open brace before a 'sub' keyword for some reason. Padre solved the problem in one-click.
http://padre.perlide.org/

use syntax highlighting, vim almost always get this right, and has a very sophisticated perl syntax highlighting scheme.
:syntax on

It sounds like you may be talking about a teaching situation, in which case teaching good indentation will solve most of these issues.
However, sometimes I'm on a server with no niceties like vim and perltidy, and I use a quick'n'dirty technique to find the syntax error - just add a right-curly at different points in your code until the line number changes, and there's your trouble spot.

If you don't see any missing braces :
Replacing \r with \n can help to fix this issue if the file created in windows and trying to use in Linux.

I got this error in a script that appeared to have perfectly matched curly and square braces... except that I had used bash-style syntax which actually commented out the second half of one line (with the second half of a curly brace pair).
The error went away when I changed this line:
$data_len="${#insert_data}";
to this:
$data_len=length($insert_data);

Use regular expression to narrow down where offending code. Example using shell, pcregrep
cat index.pl |pcregrep '[\{]{1}[\w\W^}^{]{90,}'
varying 90 as needed for limiting block length before expecting an ending brace.

As a simple re-statement and combination of #Ether and #Matthew Glidden:
Intent shown like this ( vi command like this )
Go to top of file ( 1G )
Search for brackets ( /[[({] then press "Enter" )
That's "slash" "open square brace" "open square brace" "open round brace" "open curly brace" "close square brace"
As a regex, we're searching for a custom character class which is all opening braces.
Find end matching bracket ( % )
Find starting bracket again ( % )
Find next opening bracket ( n )
Repeat from 3 until you've checked all brackets in file.
Works as far back as vi on HP-UX 11.11 (like ~2001).

Related

Shell Script doesn't color multiline <<EOF statement

I'm working with a shell script in VSCode,
I'd like to be able to collapse the function.
In order for me to do that, the 'EOF' word has to have some whitespace before it.
But if I put whitespace before it, the entire coloring of the file is ruined (including all the functions appearing thereafter)
Is there a setting / or another way to do it so it will not behave like this?
Thanks
With EOF word at the beginning of the line
With some whitespace before the EOF

i have this book called learning python the hard way and i have queries regarding that

my code and the terminal .
file = "ex25.py", line 27
words=sort_sentence(sentence)
IndentationError: unindent does not match any other indentation level
The code I wrote in ex25 is:
def print_first_and_last_sorted(sentence):
words =sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
After you define function with the first line, in the second line you need to use proper indentation or spaces. The standard is 4 spaces (4 space keystrokes) or 1 tab.
def print_first_and_last_sorted(sentence):
words =sort_sentence(sentence) # This line and next should be spaced 4 times with
print_first_word(words) # respect to the above one
print_last_word(words)
Your second line is not indented properly. You can compare it with the next lines. They all should be vertically parallel at their start points.
I can't comment but from both the edit and the original post, therefore I can't tell what the indentation actually is.
Python indentation works like blocks of code, similar to other languages except without the curly braces. For example:
def print_first_and_last_sorted(sentence):
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
You may have mixed up spaces & tabs. From this answer, try searching and replacing to replace them with a few spaces.

Emacs highlighting: how to deal with highlighting messed up by unusual usage of special characters?

Problem:
In Emacs configuration modes (e.g. conf-xdefaults-mode or conf-space-mode), some special characters are used in unusual ways, for instance when they define keybindings. This messes up the highlighting for the rest of the buffer.
Example:
The ranger rc.conf file uses conf-space-mode which greatly helps its readability. But lines such as:
map # console shell -p%space
map "<any> tag_toggle tag=%any
mess up the highlighting since # usually defines a comment and is followed by font-lock-comment-face until the end of the line and " defines the beginning of a string and is followed by font-lock-string-face until it encounters a closing quote.
Escaping those characters is not an option because it would prevent them from defining the keybindings.
Possible solution:
The best solution I can think of is to fiddle with font lock settings for those configuration modes to remove the highlighting after those special characters. But I will then loose the proper highlighting after those characters when it is suitable.
A compromise could be to keep highlighting after # since this only messes up one line and there are a lot of comments in those configuration files, while removing the highlighting after single and double quotes since those mess up the entire rest of the buffer and strings are not so common in configuration files.
Question:
What is the proper way to deal with these situations?
Is there a way to reset the highlighting at a point in the buffer? or to insert a character which would affect the highlighting (to fix it) without affecting the code? or is there a way to "escape" some characters for the highlighting only without affecting the code?
The easy way
It's probably easiest to just live with it but keep things constrained. Here, I took ranger's default rc.conf and re-arranged some of the font-lock errors.
Let's ignore the blue "map" for now. We have two visible font-lock errors. The map #... is font-locking as a comment, and the map "... font-locking as a string to the end of the buffer. The first error is self-constrained. Comments end at the end of the line. The second error we constrain by adding a comment. (I don't know if ranger would accept comments in the middle of the line, so I'm only using beginning-of-line comments here.)
The second error is now constrained to one line, but a couple more errors have popped up. Quickly adjusting these we get.
This is something that I could live with, as I'm not in conf files all day long (as opposed to say, source code.) It would be even neater if our new "comments" could be included on the same line.
The hard way
You'll want to use Emacs font-lock-add-keywords. Let's get back to that blue map in the first image. It's rendering blue because conf-space-mode thinks that a string, followed by any amount of whitespace, followed by an opening brace should be rendered in font-lock-type-face (the actually regexp that triggers this is ^[_space__tab_]*\\(.+?\\)[_space__tab_\n]*{[^{}]*?$ where _space_ and _tab_ are actual space and tab characters.)
We can override this in a simple fashion by evaluating
(font-lock-remove-keywords
'conf-space-mode
'(("^\\<\\(map\\)\\>" 1 font-lock-variable-name-face)))
and reloading the buffer with C-x C-v RET. Now, every time that the word "map" appears at the beginning of a line it's rendered as font-lock-variable-name-face (yellow in our example.)
You can make this change permanent by adding a hook to your init file.
(add-hook 'conf-space-mode-hook (lambda ()
(font-lock-remove-keywords
nil
'(("^\\<\\(map\\)\\>" 1 font-lock-variable-name-face)))))
This method doesn't appear to work for your comment (#) and string (' ") delimiters as they're defined in the syntax table. Modifying the syntax table to provide special cases is probably more effort than it's worth.

Eclipse code formatter multiline function call closing bracket indention

Currently my eclipse formatter formats a multiline function call like this:
someObject.doSomething(
some().long().chain().of().methods()
);
But what I want is for eclipse to align the closing bracket with the method call:
someObject.doSomething(
some().long().chain().of().methods()
);
I have tried playing around with new line and wrapping rules in the code formatter but haven't been able to achieve this. What would be the solution?
After some time of digging I found a similar question which has an accepted answer but seems not to answer the same question:
Can the Eclipse formatter be configured to indent multiple lines between parenthesis properly?
The author of this question also states:
Edit: I found the settings for "Line Wrapping" -> "Default indentation
for wrapped lines" and "Default indentation for array initializes" and
have set them to "1" instead of "0". That is better for the array
initializers, but still doesn't indent closing parethesis to match the
opening parenthesis the way that I want it to:
The latest proposal on this does not take into account the closing );, but the first expression.
See Eclipse 4.23 (Q1 2022):
Method invocation wrapping indentation
It turns out it's not obvious how to indent a wrapped method invocation when the preceding expression itself is complex enough to also be wrapped into multiple lines.
Should the indentation be added to the existing indentation at the end of the expression, or just reset and assume that only the indentation of expression's first line matters?
Previously only the former behavior was available, now there's a setting to choose the latter.
The checkbox called Indent from the base expression's first line is located in the Line Wrapping > Wrapping settings > Function calls section, right under the Qualified invocations setting.

Unexpected 'INDENT' in CoffeeScript Example Code

As I was playing around for the first time with CoffeeScript, I ran in to a problem. In order to debug my problem, I tried replacing my whole file with one of the example bits of code from the coffee script site:
kids =
brother:
name: "Max"
age: 11
sister:
name: "Ida"
age: 9
However, when I try to compile that code, I get:
Error: In coffee/main.coffee, Parse error on line 3: Unexpected 'INDENT'
at Object.parseError (/usr/lib/coffeescript/parser.js:501:11)
at Object.parse (/usr/lib/coffeescript/parser.js:573:32)
at Object.compile (/usr/lib/coffeescript/coffee-script.js:23:22)
at /usr/lib/coffeescript/command.js:99:27
at /usr/lib/coffeescript/command.js:72:28
at fs:84:13
at node.js:773:9
In coffee/main.coffee, Parse error on line 3: Unexpected 'INDENT'
Since this is code from the CoffeeScript site, I assume the code itself isn't the problem. However, the compiler also seems to be working properly; if I compile:
a = 2
it generates a file with:
(function(){
var a;
a = 2;
})();
as expected. So in other words, the code is good, the compiler is good, and yet somehow I'm getting this Unexpected 'IDENT' error ... can anyone help me understand what is going on?
I am pretty sure this is a tabs-vs-spaces issue. Tell your editor not to convert spaces to tabs if it does that. Also, go through your code with the cursor and make sure it doesn't jump over blank areas.
The issue is that while normal editors see a tab as equivalent to two or four spaces, coffeescript sees it as one space, so the indentation gets messed up.
If this all doesn't help, make sure you have a recent coffeescript version, e.g. 1.1.0 or newer.
If you are using a JetBrains IDE (IntelliJ, PHPStorm, etc) the change of setting that worked for me is:
File > Settings > Project Settings > Code Style > CoffeeScript > Tabs
and Indents
Tick "Use tab character" & "Smart tabs"
Code is fine. Make sure you haven't messed up the whitespace (strange control chars showing as blanks, tabs or similar).
If you have the same problem, but your indentation is okay,
then you must be suffering from bug 2868.
Basically, the error is misleading. Check for indentation
errors in the required files.
When in Atom you can automatically convert tabs to spaces:
Packages > Whitespace > Convert Tabs to Spaces
You can resolve this two ways
1. IF using webstorm File->Default Settings as said above
2. Other workaround, is to use a different editor like Sublime, there u can press enter on earlier line and it will auto tab it for you with spaces