Use commands onto the Manage Snippets plugin from Gedit - plugins

I have gedit and the Manage Snippets plugin and I would like to create a snippets to comment a line (it's easy, just add : "# $GEDIT_CURRENT_LINE", for python code for example) but, if the line is ever commented, I would like to uncomment it.
Is there a special syntax to use, I don't know, python or c++ statements like an if with a condition on $GEDIT_CURRENT_LINE ? Because any of code write on the snippets will be only print.

Ok, actually, I just find how a way to do it.
To use bash commands onto the manage snippets plugin, just use `.
For example, in my case, to know what is the first caracter on the line : `${GEDIT_CURRENT_LINE:0:1}` and, with the if statement :
``if [ ${GEDIT_CURRENT_LINE:0:1} == "#" ]; then echo ${GEDIT_CURRENT_LINE:2}; else GEDIT_CURRENT_LINE_STR=$GEDIT_CURRENT_LINE; echo "# $GEDIT_CURRENT_LINE_STR"; fi``
this snippets will comment the line or uncomment it if it is ever commented. (Just as Notepad++ do it).
Edit : you have to create a new variable with the line to rewrite it : GEDIT_CURRENT_LINE_STR=$GEDIT_CURRENT_LINE;. Without that new variable, the current line text can be interpreted as a command and then, just erase the line because of an error. (I updated the code above)
Edit2 : here a snippets to comment/uncomment all the selected lines with python (and not just on as before) :
$<
AllLines = $GEDIT_SELECTED_TEXT.split('\n')
if AllLines == ['']:
AllLines = $GEDIT_CURRENT_LINE.split('\n')
NewLines = []
for line in AllLines:
if line[0:2] == '# ':
NewLines += [line.replace('# ', '')]
elif line[0] == '#':
NewLines += [line.replace('#', '')]
elif line[0] != '#':
NewLines += ['# ' + line]
return '\n'.join(NewLines)
>

Related

Is it possible to have a snippet that considers the length of my input?

I would like to define a snippet for comments like
//************
//* foo A1 *
//************
where I enter foo A1 and it would create a line with (6+ len(${1}) asterisks etc. - is that doable and if so, how?
While I am a big proponent of HyperSnips (see
[VSCODE]: Is there a way to insert N times the same characters,
VS Code: how to make a python snippet that after string or expression hitting tab will transform it and
VSCode Advanced Custom Snippets for how to use it),
it is instructive to see how to do this with just the built-in snippet functionality in vscode. Here is a snippet that does what you want:
"Custom Comment": {
"prefix": ["cc2"], // whatever trigger you want, then tab, write your info and tab again
"body": [
"//***${1/./*/g}***",
"//* $1 *",
"//***${1/./*/g}***"
]
},
That just adds 3 asterisks to the beginning and 3 to the end of your added comment, each character of which is replaced by an asterisk as well.
You can use the extension HyperSnips
snippet comment "Comment" A
``rv = '//' + '*'.repeat(t[0].length + 6)``
//* $1 *
``rv = '//' + '*'.repeat(t[0].length + 6)``
endsnippet

VSCode: Extension: folding section based on first blank line found or to the start of the next similar section

How can I make a VSCode extension folding strategy based on the first blank line following a starting folding marker?
## Some section --|
Any text... | (this should fold)
...more text. --|
(blank line)
## Another section (next fold...)
I've tried lots of regex in the language-configuration.json.
"folding": {
"markers": {
"start": "^##",
"end": "^\\s*$"
} },
If I change things to test with something other than a blank (or whitespace) line as the end delimiter it works. Can't use the next start marker to mark the end of the last or it includes it in the fold (I tried look ahead regex, but I think the regex are applied line by line and the matches can't span lines?)
It's similar to the folding needed for Markdown which VSCode handles well (don't know if that's using a more complex method like https://code.visualstudio.com/api/references/vscode-api#FoldingRangeProvider).
Maybe something in the fixes for [folding] should not fold white space after function has something to do with it.
What I learned: 1. the begin and end regex are applied line by line. 2. tmLanguage start/end regex will work on blank lines, but currently language-configuration folding doesn't seem to work on blank lines.
And since blank lines are in this case a hack for ending at the next begin section:
To solve the problem of folding a section to the next similar section I used the FoldingRangeProvider.
disposable = vscode.languages.registerFoldingRangeProvider('myExt', {
provideFoldingRanges(document, context, token) {
//console.log('folding range invoked'); // comes here on every character edit
let sectionStart = 0, FR = [], re = /^## /; // regex to detect start of region
for (let i = 0; i < document.lineCount; i++) {
if (re.test(document.lineAt(i).text)) {
if (sectionStart > 0) {
FR.push(new vscode.FoldingRange(sectionStart, i - 1, vscode.FoldingRangeKind.Region));
}
sectionStart = i;
}
}
if (sectionStart > 0) { FR.push(new vscode.FoldingRange(sectionStart, document.lineCount - 1, vscode.FoldingRangeKind.Region)); }
return FR;
}
});
Set "editor.foldingStrategy": "auto". You can make it more sophisticated to preserve white space between sections.

Replace a middle string in .bat file using AutoHotKey without deleting file

I need to edit standalone.bat file using ahk script. I want to increase my heap size using ahk so below is line where i have to change heap in my bat file. Now i have trying to edit this using StringReplace and FileAppend but FileAppend keeps on appending string to the end
from
set "JAVA_OPTS=-Dprogram.name=%PROGNAME% -Xms64M -Xmx1426M %JAVA_OPTS%"
to
set "JAVA_OPTS=-Dprogram.name=%PROGNAME% -Xms64M -Xmx1426M %JAVA_OPTS%"xms000M
I am new to .ahk, i have tried this using some search
Loop, read, C:\standalone.bat
{
Line = %A_LoopReadLine%
replaceto = xms000M
IfInString, Line, Xmx1426M
, Line, replaceto, %Line%, %replaceto%
FileAppend, %replaceto%`n
StringReplace FileAppend
}
Is it possible to replace middle string using ahk. thanks
Fileappend will always append to the end of a file. Why do you want to prevent a temporary deletion of your batch file?
Typically, in ahk, you'd do it like this..
batFile = C:\standalone.bat
output := ""
Loop, read, %batFile%
{
Line = %A_LoopReadLine%
IfInString, Line, Xmx1426M
{
StringReplace, Line, Line, Xmx1426M, xms000M
; note: Regular Expressions can be used like Line := regExReplace(Line, "...", "...")
}
output .= Line . "`n" ; note: this is the same as if to say output = %output%%Line%`n or output := output . line "`n"
}
FileDelete, %batFile%
FileAppend, %output%, %batFile%
This will delete your file for some little milliseconds, just to recreate it with the new content afterwards. I don't really see any difference to editing it without deletion, because in either way, you'll need write access to the file.
Some words about your code sample:
IfInString, Line, Xmx1426M
, Line, replaceto, %Line%, %replaceto%
will be interpreted as
"If the string 'Line' contains 'Xmx1426M , Line, replaceto, %Line%, %replaceto%'"
which does not make any greater sense.
FileAppend, %replaceto%\n is lacking a destination file.
StringReplace FileAppend: these are two commands without any further parameters. You must never put two non-function-commands in the same line!

perl script for find and replace or insert if blank

I am trying to write a perl script to search a config file for the following line:
remote_phonebook.data.1.url =
and do 1 of 2 things:
if the right of side of the = is blank add someString
if there is something there, replace anything there with someString
This will insert just fine:
s/remote_phonebook\.data\.1\.url = /remote_phonebook.data.1.url = someString/;
however if someString already exists, it will append it to look like this:
remote_phonebook.data.1.url = someString someString
This will replace just fine if someString already exists, but wont insert if its blank.
s/remote_phonebook\.data\.1\.url = someString/remote_phonebook.data.1.url = someString/;
.* is your friend, here. It means "match 0 or more (*) of any character (.)":
s/remote_phonebook\.data\.1\.url =.*/remote_phonebook.data.1.url = someString/;
So whether or not there is anything after the =, you'll end up with the contents you want. To make sure that you're matching from the start of the line (so "xxxremote_phonebook..." won't match), and to allow for more (or less) space before the "=", I'd use:
s/^remote_phonebook\.data\.1\.url\s*=.*/remote_phonebook.data.1.url = someString/;
s/^\s*remote_phonebook\.data\.1\.url\s*=\K.*/someString/;
The .* will match anything up to a newline.
The \K makes it so you don't have to repeat everything.

Insert double quotes multiple times into string

I have inherited a flat html file with a few hundred lines similar to this:
<blink>
<td class="pagetxt bordercolor="#666666 width="203 colspan="3 height="20>
</blink>
So far I have not been able to work out a sed way of inserting the closing double quotes for each element. Probably needs something other than sed to do this. Can anyone suggest an easy way to do this?
Thanks
sed -i 's/"\([^" >]\+\)\( \|>\)/"\1"\2/g' file.html
Explanation:
" - leading double quote
\([^" >]\+\) - non-quote-or-space-or-'>' chars, grouped (into group 1)
\( \|>\) - terminating space or '>', grouped (into group 2)
We replace it with '"<group1>"<group2>'.
One solution that pops out at me is to parse through each line of the file looking for the quote. When it finds one, activate a flag to keep track of being inside a quoted area, then continue parsing the line until it hits the first space or > it comes to and inserts an additional " just before it. Flip the flag off, then continue through the string looking for the next quote. Probably not a perfect solution, but a start perhaps.
If all lines share the same structure, you could use a simple texteditor to globally replace
' bordercolor'
with
'" bordercolor'
(without single-quotes). This is then independend from the field values and works similarly for the other fields. You still have to do some manual work, but if it's just one big file, I'd bite the bullet this time and not waste probably more time working out a sed-solution.
This should do if your file is simple - it won't work if you have whitespace which should be inside the quotes - in that case, a more complex code will be needed, but can be done along the same lines.
#!usr/bin/env python
#change the "utf-8" bellow to your files encoding
data = open("<myfile.html>").read().decode("utf-8")
new_data = []
inside_tag = False
inside_quotes = False
for char in data:
if char == "<":
inside_tag = True
if char == '"':
inside_quotes = True
if inside_tag and (char.isspace() or char==">") and inside_quotes:
new_data.append('"')
inside_quotes = False
if char == ">":
inside_tag = False
new_data.append(char)
outputfile = open("<mynewfile.html>", "wt")
outputfile.write("".join(new_data).encode("utf-8"))
outputfile.close()
with bash
for file in *
do
flag=0
while read -r line
do
case "$line" in
*"<blink>"*)
flag=1
;;
esac
if [ "$flag" -eq 1 ];then
case "$line" in
*class=\"pagetxt*">" )
line="${line%>}\">"
flag=0
;;
esac
fi
echo "${line}"
done <"file" > temp
mv temp "$file"
done
Regular expressions are your friend:
Find: (="[^" >]+)([ >])
Replace: \1"\2
After you've done that, make sure to run this one too:
Find: </?blink>
Replace: \n
(This won't fix more than one class on an element, like <element class="class1 class2 id="jimmy">)