Stylus not allowing basic subtraction - stylus

Noticed an issue when using semantic grids stylus.
*width total-width * ((((gutter-width + column-width ) * x) - gutter-width) / _gridsystem-width)-correction
is processing to something along the lines(read different numbers)
*width: 89.5833333333333% -correction;
So, I decided to performan an experiment. When running stylus -i I found subtraction there was also not operating (at all)
To verify I wrote this in my file
x=10
y=20
.something
font-size y-x
which process to
.something {
font-size: y-x;
}
Am I crazy? Did I interpret operators incorrectly with stylus?
Pending the results here I may open a ticket on github. I did find another person with an issue around percentages that highlights the - operator not functioning as expected. However, this doesn't seem related to my issue.
Tldr: basic math without units doesn't seem to be working

This is a known problem, dash - is counted as a part of a variable name, so when you write -correction, Stylus sees it as a variable -correction.
The obvious fix is to always use spaces around the minus: - correction, this way Stylus would always recognize the operator.

Related

Parsing shell commands in c: string cutting with respect to its contents

I'm currently creating Linux shell to learn more about system calls.
I've already figured out most of the things. Parser, token generation, passing appropriate things to appropriate system calls - works.
The thing is, that even before I start making tokens, I split whole command string into separate words. It's based on array of separators, and it works surprisingly good. Except that I'm struggling with adding additional functionality to it, like escape sequences or quotes. I can't really live without it, since even people using basic grep commands use arguments with quotes. I'll need to add functionality for:
' ' - ignore every other separator, operator or double quotes found between those two, pass this as one string, don't include these quotation marks into resulting word,
" "- same as above, but ignore single quotes,
\\ - escape this into single backslash,
\(space) - escape this into space, do not parse resulting space as separator
\", \' - analogously to the above.
Many other things that I haven't figured out I need yet
and every single one of them seems like an exception on its own. Each of them must operate on diversity of possible positions in commands, being included into result or not, having influence on the rest of the parsing. It makes my code look like big ball of mud.
Is there a better approach to do this? Is there a more general algorithm for that purpose?
You are trying to solve a classic problem in program analysis (of lexing and parsing) using a nontraditional structure for lexer ( I split whole command string into separate words... ). OK, then you will have non-traditional troubles with getting the lexer "right".
That doesn't mean that way is doomed to failure, and without seeing specific instances of your problem, (you list a set of constructs you want to handle, but don't say why these are hard to process), it is hard to provide any specific advice. It also doesn't mean that way will lead to success; splitting the line may break tokens that shouldn't be broken (usually by getting confused about what has been escaped).
The point of using a standard lexer (such as Flex or any of the 1000 variants you can get) is that they provide a proven approach to complex lexing problems, based generally on the idea that one can use regular expressions to describe the shape of individual lexemes. Thus, you get one regexp per lexeme type, thus an ocean of them but each one is pretty easy to specify by itself.
I've done ~~40 languages using strong lexers and parsers (using one of the ones in that list). I assure you the standard approach is empirically pretty effective. The types of surprises are well understood and manageable. A nonstandard approach always has the risk that it will surprise you in a bad way.
Last remark: shell languages for Unix have had people adding crazy stuff for 40 years. Expect the job to be at least medium hard, and don't expect it to be pretty like Wirth's original Pascal.

How to properly locate unbalanced parenthesis in source code?

Recently I learned some text editor has functions to check whether all parentheses are balanced inside a file. (e.g. check-parens in Emacs). It may even be able to highlight the 1st unbalanced parenthesis if there is any. However I am not clear whether there is a way to properly locate it instead of always highlight the 1st unbalanced occurrence.
Consider below code:
void foo()
{
int some_num0 = 0;
{
int some_num1 = 1;
{
int some_num2 = 2;
{
int some_num3 = 3;
//ops I forgot to close this block.
}
}
}
A simple balance check, (e.g. check-parens in Emacs) will bring me to the opening brace of foo's definition. However a more reasonable indication should bring me to somewhere around the innermost level, the one near some_num3. Is there a way to achieve this?
The parenthesis check basically reads the code and updates a counter whenever it hits a parenthesis. If it is an opening bracket, it adds 1 ; if it is a closing one, it adds -1 (subtracts 1). If the counter ever hits a negative number, there is a problem, and it tells you. If, at the end of the code, the counter is not zero, there also is a problem ; that is your case.
But how do you want it to know where the missing brace(s) actually is/are ? The only way to do something close to what you want is to check for the indentation as well. But what if your code is not properly indented ?
I do not know of any tool that checks for indentation while checking braces, and I doubt there is a good one (if any).
The fact is, the more you forget a parenthesis, and above all, the more you write code, the more you remember to not forget these parenthesis. Or at least, it is likely to happen.
So, do not blame your IDE for not being endowed with reason, but rather blame you for not immediately locating missing brackets. And write code.
Some of the popular Emacs libraries include, but are not limited to:
highlight-parentheses: https://github.com/nschum/highlight-parentheses.el
rainbow-delimiters: https://github.com/jlr/rainbow-delimiters
Here is a link to a recent modification that I made to one of the functions used by highlight-parentheses, which will preserve the overlays when using scroll-up, scroll-down, or mwheel-scroll: https://stackoverflow.com/a/25269210/2112489
Here is a link to a modified version of highlight-parentheses, which is what I use: https://stackoverflow.com/a/23998965/2112489 I have not yet updated the posted version of parens-mode to include the modification for scrolling that is referred to in the previous link. My personal preference is to add / delete overlays, instead of storing them at the beginning of the buffer and moving them around.
Here is a screen-shot of a modified version of highlight-parentheses:
(source: lawlist.com)
If you indented all of the closing braces by one level, would you still say that it would be more reasonable to indicate the 4th opening brace?
If not, perhaps it should be checking for consistent indentation too.
Not realy a check-parens solution but when something like this happens to me I usually mark the whole block and go M-x indent-region to have emacs try to indent the selected region correctly.
In your simple case it would indent them all one level (MRABs answer) and you would just close the last brace.
In a more complicated case indentation will break somewhere (i.e the code won't look like you expect it to do) and that is usually where the parenthesis is missing.
I just used notepad++ with the BracketsCheck plugin https://community.notepad-plus-plus.org/topic/14090/best-way-to-find-unmatched-parentheses/2. After some hours searching and trying VSCode plugins, n++ did it for me :) I was checking a 2.5K lines XML file with about 270 formula expressions. Checking parenthesis formula by formula using the usual matching parenthesis highlighting feature wasn't looking much of an option.

Calculating input.

I tried to make a code that calculates the values of the formulas the user inputs. I.e , if user inputs "10+5" , the program would print "The sum is 15" etc. At first, i thought this is a easy thing to do, but if realized that just using scanf orsth wouldn't do the trick. Then i messed around with arrays and loops to see if the loop encounters "-" or "+" signs in input and then saving the character before "-" or "+" and after it and then calculating it, but i couldnt make this work either.
Could you please lead me in the right direction on how to get this done.
Thank you very much!
This can be quite complicated, especially when you get to operator precedence and you need to correctly calculate, for example, 2 + 5 * 6, which needs to be treated as 2 + (5 * 6). The correct way to approach this is to construct an expression tree (just like a compiler would). e.g.
+
/ \
2 *
/ \
5 6
You do this by creating binary tree. Each nodes holds an operation and (up to) two subnodes. Then you evaluate your expression by traversing the expression tree.
What you are trying to do is to parse arithmetic expressions, then evaluate them. There is a ton of stuff on this on the internet so, since this is your homework, I'll leave you to Google. Your first thought, that this would be easy to do, is probably a naive thought, though it's not a terribly difficult problem if you don't get too ambitious too quickly.
This might be a little over your head, but what you can do is use a grammer engine for c and a lexical analyzer.
I believe it is called "BISON" and "YYLEX"
From what I remember in school, it is how we made our pascal compiler.
http://en.wikipedia.org/wiki/GNU_bison
After creating a tree. you then can analyze sub trees and then the root node will be the sum of the sub trees.
These might be some steps that you might want to consider
get the input using getline() or fgets()
start reading the string from the beginning
do two passes, use one queue for operators and another for operands (numbers)
during the first pass, you reach an * or /, read the next number, perform the operation on the next number and the number you read before, and insert the result in a queue
also during the first pass, if you read a + or -, silently push the operator and operands into their respective queues
during the second phase handle + and -... using queues will help you properly handle successive minuses e.g. 4-3-3
These are not EXACT steps, but it's a heuristic worth looking into - try to work through these, change them according to what makes sense to you etc.

How can I automatically fold a long C code in Vim?

I regularly run into C-codes without folding. It is irritating to read them if there is no folding, particularly with long files. How can I fold them?
To fold according to syntax
:set foldmethod=syntax
If you want to do it manually on the bits you want to fold away
:set foldmethod=manual
then create new folds by selecting / moving and pressing zf
e.g.
shift-v j j zf
(ignoring the spaces)
Edit: Also see the comments of this answer for indent and marker foldmethods.
I think you may have mixed the terminology. Do you need "wrapping" or "folding". Wrapping is the one where lines that wouldn't usually fit on screen due to their length, are wrapped, i.e. shown on several consecutive lines on screen (actually, it is one line, in several lines - hard to explain, best to see in practice).
In vim wrapping is set by
:set wrap
to turn it on, and
:set textwidth=80
to determine where vim should wrap the text (80 characters is usually a nice measure).
Folding on the other hand is a completely different matter. It is the one where vim folds several lines of code (for example, a function) into one line of code. It is useful for increasing readability of code. Vim has several folding methods, you can see all of them if you
:help folding
What you are looking for, I think would be, syntax folding, but I could be wrong. I recommend reading the help page, it is not long, and very useful.
Actually, there is another very straight forward and effective way, which is using foldmethod = marker and set foldmarker to be {,}. Then the fold result would looks like:
all of the functions fold-ed. Basically, it looks like the outline in IDE. (and you can also set foldlevel=1or more, if you do not want to fold everything at the beginning)
this is what a normal function looks like when you open it with level-1 via zo.
In addition, to do folding by syntax needs a bit of extra work, and here is a good tutorial about it. But I think fold by marker={,} is quite enough, and most importantly, it's simple and neat.
I've rolled up a fold plugin for C and C++. It goes beyond what is done with syntax folding (may be it could be improved, I don't know), and leaves less noisy and not really useful things unfolded, compared to indentation and marker based folding.
The caveat: in order to have decent reaction times, I had to make some simplifications, and sometimes the result is quite messed-up (we have to type zx to fix it).
Here is a little screencast to see how the plugin folds a correctly balanced C++ source code, which is not currently being modified :(
In vi (as opposed to vim) the answer was:
:set wm=1
This sets the wrap margin to one character before the end of the line. This isn't the world's best specification with variable sized windows (it made sense with green screens when it was hard to change the size).
That means there is also an alternative way to do it in vim:
:set textwidth=30
See: VimDoc User Manual Section 25.1
The you probably want the setting
:set foldmethod=syntax
But don't put that in manually! Thats missing out on one of Vims biggest features which is having custom settings for hundreds of file types already builtin. To get that, add this to your ~/.vimrc
filetype plugin on
filetype indent on
filetype detection is mostly based on extension, in this case *.c files. See :help :filetype for more info. You can also customize these filetype based settings.

What is this strange C code format?

What advantage, if any, is provided by formatting C code as follows:
while(lock_file(lockdir)==0)
{
count++;
if(count==20)
{
fprintf(stderr,"Can't lock dir %s\n",lockdir);
exit(1);
}
sleep(3);
}
if(rmdir(serverdir)!=0)
{
switch(errno)
{
case EEXIST:
fprintf(stderr,"Server dir %s not empty\n",serverdir);
break;
default:
fprintf(stderr,"Can't delete dir %s\n",serverdir);
}
exit(1);
}
unlock_file(lockdir);
versus something more typical such as
while(lock_file(lockdir)==0) {
count++;
if(count==20) {
fprintf(stderr,"Can't lock dir %s\n",lockdir);
exit(1);
}
sleep(3);
}
if(rmdir(serverdir)!=0) {
switch(errno) {
case EEXIST:
fprintf(stderr,"Server dir %s not empty\n",serverdir);
break;
default:
fprintf(stderr,"Can't delete dir %s\n",serverdir);
}
exit(1);
}
unlock_file(lockdir);
I just find the top version difficult to read and to get the indenting level correct for statements outside of a long block, especially for longs blocks containing several nested blocks.
Only advantage I can see is just to be different and leave your fingerprints on code that you've written.
I notice vim formatting would have to be hand-rolled to handle the top case.
The top example is know as "Whitesmiths style". Wikipedia's entry on Indent Styles explains several styles along with their advantages and disadvantages.
The indentation you're seeing is Whitesmiths style. It's described in the first edition of Code Complete as "begin-end Block Boundaries". The basic argument for this style is that in languages like C (and Pascal) an if governs either a single statement or a block. Thus the whole block, not just its contents should be shown subordinate to the if-statement by being indented consistently.
XXXXXXXXXXXXXXX if (test)
XXXXXXXXXXXX one_thing();
XXXXXXXXXXXXXXX if (test)
X {
XXXXX one_thing();
XXXXX another_thing();
X }
Back when I first read this book (in the 90s) I found the argument for "begin-end Block Boundaries" to be convincing, though I didn't like it much when I put it into practice (in Pascal). I like it even less in C and find it confusing to read. I end up using what Steve McConnel calls "Emulating Pure Blocks" (Sun's Java Style, which is almost K&R).
XXXXXXXXXXXXXX X if (test) {
XXXXXX one_thing();
XXXXXX another_thing();
X }
This is the most common style used to program in Java (which is what I do all day). It's also most similar to my previous language which was a "pure block" language, requiring no "emulation". There are no single-statement bodies, blocks are inherent in the control structure syntax.
IF test THEN
oneThing;
anotherThing
END
Nothing. Indentation and other coding standards are a matter of preference.
Personal Preference I would have thought? I guess it has the code block in one vertical line so possibly easier to work out at a glance? Personally I prefer the brace to start directly under the previous line
It looks pretty standard to me. The only personal change I'd make is aligning the curly-braces with the start of the previous line, rather than the start of the next line, but that's just a personal choice.
Anyway, the style of formatting you're looking at there is a standard one for C and C++, and is used because it makes the code easier to read, and in particular by looking at the level of indentation you can tell where you are with nested loops, conditionals, etc. E.g.:
if (x == 0)
{
if (y == 2)
{
if (z == 3)
{
do_something (x);
}
}
}
OK in that example it's pretty easy to see what's happening, but if you put a lot of code inside those if statements, it can sometimes be hard to tell where you are without consistent indentation.
In your example, have a look at the position of the exit(1) statement -- if it weren't indented like that, it would be hard to tell where this was. As it is, you can tell it's at the end of that big if statement.
Code formatting is personal taste. As long as it is easy to read, it would pay for maintenance!
By following some formatting and commenting standards, first of all you show your respect to other people that will read and edit code written by you. If you don't accept rules and write somehow esoteric code the most probable result is that you will not be able communicate with other people (programmers) effectively. Code format is personal choice if software is written only by you and for you and nobody is expected to read it, but how many modern software is written only by one person ?
The "advantage" of Whitesmiths style (as the top one in your example is called) is that it mirrors the actual logical structure of the code:
indent if there is a logical dependency
place corresponding brackets on the same column so they are easy to find
opening and closing of a context (which may open/close a stack frame etc) are visible, not hidden
So, less if/else errors, loops gone wrong, and catches at the wrong level, and overall logical consistency.
But as benefactual wrote: within certain rational limits, formatting is a matter of personal preference.
Its just another style--people code how they like to code, and that is one accepted style (though not my preferred). I don't think it has much of a disadvantage or advantage over the more common style in which brackets are not indented but the code within them is. Perhaps one could justify it by saying that it more clearly delimits code blocks.
In order for this format to have "advantage", we really need some equivalent C code in another format to compare to!
Where I work, this indentation scheme is used in order to facilitate a home-grown folding editor mechanism.
Thus, I see nothing fundamentally wrong with this format - within certain rational limits, formatting is a matter of personal preference.

Resources