Terminal, Editor, Project - j

I want to write a piece of code, a loop.
So I start:
for_i. i.10 do.
Press "Enter" in order to write a new line, get an error:
|spelling error
| for_i. i.10 do.
| ^
So I go to the Editor (one with green code area, Terminal has yellow color).
Write these code, press "run".
But Editor runs code in the Terminal as well. And yes, I get the same error.
I start new project in Editor. Write the code. Press "run project". And??? Nothing. No errors, no results, no anything.
I know that I can wrap this code into function, like
f =: 3 : 0
for_i. i.10 do.
....
)
And it will work.
But why doesn't it work in straightforward way?
Why doesn't it work even in editor?
How to make a code in projects run? And where should I see results?

Think of editor as an area of definition. By assigning definitions to variables using =: (necessary because =. only establishes assignment local to the editor) running the editor script establishes those definitions in your terminal, where you can actually run them.
If you actually want to run a verb from the editor, write the verb with its arguments in the editor and then the verb will be executed and produce results. After all, that is what it is doing with the assignments, but in that case the execution produces the assigned definitions.
Try this in your editor and see if it makes more sense when you run it.
a=: 3 : 0 NB. establishes definition of a. This needs to be defined first
+/y
)
a 2 3 4 5 NB. runs a in Terminal from editor

J's control structures only work in an explicit definition (which is what bob was getting at).
If you want to use them on a single line, you'll need a complete enclosing explicit definition on that line. And if you want results from that line you will also need to provide that definition with an argument to work on.
For example:
verb def 'for_i. i.10 do. echo i end.' 0

Related

modifying previously executed commands on linux

I want to modify a previously run command with slightly different arguments. Is there a quick way of reaching the argument which is somewhere between in the big command, instead of going to that place from beginning (or end) of the command?
Currently I wrap the big command into some small command and pass the argument to the wrapper command.
Was wondering if there was any other way.
You can press ↑ to bring the last line;
Then you can jump over the arguments with Alt+F and Alt+B.
(if you're on Mac it's Esc+F and Esc+B)
You may also type !:1 to refer to the first argument in the previous entry, or !:2 to refer to the second argument, and so on.

vim: Run multiple commands based off of one :global command

Apologies if this has been posted already, for I cannot find an answer, even on the vim wiki.
Is there a way I can run multiple commands in vim command-line mode off of a single :g search?
For example,
:%g/foo/ s/bar/\=#a/g | exe "norm /cat\<enter>\"ayiw"
Which (for what I intend it to do) should, on every line matching foo, replace bar with the contents of register a, and then find the next iteration of cat (even if it is many lines ahead), and put the surrounding word into register a.
Instead, this specific syntax completes the subsitution command using the current contents of the initial a register, and then executes the normal mode command on a single line (after the substitution has been completed).
This example is not my specific use-case but shows one instance where this functionality is useful. I realize I could put it all into a single exe, i.e., %g/foo/exe "norm :s/bar/\\=#a/g\<enter>/cat\<enter>\"ayiw", but I would like to do it the first way, as I feel it is more flexible.
I would prefer to do this using vanilla vim, but if a plugin exists for this, that is an okay alternative. Does anybody know if there is syntax to do such a thing?
Okay a "little bit" dirty, but does this work for you?
:let list = split(execute('g/cat/p'), '\n') | g/foo/ s/bar/\=matchstr(remove(list, 0), '\s\d\+\s\zs.*')/g
It first reads all occurences of cat save them in a list.
Then replace the first bar with the first cat... and so on.
The dirty part ist the matchstr command. the g//p also returns a number for the result so the list looks like this:
1 cat
2 cat
3 cat
...
that's why we have to remove a bit from the front. I would love to hear if someone knows a clean solution for that (I am also interested in a clean vimscript solution, does not have to be a oneliner).
You can do this (at least for multiple :s commands applied to a single :g). Example:
" SHORT STORY TITLES to single word of CapitalizedWords within <h3>s
.,$g/^\L\+$/s/[^A-Z0-9 ]\+//ge|s/\u\+/\L&/ge|s/\<\l\+\>/\u&/ge|s/ \+//ge|s/.*/<h3>&<\/h3>/

How to provide parameter in vim macro

Is it possible to provide some parameter when recording a macro in vim via prompt or some other ways?
Edit:
I have such code:
foo
bar
And I would like to surround each with ruby block:
expect do
foo
end.to raise_error(CustomClass)
expect do
foo
end.to raise_error(OtherCustomClass)
So, it is easy to create a macro that will result with:
expect do
foo
end.to raise_error()
expect do
foo
end.to raise_error()
But it will be nice to have prompt that will be used to set raise_error method parameter. In each use of macro this parameter will be different.
While I agree with everyone else that if you need this feature, you're probably going about things inefficiently, it is possible to insert a variable text string into a document as part of a macro. The trick is to store the text you want to use in your macro in a register.
yank some text into a named register, for example "xyw to yank a word into the x register
record your macro, qq, when you want to place the variable text, put it, for example "xp to put the text in the x register into the document where the cursor is
now, when you play your q macro, #q, it will use whatever is currently in the x register, so you can yank different text into the x register, play your q macro, and the newly yanked text will be used.
If you are talking about recording a macro with qx...q, this is not possible.
However you could still do : :let #y = substitute(#x, 'old_pattern', 'replacement', 'g') and then use #y.
You could also define a function:
function Play(myArg)
execute 'normal sequence_of_characters' . a:myArg . 'other_sequence_of_characters'
endfunction
call Play('foo')
Very particularly in the OP's situation, where you really only have precisely two variable pieces of content, I find the easiest method to be a bastardisation of #mkomitee's approach above.
Instead of manually saving the two ‘parameters’ into registers before each usage of the macro, I prefer to type the “first parameter,” visual-select it, evaluate the macro, then type the “second parameter.” To achieve this, I start the macro with a deletion command (a simple d, assuming you're always going to invoke the macro in visual-mode, for instance); then finish it with a command that switches to insert mode (like c or i), and finally, while still in insert mode, a Ctrl-O q to cause the macro to also leave Vim in insert mode when it's done.
As a slightly simple example, if the two “parameters” are single words, here's the keystrokes to create (and then invoke) a macro to manipulate widget.snog() to a parameterised widgetFoo.fooSnog(bar):
foob qq "zdw — we're now recording to the q register, with the first ‘argument’ in z
‸
"aP — prefix-paste from a fixed register used elsewhere in the document
widget.snog()‸
^ea␣Ctrl-rEscb~hx — paste the first arg, and capitalize
widget‸Foo.snog()
2w~b"zP — capitalize existing word, then paste the first arg again
widgetFoo.fo‸oSnog()
$Ctrl-Oq — move to the last position, enter insert-mode, and end the macro
widgetFoo.fooSnog(‸)
After finishing the first instance with bar, we can now use it several times:
obazEscb — set up our first ‘argument’,
widgetFoo.fooSnog(bar)
‸baz
#qquuxEsc — invoke the macro, and finish with the second one
widgetFoo.fooSnog(bar)
widgetBaz.bazSnog(quux‸)
ocorgeEscb##graultEsc — repeat a third time
widgetFoo.fooSnog(bar)
widgetBaz.bazSnog(quux)
widgetCorge.corgeSnog(grault‸)
ogarplyEscb##waldoEsc — … and so on
widgetFoo.fooSnog(bar)
widgetBaz.bazSnog(quux)
widgetCorge.corgeSnog(grault)
widgetGarply.garplySnog(waldo‸)
Of course, it looks laborious, typed out in such a long fashion — but it's surprisingly few key-strokes in practice, and very easy to train into your fingers.
tl;dr: type the first argument; enter macro-recording before deleting it into a register; manipulate your text as desired; then leave vim in insert-mode at the position of the second argument with Ctrl-Oq.
If you need to generate a code, which is the case, the best way for this is to use vim snippets. You can configure snippet to put cursor where you need when you [tab].

Could vim automate the refactoring of this snippet? is that what macros are for?

I have blocks of code that look like:
ICar car = new Car<int>(10);
var result = car.Start(100);
Assert.IsTrue(result.IsValid);
That I want to convert to this:
Assert.IsTrue((new Car<int>(10).Start(100)).IsValid);
I have about 20 of these types of snippets with the exact same format, could this be automated in vim?
Crash course in macros:
Go to ICar in normal mode.
Press qq to start the macro.
Modify the code. Try using word-based movements instead of left/right arrows.
Go to the next snippet, like with /ICar.
Press q again in normal mode to stop recording.
You can then type #q to execute the q macro and reformat one snippet. If it works as expected then type 20#q to execute 20 times.
:%s:^.* = \([^;]\+\);\_.[^.]\+\([^;]\+\);\n\n\+\([^(]\+\)(.*\.\(.*$\):\3((\1\2).\4
Will do it with the exact same format (placement of .s and =, etc are important in the original pattern.
HTH
Macros are the easiest, but another way to do it is with global commands - :g/regular expression/Ex command. For example(not your example - we will get to it later), you can use :g/^\s*ICar/delete will delete all lines starting with ICar(^ is for start of line, \s* is for skipping the tabs and spaces used for indention).
The advantage of this method over macros is that you can use it on a range: go into visual mode, mark the part you want to refactor, and use the global command. Only matches in the marked block will be affected. If you use macros, you need to either press ## over and over again until you clear the block, count the exact number of times you want the macro to run, or set a high number and make the no-match error stop the macro. While the third option is quite easy to execute, it's also quite dangerous - you need to make sure the pattern appears only in the parts you want to refactor - so it won't affects unrelated parts of the code - and that the refactoring removes it - otherwise the macro will run on the same lines over and over again.
The advantage of macros is that they are easier to record. In complex refactoring like yours, the global command you need to run can be very long and complex. A macro to do the same thing is just as long and complex as a global command - but you can see how it works while you record it - much easier than calculating the result in your head while designing the global command.
Luckily, you can enjoy both world!
First you record your macro like cdleonard explained in his answer, with two main differences.
The first one is that the first keystroke in the macro should be ^ or _ - to go to the first non-white-space character in the line(that means you start with qq_ and then record as usual). This will guarantee the macro starts from the right place in the line every time.
The second difference is that you don't need to go to the next snippet in the end of the macro. The global command will take care of that for you.
After you've recorded the macro(I'll assume you recorded it to q) mark all the snippets using visual mode, and type :g/^\s*ICar/norm #q - this will search the marked range for all lines that begin with ICar(possibly with indentation before them) and performs the macro on them. This is assuming everything in the range that begins with ICar - and only those places - are snippets you want to refactor. If you have lines that begin with ICar and you don't want to refactor, or if you have lines that you do want to apply the macro to, but they don't begin with ICar - you will have to modify the regex.

Why BASIC had numbered lines? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why did we bother with line numbers at all?
I'm curious about why early versions of the BASIC programming language had line numbering like in:
42 PRINT "Hello world!"
The text editors back then had no line numbering?
EDIT: Yes, I know they are used for GOTOs, but why? I mean having labels was too computationally expensive?
Many microcomputers had a BASIC interpreter in ROM that would start upon bootup. The problem was that there was no text editor or file system to speak of. You had an interactive prompt to do everything through. If you wanted to insert a line of code, you just typed it, starting with the line number. It would insert it into the correct spot in you code. e.g:
>10 print "hello"
>30 goto 10
>20 print "world"
>list
10 PRINT "hello"
20 PRINT "world"
30 GOTO 10
>
(In that example > is the BASIC prompt)
If you wanted to erase a line, you would type something like ERASE 20.
Some really fancy systems gave you a line editor (i.e. EDIT 10)
And if you didn't plan your line numbers and ran out (how do I insert a line between 10 and 11?) some systems gave you a RENUM command which would renumber your code (and adjust GOTOs and GOSUBs appropriately).
Fun Times!
The original BASIC line numbering was actually an integral part of the language, and used for control flow.
The GOTO and GOSUB commands would take the line, and use it for control flow. This was common then (even though it's discouraged now).
They were used as labels for GOTO and GOSUB
Like this:
10 PRINT "HELLO WORLD"
20 GOTO 10
There were no named labels in some early BASIC versions
They were also required if you wanted to insert a line between 2 existing lines of code, because in the early days, you had no full text editors. Everything had to be typed in the "interactive" interpreter.
So if you typed:
15 PRINT "AND THE UNIVERSE"
The program would become:
10 PRINT "HELLO WORLD"
15 PRINT "AND THE UNIVERSE"
20 GOTO 10
When you ran out of line numbers, you could run a "renumbering" tool to renumber all lines in your program, but in the very early days of the Commodore 64 and other home computers, we didn't even have that, so you'd have to renumber manually. That's why you had to leave gaps of 10 or more in the line numbers, so you could easily add lines in between.
If you want to try out the Commodore 64 interpreter, check out this C64 emulator written in Flash: http://codeazur.com.br/stuff/fc64_final/ (no install required)
In BASIC, the line numbers indicated sequence.
Also, many older editors weren't for files, but simply lines ("line editors", e.g. ed, the standard editor). By numbering them this way, you knew which line you were working on.
A simple google reveals what wikipedia has to say about it:
Line numbers were a required element of syntax in some older programming languages such as GW-BASIC.[2] The primary reason for this is that most operating systems at the time lacked interactive text editors; since the programmer's interface was usually limited to a line editor, line numbers provided a mechanism by which specific lines in the source code could be referenced for editing, and by which the programmer could insert a new line at a specific point. Line numbers also provided a convenient means of distinguishing between code to be entered into the program and commands to be executed immediately when entered by the user (which do not have line numbers).
Back in the day all languages had sequence numbers, everything was on punched cards.
There was one line per card.
Decks of cards made up your program.
When you dropped the cards, you'd put them in a card sorter that used those sequence numbers.
And of course, they were referenced by control flow constructs.
On the C64, there wasn't even a real editor (built-in at least). To edit a part of the program, you'd do something like LIST 100-200, and then you'd only be able to edit those lines that were currently displayed on the screen (no scrolling upwards!)
They were labels for statements, so that you could GOTO the line number. The number of the statements did not necessarily have to match the physical line numbers in the file.
The line numbers were used in control flow. There were no named subroutines. You had to use GOSUB 60, for instance, to call the subroutine starting at line 60.
On your update, not all languages had labels, but all languages had line numbers at one time. At one time, everything was punch cards. BASIC was one of the very first interactive languages, where you could actually type something and have a response immediately. Line numbers were still the current technology.
Labels are an extra expense. You have to keep track of the correlation between the symbolic label and the code or data to which it refers. But if every line has a line number (and if all transfer of control flow statements always refer to the beginning of a line), then you don't need a separate symbol table.
Also keep in mind that original BASIC interpreters didn't need a symbol table for variables: There were 26 variables named A-Z. Some were sophisticated and had An-Zn. Some got very fancy and added a distinction between string, integer and floating point by adding "$" or "%" after the variable. But no symbol table was required.
IIRC, line numbers were mostly used as labels for GOTO and GOSUB statements, since in some (most?) flavors of BASIC there was no way to label a section of code.
They were also used by the editor - ie you said:
edit 100
to edit line 100.
As others have pointed out, these line numbers were used as part of subroutines.
Of course, there's a reason that this isn't done anymore. Imagine if you say GOTO 20 on line 10, and then later realize you need to write 10 more lines of code after line 10. All of a sudden, you're smashing up against 20 so you either need to shift your subroutine farther away (higher numbers) and change your GOTO value, or you need to write another subroutine that jumps farther in the code.
In other words, it became a nightmare of true spaghetti code and is not fun to maintain.
It was entered in on the command-line in many instances (or was, on my old Commodore 64) so there might not always have been a text editor, or if there was, it was quite basic.
In addition, you would need to do GOTOs and the like, as well as inserting lines in between others.
ie:
10 PRINT "HELLO"
20 GOTO 10
15 PRINT " WORLD"
where it would go in the logical 10 15 20
Some editors only had an "overwrite" mode and no "insert" mode. This made editing of existing code extremely painful. By adding that line-number feature, you could however patch existing code from anywhere within the file:
100 PRINT "Broken Code"
200 PRINT "Foobar"
...
101 patch the broken code
102 patch more broken code
Because line numbers didn't have to be ordered within the file.
Line numbers were a PART of the language, in some VERY early ones, even the OS was just these simple lines. ALL you had was one line at a time to manipulate. Try writing an accounting system using 1-4k program files and segmenting it by size to get stuff done. To edit you used the line numbers to tell what you were editing. So, if you entered like:
10 PRINT "howdy"
20 GOTO 10
10 PRINT "WOOPS"
15 PRINT "MORE WOOPS"
20
RUN
YOU WOULD GET:
WOOPS
MORE WHOOPS
The blank 20 would effectivly delete that line.

Resources