在终端窗口中使用R时获得正确的回车行为

问题描述

我正在研究R中需要跨平台/ GUI无关的东西,它涉及显示一些跨越多行的间歇更新进度信息。这是一个最小的示例,它说明了我正在做的事情(f()是主要的事情,get_width()只是必要的帮助者):

get_width = function(){
  is_rstudio_console <- function() (Sys.getenv("RSTUdio") == "1") && !nzchar(Sys.getenv("RSTUdio_TERM"))
  is_rstudio_terminal <- function() (Sys.getenv("RSTUdio") == "1") &&  nzchar(Sys.getenv("RSTUdio_TERM"))
  space_adjustment = ifelse(
    is_rstudio_console(),2 #adjustment for rstudio's console,ifelse(
      is_rstudio_terminal(),4 #adjustment for rstudio's terminal,0 #adjustment for regular ol' terminal
    )
  )
  getoption('width')+space_adjustment
}

f = function(){
  cat(strrep('-',get_width())) #line 1
  cat(strrep('-',get_width())) #line 2
  cat('\r') #this *should* return to the start of line 1
  cat(strrep('x',get_width())) #over-writing line 1
}
f()

现在,在RStudio中,它按预期运行,产生一行x,然后一行+,但是当我在终端(在RStudio的终端选项卡或直接在unix终端中)中运行R时,我得到一排+,然后是一排x。有没有解决此问题的方法?我试过连续放置两个cat('\r'),但没有骰子。

请注意,无论我是如上所述多次使用cat()还是将所有文本附加到单个字符串后再调用cat()一次,这种情况都会发生:

g = function(){
  txt = paste0(
    strrep('-',get_width()),strrep('-','\r',strrep('x',get_width())
  )
  cat(txt)
}
g() #same behavIoUr as f()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)