handle lines in region or not - emacs

I have N lines with code like this:
let aafdafa
let bfaf
let cb
I want translate this code to this:
let aafdafa = aafdafa.len();
let bfaf = bfaf.len();
let cb = cb.len();
replace-regexp not work with selection,
how should I solve this task in emacs?

This would be a task for an Emacs Macro: https://www.emacswiki.org/emacs/KeyboardMacros
Macros are built-in powerful features to record and repeat key strokes. You could:
Go to the beginning of the line
Jump one word (to the var) and yank it
Add an =
Paste the var
Add .len();
And then repeat n times.

replace-regexp does work with a region. Even if it didn't, you can set the region and do narrow-to-region and operate on the narrowed buffer. Anyway, the regexp should be something like let \(.+\) -> \& = \1.len(), where \& means the entire match and \1 means the first group.

Related

Converting numbers into timestamps (inserting colons at specific places)

I'm using AutoHotkey for this as the code is the most understandable to me. So I have a document with numbers and text, for example like this
120344 text text text
234000 text text
and the desired output is
12:03:44 text text text
23:40:00 text text
I'm sure StrReplace can be used to insert the colons in, but I'm not sure how to specify the position of the colons or ask AHK to 'find' specific strings of 6 digit numbers. Before, I would have highlighted the text I want to apply StrReplace to and then press a hotkey, but I was wondering if there is a more efficient way to do this that doesn't need my interaction. Even just pointing to the relevant functions I would need to look into to do this would be helpful! Thanks so much, I'm still very new to programming.
hfontanez's answer was very helpful in figuring out that for this problem, I had to use a loop and substring function. I'm sure there are much less messy ways to write this code, but this is the final version of what worked for my purposes:
Loop, read, C:\[location of input file]
{
{ If A_LoopReadLine = ;
Continue ; this part is to ignore the blank lines in the file
}
{
one := A_LoopReadLine
x := SubStr(one, 1, 2)
y := SubStr(one, 3, 2)
z := SubStr(one, 5)
two := x . ":" . y . ":" . z
FileAppend, %two%`r`n, C:\[location of output file]
}
}
return
Assuming that the "timestamp" component is always 6 characters long and always at the beginning of the string, this solution should work just fine.
String test = "012345 test test test";
test = test.substring(0, 2) + ":" + test.substring(2, 4) + ":" + test.substring(4, test.length());
This outputs 01:23:45 test test test
Why? Because you are temporarily creating a String object that it's two characters long and then you insert the colon before taking the next pair. Lastly, you append the rest of the String and assign it to whichever String variable you want. Remember, the substring method doesn't modify the String object you are calling the method on. This method returns a "new" String object. Therefore, the variable test is unmodified until the assignment operation kicks in at the end.
Alternatively, you can use a StringBuilder and append each component like this:
StringBuilder sbuff = new StringBuilder();
sbuff.append(test.substring(0,2));
sbuff.append(":");
sbuff.append(test.substring(2,4));
sbuff.append(":");
sbuff.append(test.substring(4,test.length()));
test = sbuff.toString();
You could also use a "fancy" loop to do this, but I think for something this simple, looping is just overkill. Oh, I almost forgot, this should work with both of your test strings because after the last colon insert, the code takes the substring from index position 4 all the way to the end of the string indiscriminately.

Count leading tabs in Swift string

I need to count the number of leading tabs in a Swift string. I know there are fairly simple solutions (e.g. looping over the string until a non-tab character is encountered) but I am looking for a more elegant solution.
I have attempted to use a regex such as ^\\t* along with the .numberOfMatches method but this detects all the tab characters as one match. For example, if the string has three leading tabs then that method just returns 1. Is there a way to write a regex that treats each individual tab character as a single match?
Also open to other ways of approaching this without using a regex.
Here is a non-regex solution
let count = someString.prefix(while: {$0 == "\t"}).count
You may use
\G\t
See the regex demo.
Here,
\G - matches a string start position or end of the previous match position, and
\t - matches a single tab.
Swift test:
let string = "\t\t123"
let regex = try! NSRegularExpression(pattern: "\\G\t", options: [])
let numberOfOccurrences = regex.numberOfMatches(in: string, range: NSRange(string.startIndex..., in: string))
print(numberOfOccurrences) // => 2

Adding new line to NSCharacterSet

I want to strip a string of all new lines and commas (and place it into an array), so I created this:
let results = text.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: ",\n"))
However, the newlines are still existing in my array (the commas are being removed). What's the correct way of adding newline to the NSCharacterSet? Or, how to add comma to NSCharacterSet.newLineCharacterSet.
Thanks.
Here is janky solution, but still looking for a more elegant one.
var results = text.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: ","))
text = results.joinWithSeparator(" ")
results = text.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
(one-line) SOLUTION:
var results = text.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: " ,\u{000A}\u{000B}\u{000C}\u{000D}\u{0085}"))
Explanation is below.
You can unite two NSCharacterSet by first using an NSMutableCharacterSet, for example:
let charset = NSMutableCharacterSet(charactersInString: ",")
charset.formUnionWithCharacterSet(NSCharacterSet.newlineCharacterSet())
let results = text.componentsSeparatedByCharactersInSet(charset)
So MartinR brought to my attention that there are more line feeds than just "\n".
I looked at the values used in NSCharacterSet.newlineCharacterSet and added them all, giving me:
var results = text.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: " ,\u{000A}\u{000B}\u{000C}\u{000D}\u{0085}"))
This got rid of all the whitespace, commas, and new lines. Interestingly - when I used all the newline values separately to see if I could figure out which newline was being used in my case, none of them worked. But when used all together, it strips my new lines.

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 [^:]+.)

In Emacs, how to line up equals signs in a series of initialization statements?

I saw this somewhere, but cannot find it now.
Is there a built-in function in emacs, or does someone have elisp, to line up all the equals signs in a series of inititialization statments in cc-mode?
Before:
int t=9;
Graphics g = new Graphics();
List<String> list = new List<String>();
After:
int t = 9;
Graphics g = new Graphics();
List<String> list = new List<String>();
Use M-x align-regexp (here, M-x align-regexp RET = RET). You can also add an "alignment rule" to the variable align-rules-list, so that in future M-x align will do it. See the documentation (C-h f align) for details.
This is in response to harpo's comment to ShreevatsaR's answer:
The only problem with this is that it "tabifies" the output, which is probably not what you want. Do you know any way to prevent this?
Here's what I did to resolve that issue:
;; Align with spaces only
(defadvice align-regexp (around align-regexp-with-spaces)
"Never use tabs for alignment."
(let ((indent-tabs-mode nil))
ad-do-it))
(ad-activate 'align-regexp)
M-x align should do the trick.