Monday, June 6, 2022

[SOLVED] "Right Click > Open In Terminal" Does not work if I activate tmux whenever I start a new shell session

Issue

I am using Linux Mint 20 Ulyana, Cinnamon 4.6.6

I am using the following code to activate tmux whenever I start a new shell session.

function tmux-as-default-terminal () {

  if command -v tmux &> /dev/null && [ -n "$PS1" ] && [[ ! "$TERM" =~ screen ]] && [[ ! "$TERM" =~ tmux ]]  && [ -z "$TMUX" ]; then
    tmux attach -t default || tmux new -s default
  fi

}

tmux-as-default-terminal

However, It has a small issue. When I right click a directory and click "Open In Terminal", it does not open that path. Instead it just open the previous tmux session.

What could be done here?

Update 1

I figured out tmux new-session -c $PWD open a new tmux session in current directory.

tmux attach -t 0 -c $PWD \; new-window \; attach to existing session and open a new window with current directory.

This bit of information might be important to solve this puzzle.

Update 2

From Is it possible to send input to a tmux session without connecting to it? I found out that I can use

$ tmux new -d -s mySession
$ tmux send-keys -t mySession.0 "^U"
$ tmux send-keys -t mySession.0 "cd /tmp" ENTER
$ tmux a -t mySession

to cd to a directory in current session.

Update 3

A solution with some strings attached

function tmux-as-default-terminal () {

  if command -v tmux &> /dev/null && [ -n "$PS1" ] && [[ ! "$TERM" =~ screen ]] && [[ ! "$TERM" =~ tmux ]]  && [ -z "$TMUX" ]
  then

    if tmux has-session -t default
    then
        tmux send-keys -t default.0 "^U"
        tmux send-keys -t default.0 "cd $PWD &> /dev/null" ENTER
        tmux send-keys -t default.0 "^L"
        tmux attach-session -t default.0
    else
        tmux new-session -s default -c $PWD
    fi
  fi

}

tmux-as-default-terminal

It works, as long as I do not open multiple terminals simultaneously.


Solution

OP here. for each tmux client, it will create a new session.

function tmux-as-default-terminal () {

  if command -v tmux &> /dev/null && [[ ! "$TERM" =~ screen ]]  
  then

    notmuxsession=$(tmux list-clients | wc -l)
    # notmuxsession=$(ps -e | grep "tmux: client" | wc -l)
    # notmuxsession=$(tmux ls | cut -d: -f1 | grep "default.*" | wc -l)

    if tmux has-session -t default${notmuxsession}
    then
        # tmux send-keys -t default${notmuxsession}:!.! "^U"
        tmux send-keys -t default${notmuxsession}:1.1 "^U"
        tmux send-keys -t default${notmuxsession}:1.1 "cd $PWD &> /dev/null" ENTER
        tmux send-keys -t default${notmuxsession}:1.1 "^L"
        tmux attach-session -t default${notmuxsession}:1.1
    else
        tmux new-session -s default${notmuxsession} -c $PWD
    fi
  fi

}

tmux-as-default-terminal

Which tmux session you will be attached to by default, depends on how many clients are open.



Answered By - Ahmad Ismail
Answer Checked By - Terry (WPSolving Volunteer)