/src/utils/prompt.m

http://slac-lucretia.googlecode.com/ · MATLAB · 86 lines · 48 code · 4 blank · 34 comment · 9 complexity · b097501a69c359b7b8a0d584cbb3b713 MD5 · raw file

  1. function s=prompt(str,options,deflt_option)
  2. % s=prompt(str,options[,deflt_option]);
  3. %
  4. % Prompts user for input of ONE character from options string. It uses only
  5. % the first character of the user's response, converted to lower case, and
  6. % returns this character which will then match at least one of the characters
  7. % in the options string. Each character in the options string is an acceptable
  8. % choice. If the user types a character not in the options string, the
  9. % function displays a message and prompts again.
  10. %
  11. % INPUTs:
  12. %
  13. % str = the prompt string (the list of options and a colon are
  14. % tacked on at the end)
  15. % options = a character string of options
  16. % deflt_option = one character from options which is the default selection
  17. % when <CR> is the response to the prompt
  18. % (OPTIONAL ... if not present, no default option is assumed;
  19. % the <CR> response to the prompt returns an empty matrix)
  20. %
  21. % OUTPUT:
  22. %
  23. % s = the character chosen by the user which has been converted to
  24. % lower case, is guaranteed to be only one character in
  25. % length, and matches at least one of the characters in the
  26. % options string
  27. %
  28. % EXAMPLE:
  29. %
  30. % ? opts=['yn'];
  31. % ? s=prompt(' Plot this again?',opts);
  32. %
  33. % Plot this again? [y/n]:
  34. %
  35. % (now the user may only enter 'y', or 'Y', or 'n', or 'N')
  36. n=length(options);
  37. if (n<=1)
  38. error(' < 2 options makes no sense')
  39. end
  40. options=lower(options);
  41. if (~exist('deflt_option'))
  42. no_default=1;
  43. else
  44. deflt_option=lower(deflt_option(1));
  45. id=find(deflt_option==options);
  46. if (length(id)==0)
  47. error(' "default_option" must be one of the provided "options"')
  48. end
  49. no_default=0;
  50. end
  51. opts=' (';
  52. for j=1:(n-1)
  53. opts=[opts options(j) '/'];
  54. end
  55. opts=[opts options(n) ')'];
  56. if (no_default)
  57. opts=[opts ': '];
  58. else
  59. opts=[opts ' [' deflt_option ']: '];
  60. end
  61. str=[' ' str opts];
  62. while (1)
  63. disp(' ')
  64. s=input(str,'s');
  65. ns=length(s);
  66. if (ns==0)
  67. if (no_default)
  68. s=[];
  69. else
  70. s=deflt_option;
  71. end
  72. return
  73. else
  74. s=lower(s(1));
  75. if (find(options==s))
  76. return
  77. else
  78. disp(' ')
  79. disp([' Select only from the following: ' options])
  80. end
  81. end
  82. end