How do I get word-based movements in emacs go-mode to not skip over backquoted strings? - emacs

If I have code like so:
func main() {
a := `line 1
line 2
line 3
line 4`
fmt.Println(a)
}
doing forward-word or backword-word when the cursor is
in the multi-line string moves to the end or the start
of the string respectively. I'm using go-mode.el v1.3.1
from https://github.com/dominikh/go-mode.el
Similar if the cursor is inside the string and you do
I tried doing
(modify-syntax-entry ?` ".")
in the go-mode-hook but that didn't change the behavior.

Related

Can Sed match matching brackets?

My code has a ton of occurrences of something like:
idof(some_object)
I want to replace them with:
some_object["id"]
It sounds simple:
sed -i 's/idof(\([^)]\+\))/\1["id"]/g' source.py
The problem is that some_object might be something like idof(get_some_object()), or idof(my_class().get_some_object()), in which case, instead of getting what I want (get_some_object()["id"] or my_class().get_some_object()["id"]), I get get_some_object(["id"]) or my_class(["id"].get_some_object()).
Is there a way to have sed match closing bracket, so that it internally keeps track of any opening/closing brackets inside my (), and ignores those?
It needs to keep everything that's between those brackets: idof(ANYTHING) becomes ANYTHING["id"].
Using sed
$ sed -E 's/idof\(([[:alpha:][:punct:]]*)\)/\1["id"]/g' input_file
Using ERE, exclude idof and the first opening parenthesis.
As a literal closing parenthesis is also excluded, everything in-between the capture parenthesis including additional parenthesis will be captured.
[[:alpha:]] will match all alphabetic characters including upper and lower case while [[:punct:]] will capture punctuation characters including ().-{} and more.
The g option will make the substitution as many times as the pattern is found.
Theoretically, you can write a regex that will handle all combinations of idof(....) up to some limit of nested () calls inside ..... Such regex would have to list with all possible combinations of calls, like idof(one(two(three))) or idof(one(two(three)four(five)) you can match with an appropriate regex like idof([^()]*([^()]*([^()]*)[^()]*)[^()]*) or idof([^()]*([^()]*([^()]*)[^()]*([^()]*)[^()]*) respectively.
The following regex handles only some cases, but shows the complexity and general path. Writing a regex to handle all possible cases to "eat" everything in front of the trailing ) is left to OP as an exercise why it's better to use something else. Note that handling string literals ")" becomes increasingly complex.
The following Bash code:
sed '
: begin
# No idof? Just print the line!
/^\(.*\)idof(\([^)]*)\)/!n
# Note: regex is greedy - we start from the back!
# Note: using newline as a stack separator.
s//\1\n\2/
# hold the front
{ h ; x ; s/\n.*// ; x ; s/[^\n]*\n// ; }
: handle_brackets
# Eat everything before final ) up to some number of nested ((())) calls.
# Insert more jokes here.
: eat_brackets
/^[^()]*\(([^()]*\(([^()]*\(([^()]*\(([^()]*\(([^()]*\(([^()]*)\)\?[^()]*)\)\?[^()]*)\)\?[^()]*)\)\?[^()]*)\)\?[^()]*)\)/{
s//&\n/
# Hold the front.
{ H ; x ; s/\n\([^\n]*\)\n.*/\1/ ; x ; s/[^\n]*\n// ; }
b eat_brackets
}
/^\([^()]*\))/!{
s/^/ERROR: eating brackets did not work: /
q1
}
# Add the id after trailing ) and remove it.
s//\1["id"]/
# Join with hold space and clear the hold space for next round
{ H ; s/.*// ; x ; s/\n//g ; }
# Restart for another idof if in input.
b begin
' <<EOF
before idof(some_object) after
before idof(get_some_object()) after
before idof(my_class().get_some_object()) after
before idof(one(two(three)four)five) after
before idof(one(two(three)four)five) between idof(one(two(three)four)five) after
before idof( one(two(three)four)five one(two(three)four)five ) after
before idof(one(two(three(four)five)six(seven(eight)nine)ten) between idof(one(two(three(four)five)six(seven(eight)nine)ten) after
EOF
Will output:
before some_object["id"] after
before get_some_object()["id"] after
before my_class().get_some_object()["id"] after
before one(two(three)four)five["id"] after
before one(two(three)four)five["id"] between one(two(three)four)five["id"] after
before one(two(three)four)five one(two(three)four)five ["id"] after
ERROR: eating brackets did not work: one(two(three(four)five)six(seven(eight)nine)ten) after
The last line is not handled correctly, because (()()) case is not correctly handled. One would have to write a regex to match it.

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.

haxe: get line number and line position from haxe.macro.Position

In haxe macro for every expression we can get it's position in form of http://api.haxe.org/haxe/macro/Position.html :
{
file:String, // filename - relative to source path
min:Int, // position of first character in file
max:Int // position of last character in file
}
I want to get line number and position in line for min and max variables.
I definitely can do this by opening the file
FileSystem.absolutePath(Context.resolvePath(posInfo.file));
and calculating line number, but haxe already does this, it's much better to get this info from compiler. Is it possible?
In the current versions of Haxe you can use PositionTools.toLocation
class Macro {
public static macro function log(args:Array<Expr>):Expr {
var loc = PositionTools.toLocation(Context.currentPos());
var locStr = loc.file + ":" + loc.range.start.line;
args.unshift(macro $v{locStr});
return macro SomeExtern.logFunc($a{args});
}
}
to have Macro.log("hi!") translate into SomeExtern.logFunc("Main:5", "hi!")
I know a few projects do that manually (like checkstyle)
Load the file content, find the carriage returns (\n, \r or \n\r) mark the character position for each new line, lookup your pos.min against those positions
I guess it might be more problematic if you have multibyte characters in the file ...
In haxe 4 PositionTools.toLocation function was added.

backward-paragraph skips closest paragraph

I've modified the variable paragraph-start to count lines starting with .*: as a paragraph start:
(setq paragraph-start "\f\\|[ \t]*$\\|[ \t]*[0-9.]\.\\|.*:$\\|" )
However, if I have a buffer:
foo:
bar:
baz: some stuff
more
_
(Where _ indicates point location)
Then the first backward-paragraph skips to the beginning of the line 'bar:', not the line starting with 'baz:' as expected. How do I change this behaviour/why is it behaving this way?
It's because you have $ after ::
"\f\\|[ \t]*$\\|[ \t]*[0-9.]\.\\|.*:$\\|"
$ matches at the end of a line. So the part of your regexp that matches something followed by : also requires that nothing follow the :.
The first line (going backward from point) that ends in a : is the bar: line.
(Note too that you might not want .*:, if you want to exclude the possibility that what precedes the : not include a :, e.g., if you want to exclude a:b:c foo. To exclude :, use [^:]* instead of .*. And to exclude a lone :, use [^:]+.)

Remove last n characters of string after the dot with Autohotkey

I am using Autohotkey.
I have a string that looks like this S523.WW.E.SIMA. I want to remove the last few characters of the string after the dot (including the dot itself). So, after the removal, the string will look like S523.WW.E.
This may look like a simple question but I just cannot figure out using the available string functions in Autohotkey. How can this be done using Autohotkey? Thank you very much.
Example 1 (last index of)
string := "S523.WW.E.SIMA"
LastDotPos := InStr(string,".",0,0) ; get position of last occurrence of "."
result := SubStr(string,1,LastDotPos-1) ; get substring from start to last dot
MsgBox %result% ; display result
See InStr
See SubStr
Example 2 (StrSplit)
; Split it into the dot-separated parts,
; then join them again excluding the last part
parts := StrSplit(string, ".")
result := ""
Loop % parts.MaxIndex() - 1
{
if(StrLen(result)) {
result .= "."
}
result .= parts[A_Index]
}
Example 3 (RegExMatch)
; Extract everything up until the last dot
RegExMatch(string, "(.*)\.", result)
msgbox % result1
Example 4 (RegExReplace)
; RegExReplace to remove everything, starting with the last dot
result := RegExReplace(string, "\.[^\.]+$", "")