Tuesday, April 21, 2009

Vim replace expressions

Today I discovered the the existence of evaluated expressions as replacements in vim. Consider the following snippet
String tStr = request.getParameter("frmAmt_D_DR");
if ( tStr != null && !"".equals(tStr.trim()) ) {
  xxxDDrAmt = Double.parseDouble(trStr);
}
In this I want to transform the Double.parseDouble line to
xxxDDrAmt = parseLocalizedDouble(request, "frmAmt_D_DR", locale);
The change had to be done in a lot of files and I was racking my brains trying to figure out a macro to do this. I even tried to match the entire snippet but, ran into trouble with both approaches especially because the if condition could include other conditions and there might also be more than one limits that had to be processed. Then I found some obscure comment somewhere in one of the my numerous entreaties to google that referred to evaluated expression in the replacement giving me my Eureka! moment :). Since all the variable names were always some contraction of the actual input parameter name all I needed to do was to device an expression that constructed the parameter name from the variable name. Its long and ugly but gets the job done :D
:g/Double\.parseDouble/s/\(\w\+Amt\w*\).*$/\= submatch(1) . " = parseLocalizedDouble(request, \"frm_" . toupper(strpart(submatch(1), 3, 1)) . "_" . toupper(strpart(submatch(1), 4, 2)) . (strlen(strpart(submatch(1), 9)) > 1 ? "_" . strpart(submatch(1), 9) : "") . "\", locale);"/
Running this,
xxxDDrAmt = Double.parseDouble(trStr);
becomes
xxxDDrAmt = parseLocalizedDouble(request, "frm_D_DR", locale);
and
xxxDDrAmtUSD = Double.parseDouble(trStr);
becomes
xxxDDrAmtUSD = parseLocalizedDouble(request, "frm_D_DR_USD", locale);
Here is an annotated version but don't try using this one vim expects the entire thing to be in a single line :|
:g/Double\.parseDouble/                       # global search for double parsing
s/\(\w\+Amt\w*\).*$                           # search for variable names containing Amt
/\= submatch(1)                               # submatch(1) gives the first group
  . " = parseLocalizedDouble(request, \"frm_" # . is the string concatenation operator
  . toupper(strpart(submatch(1), 3, 1)) . "_" # strpart is the substr equivalent in vim
  . toupper(strpart(submatch(1), 4, 2))
  . (strlen(strpart(submatch(1), 9)) > 1      # don't change Amts to _S :)
    ? "_" . strpart(submatch(1), 9) : "")     # vim even supports the ternary operator ^_^
  . "\", locale);"
/

No comments: