Operation:
This is the subroutine code only, you will have to assign this to a hotkey (I use Capslock + Q). Currently optimized for Firefox to Python, see notes for more info. After running the subroutine, the modified text will be stored back into the clipboard so you can Ctrl-V it where you want it to go.
Notes:
- I am working in Python so my comment character is #. This character is stored in the CommentChar variable under Definitions.
- I am copying from Firefox, and had an issue where it sometimes lost focus before copying, so I made the script select a Firefox window first. Feel free to change the class of window you want to activate, or delete this.
- The "soft line limit" is 75 characters by default, the script then waits for a space to start your new line. So if you reach your limit in the middle of a very long word, that word will stick out from the rest of your comments. I wasn't sure how to make this better without making a look-ahead feature, which I decided was outside the scope of the project.
- I would love any suggestions etc.
Code: Select all
; ----------------------------------------------------
; Convert clipboard to code comments function
; ----------------------------------------------------
ConvertToComments:
Clipboard = ;
; Robust get clipboard
Loop
{
WinActivate, ahk_class MozillaWindowClass ; Set to make sure the last Firefox window is active; if you want
Send, ^c ; to use a different class of window or take this out, feel free.
ClipWait, .5
If Clipboard != ""
Break
}
ClipSaved := Clipboard
; Definitions
NextLineFlag := "" . 0
LineChars := 75 ; Set line length flag; script waits for end of word to change line.
IndexCtr := "" . 0
CarriageReturn := "`n"
CommentChar := "#" ; Set language comment character here
Newline := " " . CarriageReturn . CommentChar . " "
ClipNew := CommentChar . " " ; Begin new text with comment and two spaces
; Begin loop
Loop, parse, ClipSaved , ,
{
If ("" . A_LoopField) = CarriageReturn ; If <enter> in clipboard, create a new line
{
ClipNew .= A_LoopField . CommentChar . " "
IndexCtr := 0
Continue
}
IndexCtr += 1 ; Increment counter for line length check
If (IndexCtr = LineChars) ; Set flag if line limit reached
{
NextLineFlag := 1
}
If (NextLineFlag = 1) ; Check for space before breaking line
{
If ("" . A_LoopField) = A_Space ; If space, create new line
{
ClipNew .= Newline . A_LoopField
NextLineFlag := "" . 0
IndexCtr := 0
Continue
}
Else
{
ClipNew .= A_LoopField ; If no space, continue word
PrevLoopField .= A_LoopField ; Store prev character for space detection
Continue
}
}
Else
{
ClipNew .= A_LoopField ; Normal write
Continue
}
}
Clipboard := ClipNew ; Dump to clipboard
ClipWait, 1
Return
Return