在OCaml自定义顶层中设置提示

问题描述

| 在OCaml自定义顶层中,是否可以通过编程将提示从ѭ0设置为其他内容?我希望能够根据用户自定义功能的最后一项进行更改(有点像
bash
中的设置
PS1
)。我什至找不到更改它的#指令。谢谢!     

解决方法

        在toplevel / toploop.ml中:
let prompt =
  if !Clflags.noprompt then \"\"
  else if !first_line then \"# \"
  else if Lexer.in_comment () then \"* \"
  else \"  \"
in
可是等等!计算的提示将传递给
!read_interactive_input
, 并且此引用已导出: 在toplevel / toploop.mli中:
(* Hooks for external line editor *)

val read_interactive_input : (string -> string -> int -> int * bool) ref
这样看来,您所要做的就是将
Toploop.read_interactive_input
的值从默认值更改为忽略传递的提示并打印您想要的提示的函数。
read_interactive_input
的默认值为:
let read_input_default prompt buffer len =
  output_string Pervasives.stdout prompt; flush Pervasives.stdout;
  let i = ref 0 in
  try
    while true do
      if !i >= len then raise Exit;
      let c = input_char Pervasives.stdin in
      buffer.[!i] <- c;
      incr i;
      if c = \'\\n\' then raise Exit;
    done;
    (!i,false)
  with
  | End_of_file ->
      (!i,true)
  | Exit ->
      (!i,false)
因此,您可以使用:
# let my_read_input prompt buffer len =
  output_string Pervasives.stdout  \"%%%\" ; flush Pervasives.stdout;
  let i = ref 0 in
  try
    while true do
      if !i >= len then raise Exit;
      let c = input_char Pervasives.stdin in
      buffer.[!i] <- c;
      incr i;
      if c = \'\\n\' then raise Exit;
    done;
    (!i,false)
                                  ;;
val my_read_input : \'a -> string -> int -> int * bool = <fun>
# Toploop.read_interactive_input := my_read_input ;;
- : unit = ()
%%%