Hi!
Let’s imagine I have a buffer with the one and only line: 1+1.
Now if I select the entire buffer with % and execute the following command from Kakoune command prompt: echo $sh{echo $kak_selection | bc} the result will be 2, which is what I’m expecting.
But if I select the entire buffer with % and press |bc<ret> keys the 1+1 line is replaced with empty string, meaning, that there is no output from bc command.
Why this happens?
The echo shell command sends its argument to stdout, followed by a newline.
$ echo 1+1 | hexdump -C
00000000 31 2b 31 0a |1+1.|
00000004
$ echo 1+1 | bc
2
If you just select 1+1 and pipe it to bc, that doesn’t include the trailing newline.
$ printf 1+1 | hexdump -C
00000000 31 2b 31 |1+1|
00000003
$ printf 1+1 | bc
(standard_in) 1: syntax error
For whatever reason, bc really really wants a newline at the end of the expression, it does not recognise “end of file” as a valid terminator, much to the frustration of Kakoune users everywhere.
For my kakoune-inc-dec plugin, I eventually switched from using bc to using shell arithmetic just because it required less messing around with newlines.
I cannot reproduce this behaviour. Kakoune requires every buffer to have a least one line, and every line to have a terminating newline, so there will always be a newline at the end of the buffer, and so % should select the newline along with the expression, and bc should correctly evaluate it.
2 Likes
Thanks a lot for explanations! I was never aware of this newline bc requirement. Yes, including newline in selection makes piping to bc work correctly.
And additional thanks for the example with echo and printf: now I understand the difference much better.
Kakoune requires every buffer to have a least one line, and every line to have a terminating newline, so there will always be a newline at the end of the buffer, and so % should select the newline along with the expression, and bc should correctly evaluate it.
You are right: piping to bc does not work if there is no newline in selection. And if the one-line file is selected using % - there is always a new line. So, my initial example was misleading.
Some time ago, @Screwtapello helped me with this same issue.
So I updated the example in the Kakoune Wiki:
2 Likes