Open selection in new buffer

I would like to be able to take a piece of text and open it in a new buffer. I have this right now:

define-command chunk %{
	execute-keys '"Oy'
	edit -scratch "chunk"
	execute-keys '"Op'
	format
}

It kinda works but it doesn’t format properly and i don’t get any syntax highlighting as it doesn’t set the new buffers file type. How could i make it so that the new buffer gets the same file type as the one i called the command in?

(untested)

define-command chunk %{
	execute-keys '"Oy'
	evaluate-commands %exp{
		edit -scratch chunk
		set-option buffer filetype %opt{filetype}
	}
	execute-keys '"Op'
	format
}

if your Kakoune version doesn’t support %exp{foo} then use "foo" instead

I am not sure that Krobelus’ solution works, because it tries to save the filetype once the scratch buffer is already open (with an empty filetype). Perhaps it is safer to save the filetype information in a dedicated option and while still in the first buffer:

declare-option str scratch_type

define-command chunk %{
    set-option global scratch_type %opt(filetype)
    #          ^-- use global scope so that the value of scratch_type persists
    #              in the newly created buffer
    execute-keys '"Oy'
    edit -scratch chunk
    execute-keys '"Op'
    set-option buffer filetype %opt(scratch_type)
    format
}


Edit: I just tried and Krobelus’ solution does work! My bad :frowning:

Interesting, wasn’t aware of %exp{} qutoed string, which is the magic why it works. It recursively expands it’s contents, so the expansion of %opt{filetype} is done before evaluating the commands.

Yes, this is what does the trick. Hence the solution with %exp is short and elegant.