Trim text / delete trailing spaces from clipboard with AHK - regex

I'm struggling with the following thing. I have a simple script, that points to a word with mouse, clicks on it, does copy (ctrl+c), then does paste (ctrl+v).
Now, when a copy is done, I need to trim the text in the buffer/clipboard, meaning delete either beginning space (if any) or ending space (if any) - or both. Here's the code I have so far (I list only relevant part):
MouseMove, 439, 219
Click 2
Send ^c
ClipWait
clipboard := RegexReplace(clipboard, "^\s+|\s+$")
clipboard := Trim(clipboard," \`t\`r\`n")
clipboard := LTrim(clipboard, OmitChars = " \`t\`r\`n")
clipboard := RTrim(clipboard, OmitChars = " \`t\`r\`n")
StringReplace, clipboard, clipboard, \`t\`r\`n, , All
StringReplace, clipboard, clipboard, %A_Space%, , All
Send ^v
As you can see I used all the possible options I could find, and STILL the space does not get removed. But also, the strange thing is sometimes the space is removed, but in around 40% of cases it's not. But in any case, I simply need to a solution that would trim/remove spaces in all cases (every single time).
Any ideas, suggestions?

Your code seems to work for me. This leads be to believe it has something to do with the timing of your clipboard contents. The likely culprit of your problem is your usage of ClipWait. The most reliable way to use it is to clear out your clipboard first, then copy, then use ClipWait with a timeout value. Here is some example usage.
clipboard := "" ; Clear clipboard
Send ^c
ClipWait, 10 ; Waits 10 seconds for clipboard to contain something
Msgbox % clipboard

Related

Execute current Rmarkdown chunk and move to next one in RStudio

RStudio has a native feature (and keyboard shortcut) to run the next chunk in Rmarkdown and move the cursor to it (Ctrl + Alt + N). I'd like to be able to run the current chunk and move the cursor to the next one. I just want to run each chunk successively, without skipping the first one, and by seeing what I'm about to run. Is there a way to do that? Do I have to write an addin?
This is a late answer. but still useful for someone looking for it.
Start with ctrl + alt + c and then keep hitting ctrl + alt + n. It will do what you are trying to do
The behaviour of the existing Execute Next Chunk command has bothered me for quite some time.
One workaround that executes the current chunk and then moves to the beginning of the next chunk uses the shrtcts package, which lets you assign Keyboard Shortcuts to arbitrary R Code, in combination with the rstudioapi package:
Use the command shrtcts::edit_shortcuts() in the RStudio Console to open the file where you define your custom shortcuts.
Paste the following code inside that file (set your preferred keybinding in the #shortcut line):
#' Run Current Chunk and Advance
#'
#' #description Run Current RMarkdown Chunk and Advance to Next Chunk
#' #interactive
#' #shortcut Ctrl+Shift+Enter
function() {
rstudioapi::executeCommand(commandId = "executeCurrentChunk")
rstudioapi::executeCommand(commandId = "goToNextChunk") |>
capture.output() |>
invisible()
}
This solution uses the native pipe |> and thus requires R 4.1.
You can of course just define separate variables in each line or use the magrittr pipe if you use earlier versions of R.
Use the command shrtcts::add_rstudio_shortcuts(set_keyboard_shortcuts = TRUE) in the RStudio Console to add the new shortcut with its assigned keybinding. Then restart RStudio.
One potential downside of this approach is that you cannot press e.g. Ctrl+Shift+Enter multiple times in advance even though the first chunks are still running since the line
rstudioapi::executeCommand(commandId = "goToNextChunk")
gets executed only after
rstudioapi::executeCommand(commandId = "executeCurrentChunk")
has finished.

Autohotkey increase/decrease last number in selected text

I'm trying to make a useful system to automatically increase numbers in selected text. For example, when I working in Zbrush on the project named "Example_character012" I have a folder with 23 files from "Example_character012_prj_01.zpr" to "Example_character012_prj_23.zpr". When I need to save next iteration I'm pressing "ctrl+s" and then regular saving screen opens in the last working directory with preselected filename text, in this scenario it would be "Example_character012_prj_23.zpr". I need to copy this text, select the last number(23) increase it by one, and past it all the text back to the text-field. In this case it would be "Example_character012_prj_24.zpr".
This kind of script would be really useful in all kinds of scenario, mainly with saving in different programs.
I tried to made it myself and come up with this:
^!Numpad1::
Sleep 100
Send ^c
Sleep 10
RegExMatch(clipboard,"(\d+)(?!.*\d)",Number)
NewNumber:=Number1+1
OldNumber:=NewNumber-1
Clipboard:=RegExReplace(clipboard, OldNumber, NewNumber)
Sleep 10
Send ^v
Sleep 10
Send +{Home}
Return
^!Numpad0::
Sleep 100
Send ^c
Sleep 10
RegExMatch(clipboard,"(\d+)(?!.*\d)",Number)
NewNumber:=Number1-1
OldNumber:=NewNumber+1
Clipboard:=RegExReplace(clipboard, OldNumber, NewNumber)
Sleep 10
Send ^v
Sleep 10
Send +{Home}
Return
Ctrl+alt+Num1 for increase and Ctrl+alt+Num0 for decrease.
It's work fine with in the simplest scenario, but have significant problems I can't solve myself:
It only works in english keyboard-layout. When I use it in russian layout - it puts "cv" instead of pasting(If I paste manually afterwards it put the correct text)
Sometimes it increases not only the last number "Example_character012_prj_01.zpr" changing to "Example_character022_prj_02.zpr" instead of "Example_character012_prj_02.zpr"
Zeros working incorrectly "Example_prj_09.zpr" changing to "Example_prj_010.zpr" instead of "Example_prj_10.zpr"
After pasting it selects the whole line instead of only what just have been pasted
If it's possible, it would be great to make it work without affecting clipboard at all.
Sometimes some keys like "ctrl" just get stuck until being clicked manually for some reason.
Edit:
Got some help at Autohotkey forums, current version of script below. Only questions 4 and 5 left.
^!Numpad1::
^!Numpad0::
Sleep 50
Send {Ctrl up}^{Ins}
Sleep 10
RegExMatch(Clipboard, "^(.*)(?=_)_(\d+)(\....)$", Match)
Len := StrLen(Match2)
if InStr(A_ThisHotkey, 1)
Match2++
else
Match2--
if (StrLen(Match2) < Len)
Match2 := Format("{:0" Len "}", Match2)
Clipboard := Match1 "_" Match2 Match3
Sleep 10
Send +{Ins}
Sleep 10
Send +{Home}
Return
The reason your CTRL key is misbehaving is maybe because:
If you have a hotkey like
^F12::
Send {a}
What actually happens when you hit CTRL+F12 is that AHK releases CTRL, sends a, then re-hits CTRL.
This can get more complicated, eg in your scenario.
Try prefixing your Send commands with {Blind} eg Send {Blind}^v to suppress this behavior.
This may or may not work (ie if the hotkey is shift+ctrl+something but the hotkey sends ctrl+v, then what would actually get sent is ctrl+shift+v) but if it does still work, it may make CTRL start behaving itself more.

NCURSES: creating a title bar without loops

I wanted to create a program where I can stop, start and monitor processes and their outputs, notifications, errors, etc. Probably has been done but I haven't found it.
This my first ncurses program and I'm having a styling issue. I'm reading in an XML file which contains all the initial layout information. This breaks up the terminal into a few sections. Each section I wanted to have a title bar. This would simply be A_REVERSE, or a specified fg/bg color pair.
I hadn't discovered the wattr_on() wattr_off() functions til a minute ago. That's a step in the right direction. But I make a call to wborder() and I'm getting characters where I want none. Specifically:
wborder(pwin, '\0', '\0', ' ', '\0', ' ', ' ', '\0', '\0');
I wanted the NULLs to be no character, not the default. I was trying to do this without loops. Is it possible?
Answer
mvwhline(pwin,0,0,' ',xmax);
wprintw(pwin,"%s",sztitle);
mvwchgat(pwin,0,0,-1,A_REVERSE,0,0);
window borders are window borders, not a headline. If you only want that, it's probably best to just use mvwchgat() to make the headline stand out.

cursor blinking removal in terminal, how to?

I use the following lines to output my simulation's progress info in my c++ program,
double N=0;
double percent=0;
double total = 1000000;
for (int i; i<total; ++i)
{
percent = 100*i/total;
printf("\r[%6.4f%%]",percent);
}
It works fine!
But the problem is I see the terminal cursor keeps blinking cyclically through the numbers, this is very annoying, anyone knows how to get rid of this?
I've seen some programs like wget or ubuntu apt, they use progress bar or percentages too, but they seems no blinking cursor issue, I am wondering how did they do that?
Thanks!
You can hide and show the cursor using the DECTCEM (DEC text cursor enable mode) mode in DECSM and DECRM:
fputs("\e[?25l", stdout); /* hide the cursor */
fputs("\e[?25h", stdout); /* show the cursor */
Just a guess: try to use a proper number of '\b' (backspace) characters instead of '\r'.
== EDIT ==
I'm not a Linux shell wizard, but this may work:
system("setterm -cursor off");
// ...display percentages...
system("setterm -cursor on");
Don't forget to #include <cstdlib> or <iostream>.
One way to avoid a blinking cursor is (as suggested) to hide the cursor temporarily.
However, that is only part of the solution. Your program should also take this into account:
after hiding the cursor and modifying the screen, before showing the cursor again move it back to the original location.
hiding/showing the cursor only keeps the cursor from noticeably blinking when your updates take only a small amount of time. If you happened to mix this with some time-consuming process, your cursor will blink.
The suggested solution using setterm is not portable; it is specific to the Linux console. And running an executable using system is not really necessary. But even running
system("tput civis");
...
system("tput cnorm");
is an improvement over using setterm.
Checking the source-code for wget doesn't find any cursor-hiding escape sequences. What you're seeing with its progress bar is that it leaves the cursor in roughly the same place whenever it does something time-consuming. The output to the terminal takes so little time that you do not notice the momentary rewrite of the line (by printing a carriage return, then writing most of the line over again). If it were slower, then hiding the cursor would help — up to a point.
By the way — this cursor-hiding technique is used in the terminal drivers for some editors (vim and vile).
Those apps are probably using ncurses. See mvaddstr
The reason the cursor jumps around is because stdout is buffered, so you don't know actually how many characters are being printed at some point in time. The reason wget does not have a jumping cursor is that they are actually printing to stderr instead, which is unbuffered. Try the following:
fprintf(stderr, "\r[%6.4f%%]", percent);
This also has the advantage of not cluttering the file if you are saving the rest of the output somewhere using a pipe like:
$ ./executable > log.data
Press insert key...if that doesn't work then press the fn key in your keyboard.
This will definitely work
Hope this helps

Undo a newline (\n) printed to command line

printf("Error %d\n", 1);
printf("\nStatus: %d%%", 50);
prints
Error 1
Status: 50%
In this set up, is there any chance to insert Error 2\n between Error 1\n and \nStatus: 50%. I understand that \r and \b can be used to change printed text in the same line (e.g., if there is a single \n between Error 1 and Status: 50%), but can I change text in a previous line?
Thanks!
What #Ryan said.
Explanation why: stdout is some abstract stream that doesn't have to be the terminal. It may be a file, a pipe, a socket, a printer, a text to speech device or whatever. In many cases there is no sense to what you asked to do. Hence you need some library that works with the terminal specifically.
Sorry, you cannot.
But you may issue system calls to clear the whole screen instead, like system("clear") (OS-dependent).
Or use ncurses just as Kos mentioned in the comment.
You could use ANSI Escapesequences to move your "cursor" one line up:
void cursorOnLineUp(void) { printf("\033[1A"); }
Or set it to a specific position:
void setCursor(int column, int row) { printf("\033[%d;%dH", row, column) }
Haven't tried it for C++, but succesfully used it for a simple game in ANSI-C!