Wednesday, January 30, 2013

Return Text

do file

* The following program will create a tiny program that will send to the display input text.
cap program drop rt
program define rt
    local caller : di _caller()
    * This will parse the `0' text so that there is a before the colon and an after the colon
capt _on_colon_parse `0'

* This will save the after the colon in the macro s(after)
local command = s(after)

* Now we will display the command input
di as input `"`command'"'

* Next we will run the command.

rt: di "adsf"
rt: clear
rt: set obs 1000
rt: gen a = "324"
rt: sum

* Without rt the following commands will see only the output.
forv i = 1/5 {
 set obs `i'000
 gen a = rnormal()

* With rt prefix we will see both the command as well as the output.
forv i = 1/5 {
 rt: clear
 rt: set obs `i'000
 rt: gen a = rnormal()
 rt: sum

1 comment:

  1. Useful command! One comment: I think -local command = s(after)- should be -local command "`s(after)'"-. [R] saved results reads:

    "Say that some command set r(scalar) and r(macro), the first being stored as a scalar and the second as a macro. ... For r(macro), you are supposed to refer to it in quotes: `r(macro)'. If, however, you omit the quotes in an expression context, Stata evaluates the macro and then pretends that it is the result of function-returning-string. There are side effects of this, the most important being that the result is trimmed to 80 characters. Referring to r(macro) without quotes is never a good idea; the feature was included merely for

    I don't know what this 80 characters is about: I think the limit is closer to 244 characters. But there is some limit, and it'll bite for long commands. Here's a modified example from -help line-:

    sysuse uslifeexp, clear
    generate diff = le_wm - le_bm
    rt: line le_wm year, yaxis(1 2) xaxis(1 2) || line le_bm year || line diff year || lfit diff year ||, ylabel(0(5)20, axis(2) gmin angle(horizontal)) ylabel(0 20(10)80, gmax angle(horizontal)) ytitle("", axis(2)) xlabel(1918, axis(2)) xtitle("", axis(2))