Skip to content

Instantly share code, notes, and snippets.

@t9md
Last active August 29, 2015 14:15
Show Gist options
  • Save t9md/58157a1cde0c1333b78c to your computer and use it in GitHub Desktop.
Save t9md/58157a1cde0c1333b78c to your computer and use it in GitHub Desktop.
on the fly macro

目的は以下のコードおセレクトして、変換結果に置き換えること。

const (
	Running State = iota
	Stopped
	Rebooting
	Terminated
)

期待する置き換え結果

const (
	Running State = iota
	Stopped
	Rebooting
	Terminated
)

func (s State) String() string {
  switch s {
  case Stopped:
    return "Stopped"
  case Rebooting:
    return "Rebooting"
  case Terminated:
    return "Terminated"
  default:
    return "Unknown"
  }
}

:'<,'>Transform go_const_stringfy.rb<CR> でうまくいかない。 そもそも、escape が必要だと思うが、readfile()ではなく、quickrun に直接ファイルPATHを渡して読んでもらえないか?

/var/folders/ml/4y1cgytd3wx_9c87136syqq00000gp/T/vN5wXw9/187:19:in `transform': undefined method `downcase' for nil:NilClass (NoMethodError)
	from /var/folders/ml/4y1cgytd3wx_9c87136syqq00000gp/T/vN5wXw9/187:56:in `'const (

v = "%s"
puts(v)
puts(v)
__END__
## Input
const (
Running State = iota
Stopped
Rebooting
Terminated
)
## Output
const (
Running State = iota
Stopped
Rebooting
Terminated
)
const (
Running State = iota
Stopped
Rebooting
Terminated
)
v = eval("%s")
puts v
__END__
## Input
[1,2,3]
## Transformed
1
2
3
def parse(s)
enums = []
type = ""
s.split("\n").each do |e|
next if e =~ /\(|\)/
n = e.split
if n.size == 1
enums << n.first
else
type << n[1]
end
end
[type, enums]
end
def transform(s)
type, enums = *parse(s)
v = type[0].downcase
out = ""
enums.each do |e|
out << " case #{e}:\n"
out << " return \"#{e}\"\n"
end
return <<-EOS
#{s}
func (#{v} #{type}) String() string {
switch #{v} {
#{out.chomp}
default:
return "Unknown"
}
}
EOS
end
# "const (\n\tRunning State = iota\n\tStopped\n\tRebooting\n\tTerminated\n)"
s = "const (
Running State = iota
Stopped
Rebooting
Terminated
)"
# v = s
v = "%s"
puts transform(v)
__END__
## Original
const (
Running State = iota
Stopped
Rebooting
Terminated
)
__END__
## Input
const (
Running State = iota
Stopped
Rebooting
Terminated
)
## Output
const (
Running State = iota
Stopped
Rebooting
Terminated
)
func (s State) String() string {
switch s {
case Stopped:
return "Stopped"
case Rebooting:
return "Rebooting"
case Terminated:
return "Terminated"
default:
return "Unknown"
}
}
function! Transform(template)
let tmpl = join(readfile(a:template),"\n")
let cmd = "QuickRun -outputter replace_region -type transform -mode v -hook/eval/template '" . tmpl . "'"
exe cmd
endfunction
command! -range -nargs=1 -complete=file Transform :call Transform(<f-args>)
let g:quickrun_config.transform = {
\ 'command': 'ruby',
\ "hook/sweep/enable": 0,
\ 'outputter': 'replace_region',
\ 'hook/eval/enable': 1,
\ }
" ex)
" '<,'>Transform tmpl_eval.rb
" '<,'>Transform tmpl_duplicate.rb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment