How do I use an or in a tcl switch statement? - tcl

I want to have a large list of options in my script. The user is going to give input that will only match one of those options. I want to be able to have multiple different options run the same commands but I cannot seem to get ORs working. Below is what I thought it should look like, any ideas on how to make the a or b line work?
switch -glob -- $opt {
"a" || "b" {
puts "you selected a or b, probably not both"
}
default {
puts "Your choice did not match anything"
}
}

You can use - as the body for a case, to fall-through to the next body, as explained in the Tcl Manual:
If a body is specified as “-” it means that the body for the next
pattern should also be used as the body for this pattern (if the next
pattern also has a body of “-” then the body after that is used, and
so on). This feature makes it possible to share a single body among
several patterns.
Also, if your options are a big string of concatentated characters, you are going to have to bookend your option patterns with wildcards, or your cases will only match when opt only contains a single option:
switch -glob -- $opt {
"*a*" -
"*b*" {
puts "you selected a or b, probably not both"
}
default {
puts "Your choice did not match anything"
}
}

Also working this:
switch -regexp -- $opt {
a|b {
puts "you selected a or b, probably not both"
}
default {
puts "Your choice did not match anything"
}
}
Attention: no spaces between "a|b"

There's two ways. From the switch documentation examples: "Using glob matching and the fall-through body is an alternative to writing regular expressions with alternations..."

Related

if command not working Actionscript 3

I am making a console like program where you input text, and when you press enter, that text gets turned into the variable "code" which gets read by the if/elseif command to direct it to a certain frame.
When I did this though, actionscript completely ignored the if and just executed what was inside of the if.
There are no errors, but there is a warning. This is my full code
import flash.events.KeyboardEvent;
stop();
stage.focus=textbox;
var code:String=textbox.text;
textbox.addEventListener(KeyboardEvent.KEY_DOWN,thefunction);
function thefunction(event:KeyboardEvent){
if(event.charCode == 13){
code=textbox.text;
trace(code);
page();
}
}
function page(){
if(code="red"){
gotoAndPlay(19)
}
else{
gotoAndStop(1)
}
}
The warning is here=
function page(){
if(code="red"){
gotoAndPlay(19)
}
else{
gotoAndStop(1)
}
}
It says: Warning: 1100: Assignment within conditional. Did you mean == instead of =?
I then tried doing what it said, and nothing happens when I type in anything and press enter (charCode 13).
I have tried doing this with textbox.textinstead of the variable code, and still nothing happens. (trace(code) works fine, so it must be something with the bottom portion, but I'm not sure)
I am new to actionscript, so I do not know how to fix this (my excuse :D). If anybody knows how, I would love to figure out how to fix it.
first of all, as a general rule, you should never use the assignment operator (single =) in an if statement, always use the equality operator (double =)
what you're saying right now is "if you assigned the value 'red' to code without errors, then..." which of course is always true
then, to debug your problem, try to use trace("'" + code + "'"); to see exactly what your textfield contains. if you're still in doubt, convert your text in character codes and print those. Why? if there's a non-printable or non-visible character in your textfield, your if statement wouldn't match (think "red " == "red" > false)
my guess is that your textfield is set to multiline, so your enter key would be added to the text and break your check. set it to single line to avoid possible problems (if you do need a multiline input field, you need a smarter way to compare text, like using regular expressions and such ...)

Unusual behavior with the Text widget indexing? (Tcl/Tk)

I am trying to create bindings for the Tk Text widget to limit the User so s/he can't delete the first character in the line (the character serves as a sort of prompt like in a terminal.)
Here's how I'm almost accomplishing this:
bind .text <BackSpace> {
if{[.text index insert] == [.text index {insert linestart+1c}]} {
break;
}
}
It works in terms of not letting the user delete the first character in the line, but for whatever reason, it also stops the user from deleting the ninth character in the line as well! For example:
>hello world!
Pressing backspace now from the end of that line will delete until
hello wor
and then stop! I can press the left-arrow to move to the next character after 'r' and keep deleting, and then as it should, it doesn't delete the carrot. I see no reason why this should be happening. If someone could either point out my mistake or let me know of a better way to achieve what I'd like that would be great.
At the point where it stops, [.text index insert] gives an index of 1.10 and [.text index {insert linestart+1c}] gives an index of 1.1.
These are numerically equal, and == likes to use numeric equality if at all possible.
The fix is to use the compare method of the text widget, perhaps like this:
bind .text <BackSpace> {
if {[.text compare insert == {insert linestart+1c}]} {
break
}
}
(I think you might actually be better off doing your overall goal a different way, perhaps by setting a tag on the text you want to preserve and checking before deletion whether any of the text to be deleted has the tag. But that's a very different approach.)

Sublime text 2 how to delete comments only

In my sass code, I have inline comments and I wish to remove these in sublime text. Is it possible to permanently delete all comment content alone?
#function emCalc($values) {
$emValues: '';
$max: length($values); //Get the total number of parameters passed
#for $i from 1 through $max {
$value: (nth($values, $i)); //Take the individual parameter
$value: $value / ($value * 0 + 1); //Doing this gets you one unit (1px)
$value: $value / $em-base * 1em; //Divide the px value by emBase and return the value as em
$emValues: #{$emValues + $value}; //Append to array
#if $i < $max {
$emValues: #{$emValues + " "}; //Adding space between parameters (except last), if there are multiple parameters
}
}
#return $emValues; //Call emCalc like so emCalc(10, 20, 30, 40) it should return margin: 0.625em 1.25em 1.875em 2.5em
}
You'll need to double check this (have a backup handy!), but the following regular expression should work in the "replace" window, with regular expressions enabled (the * icon):
Open the "replace" window (ctrl + h / cmd + option + f)
Enable regular expression matching by making sure the * icon is selected
Enter the following in the "Find What?" box
\/\/.*
Leave the "replace with" box empty to delete found text.
Click "Replace All"
Edit
as #ollie noted, this also will delete any urls prefixed with //. The following (lightly tested) regex should serve to better target comments: (^\/\/.*)|(\s+\/\/.*)
Edit v2
A solution for single and multi-line comments (^\/\/.*)|(\s+\/\/.*)|((\/\*)(.|\n)+?(\*\/))
If you have no other possibility, you could select every // (Select first // then CtrlD while there's comments left if my memory is correct).
Then press ShiftEnd to select every end of line with a // and Del ! :)
(There's probably a plugin for that, but this is the simplest method I think. This suggest that all your // refers to the beginning of a comment, of course)
None of the answers here seem to take advantage of the fact that the syntax highlighting has already determined where all the comments are - just execute this in the Python console (View menu -> Show Console) to select all comments:
view.sel().clear(); view.sel().add_all(view.find_by_selector('comment'))
(press Enter after typing/pasting it to execute it)
then press Delete to delete all the selections and Esc to go back to single selection mode
None of the other answers cover all cases (multi-line comments, single line comments, double-slash comments and slash-star/star-slash comments).
In order to match all possible cases (without matching URLs), use the following:
(^[\s]*?\/\/.*)|(/\*[\s\S]+?\*/)
Here is what I do in ST3 in HTML to strip all comments, especially nasty comments embedded within <p> body text, for example ...
package control install SelectUntil
quit and restart sublime
ctrl+f <!--
alt+enter to select all instances of <!--
ctrl+shift+s will pull up an input field, where
you can type: -->
hit delete!
Well well, there is an easy way to do it in mac Sublime Text if you are sure there are no // in print statements.
search for // and hit that cmd+ctrl+G and then to select the whole line which has hit cmd+shift+Arrow and delete it. Assuming you have used only single line comments

Deleting entire function definition in Vim

I've been trying Vim for any text editing work for almost a week now. I want to know the fastest way to select a C function definition.
For example, if I have a function like this:
void helloworlds( int num )
{
int n;
for ( n = 0; n < num; ++n ) {
printf( "Hello World!\n" );
}
}
How would I be able to delete the whole definition including the function name?
As is common in Vim, there are a bunch of ways!
Note that the first two solutions depend on an absence of blank lines.
If your cursor is on the line with the function name, try d}. It will delete everything to the next block (i.e. your function body).
Within the function body itself, dap will delete the 'paragraph'.
You can delete a curly brace block with da}. (If you like this syntax, I recommend Tim Pope's fantastic surround.vim, which adds more features with a similar feel).
You could also try using regular expressions to delete until the next far left-indented closing curly brace: d/^}Enter
]] and [[ move to the next/previous first-column curly brace (equivalent to using / and ? with that regex I mentioned above. Combine with the d motion, and you acheive the same effect. In addons like Python-mode, these operators are redefined to mean exactly what you're looking for: move from function to function.
How to delete the whole block, header included
If you're on the header/name, or the line before the block, da} should do the trick.
If you're below a block, you can also make use of the handy 'offset' feature of a Vim search. d?^{?-1 will delete backwards to one line before the first occurrence of a first-column opening curly brace. This command's a bit tricky to type. Maybe you could make a <leader> shortcut out of it.
Plugins
I don't do much C programming in Vim, but there are surely plugins to help with such a thing. Try Vim Scripts or their mirror at GitHub.
To delete an entire function, including its definition, such as:
function tick() {
// ...
}
Move to the line with the function name.
Move the cursor to the opening brace, f{ should do it, or simply $.
Press V%d (Visual line, move to matching pair, delete)
If your functions look like this:
function tick()
{
// ...
}
Move to the line with the function name.
Press J (join the current line with line bellow. This also puts your cursor at the last character on the resulting line, {, just the one we need for the next command.)
Press V%d (Visual line, move to matching pair, delete.)
or
Move to the line with the function name.
Press V[Down]%d (Visual line, move one line down, move to matching pair, delete.)
If you are willing to install plugins vim-textobj-function will give you vif for Visual select Inside Function and vaf for Visual select A Function.
daf will delete the function, both the line with the signature and the function body ({})
The text object defined by this plugin are more specific and they don't rely on the function body being a contiguous block of text or { being placed at the first character on the line.
The drawback is that you depend on an external plugin.
You can use this shortcut to delete not only the function, also the lines between curly braces, i.e the code between if-else statements,while,for loops ,etc.
Press Shitf + v [Will get you in visual Mode] at the curly brace start/end.
Then Press ] + } i.e ] + Shitf ] - If you are in start brace.
Then Press [ + { i.e [ + Shitf [ - If you are in end brace.
Then DEL to delete the lines selected.
The simplest and most direct way way is as follows (works anywhere inside function):
v enter visual mode
{ move to first brace in function (may have to press more than once)
o exchange cursor from top to bottom of selection
} extend selection to bottom of function
d delete selected text
The complete command sequence would be v{o}d. Note that you can do other operations besides delete the same way. For example, to copy the function, use y (yank) instead of d.
Use this simple way
1.Go to the function definition
2.dd - delete function definition
3.d -start delete operation
4.shift+5(%) - delete the lines between { to }
If your function were separated by the blank lines, just type:
dip
which means "delete inner paragraph".
Another way is to go to the line of the start of your function and hit: Vj% (or V%% if your style puts the opening brace on the same line). This puts you into Visual-Line mode and the percent takes you to the matching closing brace. In the second style, the first % takes you to the opening brace on the line that you selected and the second to its matching closing brace.
Also works for parentheses, brackets, C-style multi-line comments and preprocessor directives.
See the manual for more info.
Pre-condition: be somewhere inside the function.
Go to the previous closing curly bracket on the first line using
[]
Then delete down to the next closing curly bracket on the first line using
d][
Most posted methods have a downside or two. Usually, when working withing a class definition of some object oriented language, you might not have an empty line after the function body, because many code formatters put the closing braces of last method and class on consecutive lines. Also, you might have annotations on top of the function. To make matters worse, there might be empty lines within your function body. Additionally you'd prefer a method that works with the cursor anywhere within the function, because having to move it to a specific line or worse, character, takes valuable time. Imagine something like
public class Test {
/* ... */
#Test
public void testStuff() {
// given
doSetup();
// when
doSomething();
// then
assertSomething();
}
}
In this scenario, vap won't do you any good, since it stops at the first empty line within your function. v{o} is out for the same reason. va{V is better but doesn't catch the annotation on top of the method. So what I would do in the most general case is va{o{. va{ selects the whole function body (caveat: if your cursor is within a nested block, for instance an inner if statement, then you'll only get that block), o puts the cursor to the beginning of the selection and { selects the whole paragraph prepending your selection. This means you'll get the function definition, all annotations and doc comments.
the most easy way I found is:
Get to the line where the function starts and do this: ^^vf{% to mark the entire function and then whatever you like.
^^ - start of the line
v - start visual mode
f - jump to the next search character
{ - this is the search character
% - jump to the closing brackets
This is also very logical after you have used it a few times.
non-visual way:
d/^}/e
... delete by searching for } at line beining, including it for deletion.
without /e (not mentioned in above answers), solution is incomplete.
with /e - searching goes to end of match, so closing bracket is included, and command is well for yanking too:
y/^}/e
if you use neovim version :>0.5
the modern way is to use treesitter and build your model, then you can be selected or yanked or deleted...
Tree-sitter is a parser generator tool and an incremental parsing library. It can build a concrete syntax tree for a source file and efficiently update the syntax tree as the source file is edited
I suggested this video on youtube to learn how to use treesitter to build your model : Let's create a Neovim plugin using Treesitter and Lua
I tried all the top answers here, but none of them works except the one by Nick which suggests to press f{ to get to the opening curly brace. Then V%d to delete the whole function.
Note that, the whole function gets yanked, so you can paste it elsewhere. I come across this use-case frequently, especially when moving if blocks inside another.
I use this map. It work for me
"delete function definition
"only support function body surround by {}
nnoremap <LEADER>df {v/{<cr>%d

What is the prefered style for single decision and action statements?

In the case of languages that support single decision and action without brackets, such as the following example:
if (var == true)
doSomething();
What is the preferred way of writing this? Should brackets always be used, or should their usage be left as a preference of the individual developer? Additionally, does this practice depend on the size of the code block, such as in the following example:
if (var == 1)
doSomething(1);
else if (var > 1 && var < 10)
doSomething(2);
else
{
validate(var);
doSomething(var);
}
There isn't really a right answer. This is what coding standards within the company are for. If you can keep it consistent across the whole company then it will be easy to read. I personally like
if ( a == b) {
doSomething();
}
else {
doSomething();
}
but this is a holy war.
I recommend
if(a==b)
{
doSomething();
}
because I find it far easier to do it up-front than to try to remember to add the braces when I add a second statement to to success condition...
if(a==b)
doSomething();
doSomethingElse();
is very different to
if(a==b)
{
doSomething();
doSomethingElse();
}
see Joel's article for further details
I tend to use braces at all times. You can get some subtle bugs where you started off with something like:
if(something)
DoOneThing();
else
DoItDifferently();
and then decide to add another operation to the else clause and forget to wrap it in braces:
if(something)
DoOneThing();
else
DoItDifferently();
AlwaysGetsCalled();
AlwaysGetsCalled() will always get called, and if you're sitting there at 3am wondering why your code is behaving all strange, something like that could elude you for quite some time. For this reason alone, I always use braces.
My preference is to be consistent, e.g., if you use brackets on one block, use brackets all throughout even with just one statement:
if (cond1)
{
SomeOperation();
Another();
}
elseif (cond2)
{
DoSomething();
}
else
{
DoNothing();
DoAnother();
}
But if you have just a bunch of one liners:
if (cond1)
DoFirst();
elseif (cond2)
DoSecond();
else
DoElse();
Looks cleaner (if you don't mind the dummy method names ;) that way, but that's just me.
This also applies to loop constructs and the like:
foreach (var s as Something)
if (s == someCondition)
yield return SomeMethod(s);
You should also consider that this is a convention that might be more suited to .NET (notice that Java peepz like to have their first curly brace in the same line as the if).
Chalk this one to lack of experience, but during my seven-year stint as a code monkey I've never actually seen anyone make the mistake of not adding braces when adding code to a block that doesn't have braces. That's precisely zero times.
And before the wisecrackers get to it, no, the reason wasn't "everyone always uses braces".
So, an honest question -- I really would like to get actual replies instead of just downvotes: does that ever actually happen?
(Edit: I've heard enough outsourcing horror stories to clarify a bit: does it ever actually happen to competent programmers?)
It doesn't really matter, as long as you're consistent with it.
There does seem to be a tendency to demand sameness within a single statement, i.e. if there's brackets in one branch, there's brackets everywhere. The Linux kernel coding standards, for one, mandate that.
I would strongly advocate always using braces, even when they're optional. Why? Take this chunk of C++ code:
if (var == 1)
doSomething();
doSomethingElse();
Now, someone comes along who isn't really paying enough attention and decides that something extra needs to happen if (var == 1), so they do this:
if (var == 1)
doSomething();
doSomethingExtra();
doSomethingElse();
It's all still beautifully indented but it won't do what was intended.
By always using braces, you're more likely to avoid this sort of bug.
I personnally side with McConnell's explanation from Code Complete.
Use them whenever you can. They enhance your code's readability and remove the few and scarce confusions that might occur.
There is one thing that's more important though....Consistency. Which ever style you use,make sure you always do it the same way.
Start writing stuff like:
If A == true
FunctA();
If B == "Test"
{
FunctB();
}
You are bound to end up looking for an odd bug where the compiler won't understand what you were trying to do and that will be hard to find.
Basically find the one you are comfortable writing everytime and stick to it. I do believe in using the block delimeters('{', '}') as much as possible is the way to go.
I don't want to start a question inside another, but there is something related to this that I want to mention to get your mental juices going. One the decision of using the brackets has been made. Where do you put the opening bracket? On the same line as the statement or underneath. Indented brackets or not?
If A == false {
//calls and whatnot
}
//or
If B == "BlaBla"
{
//calls and whatnot
}
//or
If C == B
{
//calls and whatnot
}
Please don't answer to this since this would be a new question. If I see an interest in this I will open a new question your input.
I've always used brackets at all times except for the case where I'm checking a variable for NULL before freeing it, like is necessary in C
In that case, I make sure it's clear that it's a single statement by keeping everything on one line, like this:
if (aString) free(aString);
There is no right or wrong way to write the above statement. There are plenty of accepted coding styles. However, for me, I prefer keeping the coding style consist throughout the entire project. ie. If the project is using K&R style, you should use K&R.
Ruby nicely obviates one issue in the discussion. The standard for a one-liner is:
do_something if (a == b)
and for a multi-line:
if (a == b)
do_something
do_something_else
end
This allows concise one-line statements, but it forces you to reorganize the statement if you go from single- to multi-line.
This is not (yet) available in Java, nor in many other languages, AFAIK.
As others have mentioned, doing an if statement in two lines without braces can lead to confusion:
if (a == b)
DoSomething();
DoSomethingElse(); <-- outside if statement
so I place it on a single line if I can do so without hurting readability:
if (a == b) DoSomething();
and at all other times I use braces.
Ternary operators are a little different. Most of the time I do them on one line:
var c = (a == b) ? DoSomething() : DoSomethingElse();
but sometimes the statements have nested function calls, or lambda expressions which
make a one-line statement difficult to parse visually, so I prefer something like this:
var c = (a == b)
? AReallyReallyLongFunctionName()
: AnotherReallyReallyLongFunctionOrStatement();
Still more concise than an if/else block but easy to see what's going on.
Sun's Code Conventions for the Java programming Language has this to say:
The if-else class of statements should
have the following form:
if (condition) {
statements;
}
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
Our boss makes us put { } after a decision statement no matter what, even if it's a single statement. It's really annoying to add two extra lines. The only exception is ternary operators.
I guess it's a good thing I have my code monitor in portrait orientation at 1200x1600.
I prefer
if (cond)
{
//statement
}
even with only a single statement. If you were going to write something once, had no doubts that it worked, and never planned on another coder ever looking at that code, go ahead and use whatever format you want. But, what does the extra bracketing really cost you? Less time in the course of a year than it takes to type up this post.
Yes, I like to indent my brackets to the level of the block, too.
Python is nice in that the indentation defines the block. The question is moot in a language like that.
I tend to agree with Joel Spolsky on that one with that article (Making Wrong Code Look Wrong) with the following code example :
if (i != 0)
bar(i);
foo(i);
Foo is now unconditionnal. Wich is real bad!
I always use brackets for decision statements. It helps code maintainability and it makes the code less bug prone.
I use curly braces around every statement if and only if at least one of them requires it.
In Perl if you are doing a simple test, sometime you will write it in this form:
do_something if condition;
do_something unless condition;
Which can be really useful to check the arguments at the start of a subroutine.
sub test{
my($self,#args) = #_;
return undef unless defined $self;
# rest of code goes here
}
The golden rule is that, when working in an existing project, follow those coding standards.
When I'm at home, I have two forms.
The first is the single line:
if (condition) doThis();
and the second is for multiple lines:
if (condition) {
doThis();
}
I used to follow the "use curly braces always" line like an apparatchik. However, I've modified my style to allow for omitting them on single line conditional expressions:
if(!ok)return;
For any multistatement scenario though I'm still of the opinion that braces should be mandatory:
if(!ok){
do();
that();
thing();
}