Bhavy Garg
Bhavy Garg

Reputation: 11

Change prompt from a command (not working)

I am trying to change the prompt based on a variable current_username which changes within the script, I want the prompt to change whenever current_username changes.

Here's what I tried - Also even the prompt changes for one time using the command initialize it would be fine, cause then I can make another function which changes it again whenever current_username is changed.

var current_username = "";
var host = "localhost";
var initialized = "False";
var prompt1 = current_username + "@" + host + "> ";
$('body').bind('keydown', function(e) {
  if (event.keyCode == 13 && initialized == "False") {
    alert('Enter command "initialize".')
    initialized = "True"
    return false;
  }
});
var term = $('body').terminal({
  initialize: async function() {
    term.set_prompt(prompt1)
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.terminal/2.39.3/js/jquery.terminal.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.terminal/2.39.3/css/jquery.terminal.min.css"/>

Upvotes: 0

Views: 66

Answers (1)

jcubic
jcubic

Reputation: 66478

If you want to change the prompt when you change the variable inside the command, you can use dynamic prompt in form of a function. After you press enter, the function prompt will be executed and the new value of the variable will be used.

var current_username = "";
var host = "localhost";
var initalize = false;
var prompt1 = () => current_username + "@" + host + "> ";
var term = $('body').terminal({
  initialize: async function() {
    initalize = true;
    term.set_prompt(prompt1);
  },
  'set-user': function(name) {
    current_username = name;
  }
}, {
  completion: true,
  keymap: {
    ENTER: function(e, original) {
       var was_initalize = this.get_command().match(/^\s*initialize\s*$/);
       if (!initalize && !was_initalize) {
          alert('Enter command "initialize".')
       } else {
          original();
       }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.terminal/2.39.3/js/jquery.terminal.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.terminal/2.39.3/css/jquery.terminal.min.css"/>

Upvotes: 0

Related Questions