Open new terminal tab in same directory as existing tab (OSC 7?) #4405

Open
opened 2026-01-30 23:46:08 +00:00 by claunia · 189 comments
Owner

Originally created by @edencorbin on GitHub (Oct 11, 2019).

Description of the new feature/enhancement

Have the option (or default) of a new terminal tab opening in the current directory of the window of which you hit the hotkey to open a new tab. This is the standard way most linux terminals work and is most handy. I often work in a directory where I need to launch multiple seperate processes, its a pain to CD back into the directory each time.

Proposed technical implementation details (optional)

Hit the new tab hotkey, the new terminal should then be in the same folder as the previouse.


maintainer edit: Before commenting, make sure to check out

Tutorial: Opening a tab or pane in the same directory in Windows Terminal

This is largely something configurable today, this issue is just tracking another way of configuring this

Originally created by @edencorbin on GitHub (Oct 11, 2019). <!-- 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 I ACKNOWLEDGE THE FOLLOWING BEFORE PROCEEDING: 1. If I delete this entire template and go my own path, the core team may close my issue without further explanation or engagement. 2. If I list multiple bugs/concerns in this one issue, the core team may close my issue without further explanation or engagement. 3. If I write an issue that has many duplicates, the core team may close my issue without further explanation or engagement (and without necessarily spending time to find the exact duplicate ID number). 4. If I leave the title incomplete when filing the issue, the core team may close my issue without further explanation or engagement. 5. If I file something completely blank in the body, the core team may close my issue without further explanation or engagement. All good? Then proceed! --> # Description of the new feature/enhancement Have the option (or default) of a new terminal tab opening in the current directory of the window of which you hit the hotkey to open a new tab. This is the standard way most linux terminals work and is most handy. I often work in a directory where I need to launch multiple seperate processes, its a pain to CD back into the directory each time. # Proposed technical implementation details (optional) Hit the new tab hotkey, the new terminal should then be in the same folder as the previouse. ---- _maintainer edit: Before commenting, make sure to check out_ # [Tutorial: Opening a tab or pane in the same directory in Windows Terminal](https://learn.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory) This is largely something configurable today, this issue is just tracking _another_ way of configuring this
Author
Owner

@egmontkob commented on GitHub (Oct 11, 2019):

There's a "standard" escape sequence (OSC 7 ; URI ST) to set the terminal emulator's belief about the current directory. It originates from macOS Terminal.app, and was later adopted by some other ones, including GNOME Terminal and as far as I know Konsole too.

Another possible approach is to do some OS-specific hacks to examine the inner state of the child process (or even further down to descendents).

Yet another possibility is to mix the two, e.g. go to the directory set via OSC 7 if it was ever emitted, otherwise dig into the process.

The advantage of the OSC 7 approach is that it's clever regarding when to and when not to follow a child process. E.g. you start another nested subshell, it'll be the subdirectory of that subshell that's taken into account because that one also emits this sequence. However, launch an app that internally changes directory (e.g. make) and it – luckily – won't be make's internal subdir that's used.

The disadvantage of OSC 7 is that it requires cooperation from the shell, or other apps that matter.

@egmontkob commented on GitHub (Oct 11, 2019): There's a "standard" escape sequence (OSC 7 ; URI ST) to set the terminal emulator's belief about the current directory. It originates from macOS Terminal.app, and was later adopted by some other ones, including GNOME Terminal and as far as I know Konsole too. Another possible approach is to do some OS-specific hacks to examine the inner state of the child process (or even further down to descendents). Yet another possibility is to mix the two, e.g. go to the directory set via OSC 7 if it was ever emitted, otherwise dig into the process. The advantage of the OSC 7 approach is that it's clever regarding when to and when not to follow a child process. E.g. you start another nested subshell, it'll be the subdirectory of that subshell that's taken into account because that one also emits this sequence. However, launch an app that internally changes directory (e.g. make) and it – luckily – won't be make's internal subdir that's used. The disadvantage of OSC 7 is that it requires cooperation from the shell, or other apps that matter.
Author
Owner

@DHowett-MSFT commented on GitHub (Oct 14, 2019):

I've been rejecting this feature request for as long as this project has been open-source, and I never learned about OSC 7. This is very exciting.

I'm not happy to crawl through the process tree to dig up the leafmost process's CWD, but I am extremely happy to support OSC 7.

@DHowett-MSFT commented on GitHub (Oct 14, 2019): I've been rejecting this feature request for as long as this project has been open-source, and I never learned about OSC 7. This is _very exciting._ I'm not happy to crawl through the process tree to dig up the leafmost process's CWD, but I am extremely happy to support OSC 7.
Author
Owner

@davidhewitt commented on GitHub (Nov 15, 2019):

FYI I asked about OSC 7 handling for Alacritty, which eventually led to this issue being created in the "Terminal WG" on gitlab: https://gitlab.freedesktop.org/terminal-wg/specifications/issues/20

There's not been much movement on that ticket, but you may be interested to follow it. Especially if you guys have any opinions regarding what a "formal" specification for OSC 7 might look like.

@davidhewitt commented on GitHub (Nov 15, 2019): FYI I asked about OSC 7 handling for Alacritty, which eventually led to this issue being created in the "Terminal WG" on gitlab: https://gitlab.freedesktop.org/terminal-wg/specifications/issues/20 There's not been much movement on that ticket, but you may be interested to follow it. Especially if you guys have any opinions regarding what a "formal" specification for OSC 7 might look like.
Author
Owner

@zadjii-msft commented on GitHub (Nov 15, 2019):

So for the record, the thread at https://github.com/jwilm/alacritty/pull/2937 has a pretty great discussion.

Honestly, I'm pretty okay using the de-facto standard that's already in place, the OSC 7 ; <URI> ST mechanism. I'm not really sure there needs to be anything more formal than that.


Wait no I had a terrible thought. Say bash is configured to emit that, and someone runs bash in WSL. What are we supposed to do when someone tries to set the working directory to /home/zadjii? How we:

  1. tell that this is a WSL path, not a Windows path
  2. know which WSL distro this came from?

Do we need to add some property on our side that indicates "this is a WSL distro, not a Windows exe"? What happens to users who don't set that, does the duplicate tab functionality just not work (effectively silently)?

Then the next part gets harder. What happens when this command is output over SSH? The terminal can't know that the path isn't on this machine anymore, right? How does Terminal.app handle this?

Maybe this does need more specification 😨

@zadjii-msft commented on GitHub (Nov 15, 2019): So for the record, the thread at https://github.com/jwilm/alacritty/pull/2937 has a pretty great discussion. Honestly, I'm pretty okay using the de-facto standard that's already in place, the `OSC 7 ; <URI> ST` mechanism. I'm not really sure there needs to be anything more formal than that. <hr> Wait no I had a terrible thought. Say `bash` is configured to emit that, and someone runs `bash` in WSL. What are we supposed to do when someone tries to set the working directory to `/home/zadjii`? How we: 1. tell that this is a WSL path, not a Windows path 2. know which WSL distro this came from? Do we need to add some property on our side that indicates "this is a WSL distro, not a Windows exe"? What happens to users who don't set that, does the duplicate tab functionality just not work (effectively silently)? Then the next part gets harder. What happens when this command is output over SSH? The terminal can't know that the path isn't on this machine anymore, right? How does Terminal.app handle this? Maybe this does need more specification 😨
Author
Owner

@egmontkob commented on GitHub (Nov 15, 2019):

(Off: How long is it going to be until I mix up the two of you, D Howett and D Hewitt? :))

@egmontkob commented on GitHub (Nov 15, 2019): (Off: How long is it going to be until I mix up the two of you, D Howett and D Hewitt? :))
Author
Owner

@slikts commented on GitHub (Dec 10, 2019):

This is a crucial missing feature.

@slikts commented on GitHub (Dec 10, 2019): This is a crucial missing feature.
Author
Owner

@anthonyvdotbe commented on GitHub (Jan 22, 2020):

This should be a config option for the different commands. For example, I'd like this for duplicateTab and splitPane, but not for newTab.

@anthonyvdotbe commented on GitHub (Jan 22, 2020): This should be a config option for the different commands. For example, I'd like this for `duplicateTab` and `splitPane`, but not for `newTab`.
Author
Owner

@LuanVSO commented on GitHub (Jan 26, 2020):

the escape sequence is documented in mac os terminal.app preferences as shown by this comment alacritty/alacritty#2937(comment)

On macOS, the escape sequences are actually specified in Terminal.app > Preferences... > Profiles > Tab 69387948-67d69d00-0c95-11ea-881d-375672873fb4

@LuanVSO commented on GitHub (Jan 26, 2020): the escape sequence is documented in mac os terminal.app preferences as shown by this comment [alacritty/alacritty#2937(comment)](https://github.com/alacritty/alacritty/pull/2937#issuecomment-557334660) > On macOS, the escape sequences are actually specified in Terminal.app > Preferences... > Profiles > Tab ![69387948-67d69d00-0c95-11ea-881d-375672873fb4](https://user-images.githubusercontent.com/10134823/69387948-67d69d00-0c95-11ea-881d-375672873fb4.png)
Author
Owner

@zadjii-msft commented on GitHub (Jan 27, 2020):

For the record, there's heated debate over in https://gitlab.freedesktop.org/terminal-wg/specifications/merge_requests/7 about the specification of exactly this feature. I doubt that we'll support any subset of this feature until there's an actually accepted proposal there - we'd rather not introduce another disparate implementation until there's an actual standard.

@zadjii-msft commented on GitHub (Jan 27, 2020): For the record, there's heated debate over in https://gitlab.freedesktop.org/terminal-wg/specifications/merge_requests/7 about the specification of exactly this feature. I doubt that we'll support any subset of this feature until there's an actually accepted proposal there - we'd rather not introduce another disparate implementation until there's an actual standard.
Author
Owner

@egmontkob commented on GitHub (Jan 27, 2020):

I'd recommend you to do the opposite :)

Quite a few terminals have successfully implemented OSC 7, copying from each other, resulting in happy users.

And there is somebody out there currently who thinks it isn't good enough, he thinks a formal specification is needed; comes up with a draft that is full of problems, and what I cannot understand at all, is only willing to document one of two siblings. (Note: I stopped following that thread a couple of days ago.)

Terminal-WG is not a formal authority, its documents aren't "official", aren't "standards" in any de jure way. It doesn't even have proper procedures, people with responsibilities, voting rights, whatever; no one knows what it takes to get a document "accepted" there, whatever this status means at all. It's just a collection of random unorganized folks trying to come up with something useful. Don't let those unofficial pending debates stop you from implementing a long-proven feature.

@egmontkob commented on GitHub (Jan 27, 2020): I'd recommend you to do the opposite :) Quite a few terminals have successfully implemented OSC 7, copying from each other, resulting in happy users. And there is somebody out there currently who thinks it isn't good enough, he thinks a formal specification is needed; comes up with a draft that is full of problems, and what I cannot understand at all, is only willing to document one of two siblings. (Note: I stopped following that thread a couple of days ago.) Terminal-WG is not a formal authority, its documents aren't "official", aren't "standards" in any de jure way. It doesn't even have proper procedures, people with responsibilities, voting rights, whatever; no one knows what it takes to get a document "accepted" there, whatever this status means at all. It's just a collection of random unorganized folks trying to come up with something useful. Don't let those unofficial pending debates stop you from implementing a long-proven feature.
Author
Owner

@LuanVSO commented on GitHub (Jan 28, 2020):

For the record, there's heated debate over in https://gitlab.freedesktop.org/terminal-wg/specifications/merge_requests/7

i commented it on the issue referenced in that pr too 😉

@LuanVSO commented on GitHub (Jan 28, 2020): > For the record, there's heated debate over in https://gitlab.freedesktop.org/terminal-wg/specifications/merge_requests/7 i commented it on the issue referenced in that pr too 😉
Author
Owner

@danpaolella commented on GitHub (Apr 19, 2020):

For anybody using Bash (from Git for Windows), a temporary workaround which has been saving me, is to store the new path every time you change dir (aliasing the cd command), then cd there when a new shell is started; this is in my .bashrc:

if [ "${PWD,,}" = "/c/windows/system32" ]; then
	if [ -f /tmp/pwd ]; then
		cd "$(< /tmp/pwd)"
	else
		cd ~
	fi
fi

cd() {
	command cd "$@"
	pwd > /tmp/pwd
}

I'm actually testing if I start in System32 (my terminal default start location), so that I can still type wt in the Explorer address bar and start somewhere else, but this bit is optional and should be customized if your shell starts in a different folder.

I'm not fluent enough with the PowerShell or other shells, but I guess you can do something alike.

@danpaolella commented on GitHub (Apr 19, 2020): For anybody using Bash (from Git for Windows), a temporary workaround which has been saving me, is to store the new path every time you change dir (aliasing the `cd` command), then cd there when a new shell is started; this is in my _.bashrc:_ ```bash if [ "${PWD,,}" = "/c/windows/system32" ]; then if [ -f /tmp/pwd ]; then cd "$(< /tmp/pwd)" else cd ~ fi fi cd() { command cd "$@" pwd > /tmp/pwd } ``` I'm actually testing if I start in System32 (my terminal default start location), so that I can still type `wt` in the Explorer address bar and start somewhere else, but this bit is optional and should be customized if your shell starts in a different folder. I'm not fluent enough with the PowerShell or other shells, but I guess you can do something alike.
Author
Owner

@tluanga34 commented on GitHub (May 14, 2020):

Ctrl+T should open a new tab with the same shell and the same directory.

@tluanga34 commented on GitHub (May 14, 2020): Ctrl+T should open a new tab with the same shell and the same directory.
Author
Owner

@DHowett-MSFT commented on GitHub (May 14, 2020):

Not everybody agrees with that assertion.

@DHowett-MSFT commented on GitHub (May 14, 2020): Not everybody agrees with that assertion.
Author
Owner

@tluanga34 commented on GitHub (May 14, 2020):

Not everybody agrees with that assertion.

Maybe many aggree. That's how terminal app works on most Linux desktop.

Atleast it can be made as an option.

@tluanga34 commented on GitHub (May 14, 2020): > Not everybody agrees with that assertion. Maybe many aggree. That's how terminal app works on most Linux desktop. Atleast it can be made as an option.
Author
Owner

@uranusjr commented on GitHub (May 14, 2020):

Hi, I believe it is already clear in this thread that many agree this is a useful feature, and the Windows Terminal team is also ware of this. And it is also clear that the problem here is not they don’t want to make this configurable, but they need to first figure out some technical stuff that prevents the feature from being possible.

I follow this thread to keep up to date on this feature and related discussions, but the messages like this only clutter the interface and do not help. I want to ask people to please refrain from posting messages that do little other than reiterating points that are already known.

@uranusjr commented on GitHub (May 14, 2020): Hi, I believe it is already clear in this thread that many agree this is a useful feature, and the Windows Terminal team is also ware of this. And it is also clear that the problem here is not they don’t want to make this configurable, but they need to first figure out some technical stuff that prevents the feature from being *possible*. I follow this thread to keep up to date on this feature and related discussions, but the messages like this only clutter the interface and do not help. I want to ask people to please refrain from posting messages that do little other than reiterating points that are already known.
Author
Owner

@PandaClone commented on GitHub (May 14, 2020):

Atleast it can be made as an option

This is what I don't get about the stubbornness. If you want to go against how most terminals behave, cool. Not even giving an option though? Where's the logic in that? Even Ctrl+Shit+D that represents duplicating a tab doesn't actually duplicate it as it sticks you in the default directory. Like you have a duplicate feature that doesn't even duplicate.

What's the "technical stuff" that prevents this feature from being possible? The code already exists. There's already a duplicate tab in Ctrl+Shift+D. It just needs to be fed the current working directory and you have the behaviour that most people are used to and that people are requesting. So I'm confused at how this has "technical stuff" blocking it.

I appreciate this type of discussion because it's quite clear that there is stubbornness involved which means this type of discussion is necessary.

@PandaClone commented on GitHub (May 14, 2020): > Atleast it can be made as an option This is what I don't get about the stubbornness. If you want to go against how most terminals behave, cool. Not even giving an option though? Where's the logic in that? Even Ctrl+Shit+D that represents duplicating a tab doesn't actually duplicate it as it sticks you in the default directory. Like you have a duplicate feature that doesn't even duplicate. What's the "technical stuff" that prevents this feature from being possible? The code already exists. There's already a duplicate tab in Ctrl+Shift+D. It just needs to be fed the current working directory and you have the behaviour that most people are used to and that people are requesting. So I'm confused at how this has "technical stuff" blocking it. I appreciate this type of discussion because it's quite clear that there is stubbornness involved which means this type of discussion is necessary.
Author
Owner

@zadjii-msft commented on GitHub (May 14, 2020):

Ah you're right, the original discussion is lost, because it didn't ever get linked to this thread. I'm copying the content of another post (https://github.com/microsoft/terminal/issues/2427#issuecomment-521307534) here for reference:


https://github.com/microsoft/terminal/issues/1756#issuecomment-520048598

Just chiming in;

_ (profile,working dir, environment var, etc)._

Anything about the actual process on the other end is, in the general case, impossible to replicate. The connected process could be ssh.exe, whose environment variables and working directory have no bearing on the detectable environment and working directory from the terminal side. The same actually, weirdly enough, applies to WSL. It doesn't use "working directory" and it doesn't expose its environment variables to interested Windows processes in any way.

Powershell doesn't even set the current working directory, so its directory can't be detected (!) either.

https://github.com/microsoft/terminal/issues/2315#issuecomment-519317472

This is one of those things that is impossible in the general case but technically possible. There's a lot of intricacies here, like:

cmd
powershell
cd d:\users

well, powershell isn't the first process we launched. we'd ignore the path d:\users

(in powershell)
cd d:\users

we'd ignore d:\users because powershell doesn't actually set the current working directory (!!)

If your "shell" is ssh dustin@example.com (where we strictly define shell to be "the first process Terminal spawns on your behalf"), its working directory is always going to be C:\windows\system32 regardless of what the remote working directory is.

I'd rather not provide the feature than provide the feature with so many caveats that they'd fill a documentation page. ☹️ sorry.

https://github.com/microsoft/terminal/issues/1536#issuecomment-519107586

No, because that would likely be neigh impossible to do in a general sense. How would we duplicate an instance of vim for example? What if the foreground process has opened some sort of file for exclusive access - how could we duplicate that process?

If there's a way this can be done safely and generally I'm all ears for proposed technical solutions, but I don't think it's something that's possible, so I'm not going to be investigating it.


Even if Powershell did set the working directory, we're still not positive that it's technically possible on Windows to get the CWD of another process. So that's the "technical" stuff that's preventing this from working. I'd love to add this as a setting. But there are definitely still technical questions that need answering.

The solution that's being discussed in this thread involves adding support for another VT sequence to the Terminal, that the shell would be able to emit to clue the Terminal in to what path it's in. This VT sequence isn't super well defined, and has edge cases that still need solving. Namely:

  • What happens when a WSL shell says "my CWD is /home/foo? There's no way for the Terminal to know that path is a WSL path, or even which distro it belongs to, so duplicating this tab would likely end up in C:\home\foo (if it exists)
  • What happens when you're connected to another machine over SSH? The Terminal won't be able to differentiate those paths from paths on your own local machine, so again, duplicating that path would be the wrong behavior
  • Every user will need to customize their prompt for various shells manually to cooperate with this behavior. This isn't a blocker, but this does mean it'll be a setting that won't just work out of the box.
@zadjii-msft commented on GitHub (May 14, 2020): Ah you're right, the original discussion is lost, because it didn't ever get linked to this thread. I'm copying the content of another post (https://github.com/microsoft/terminal/issues/2427#issuecomment-521307534) here for reference: <hr> ### https://github.com/microsoft/terminal/issues/1756#issuecomment-520048598 > > Just chiming in; > > > _ (profile,working dir, environment var, etc)._ > > Anything about the _actual process_ on the other end is, in the general case, impossible to replicate. The connected process could be `ssh.exe`, whose environment variables and working directory have no bearing on the detectable environment and working directory from the terminal side. The same actually, weirdly enough, applies to WSL. It doesn't use "working directory" and it doesn't expose its environment variables to interested Windows processes in any way. > > Powershell doesn't even _set_ the current working directory, so its directory can't be detected (!) either. ### https://github.com/microsoft/terminal/issues/2315#issuecomment-519317472 > > > This is one of those things that is impossible in the general case but _technically possible_. There's a lot of intricacies here, like: > > ``` > cmd > powershell > cd d:\users > ``` > > well, powershell isn't the first process we launched. we'd ignore the path `d:\users` > > ``` > (in powershell) > cd d:\users > ``` > > we'd ignore `d:\users` because powershell _doesn't actually set the current working directory_ (!!) > > If your "shell" is `ssh dustin@example.com` (where we strictly define shell to be "the first process Terminal spawns on your behalf"), its working directory is always going to be `C:\windows\system32` regardless of what the remote working directory is. > > I'd rather not provide the feature than provide the feature with so many caveats that they'd fill a documentation page. ☹️ sorry. ### https://github.com/microsoft/terminal/issues/1536#issuecomment-519107586 > > No, because that would likely be neigh impossible to do in a general sense. How would we duplicate an instance of vim for example? What if the foreground process has opened some sort of file for exclusive access - how could we duplicate that process? > > If there's a way this can be done safely and generally I'm all ears for proposed technical solutions, but I don't think it's something that's possible, so I'm not going to be investigating it. <hr> Even if Powershell _did_ set the working directory, we're still not positive that it's _technically_ possible on Windows to get the CWD of another process. So that's the "technical" stuff that's preventing this from working. **I'd love to add this as a setting.** But there are definitely still technical questions that need answering. The solution that's being discussed in this thread involves adding support for another VT sequence to the Terminal, that the _shell_ would be able to emit to clue the Terminal in to what path it's in. This VT sequence isn't super well defined, and has edge cases that still need solving. Namely: * What happens when a WSL shell says "my CWD is `/home/foo`? There's no way for the Terminal to know that path is a WSL path, or even which distro it belongs to, so duplicating this tab would likely end up in `C:\home\foo` (if it exists) * What happens when you're connected to another machine over SSH? The Terminal won't be able to differentiate those paths from paths on your own local machine, so again, duplicating that path would be the wrong behavior * Every user will need to customize their prompt for various shells _manually_ to cooperate with this behavior. This isn't a blocker, but this does mean it'll be a setting that won't just work out of the box.
Author
Owner

@PandaClone commented on GitHub (May 14, 2020):

You're trying to duplicate the running processes? Let's look at Linux for example. If you're running SSH in your terminal and open a new tab, the new tab doesn't open an SSH connection and browse to where you are in the SSH connection. It opens up a new tab where you are on your machine. Even if the process was local and not SSH it doesn't run the process. All that's being duplicated is the tab, not the running processes.

It sounds like this is being overly complicated. You aren't duplicating VIM or SSH or any other application that's running. You're duplicating the terminal and that answers the edge cases:

  • For WSL you aren't browsing your local. If the return is /home/foo that's the location. If the location was C:\home\foo it would return /mnt/c/home/foo.
  • SSH is a process. It runs in the shell. You aren't duplicating processes. Other terminals don't. You're duplicating the tab.
  • I'm not sure what the user would have to customize, but since when is customization an issue?

There's nothing wrong with duplicating the processes. I'm sure some would love that. It's just that would be another option on top of the option to duplicate the tabs. It shouldn't be a road-block. That's extra and optional.

@PandaClone commented on GitHub (May 14, 2020): You're trying to duplicate the running processes? Let's look at Linux for example. If you're running SSH in your terminal and open a new tab, the new tab doesn't open an SSH connection and browse to where you are in the SSH connection. It opens up a new tab where you are on your machine. Even if the process was local and not SSH it doesn't run the process. All that's being duplicated is the tab, not the running processes. It sounds like this is being overly complicated. You aren't duplicating VIM or SSH or any other application that's running. You're duplicating the terminal and that answers the edge cases: - For WSL you aren't browsing your local. If the return is /home/foo that's the location. If the location was C:\home\foo it would return /mnt/c/home/foo. - SSH is a process. It runs in the shell. You aren't duplicating processes. Other terminals don't. You're duplicating the tab. - I'm not sure what the user would have to customize, but since when is customization an issue? There's nothing wrong with duplicating the processes. I'm sure some would love that. It's just that would be another option on top of the option to duplicate the tabs. It shouldn't be a road-block. That's extra and optional.
Author
Owner

@DHowett-MSFT commented on GitHub (May 14, 2020):

@PandaClone it might surprise you to learn that some people set ssh.exe as the first thing that a profile launches, without running it from a shell.

Like as not, there really isn’t a way for the Terminal to interrogate wsl.exe, the wrapper application that communicates with Linux processes, to get it to say what the current working directory is of the first process in its process tree.
Because it doesn’t use the windows working directory infrastructure, which stores the WD in the process environment block, just using the boring old Windows APIs is not sufficient to tell what its working directory is.

These are technical problems that we have to solve. Otherwise, we write a feature that only works for, like, 25% of people.

If it proves to be easy: we are always willing to accept community contributions.

@DHowett-MSFT commented on GitHub (May 14, 2020): @PandaClone it might surprise you to learn that _some people set ssh.exe as the first thing that a profile launches, without running it from a shell_. Like as not, there really isn’t a way for the Terminal to interrogate `wsl.exe`, the wrapper application that communicates with Linux processes, to get it to say what the current working directory is of the first process in its process tree. Because it doesn’t use the windows working directory infrastructure, which stores the WD in the process environment block, just using the boring old Windows APIs _is not sufficient to tell what its working directory is._ These are technical problems that we have to solve. Otherwise, we write a feature that only works for, like, 25% of people. If it proves to be easy: we are always willing to accept community contributions.
Author
Owner

@zadjii-msft commented on GitHub (May 14, 2020):

  • For WSL you aren't browsing your local. If the return is /home/foo that's the location. If the location was C:\home\foo it would return /mnt/c/home/foo.

Ah but see, the way this feature works as spec'd, the Terminal doesn't know who or what said "The current working directory is /home/foo". This could be cmd.exe - then yea, the user wants C:\home\foo. This could be their Ubuntu distro, or their Fedora distro, or this could be ssh connected to centos or any other possibility. All the terminal gets is a string saying "this is the working directory now".

  • I'm not sure what the user would have to customize, but since when is customization an issue?

Pretty much every shell the user runs is going to need to manually be configured to enable sending this sequence. For cmd users, they'll need to manually configure their %PROMPT% to include the sequence $e]7;$P$e. bash users will need to set it up in their PS1. PowerShell will certainly have another way to do it. The fundamental issue here though is that the shells don't emit this sequence by default.

@zadjii-msft commented on GitHub (May 14, 2020): > * For WSL you aren't browsing your local. If the return is /home/foo that's the location. If the location was C:\home\foo it would return /mnt/c/home/foo. Ah but see, the way this feature works as spec'd, the Terminal doesn't know who or what said "The current working directory is `/home/foo`". This could be `cmd.exe` - then yea, the user wants `C:\home\foo`. This could be their Ubuntu distro, or their Fedora distro, or this could be ssh connected to centos or any other possibility. All the terminal gets is a string saying "this is the working directory now". > * I'm not sure what the user would have to customize, but since when is customization an issue? Pretty much every shell the user runs is going to need to manually be configured to enable sending this sequence. For `cmd` users, they'll need to manually configure their %PROMPT% to include the sequence `$e]7;$P$e`. `bash` users will need to set it up in their `PS1`. PowerShell will certainly have another way to do it. The fundamental issue here though is that the shells _don't_ emit this sequence by default.
Author
Owner

@PandaClone commented on GitHub (May 14, 2020):

SSH isn't a shell. You can set your profile to run it first, but it's still being run from the shell. It's just your profile is being instructed to run an application immediately. That application can be anything. It doesn't have to SSH. You can instruct your profile to run another shell if you wanted to.

And even in the case that there is no terminal, how is that a problem? There are always exceptions. Defaulting to the home directory when there is no directory to go to is fine. That's not a problem where you just "oh this can't be done".

Also, this is a feature that's standard in the majority terminals with tabs. Run any Linux distro which has their own terminal flavours and they all exhibit this behaviour of opening a new tab. This isn't a feature that's going to be ground breaking magic for Windows Terminal. It's a standard feature.

@PandaClone commented on GitHub (May 14, 2020): SSH isn't a shell. You can set your profile to run it first, but it's still being run from the shell. It's just your profile is being instructed to run an application immediately. That application can be anything. It doesn't have to SSH. You can instruct your profile to run another shell if you wanted to. And even in the case that there is no terminal, how is that a problem? There are always exceptions. Defaulting to the home directory when there is no directory to go to is fine. That's not a problem where you just "oh this can't be done". Also, this is a feature that's standard in the majority terminals with tabs. Run any Linux distro which has their own terminal flavours and they all exhibit this behaviour of opening a new tab. This isn't a feature that's going to be ground breaking magic for Windows Terminal. It's a standard feature.
Author
Owner

@DHowett-MSFT commented on GitHub (May 14, 2020):

Terminal doesn’t just spawn shells. It literally calls CreateProcess on the thing you provide in the profile config. SSH isn’t running in, or spawned by, a shell.

Look, we’re arguing about how possible this feature is. Can we just agree that we want this, everyone wants it, and if we had a reasonable way forward that worked in the vast majority of the use cases users care about that we would have done it already? I’m trying to reduce the number of times we have to say “on that can’t be done” with some upfront planning and design work.

It’s not groundbreaking magic, it’s just complicated by the Windows and WSL process model and we think it’ll fall over in some circumstances. Nobody’s saying anything more than that.

@DHowett-MSFT commented on GitHub (May 14, 2020): Terminal doesn’t just spawn shells. It literally calls `CreateProcess` on the thing you provide in the profile config. SSH isn’t running in, or spawned by, a shell. Look, we’re arguing about how possible this feature is. Can we just agree that _we want this, everyone wants it, and if we had a reasonable way forward that worked in the vast majority of the use cases users care about_ that we would have done it already? I’m trying to reduce the number of times we have to say “on that can’t be done” with some upfront planning and design work. It’s not groundbreaking magic, it’s just complicated by the Windows and WSL process model and we think it’ll fall over in some circumstances. Nobody’s saying anything more than that.
Author
Owner

@PandaClone commented on GitHub (May 14, 2020):

  • For WSL you aren't browsing your local. If the return is /home/foo that's the location. If the location was C:\home\foo it would return /mnt/c/home/foo.

Ah but see, the way this feature works as spec'd, the Terminal doesn't know who or what said "The current working directory is /home/foo". This could be cmd.exe - then yea, the user wants C:\home\foo. This could be their Ubuntu distro, or their Fedora distro, or this could be ssh connected to centos or any other possibility. All the terminal gets is a string saying "this is the working directory now".

How doesn't it know who or what said the current working directory is? You're the one asking for it. You know whether it's a Command Prompt or a WSL or a PowerShell. You know where it's coming from so you know how to format the location.

  • I'm not sure what the user would have to customize, but since when is customization an issue?

Pretty much every shell the user runs is going to need to manually be configured to enable sending this sequence. For cmd users, they'll need to manually configure their %PROMPT% to include the sequence $e]7;$P$e. bash users will need to set it up in their PS1. PowerShell will certainly have another way to do it. The fundamental issue here though is that the shells don't emit this sequence by default.

How is that a problem? This wouldn't be the first application to require configuration and it won't be the last. Not everything is plug and play and that's understandable. If the only way to make this work is for the user to require a configuration, how is that stopping point?

@PandaClone commented on GitHub (May 14, 2020): > > * For WSL you aren't browsing your local. If the return is /home/foo that's the location. If the location was C:\home\foo it would return /mnt/c/home/foo. > > Ah but see, the way this feature works as spec'd, the Terminal doesn't know who or what said "The current working directory is `/home/foo`". This could be `cmd.exe` - then yea, the user wants `C:\home\foo`. This could be their Ubuntu distro, or their Fedora distro, or this could be ssh connected to centos or any other possibility. All the terminal gets is a string saying "this is the working directory now". How doesn't it know who or what said the current working directory is? You're the one asking for it. You know whether it's a Command Prompt or a WSL or a PowerShell. You know where it's coming from so you know how to format the location. > > > * I'm not sure what the user would have to customize, but since when is customization an issue? > > Pretty much every shell the user runs is going to need to manually be configured to enable sending this sequence. For `cmd` users, they'll need to manually configure their %PROMPT% to include the sequence `$e]7;$P$e`. `bash` users will need to set it up in their `PS1`. PowerShell will certainly have another way to do it. The fundamental issue here though is that the shells _don't_ emit this sequence by default. How is that a problem? This wouldn't be the first application to require configuration and it won't be the last. Not everything is plug and play and that's understandable. If the only way to make this work is for the user to require a configuration, how is that stopping point?
Author
Owner

@liamness commented on GitHub (May 14, 2020):

What happens when a WSL shell says "my CWD is /home/foo? There's no way for the Terminal to know that path is a WSL path, or even which distro it belongs to, so duplicating this tab would likely end up in C:\home\foo (if it exists)

I can only really speak for myself, but if I had a tab open using one profile, navigated somewhere specific, and then opened a new tab in a different profile, it would not surprise or disappoint me in the slightest if the working dir did not carry over, and the default was used instead.

I think you understand that most people asking for this feature are missing the behaviour in terminals such as those included with GNOME and macOS. Those terminals don't have to deal with the same complexities that this does, but at the same time, I don't think anyone is expecting you to try and smartly handle edge cases that simply don't exist in the software they're using as a reference point.

It sounds like a pretty hairy task even if you reduce the scope somewhat though. I hope a way can be found to include some version of this feature, as it is a nice time saver.

@liamness commented on GitHub (May 14, 2020): > What happens when a WSL shell says "my CWD is /home/foo? There's no way for the Terminal to know that path is a WSL path, or even which distro it belongs to, so duplicating this tab would likely end up in C:\home\foo (if it exists) I can only really speak for myself, but if I had a tab open using one profile, navigated somewhere specific, and then opened a new tab in a different profile, it would not surprise or disappoint me in the slightest if the working dir did not carry over, and the default was used instead. I think you understand that most people asking for this feature are missing the behaviour in terminals such as those included with GNOME and macOS. Those terminals don't have to deal with the same complexities that this does, but at the same time, I don't think anyone is expecting you to try and smartly handle edge cases that simply don't exist in the software they're using as a reference point. It sounds like a pretty hairy task even if you reduce the scope somewhat though. I hope a way can be found to include some version of this feature, as it is a nice time saver.
Author
Owner

@dallonf commented on GitHub (Jun 15, 2020):

Could this use case be handled by #4472 in the short term? I'd personally be content with some variant of cmd.exe /c "wt.exe" new-tab -p "Ubuntu-20.04" -d $(pwd) (probably bound to a Bash macro) that would open up a new tab in the most recently focused window (which is almost certainly the window that I typed the command in).

@dallonf commented on GitHub (Jun 15, 2020): Could this use case be handled by #4472 in the short term? I'd personally be content with some variant of `cmd.exe /c "wt.exe" new-tab -p "Ubuntu-20.04" -d $(pwd)` (probably bound to a Bash macro) that would open up a new tab in the most recently focused window (which is almost certainly the window that I typed the command in).
Author
Owner

@DHowett commented on GitHub (Jun 15, 2020):

Gonna go out on a limb and say that implementing detection for the root process's current directory is easier than implementing commandline remoting and IPC to get WT to open tabs in the same window 😄

@DHowett commented on GitHub (Jun 15, 2020): Gonna go out on a limb and say that implementing detection for the root process's current directory is easier than implementing commandline remoting and IPC to get WT to open tabs in the same window :smile:
Author
Owner

@arbaieffendi commented on GitHub (Jun 21, 2020):

wow, i just came here and realize that it seems need a long journey :)

@arbaieffendi commented on GitHub (Jun 21, 2020): wow, i just came here and realize that it seems need a long journey :)
Author
Owner

@arbaieffendi commented on GitHub (Jun 22, 2020):

We found that in windows terminal we could split the shell windows by press shortcut alt+shift+D, but it doesn't set to same directory

@arbaieffendi commented on GitHub (Jun 22, 2020): We found that in windows terminal we could split the shell windows by press shortcut alt+shift+D, but it doesn't set to same directory
Author
Owner
@LuanVSO commented on GitHub (Jun 29, 2020): https://gitlab.freedesktop.org/terminal-wg/specifications/-/merge_requests/7#note_552774
Author
Owner

@IlliaBalia commented on GitHub (Jul 7, 2020):

I've come with a workaround: change the starting directory.

Put this function into $PROFILE (make sure to adjust $path)

function sd {
    $path = 'C:\Users\Admin\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json'
     ((Get-Content -path $path) -replace '"startingDirectory":.*', ("`"startingDirectory`": `"$pwd`"") -replace "\\", "\\") | Set-Content -Path $path
}

.. and you'll be able to a open new tab in the same directory almost with no hassle, just make sure to type sd before opening a new tab.

Of course, the drawback is that startingDirectory is changed every time the function is called.

It would be best to use this approach with a key re-mapper, so that when Ctrl+T is pressed the function is called automatically, and when Ctrl+F4 is pressed startingDirectory is reverted back to its original value.

@IlliaBalia commented on GitHub (Jul 7, 2020): I've come with a workaround: change the starting directory. Put this function into `$PROFILE` (make sure to adjust `$path`) ``` function sd { $path = 'C:\Users\Admin\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json' ((Get-Content -path $path) -replace '"startingDirectory":.*', ("`"startingDirectory`": `"$pwd`"") -replace "\\", "\\") | Set-Content -Path $path } ``` .. and you'll be able to a open new tab in the same directory almost with no hassle, just make sure to type `sd` before opening a new tab. Of course, the drawback is that `startingDirectory` is changed every time the function is called. It would be best to use this approach with a key re-mapper, so that when `Ctrl+T` is pressed the function is called automatically, and when `Ctrl+F4` is pressed `startingDirectory` is reverted back to its original value.
Author
Owner

@FrederickEngelhardt commented on GitHub (Sep 8, 2020):

Alternative solution

Inside whatever profile you are using example profile.sh or .zshrc create a ~/paths.sh file located within your $HOME directory. Paths will be updated whenever you call setCWD

This solution overrides the startingDirectory completely. Whenever you spawn a new terminal call setCWD before spawning the terminal and it will always start in the directly you last called setCWD in.

Note that I did this within .zshrc

Code:

source ~/paths.sh

if [[ $SAVED_PWD != $PWD  ]]
then
  cd $SAVED_PWD
fi

function setCWD(){
  echo export SAVED_PWD=$(pwd) > ~/paths.sh
}

You may need to create an initial file so just call setCWD.

BTW if you are using autohotkey, here's a nice and quick script to get things working

Make a file called windows-terminal.ahk and then paste this code below. Run the file and you are all set. (I recommend moving this file into the startup section so that when you restart this functionality is re-applied.

#IfWinActive, ahk_exe WindowsTerminal.exe
  ^t::
    Send, setCWD {enter}
    Send, ^t
@FrederickEngelhardt commented on GitHub (Sep 8, 2020): ### Alternative solution Inside whatever profile you are using example **profile.sh** or **.zshrc** create a ~/paths.sh file located within your $HOME directory. Paths will be updated whenever you call **setCWD** This solution overrides the **startingDirectory** completely. Whenever you spawn a new terminal call setCWD before spawning the terminal and it will always start in the directly you last called **setCWD** in. Note that I did this within `.zshrc` Code: ```bash source ~/paths.sh if [[ $SAVED_PWD != $PWD ]] then cd $SAVED_PWD fi function setCWD(){ echo export SAVED_PWD=$(pwd) > ~/paths.sh } ``` You may need to create an initial file so just call **setCWD**. BTW if you are using autohotkey, here's a nice and quick script to get things working Make a file called `windows-terminal.ahk` and then paste this code below. Run the file and you are all set. (I recommend moving this file into the startup section so that when you restart this functionality is re-applied. ```ahk #IfWinActive, ahk_exe WindowsTerminal.exe ^t:: Send, setCWD {enter} Send, ^t ```
Author
Owner

@osiris-plus commented on GitHub (Sep 12, 2020):

Guys, this is very important for productivity, almost like it's above everything else. Please fix this, me and my friends will happily abandon all of the other inferior terminal emulators.

@osiris-plus commented on GitHub (Sep 12, 2020): Guys, this is very important for productivity, almost like it's above everything else. Please fix this, me and my friends will happily abandon all of the other inferior terminal emulators.
Author
Owner

@TBBle commented on GitHub (Sep 13, 2020):

It looks like the attempt to 'standardise' OSC 7 at terminal-wg has stalled.

Is there still interest in implementing OSC 7 basically as it stands in Terminal.app?

Given that, we'd have "current host and CWD" for a given terminal, which just blats the 'process hacking' discussion; and then can decide/implement the user behaviours to make use of that information, e.g.,:

  • a "new Tab in current directory" command;
  • making "split" do this by default;
  • something magic to distinguish a WSL session from a Windows session (if they even report the same hostname? I haven't looked...);
  • a config option for "suppress OSC 7" on profiles where you know it's going to send a valid-looking OSC 7 that you don't want to use, such as sshing to a remote machine that claims the same hostname as your Windows host;
  • exposing the value into something you can stick on the command line, so your ssh or wsl session can appear at the same working directory as one you just duplicated.

This discussion was very focused on the first part (getting the current CWD) but I suspect the second part is the one that will need more consideration, based on the existing comments so far above. Even for that list of ideas, I'm sure a reasonable objection exists to every one of them.

@TBBle commented on GitHub (Sep 13, 2020): It looks like the attempt to 'standardise' OSC 7 at terminal-wg [has stalled](https://gitlab.freedesktop.org/terminal-wg/specifications/-/merge_requests/7#note_589661). Is there still interest in implementing OSC 7 basically as it stands in [Terminal.app](https://github.com/microsoft/terminal/issues/3158#issuecomment-578550385)? Given that, we'd have "current host and CWD" for a given terminal, which just blats the 'process hacking' discussion; and then can decide/implement the user behaviours to make use of that information, e.g.,: * a "new Tab in current directory" command; * making "split" do this by default; * something magic to distinguish a WSL session from a Windows session (if they even report the same hostname? I haven't looked...); * a config option for "suppress OSC 7" on profiles where you _know_ it's going to send a valid-looking OSC 7 that you don't want to use, such as sshing to a remote machine that claims the same hostname as your Windows host; * exposing the value into something you can stick on the command line, so your ssh or wsl session _can_ appear at the same working directory as one you just duplicated. This discussion was very focused on the first part (getting the current CWD) but I suspect the second part is the one that will need more consideration, based on the existing comments so far above. Even for that list of ideas, I'm sure a reasonable objection exists to _every one_ of them.
Author
Owner

@skyline75489 commented on GitHub (Sep 18, 2020):

For those who are still intersted in this topic, I made a early PR in #7668 . This is a a friendly ping. I'd really love to hear from everyone about it.

@skyline75489 commented on GitHub (Sep 18, 2020): For those who are still intersted in this topic, I made a early PR in #7668 . This is a a friendly ping. I'd really love to hear from everyone about it.
Author
Owner

@pml4 commented on GitHub (Oct 8, 2020):

What is the point of multiple tabs, especially fast duplication, if they don't inherit the current directory? This is such an important feature. Why not add a "hacky" workaround for now? I really don't see a problem extracting CWD from a process on Windows if it increases productivity for all the users, considering Windows itself has contained multiple such solutions for more than 20 years.

@pml4 commented on GitHub (Oct 8, 2020): What is the point of multiple tabs, especially fast duplication, if they don't inherit the current directory? This is such an important feature. Why not add a "hacky" workaround for now? I really don't see a problem extracting CWD from a process on Windows if it increases productivity for all the users, considering Windows itself has contained multiple such solutions for more than 20 years.
Author
Owner

@dlmoffett commented on GitHub (Nov 13, 2020):

I can't understand why this feature isn't the default. I truly am boggled as to why there isn't even a way to enable this feature. This is the biggest user experience detractor I have with Terminal: from an expedience perspective I am better served by not using Terminal and instead using explorer and right clicking in the directory I want to open the shell and selecting "Open PowerShell window here" because it's faster than hitting alt+shift+d then having to cd to the right place.

Terminal adds a lot of quality of life for Windows devs. This feature would be huge jump forward for me (and I suspect others). I'll add my voice in advocating for this feature be a top priority.

@dlmoffett commented on GitHub (Nov 13, 2020): I can't understand why this feature isn't the default. I truly am **boggled** as to *why there isn't even a way* to enable this feature. This is the biggest user experience detractor I have with Terminal: from an expedience perspective I am better served by **not using Terminal** and instead using explorer and right clicking in the directory I want to open the shell and selecting "Open PowerShell window here" because it's faster than hitting `alt+shift+d` then having to `cd` to the right place. Terminal adds a lot of quality of life for Windows devs. This feature would be huge jump forward for me (and I suspect others). I'll add my voice in advocating for this feature be a top priority.
Author
Owner

@zadjii-msft commented on GitHub (Nov 13, 2020):

I can't understand why this feature isn't the default.

I can't understand why people can't be bothered to read all the investigation that's been done in this thread, in #7668, #8214, #8166, and the other linked threads, to understand why this is actually a hard problem to solve. It turns out you can't just have a client app emit it's path - because the Terminal won't necessarily know whether that's a Windows or a WSL or a cygwin path.

It's a good thing we've got a bunch of talented contributors who are hard at work finding out the right way of implementing support for this feature, without breaking backwards-compatibility for other apps. We've just this week come up with a solution we're happy with, shouldn't be long before it's implemented.

@zadjii-msft commented on GitHub (Nov 13, 2020): > I can't understand why this feature isn't the default. I can't understand why people can't be bothered to read all the investigation that's been done in this thread, in #7668, #8214, #8166, and the other linked threads, to understand why this is actually a hard problem to solve. It turns out you can't just have a client app emit it's path - because the Terminal won't _necessarily_ know whether that's a Windows or a WSL or a cygwin path. It's a good thing we've got a bunch of talented contributors who are hard at work finding out the right way of implementing support for this feature, without breaking backwards-compatibility for other apps. We've _just this week_ come up with a solution we're happy with, shouldn't be long before it's implemented.
Author
Owner

@dlmoffett commented on GitHub (Nov 13, 2020):

Thanks @zadjii-msft !

In rereading my comment I'm realizing it comes off super accusatory and that was not my intent. I came here to say this:

Terminal adds a lot of quality of life for Windows devs. This feature would be huge jump forward for me (and I suspect others). I'll add my voice in advocating for this feature be a top priority.

And that my user experience so far has been this:

I can't understand why this feature isn't the default. I truly am boggled as to why there isn't even a way to enable this feature. This is the biggest user experience...etc

I probably should have put "as a user," at the beginning of my first paragraph.

I apologize for any offense I've given.

@dlmoffett commented on GitHub (Nov 13, 2020): Thanks @zadjii-msft ! In rereading my comment I'm realizing it comes off super accusatory and that was not my intent. I came here to say this: > Terminal adds a lot of quality of life for Windows devs. This feature would be huge jump forward for me (and I suspect others). I'll add my voice in advocating for this feature be a top priority. And that my *user* experience so far has been this: > I can't understand why this feature isn't the default. I truly am boggled as to why there isn't even a way to enable this feature. This is the biggest user experience...etc I probably should have put "as a user," at the beginning of my first paragraph. I apologize for any offense I've given.
Author
Owner

@hiepxanh commented on GitHub (Jan 13, 2021):

Happy new year :D I hope this feature so so much

@hiepxanh commented on GitHub (Jan 13, 2021): Happy new year :D I hope this feature so so much
Author
Owner

@azterizm commented on GitHub (Jan 19, 2021):

I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance.

To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh)

Add following to the /root/.config/fish/config.fish or your shell's equivalent.

function cd
    builtin cd $argv
    pwd > ~/.last_dir
end
if test -f ~/.last_dir
    cd ( cat ~/.last_dir )
end

As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎

@azterizm commented on GitHub (Jan 19, 2021): I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance. To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh) Add following to the `/root/.config/fish/config.fish` or your shell's equivalent. ``` ruby function cd builtin cd $argv pwd > ~/.last_dir end if test -f ~/.last_dir cd ( cat ~/.last_dir ) end ``` ⭐As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎
Author
Owner

@kpost commented on GitHub (Jan 20, 2021):

I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance.

To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh)

Add following to the /root/.config/fish/config.fish or your shell's equivalent.

function cd
    builtin cd $argv
    pwd > ~/.last_dir
end
if test -f ~/.last_dir
    cd ( cat ~/.last_dir )
end

As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎

Nice, thanks!

The shell script version if this:

cd() {
  builtin cd $argv
  pwd > ~/.last_dir
}

if [ -f ~/.last_dir ]; then
  cd `cat ~/.last_dir`
fi
@kpost commented on GitHub (Jan 20, 2021): > I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance. > > To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh) > > Add following to the `/root/.config/fish/config.fish` or your shell's equivalent. > > ```ruby > function cd > builtin cd $argv > pwd > ~/.last_dir > end > if test -f ~/.last_dir > cd ( cat ~/.last_dir ) > end > ``` > > ⭐As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎 Nice, thanks! The shell script version if this: ``` cd() { builtin cd $argv pwd > ~/.last_dir } if [ -f ~/.last_dir ]; then cd `cat ~/.last_dir` fi ```
Author
Owner

@vdsbenoit commented on GitHub (Jan 20, 2021):

I've tried a similar solution to @azterizm's one in the past. Always opening a terminal in the previous cd location can be inconvenient in some situations :

  • When we open a terminal from a custom location (for instance, in an explorer with a "Open a terminal here" option
  • When PowerShell is embedded in another tool (e.g. in an IDE)
@vdsbenoit commented on GitHub (Jan 20, 2021): I've tried a similar solution to @azterizm's one in the past. Always opening a terminal in the previous `cd` location can be inconvenient in some situations : - When we open a terminal from a custom location (for instance, in an explorer with a "Open a terminal here" option - When PowerShell is embedded in another tool (e.g. in an IDE)
Author
Owner

@azterizm commented on GitHub (Jan 20, 2021):

I've tried a similar solution to @azterizm's one in the past. Always opening a terminal in the previous cd location can be inconvenient in some situations :

  • When we open a terminal from a custom location (for instance, in an explorer with a "Open a terminal here" option
  • When PowerShell is embedded in another tool (e.g. in an IDE)

About the option in the context menu "Open a terminal here", we can make a script for this.

A script that takes the directory of where the context menu was called from, then we convert the slashes to what Linux uses (C:\ to /mnt/c) then run the Linux command from Powershell that updates ~/.last_dir. Finally in the same script, open the terminal normally. It will be exactly what you want.

The command that will update the file should be wsl /mnt/c >> ~/.last_dir

Currently, I do not know how to make scripts for Powershell but surely someone should try that.

As for the IDE's or other embedded tools, we might need to add a script to them that clears ~/.last_dir file on opening the terminal in there.

@azterizm commented on GitHub (Jan 20, 2021): > I've tried a similar solution to @azterizm's one in the past. Always opening a terminal in the previous `cd` location can be inconvenient in some situations : > > * When we open a terminal from a custom location (for instance, in an explorer with a "Open a terminal here" option > * When PowerShell is embedded in another tool (e.g. in an IDE) About the option in the context menu "Open a terminal here", we can make a script for this. A script that takes the directory of where the context menu was called from, then we convert the slashes to what Linux uses (`C:\` to `/mnt/c`) then run the Linux command from Powershell that updates `~/.last_dir`. Finally in the same script, open the terminal normally. It will be exactly what you want. The command that will update the file should be `wsl /mnt/c >> ~/.last_dir` Currently, I do not know how to make scripts for Powershell but surely someone should try that. As for the IDE's or other embedded tools, we might need to add a script to them that clears `~/.last_dir` file on opening the terminal in there.
Author
Owner

@TBBle commented on GitHub (Jan 20, 2021):

#8330 implemented the infrastructure needed for this, it should be part of the next Terminal 1.5 1.6 preview release.

You'll need your shell to generate the OSC 9;9 messages, and once that's working, you will get this behaviour for duplicating tabs and splitting panes when that release happens.

This is compatible with ConEmu, so ConEmu's OSC 9;9 "How to set it up" instructions should roughly work, where they use ANSI codes rather than ConEmuC; the "WSL/cygwin/msys" instructions need to be adjusted as they generate Unix paths, and for Windows Terminal you need Windows paths.

These instructions also do a bunch more, the part you need is the part that generates the 9;9 message, I am unaware of Windows Terminal consuming the 9;12 message, but of course it wouldn't hurt.

e.g. for PowerShell, the given example can be trimmed to this for the minimal change:

function prompt
{
  $loc = Get-Location

  # Emulate standard PS prompt with location followed by ">"
  $out = "PS $loc> "
  
  # Add current working directory (FileSystem)
  if ($loc.Provider.Name -eq "FileSystem") {
    $out += "$([char]27)]9;9;`"$($loc.Path)`"$([char]7)"
  }

  return $out
}

Note: I haven't tested this myself, but I wanted to make sure people knew this feature desire wasn't being ignored.

@TBBle commented on GitHub (Jan 20, 2021): #8330 implemented the infrastructure needed for this, it should be part of the next Terminal ~~1.5~~ 1.6 preview release. You'll need your shell to generate the `OSC 9;9` messages, and once that's working, you will get this behaviour for duplicating tabs and splitting panes when that release happens. This is [compatible with ConEmu](https://conemu.github.io/en/AnsiEscapeCodes.html#ConEmu_specific_OSC), so [ConEmu's OSC 9;9 "How to set it up" instructions](https://conemu.github.io/en/ShellWorkDir.html#What_you_shall_do_to_get_CD_support) should roughly work, where they use ANSI codes rather than `ConEmuC`; the "WSL/cygwin/msys" instructions need to be adjusted as they generate Unix paths, and for Windows Terminal you need Windows paths. These instructions also do a bunch more, the part you need is the part that generates the `9;9` message, I am unaware of Windows Terminal consuming the `9;12` message, but of course it wouldn't hurt. e.g. for PowerShell, the given example can be trimmed to this for the minimal change: ``` function prompt { $loc = Get-Location # Emulate standard PS prompt with location followed by ">" $out = "PS $loc> " # Add current working directory (FileSystem) if ($loc.Provider.Name -eq "FileSystem") { $out += "$([char]27)]9;9;`"$($loc.Path)`"$([char]7)" } return $out } ``` Note: I haven't tested this myself, but I wanted to make sure people knew this feature desire wasn't being ignored.
Author
Owner

@skyline75489 commented on GitHub (Jan 21, 2021):

The author of #8330 here. I can confirm it in fact works with the current dev branch. It should be available in 1.6 preview.

@skyline75489 commented on GitHub (Jan 21, 2021): The author of #8330 here. I can confirm it in fact works with the current dev branch. It should be available in 1.6 preview.
Author
Owner

@songyongshun commented on GitHub (Jan 28, 2021):

I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance.
To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh)
Add following to the /root/.config/fish/config.fish or your shell's equivalent.

function cd
    builtin cd $argv
    pwd > ~/.last_dir
end
if test -f ~/.last_dir
    cd ( cat ~/.last_dir )
end

As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎

Nice, thanks!

The shell script version if this:

cd() {
  builtin cd $argv
  pwd > ~/.last_dir
}

if [ -f ~/.last_dir ]; then
  cd `cat ~/.last_dir`
fi

for bash, $argv should be $1

@songyongshun commented on GitHub (Jan 28, 2021): > > I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance. > > To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh) > > Add following to the `/root/.config/fish/config.fish` or your shell's equivalent. > > ```ruby > > function cd > > builtin cd $argv > > pwd > ~/.last_dir > > end > > if test -f ~/.last_dir > > cd ( cat ~/.last_dir ) > > end > > ``` > > > > > > ⭐As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎 > > Nice, thanks! > > The shell script version if this: > > ``` > cd() { > builtin cd $argv > pwd > ~/.last_dir > } > > if [ -f ~/.last_dir ]; then > cd `cat ~/.last_dir` > fi > ``` for bash, $argv should be $1
Author
Owner

@bardware commented on GitHub (Jan 29, 2021):

In a cmd environment I call start to open a new console. Can Terminal not capture a call to start and open a new tab instead?

@bardware commented on GitHub (Jan 29, 2021): In a `cmd` environment I call `start` to open a new console. Can Terminal not capture a call to `start` and open a new tab instead?
Author
Owner

@LuanVSO commented on GitHub (Jan 29, 2021):

no that would require #492
run this on cmd to make ctrl+shift+d keep the current dir (will have to restart the current cmd for it to take effect)

setx PROMPT $E]9;9;$P$E\$P$S
@LuanVSO commented on GitHub (Jan 29, 2021): no that would require #492 run this on cmd to make ctrl+shift+d keep the current dir (will have to restart the current cmd for it to take effect) ```cmd setx PROMPT $E]9;9;$P$E\$P$S ```
Author
Owner

@saschanaz commented on GitHub (Jan 30, 2021):

Is OSC 9;9 something that can be natively supported by shells? Should I file an issue in PowerShell repo?

@saschanaz commented on GitHub (Jan 30, 2021): Is OSC 9;9 something that can be natively supported by shells? Should I file an issue in PowerShell repo?
Author
Owner

@LuanVSO commented on GitHub (Jan 30, 2021):

@saschanaz probably, you will get a better shot on psreadline repo.
but it's pretty easy to DIY, just put this in your $profile

function prompt {
        $p = $pwd.ProviderPath
	# $ansi_escape = [char]27 on powershell 5.1 replace "`e" whith this variable
	Write-host "`e]9;9;$p`e\" -NoNewline	
	"PS $p$('>' * ($nestedPromptLevel + 1)) "
}
@LuanVSO commented on GitHub (Jan 30, 2021): @saschanaz probably, you will get a better shot on [psreadline](https://github.com/powershell/psreadline) repo. but it's pretty easy to DIY, just put this in your `$profile` ```powershell function prompt { $p = $pwd.ProviderPath # $ansi_escape = [char]27 on powershell 5.1 replace "`e" whith this variable Write-host "`e]9;9;$p`e\" -NoNewline "PS $p$('>' * ($nestedPromptLevel + 1)) " } ```
Author
Owner

@TBBle commented on GitHub (Jan 30, 2021):

So now that this is working for duplicate tab and split pane w/duplicate, I'd like it for "new tab", as per the original request. Probably as a parameter for the newTab action, not a change in the default. My use-case is that sometimes I'm in a directory in PowerShell, and I want "Git Bash here".

Should I open a new issue for that request, or is that in-scope for this one as further work after #8330?

I also noticed that the default keybindings for splitPane (alt+shift+- and alt+shift+plus) do not get this behaviour, because they are using the default splitMode, 'Manual', which launches the default shell due to lack of other parameters. I guess it might be surprising for users that a 'Manual' splitPane that picks the same profile as my current terminal, is different from a 'Duplicate' splitPane. It certainly surprised me. ^_^

(Side-note: Should the default splitPane keybinding be Duplicate rather than Manual? I guess Manual is consistent with the default newTab keybinding... Now I know this, I'm locally overriding those splitPane default keys to be Duplicate)

It's possible that for what I want, a magic token for the startingDirectory parameter of the splitPane and newTab actions would be sufficient, but personally I'd lean towards a boolean field for copyWorkingDirectory, except that this might incorrectly set the expectation that it "just works" without the current shell calling OSC 9;9 (or OSC 7 etc. in future).

A magic token could be explicitly tied to "the directory set by OSC 9;9 or OSC 7, see the WT OSC docs for details".

@TBBle commented on GitHub (Jan 30, 2021): So now that this is working for duplicate tab and split pane w/duplicate, I'd like it for "new tab", as per the original request. Probably as a parameter for the `newTab` action, not a change in the default. My use-case is that sometimes I'm in a directory in PowerShell, and I want "Git Bash here". Should I open a new issue for that request, or is that in-scope for this one as further work after #8330? I also noticed that the default keybindings for splitPane (`alt+shift+-` and `alt+shift+plus`) do _not_ get this behaviour, because they are using the default splitMode, 'Manual', which launches the default shell due to lack of other parameters. I guess it might be surprising for users that a 'Manual' splitPane that picks the same profile as my current terminal, is different from a 'Duplicate' splitPane. It certainly surprised me. ^_^ (Side-note: Should the default `splitPane` keybinding be Duplicate rather than Manual? I guess Manual is consistent with the default `newTab` keybinding... Now I know this, I'm locally overriding those `splitPane` default keys to be Duplicate) It's possible that for what I want, a magic token for the `startingDirectory` parameter of the `splitPane` and `newTab` actions would be sufficient, but personally I'd lean towards a boolean field for `copyWorkingDirectory`, except that this might incorrectly set the expectation that it "just works" without the current shell calling OSC 9;9 (or OSC 7 etc. in future). A magic token could be explicitly tied to "the directory set by OSC 9;9 or OSC 7, see the WT OSC docs for details".
Author
Owner

@ojroques commented on GitHub (Jan 31, 2021):

It wasn't clear to me how to enable OSC 9;9 for WSL but I've finally figured it out. You should put this line in your .bashrc:

export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"'
@ojroques commented on GitHub (Jan 31, 2021): It wasn't clear to me how to enable `OSC 9;9` for WSL but I've finally figured it out. You should put this line in your .bashrc: ```sh export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"' ```
Author
Owner

@TBBle commented on GitHub (Jan 31, 2021):

If anyone is using PowerLine, this is what I'm using in the Prompt array of ${ENV:AppData}\powershell\HuddledMasses.org\PowerLine\Configuration.psd1 to generate OSC 9;9, as well as output the current directory:

(ScriptBlock ' New-PromptText { "&OSC;9;9;"+$executionContext.SessionState.Path.CurrentLocation+"&ST;" + $executionContext.SessionState.Path.CurrentLocation } -ForegroundColor DarkYellow ')

I've added the last two escape sequences as well:

  EscapeSequences    = @{
    Esc    = '['
    Store  = ''
    Recall = ''
    Clear  = ''
    OSC    = ']'
    ST     = '\'
  }

Each of those lines has the same character at the start. I just copied the 'Esc' line (really should be "CSI", I think), changed the non-hidden character, and the name.

My whole Configuration.psd1 file for context

Originally generated with Export-PowerLinePrompt and then modified as the mood hit me.


@{
  ExtendedCharacters = @{
    ColorSeparator        = ''
    ReverseColorSeparator = ''
    Separator             = ''
    ReverseSeparator      = ''
    Branch                = ''
    Lock                  = ''
    Gear                  = '⛯'
    Power                 = '⚡'
  }
  PowerLineConfig    = @{
    RestoreVirtualTerminal = $True
    Prompt                 = @((ScriptBlock ' New-PromptText { "&OSC;9;9;"+$executionContext.SessionState.Path.CurrentLocation+"&ST;" + $executionContext.SessionState.Path.CurrentLocation } -ForegroundColor DarkYellow '), (ScriptBlock ' "`t" '), (ScriptBlock ' Write-VcsStatus '), (ScriptBlock ' "`n" '), (ScriptBlock ' New-PromptText { ">" * ($NestedPromptLevel + 1) } -ForegroundColor Blue -ElevatedForegroundColor Yellow '))
    Colors                 = @((RgbColor 'Black'), (RgbColor 'Black'), (RgbColor 'Black'))
    PowerLineFont          = $True
    FullColor              = $True
    DefaultAddIndex        = 2
    SetCurrentDirectory    = $True
  }
  EscapeSequences    = @{
    Esc    = '['
    Store  = ''
    Recall = ''
    Clear  = ''
    OSC    = ']'
    ST     = '\'
  }
}

@TBBle commented on GitHub (Jan 31, 2021): If anyone is using [PowerLine](https://github.com/Jaykul/PowerLine), this is what I'm using in the `Prompt` array of `${ENV:AppData}\powershell\HuddledMasses.org\PowerLine\Configuration.psd1` to generate OSC 9;9, as well as output the current directory: ```Powershell (ScriptBlock ' New-PromptText { "&OSC;9;9;"+$executionContext.SessionState.Path.CurrentLocation+"&ST;" + $executionContext.SessionState.Path.CurrentLocation } -ForegroundColor DarkYellow ') ``` I've added the last two escape sequences as well: ```Powershell EscapeSequences = @{ Esc = '[' Store = '' Recall = '' Clear = '' OSC = ']' ST = '\' } ``` Each of those lines has the same character at the start. I just copied the 'Esc' line (really should be "CSI", I think), changed the non-hidden character, and the name. <details> <summary> My whole Configuration.psd1 file for context </summary> Originally generated with `Export-PowerLinePrompt` and then modified as the mood hit me. ```Powershell @{ ExtendedCharacters = @{ ColorSeparator = '' ReverseColorSeparator = '' Separator = '' ReverseSeparator = '' Branch = '' Lock = '' Gear = '⛯' Power = '⚡' } PowerLineConfig = @{ RestoreVirtualTerminal = $True Prompt = @((ScriptBlock ' New-PromptText { "&OSC;9;9;"+$executionContext.SessionState.Path.CurrentLocation+"&ST;" + $executionContext.SessionState.Path.CurrentLocation } -ForegroundColor DarkYellow '), (ScriptBlock ' "`t" '), (ScriptBlock ' Write-VcsStatus '), (ScriptBlock ' "`n" '), (ScriptBlock ' New-PromptText { ">" * ($NestedPromptLevel + 1) } -ForegroundColor Blue -ElevatedForegroundColor Yellow ')) Colors = @((RgbColor 'Black'), (RgbColor 'Black'), (RgbColor 'Black')) PowerLineFont = $True FullColor = $True DefaultAddIndex = 2 SetCurrentDirectory = $True } EscapeSequences = @{ Esc = '[' Store = '' Recall = '' Clear = '' OSC = ']' ST = '\' } } ``` </details>
Author
Owner

@s-celles commented on GitHub (Feb 6, 2021):

As suggested in #9063, here is an other UI proposition for such a feature.

Proposed technical implementation details (optional)

Right click on a tab could have a "New" contextual menu (between rename tab and close) which could show same entries as those in the "+" tab.

The main difference would be that a new tab will be created with the "context" of a tab which was opened previously (context being here the current working directory)

@s-celles commented on GitHub (Feb 6, 2021): As suggested in #9063, here is an other UI proposition for such a feature. # Proposed technical implementation details (optional) <!-- A clear and concise description of what you want to happen. --> Right click on a tab could have a "New" contextual menu (between rename tab and close) which could show same entries as those in the "+" tab. The main difference would be that a new tab will be created with the "context" of a tab which was opened previously (context being here the current working directory)
Author
Owner

@paulvandenburg commented on GitHub (Feb 24, 2021):

It wasn't clear to me how to enable OSC 9;9 for WSL but I've finally figured it out. You should put this line in your .bashrc:

export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"'

If you tried this and it didn't work, it could be that you're running the stable version of terminal which doesn't have this yet.
You can get the preview version from the store: https://www.microsoft.com/store/productId/9N8G5RFZ9XK3
Just confirmed it working for WSL 😃

@paulvandenburg commented on GitHub (Feb 24, 2021): > > > It wasn't clear to me how to enable `OSC 9;9` for WSL but I've finally figured it out. You should put this line in your .bashrc: > > ```shell > export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"' > ``` If you tried this and it didn't work, it could be that you're running the stable version of terminal which doesn't have this yet. You can get the preview version from the store: https://www.microsoft.com/store/productId/9N8G5RFZ9XK3 Just confirmed it working for WSL 😃
Author
Owner

@gemboj commented on GitHub (Feb 25, 2021):

It wasn't clear to me how to enable OSC 9;9 for WSL but I've finally figured it out. You should put this line in your .bashrc:

export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"'

If you tried this and it didn't work, it could be that you're running the stable version of terminal which doesn't have this yet.
You can get the preview version from the store: https://www.microsoft.com/store/productId/9N8G5RFZ9XK3
Just confirmed it working for WSL 😃

I have a very strange issue with this solution. I've installed Ubuntu 20.04, put the export into my .bashrc and as expected, it started working. I've then played around, installed some additional packages into my ubuntu and reinstalled whole distro Ubuntu 20.04 from microsoft store a few times, to reset clean my wsl.

At some point, I've noticed that this trick stopped working. No matter what I do, the windows terminal no longer has the ability to properly set the directory for a new tab to match the existing tab. I've tried everything that came to my mind: reinstalling windows terminal, reinstaling all the linux distributions, installing additional distributions (Ubuntu 18.04, openSUSE Leap 15.2), reinstalling linux kernel update package, disabling and reenabling the wsl from windows features, and updating my Windows version. Nothing works.

I've no idea how to debug the issue. Is this some wsl problem? Windows terminal problem? How to make sure that everything is properly cleaned up before reinstalling everything?

Operating System info

  • Edition: Microsoft Windows 10 Education
  • Version: 20H2
  • OS build: 19042.844
  • Experience: Windows Feature Experience Pack 120.2212.551.0

Additional info

  • Windows Terminal Preview 1.6.10412.0
  • Ubuntu 20.04 LTS, WSL 2
  • Windows Subsystem for Linux Update: 5.4.7.2
@gemboj commented on GitHub (Feb 25, 2021): > > It wasn't clear to me how to enable `OSC 9;9` for WSL but I've finally figured it out. You should put this line in your .bashrc: > > ```shell > > export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"' > > ``` > > If you tried this and it didn't work, it could be that you're running the stable version of terminal which doesn't have this yet. > You can get the preview version from the store: https://www.microsoft.com/store/productId/9N8G5RFZ9XK3 > Just confirmed it working for WSL 😃 I have a very strange issue with this solution. I've installed Ubuntu 20.04, put the export into my `.bashrc` and as expected, it started working. I've then played around, installed some additional packages into my ubuntu and reinstalled whole distro Ubuntu 20.04 from microsoft store a few times, to reset clean my wsl. At some point, I've noticed that this trick stopped working. No matter what I do, the windows terminal no longer has the ability to properly set the directory for a new tab to match the existing tab. I've tried everything that came to my mind: reinstalling windows terminal, reinstaling all the linux distributions, installing additional distributions (Ubuntu 18.04, openSUSE Leap 15.2), reinstalling linux kernel update package, disabling and reenabling the wsl from windows features, and updating my Windows version. Nothing works. I've no idea how to debug the issue. Is this some wsl problem? Windows terminal problem? How to make sure that everything is properly cleaned up before reinstalling everything? Operating System info - Edition: Microsoft Windows 10 Education - Version: 20H2 - OS build: 19042.844 - Experience: Windows Feature Experience Pack 120.2212.551.0 Additional info - Windows Terminal Preview 1.6.10412.0 - Ubuntu 20.04 LTS, WSL 2 - Windows Subsystem for Linux Update: 5.4.7.2
Author
Owner

@LuanVSO commented on GitHub (Feb 26, 2021):

put

    "debugFeatures": true,

in the global settings for windows terminal
then hold down both alt keys and open the profile that you are having problems, should look something like this:
image
verify if osc9;9 is being emitted

@LuanVSO commented on GitHub (Feb 26, 2021): put ```json "debugFeatures": true, ``` in the global settings for windows terminal then hold down both alt keys and open the profile that you are having problems, should look something like this: ![image](https://user-images.githubusercontent.com/43626415/109251954-294e5d00-77cb-11eb-84c8-9f4ec6640975.png) verify if osc9;9 is being emitted
Author
Owner

@mnpenner commented on GitHub (Feb 26, 2021):

Anyone happen to know how to add OSC 9;9 to Powerlevel10K (zsh)? I don't think export PROMPT_COMMAND= works.

@mnpenner commented on GitHub (Feb 26, 2021): Anyone happen to know how to add OSC 9;9 to Powerlevel10K (zsh)? I don't think `export PROMPT_COMMAND=` works.
Author
Owner

@LuanVSO commented on GitHub (Feb 26, 2021):

here:

 __wt_osc9_9 () {
      _win_path=$(wslpath -m "$(pwd)")
      printf "\033]9;9;\"%s\"\033\\" "$_win_path"
  }

  [ -n "$BASH_VERSION" ] && [ -n "$WT_SESSION" ] && PROMPT_COMMAND="__wt_osc9_9"
  [ -n "$ZSH_VERSION"  ] && [ -n "$WT_SESSION" ] && precmd_functions+=(__wt_osc9_9)

put it in a file and then source it from .zshrc or .bashrc

@LuanVSO commented on GitHub (Feb 26, 2021): here: ```zsh __wt_osc9_9 () { _win_path=$(wslpath -m "$(pwd)") printf "\033]9;9;\"%s\"\033\\" "$_win_path" } [ -n "$BASH_VERSION" ] && [ -n "$WT_SESSION" ] && PROMPT_COMMAND="__wt_osc9_9" [ -n "$ZSH_VERSION" ] && [ -n "$WT_SESSION" ] && precmd_functions+=(__wt_osc9_9) ``` put it in a file and then source it from .zshrc or .bashrc
Author
Owner

@gemboj commented on GitHub (Feb 26, 2021):

put

    "debugFeatures": true,

After turning on the debugFeatures I got the following result:
image

The 9;9;//wsl$/Ubuntu-20.04/home/gemboj before my prompt (which is not visible in the non debugging terminal) tells me that the osc9;9 is properly emitted. Still, the directory of a new tab is not set properly.

@gemboj commented on GitHub (Feb 26, 2021): > put > > ```json > "debugFeatures": true, > ``` After turning on the `debugFeatures` I got the following result: ![image](https://user-images.githubusercontent.com/6931932/109334942-a6c4ac80-7861-11eb-9d87-8f0b36a4ec1b.png) The `9;9;//wsl$/Ubuntu-20.04/home/gemboj` before my prompt (which is not visible in the non debugging terminal) tells me that the osc9;9 is properly emitted. Still, the directory of a new tab is not set properly.
Author
Owner

@zadjii-msft commented on GitHub (Feb 26, 2021):

@gemboj Just to be sure, you're using a duplicateTab action/keybinding to attempt to duplicate the tab, right?

@zadjii-msft commented on GitHub (Feb 26, 2021): @gemboj Just to be sure, you're using a `duplicateTab` action/keybinding to attempt to duplicate the tab, right?
Author
Owner

@gemboj commented on GitHub (Feb 27, 2021):

@gemboj Just to be sure, you're using a duplicateTab action/keybinding to attempt to duplicate the tab, right?

Okay. This is the moment I want to curl up and die. At some point my muscle memory must have kicked in and I started using ctrl+shift+t (new tab) instead of duplicating the current tab. At least I've learned the neat trick with debugFeatures. Now to never come back here out of embarrassment...

@gemboj commented on GitHub (Feb 27, 2021): > @gemboj Just to be sure, you're using a `duplicateTab` action/keybinding to attempt to duplicate the tab, right? Okay. This is the moment I want to curl up and die. At some point my muscle memory must have kicked in and I started using ctrl+shift+t (new tab) instead of duplicating the current tab. At least I've learned the neat trick with `debugFeatures`. Now to never come back here out of embarrassment...
Author
Owner

@catweazle9 commented on GitHub (Feb 28, 2021):

  [ -n "$ZSH_VERSION"  ] && [ -n "$WT_SESSION" ] && precmd_functions+=(__wt_osc9_9)

Putting the above in my .zshrc meant the function was re-added each time I sourced .zshrc, and I think I noticed a slowdown in showing the prompt that worsens for each occurrence. To limit this to one instance I tweaked it slightly to this:

if [ -n "$WT_SESSION" ] ; then
    if ((!precmd_functions[(I)__wt_osc9_9])); then
        precmd_functions+=(__wt_osc9_9)
    fi
fi
@catweazle9 commented on GitHub (Feb 28, 2021): > ```shell > [ -n "$ZSH_VERSION" ] && [ -n "$WT_SESSION" ] && precmd_functions+=(__wt_osc9_9) > ``` Putting the above in my .zshrc meant the function was re-added each time I sourced .zshrc, and I _think_ I noticed a slowdown in showing the prompt that worsens for each occurrence. To limit this to one instance I tweaked it slightly to this: ```shell if [ -n "$WT_SESSION" ] ; then if ((!precmd_functions[(I)__wt_osc9_9])); then precmd_functions+=(__wt_osc9_9) fi fi ```
Author
Owner

@omar-toma commented on GitHub (Mar 2, 2021):

I confirm that @ojroques's solution works for me on wsl

If you are using fish shell like me, I managed to make make it work by adding a new file in ~/.config/fish/conf.d for ex. windows-terminal.fish and added this to it

function windows-terminal --on-event fish_prompt
    printf "\e]9;9;%s\e\\" (wslpath -m "$PWD")
end
@omar-toma commented on GitHub (Mar 2, 2021): I confirm that @ojroques's solution works for me on wsl If you are using fish shell like me, I managed to make make it work by adding a new file in `~/.config/fish/conf.d` for ex. `windows-terminal.fish` and added this to it ``` function windows-terminal --on-event fish_prompt printf "\e]9;9;%s\e\\" (wslpath -m "$PWD") end ```
Author
Owner

@robsonsobral commented on GitHub (Mar 2, 2021):

I just added this to my $profile without luck:

function prompt
{
  $loc = Get-Location

  # Emulate standard PS prompt with location followed by ">"
  $out = "PS $loc> "

  # Add current working directory (FileSystem)
  if ($loc.Provider.Name -eq "FileSystem") {
    $out += "$([char]27)]9;9;`"$($loc.Path)`"$([char]7)"
  }

  return $out
}

Running the new v1.6.10571.0 on Windows 10

@robsonsobral commented on GitHub (Mar 2, 2021): I just added this to my $profile without luck: ``` function prompt { $loc = Get-Location # Emulate standard PS prompt with location followed by ">" $out = "PS $loc> " # Add current working directory (FileSystem) if ($loc.Provider.Name -eq "FileSystem") { $out += "$([char]27)]9;9;`"$($loc.Path)`"$([char]7)" } return $out } ``` Running the new [v1.6.10571.0](https://github.com/microsoft/terminal/releases/tag/v1.6.10571.0) on Windows 10
Author
Owner

@LuanVSO commented on GitHub (Mar 2, 2021):

@robsonsobral here:
https://gist.github.com/LuanVSO/6f2b94cf3bd90f184722676c43ccc1c6

@LuanVSO commented on GitHub (Mar 2, 2021): @robsonsobral here: https://gist.github.com/LuanVSO/6f2b94cf3bd90f184722676c43ccc1c6
Author
Owner

@robsonsobral commented on GitHub (Mar 3, 2021):

Thank you, @LuanVSO ! It worked!

I also had to move PSHAZZ script to the top of the file. Actually, pshazz block the script to run. It has to be removed.

try { $null = gcm pshazz -ea stop; pshazz init } catch { }
@robsonsobral commented on GitHub (Mar 3, 2021): Thank you, @LuanVSO ! It worked! ~~I also had to move PSHAZZ script to the top of the file.~~ Actually, pshazz block the script to run. It has to be removed. ``` try { $null = gcm pshazz -ea stop; pshazz init } catch { } ```
Author
Owner

@TBBle commented on GitHub (Mar 3, 2021):

A brief look at pshazz's prompt management suggests that you could write a plugin something like the z plugin to act on each prompt-display and call the Write-Host you want (i.e. the first three lines of the prompt function from @LuanVSO), although you have to activate the plugin in your preferred theme, I assume.

Otherwise, perhaps modify global:pshazz_write_prompt, to call Write-Host with the relevant values irrespective of theme.

@TBBle commented on GitHub (Mar 3, 2021): A brief look at pshazz's [prompt management](https://github.com/lukesampson/pshazz/blob/master/lib/prompt.ps1) suggests that you could write a plugin something like the [z plugin](https://github.com/lukesampson/pshazz/blob/master/plugins/z.ps1) to act on each prompt-display and call the `Write-Host` you want (i.e. the first three lines of the `prompt` function from @LuanVSO), although you have to activate the plugin in your preferred theme, I assume. Otherwise, perhaps modify `global:pshazz_write_prompt`, to call `Write-Host` with the relevant values irrespective of theme.
Author
Owner

@robsonsobral commented on GitHub (Mar 3, 2021):

Thank you, @TBBle ! It worked!

image

I already wrote a plugin to customize things. So I added:

Import-Module "$pluginDir\z"
Set-Alias z Search-NavigationHistory -Scope "global"
function global:pshazz:z:prompt {
	$esc=[char]27
	$p = $pwd.ProviderPath
	Write-host "$esc]9;9;`"$p`"$esc\" -NoNewline
}

Thank you so much!

@robsonsobral commented on GitHub (Mar 3, 2021): Thank you, @TBBle ! It worked! ![image](https://user-images.githubusercontent.com/931642/109826678-c8cf7d80-7c19-11eb-93c3-1ba216192553.png) I already wrote a plugin to customize things. So I added: ``` Import-Module "$pluginDir\z" Set-Alias z Search-NavigationHistory -Scope "global" function global:pshazz:z:prompt { $esc=[char]27 $p = $pwd.ProviderPath Write-host "$esc]9;9;`"$p`"$esc\" -NoNewline } ``` Thank you so much!
Author
Owner

@Evineit commented on GitHub (Mar 14, 2021):

I was having trouble getting to work the new duplicate tab in the same directory, after adding the code to my PowerShell profile now it seems to be working fine and the OSC9;9 is added, i don't know why this was happening. I added both images of the debug terminal before and after adding the function.

function prompt {
        $p = $pwd.ProviderPath
	# $ansi_escape = [char]27 on powershell 5.1 replace "`e" whith this variable
	Write-host "`e]9;9;$p`e\" -NoNewline	
	"PS $p$('>' * ($nestedPromptLevel + 1)) "
}

Before
This is before using your script

After
This is after using your script

Thank you, @LuanVSO!

@Evineit commented on GitHub (Mar 14, 2021): I was having trouble getting to work the new duplicate tab in the same directory, after adding the code to my PowerShell profile now it seems to be working fine and the OSC9;9 is added, i don't know why this was happening. I added both images of the debug terminal before and after adding the function. > > ```powershell > function prompt { > $p = $pwd.ProviderPath > # $ansi_escape = [char]27 on powershell 5.1 replace "`e" whith this variable > Write-host "`e]9;9;$p`e\" -NoNewline > "PS $p$('>' * ($nestedPromptLevel + 1)) " > } > ``` Before ![This is before using your script](https://i.imgur.com/Uta44aT.png) After ![This is after using your script](https://i.imgur.com/ur6Cd9o.png) Thank you, @LuanVSO!
Author
Owner

@LuanVSO commented on GitHub (Mar 14, 2021):

that's because PowerShell by default does not emit the required escape esquece for it to work

@LuanVSO commented on GitHub (Mar 14, 2021): that's because PowerShell by default does not emit the required escape esquece for it to work
Author
Owner

@merrijo commented on GitHub (Mar 19, 2021):

Has anyone gotten OSC9;9 to work with Windows CMD? I tried the setx example above, but it didn't work...

I also noticed some weird behavior in Powershell 7.1, but I don't know if this is the best place to ask. When I pipe a command I start seeing OSC9;9 outputs, for example:

PS C:\code\online_repos\terminal> git branch | grep ^\*
* main
PS C:\code\online_repos\terminal> ]9;9;"C:\code\online_repos\terminal"

Has anyone else seen this behavior?

@merrijo commented on GitHub (Mar 19, 2021): Has anyone gotten OSC9;9 to work with Windows CMD? I tried the `setx` example above, but it didn't work... I also noticed some weird behavior in Powershell 7.1, but I don't know if this is the best place to ask. When I pipe a command I start seeing OSC9;9 outputs, for example: ```powershell PS C:\code\online_repos\terminal> git branch | grep ^\* * main PS C:\code\online_repos\terminal> ←]9;9;"C:\code\online_repos\terminal" ``` Has anyone else seen this behavior?
Author
Owner

@LuanVSO commented on GitHub (Mar 19, 2021):

I also noticed some weird behavior in Powershell 7.1, but I don't know if this is the best place to ask. When I pipe a command I start seeing OSC9;9 outputs, for example:

PS C:\code\online_repos\terminal> git branch | grep ^\*
* main
PS C:\code\online_repos\terminal> ]9;9;"C:\code\online_repos\terminal"

Has anyone else seen this behavior?

that's because the git for windows commands explicitly disables vt processing and powershell doesn't turn it back on when native commands exit, this was resolved in the latest powershell 7.2 preview

@LuanVSO commented on GitHub (Mar 19, 2021): > I also noticed some weird behavior in Powershell 7.1, but I don't know if this is the best place to ask. When I pipe a command I start seeing OSC9;9 outputs, for example: > > ```powershell > PS C:\code\online_repos\terminal> git branch | grep ^\* > * main > PS C:\code\online_repos\terminal> ←]9;9;"C:\code\online_repos\terminal" > ``` > > Has anyone else seen this behavior? that's because the git for windows commands explicitly disables vt processing and powershell doesn't turn it back on when native commands exit, this was resolved in the latest powershell 7.2 preview
Author
Owner

@LuanVSO commented on GitHub (Mar 19, 2021):

Has anyone gotten OSC9;9 to work with Windows CMD? I tried the setx example above, but it didn't work...

https://gist.github.com/LuanVSO/09ba0239fe7c1a959a9b07c7156c5e13

@LuanVSO commented on GitHub (Mar 19, 2021): > Has anyone gotten OSC9;9 to work with Windows CMD? I tried the `setx` example above, but it didn't work... https://gist.github.com/LuanVSO/09ba0239fe7c1a959a9b07c7156c5e13
Author
Owner

@patricknelson commented on GitHub (Mar 19, 2021):

For anyone looking for a workaround that is nearly as good (but not exactly the same), there is an alternative approach. Instead of maintaining the current working directory, you can at least ensure that new tabs and panes open in the same starting directory (since current will vary over time).

Alternative steps:

  1. Use the custom right-click integration by BroJenuel/Explorer-Context-Menu-Integration-for-windows-terminal (which isn't subject to the separate but related bug documented in #8933).

  2. Since that creates a duplicate right-click entry, remove it by using the fix documented here: https://github.com/microsoft/terminal/issues/7008#issuecomment-662621638, or drop this into a .reg file and run it:

    Windows Registry Editor Version 5.00
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked]
    "{9F156763-7844-4DC4-B2B1-901F640F5155}"="WindowsTerminal"
    

End result is that it will at least persist the same starting directory (albeit it will not be up-to-date with cd changes, which is really what this issue is about).

Demo:

2021-03-18_18-34-07

@patricknelson commented on GitHub (Mar 19, 2021): For anyone looking for a workaround that is _nearly as good_ (but not exactly the same), there is an alternative approach. Instead of maintaining the **current** working directory, you can at least ensure that new tabs and panes open in the same **starting directory** (since current will vary over time). **Alternative steps:** 1. Use the custom right-click integration by [BroJenuel/Explorer-Context-Menu-Integration-for-windows-terminal](https://github.com/BroJenuel/Explorer-Context-Menu-Integration-for-windows-terminal) (which isn't subject to the separate but related bug documented in #8933). 2. Since that creates a _duplicate_ right-click entry, remove it by using the fix documented here: https://github.com/microsoft/terminal/issues/7008#issuecomment-662621638, or drop this into a `.reg` file and run it: ``` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked] "{9F156763-7844-4DC4-B2B1-901F640F5155}"="WindowsTerminal" ``` End result is that it will at least persist the same starting directory (albeit it will **not** be up-to-date with `cd` changes, which is really what this issue is about). **Demo:** ![2021-03-18_18-34-07](https://user-images.githubusercontent.com/4269377/111719725-b3617280-8819-11eb-81c1-354a2c456878.gif)
Author
Owner

@merrijo commented on GitHub (Mar 19, 2021):

Has anyone gotten OSC9;9 to work with Windows CMD? I tried the setx example above, but it didn't work...

https://gist.github.com/LuanVSO/09ba0239fe7c1a959a9b07c7156c5e13

Thanks for this, however it doesn't work for me. The split panes always open in my default user path.

I also noticed some weird behavior in Powershell 7.1, but I don't know if this is the best place to ask. When I pipe a command I start seeing OSC9;9 outputs, for example:

PS C:\code\online_repos\terminal> git branch | grep ^\*
* main
PS C:\code\online_repos\terminal> ]9;9;"C:\code\online_repos\terminal"

Has anyone else seen this behavior?

that's because the git for windows commands explicitly disables vt processing and powershell doesn't turn it back on when native commands exit, this was resolved in the latest powershell 7.2 preview

Aha, thanks for clarifying! I'll test the latest Powershell 7.2 preview.

@merrijo commented on GitHub (Mar 19, 2021): > > > > Has anyone gotten OSC9;9 to work with Windows CMD? I tried the `setx` example above, but it didn't work... > > https://gist.github.com/LuanVSO/09ba0239fe7c1a959a9b07c7156c5e13 Thanks for this, however it doesn't work for me. The split panes always open in my default user path. > > > > I also noticed some weird behavior in Powershell 7.1, but I don't know if this is the best place to ask. When I pipe a command I start seeing OSC9;9 outputs, for example: > > ```powershell > > PS C:\code\online_repos\terminal> git branch | grep ^\* > > * main > > PS C:\code\online_repos\terminal> ←]9;9;"C:\code\online_repos\terminal" > > ``` > > > > > > Has anyone else seen this behavior? > > that's because the git for windows commands explicitly disables vt processing and powershell doesn't turn it back on when native commands exit, this was resolved in the latest powershell 7.2 preview Aha, thanks for clarifying! I'll test the latest Powershell 7.2 preview.
Author
Owner

@skyline75489 commented on GitHub (Mar 19, 2021):

@joshmer Remember to use "duplicate pane" instead of "new pane". Only by duplicating a pane, you'll have the same CWD in the new pane.

@skyline75489 commented on GitHub (Mar 19, 2021): @joshmer Remember to use "duplicate pane" instead of "new pane". Only by duplicating a pane, you'll have the same CWD in the new pane.
Author
Owner

@merrijo commented on GitHub (Mar 19, 2021):

Duplicate pane is alt+shift+d correct? That's what I'm using. Here's a snippet from my settings file to confirm:
image

@merrijo commented on GitHub (Mar 19, 2021): Duplicate pane is alt+shift+d correct? That's what I'm using. Here's a snippet from my settings file to confirm: ![image](https://user-images.githubusercontent.com/6571016/111730738-258f9100-88c6-11eb-861d-259bcd9366a9.png)
Author
Owner

@skyline75489 commented on GitHub (Mar 19, 2021):

@joshmer Yes. Seems like you're doing the right thing. The setx thing works for me in plain CMD. But it doesn't work for like VS Developer Command Prompt for some reason. Are you also trying to make it work for Developer Command Prompt or something?

@skyline75489 commented on GitHub (Mar 19, 2021): @joshmer Yes. Seems like you're doing the right thing. The `setx` thing works for me in plain CMD. But it doesn't work for like VS Developer Command Prompt for some reason. Are you also trying to make it work for Developer Command Prompt or something?
Author
Owner

@LuanVSO commented on GitHub (Mar 19, 2021):

@joshmer could you also try this steps please

@LuanVSO commented on GitHub (Mar 19, 2021): @joshmer could you also try [this](https://github.com/microsoft/terminal/issues/3158#issuecomment-786389738) steps please
Author
Owner

@merrijo commented on GitHub (Mar 19, 2021):

@joshmer Yes. Seems like you're doing the right thing. The setx thing works for me in plain CMD. But it doesn't work for like VS Developer Command Prompt for some reason. Are you also trying to make it work for Developer Command Prompt or something?

Nope, I'm using standard CMD via Windows Terminal.

@joshmer could you also try this steps please

Edit: Apologies, I wasn't holding both ALT keys!

␛[?9001h␛[18;56;0;1;259;1_␛[2J␛[m␛[HMicrosoft␣Windows␣[Version␣10.0.19042.867]␛]0;Command␣Prompt␇␛[?25h␍␊(c)␣2020␣Microsoft␣Corporation.␣All␣rights␣reserved.␍␊␛]0;Command␣Prompt␣-␣"C:\Program␣Files␣(x86)\clink\0.4.9\clink.bat"␣␣inject␣--autorun␣--profile␣~\clink␇␛[18;56;0;1;259;1_␛[18;56;0;1;259;1_␛[18;56;0;1;259;1_␛[18;56;0;1;259;1_␛[18;56;0;1;259;1_␛[?25lClink␣v0.4.9␣[git:2fd2c2]␣Copyright␣(c)␣2012-2016␣Martin␣Ridgers␍␊http://mridgers.github.io/clink␛[6;1H␛[?25h␛[18;56;0;1;259;1_␛[18;56;0;1;259;1_␛]0;Command␣Prompt␇␛[18;56;0;1;259;1_␍␊␛]0;Administrator:␣Command␣Prompt␇␛[18;56;0;1;259;1_

I also have clink and MSYS2 setup in my system, so maybe something there is messing with things?

@merrijo commented on GitHub (Mar 19, 2021): > > > @joshmer Yes. Seems like you're doing the right thing. The `setx` thing works for me in plain CMD. But it doesn't work for like VS Developer Command Prompt for some reason. Are you also trying to make it work for Developer Command Prompt or something? Nope, I'm using standard CMD via Windows Terminal. > > > @joshmer could you also try [this](https://github.com/microsoft/terminal/issues/3158#issuecomment-786389738) steps please Edit: Apologies, I wasn't holding both ALT keys! ``` ␛[?9001h␛[18;56;0;1;259;1_␛[2J␛[m␛[HMicrosoft␣Windows␣[Version␣10.0.19042.867]␛]0;Command␣Prompt␇␛[?25h␍␊(c)␣2020␣Microsoft␣Corporation.␣All␣rights␣reserved.␍␊␛]0;Command␣Prompt␣-␣"C:\Program␣Files␣(x86)\clink\0.4.9\clink.bat"␣␣inject␣--autorun␣--profile␣~\clink␇␛[18;56;0;1;259;1_␛[18;56;0;1;259;1_␛[18;56;0;1;259;1_␛[18;56;0;1;259;1_␛[18;56;0;1;259;1_␛[?25lClink␣v0.4.9␣[git:2fd2c2]␣Copyright␣(c)␣2012-2016␣Martin␣Ridgers␍␊http://mridgers.github.io/clink␛[6;1H␛[?25h␛[18;56;0;1;259;1_␛[18;56;0;1;259;1_␛]0;Command␣Prompt␇␛[18;56;0;1;259;1_␍␊␛]0;Administrator:␣Command␣Prompt␇␛[18;56;0;1;259;1_ ``` I also have clink and MSYS2 setup in my system, so maybe something there is messing with things?
Author
Owner

@skyline75489 commented on GitHub (Mar 19, 2021):

OK I see clink.bat and related things in it. Guess that's the cause, since it's working fine in plain CMD. Perhaps this is the same reason why VS Developer Command Prompt doesn't work.

Unfortunately I'm no expert at CMD. I hope someone could shed light on this topic.

@skyline75489 commented on GitHub (Mar 19, 2021): OK I see `clink.bat` and related things in it. Guess that's the cause, since it's working fine in plain CMD. Perhaps this is the same reason why VS Developer Command Prompt doesn't work. Unfortunately I'm no expert at CMD. I hope someone could shed light on this topic.
Author
Owner

@DHowett commented on GitHub (Mar 19, 2021):

Is there a chance vsdevcmd just ... overrides the directory on startup?

@DHowett commented on GitHub (Mar 19, 2021): Is there a chance vsdevcmd just ... overrides the directory on startup?
Author
Owner

@DHowett commented on GitHub (Mar 19, 2021):

Actually, yeah, the only OSC I'm seeing in that trace is OSC 0 (set title). There's something stripping it out before it gets printed.

@DHowett commented on GitHub (Mar 19, 2021): Actually, yeah, the only OSC I'm seeing in that trace is OSC 0 (set title). There's something stripping it out before it gets printed.
Author
Owner

@merrijo commented on GitHub (Mar 19, 2021):

Ok, so I tried to rename all vsdevcmd.bat files to prevent them from doing anything, and it didn't work. Then I uninstalled clink and I'm now getting the correct OSC prompts! I reverted the vsdevcmd file names and it's still working fine.

As a sanity check I reinstalled clink and OSC is broken again, so I'll have to do some digging into what's happening there. Thanks all for the help!

@merrijo commented on GitHub (Mar 19, 2021): Ok, so I tried to rename all vsdevcmd.bat files to prevent them from doing anything, and it didn't work. Then I uninstalled clink and I'm now getting the correct OSC prompts! I reverted the vsdevcmd file names and it's still working fine. As a sanity check I reinstalled clink and OSC is broken again, so I'll have to do some digging into what's happening there. Thanks all for the help!
Author
Owner

@TBBle commented on GitHub (Mar 19, 2021):

I was just poking around in the Clink source, and it seems like it should be passing OSC codes through but it definitely has code to parse then, e.g., 0.4.9, 1.0.0a1, and I suspect that it's locally handling them to generate Console API calls, and hence stripping them even if it doesn't handle them.

So possibly (although I couldn't find this code in 0.4.9 as GitHub has indexed after a refactoring) it's only passing through recognised codes, and OSC 9;9 isn't recognised yet.

Either way, sounds like a bug report for clink is in-order here.

@TBBle commented on GitHub (Mar 19, 2021): I was just poking around in the Clink source, and it _seems_ like [it should be passing OSC codes through](https://github.com/mridgers/clink/issues/384) but it definitely has code to parse then, e.g., [0.4.9](https://github.com/mridgers/clink/blob/0.4.9/clink/dll/ansi.x), [1.0.0a1](https://github.com/mridgers/clink/blob/1.0.0a1/clink/terminal/src/ecma48_iter.cpp#L209-L233), and I _suspect_ that it's locally handling them to generate Console API calls, and hence [stripping them even if it doesn't handle them](https://github.com/mridgers/clink/blob/823d841bc5c38a83c3cc0991c1f3ff8099d83fb5/clink/terminal/src/ecma48_terminal_out.cpp#L109-L129). So possibly (although I couldn't find this code in 0.4.9 as GitHub has indexed after a refactoring) it's only passing through _recognised_ codes, and OSC 9;9 isn't recognised yet. Either way, sounds like a bug report for clink is in-order here.
Author
Owner

@piradata commented on GitHub (Mar 21, 2021):

TL;DR

For the ones reading this right now that wants this behaviour on windows terminal WSL, just add the following line on your ~/.bashrc file:

export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"'

Then the terminal will maintain the path when you press "Alt+Shift+D", but when you split with "Alt+Shift+-" or "Alt+Shift+=" it will open with the standard path, and that is pretty ok in my opinion. To configure the standard path to be your wsl home directory, edit your setting of WSL profile to be something like this:

{ "guid": "{2c4de342-38b7-51cf-b940-2309a097f518}", "name": "Ubuntu", "source": "Windows.Terminal.Wsl", "startingDirectory": "\\\\wsl$\\Ubuntu\\home\\<Your_User>", "hidden": false }

Cheers!!

@piradata commented on GitHub (Mar 21, 2021): TL;DR For the ones reading this right now that wants this behaviour on windows terminal WSL, just add the following line on your ~/.bashrc file: `export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"'` Then the terminal will maintain the path when you press "Alt+Shift+D", but when you split with "Alt+Shift+-" or "Alt+Shift+=" it will open with the standard path, and that is pretty ok in my opinion. To configure the standard path to be your wsl home directory, edit your setting of WSL profile to be something like this: `{ "guid": "{2c4de342-38b7-51cf-b940-2309a097f518}", "name": "Ubuntu", "source": "Windows.Terminal.Wsl", "startingDirectory": "\\\\wsl$\\Ubuntu\\home\\<Your_User>", "hidden": false }` Cheers!!
Author
Owner

@JCMais commented on GitHub (Mar 21, 2021):

Is it currently possible to pass split mode to the wt CLI?

@JCMais commented on GitHub (Mar 21, 2021): Is it currently possible to pass split mode to the `wt` CLI?
Author
Owner

@DHowett commented on GitHub (Mar 21, 2021):

Is it currently possible to pass split mode to the wt CLI?

Yes.

@DHowett commented on GitHub (Mar 21, 2021): > Is it currently possible to pass split mode to the `wt` CLI? Yes.
Author
Owner

@zadjii-msft commented on GitHub (Mar 22, 2021):

Actually that might not be right - you can pass the split direction but the splitMode is always manual

@zadjii-msft commented on GitHub (Mar 22, 2021): Actually that might not be right - you can pass the split direction but the `splitMode` is always `manual`
Author
Owner

@JCMais commented on GitHub (Mar 22, 2021):

@zadjii-msft do you want me to open a new issue with that feature request or that is not needed? 😄

@JCMais commented on GitHub (Mar 22, 2021): @zadjii-msft do you want me to open a new issue with that feature request or that is not needed? 😄
Author
Owner

@zadjii-msft commented on GitHub (Mar 22, 2021):

Nope, I already filed one 😉

@zadjii-msft commented on GitHub (Mar 22, 2021): Nope, I already filed one 😉
Author
Owner

@tignioj commented on GitHub (Apr 12, 2021):

I've come with a workaround: change the starting directory.

Put this function into $PROFILE (make sure to adjust $path)

function sd {
    $path = 'C:\Users\Admin\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json'
     ((Get-Content -path $path) -replace '"startingDirectory":.*', ("`"startingDirectory`": `"$pwd`"") -replace "\\", "\\") | Set-Content -Path $path
}

.. and you'll be able to a open new tab in the same directory almost with no hassle, just make sure to type sd before opening a new tab.

Of course, the drawback is that startingDirectory is changed every time the function is called.

It would be best to use this approach with a key re-mapper, so that when Ctrl+T is pressed the function is called automatically, and when Ctrl+F4 is pressed startingDirectory is reverted back to its original value.

Thanks for you, I have made some changes to the code to accommodate those with commas after them, It work's for me!

function sdd {
  $path = "$env:USERPROFILE\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json" 
  $todir = ("$pwd") -replace "\\","\\"  
   ((Get-Content -path $path)  -replace '("startingDirectory":)(.*")(.*)', ("`$1`"$todir`"`$3")) | Set-Content -Path $path
}
@tignioj commented on GitHub (Apr 12, 2021): > I've come with a workaround: change the starting directory. > > Put this function into `$PROFILE` (make sure to adjust `$path`) > > ``` > function sd { > $path = 'C:\Users\Admin\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json' > ((Get-Content -path $path) -replace '"startingDirectory":.*', ("`"startingDirectory`": `"$pwd`"") -replace "\\", "\\") | Set-Content -Path $path > } > ``` > > .. and you'll be able to a open new tab in the same directory almost with no hassle, just make sure to type `sd` before opening a new tab. > > Of course, the drawback is that `startingDirectory` is changed every time the function is called. > > It would be best to use this approach with a key re-mapper, so that when `Ctrl+T` is pressed the function is called automatically, and when `Ctrl+F4` is pressed `startingDirectory` is reverted back to its original value. Thanks for you, I have made some changes to the code to accommodate those with commas after them, It work's for me! ```shell function sdd { $path = "$env:USERPROFILE\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json" $todir = ("$pwd") -replace "\\","\\" ((Get-Content -path $path) -replace '("startingDirectory":)(.*")(.*)', ("`$1`"$todir`"`$3")) | Set-Content -Path $path } ```
Author
Owner

@ropbastos commented on GitHub (Apr 13, 2021):

@robsonsobral here:
https://gist.github.com/LuanVSO/6f2b94cf3bd90f184722676c43ccc1c6

Many thanks for that, been wanting that feature for ages!

Unfortunately, it seems to break Chocolatey/Scoop. After installing programs with them the PATH seems to not be edited anymore. I just pasted that on my $profile, am I missing something?

@ropbastos commented on GitHub (Apr 13, 2021): > @robsonsobral here: > https://gist.github.com/LuanVSO/6f2b94cf3bd90f184722676c43ccc1c6 Many thanks for that, been wanting that feature for ages! Unfortunately, it seems to break Chocolatey/Scoop. After installing programs with them the PATH seems to not be edited anymore. I just pasted that on my $profile, am I missing something?
Author
Owner

@LuanVSO commented on GitHub (Apr 13, 2021):

Many thanks for that, been wanting that feature for ages!

Unfortunately, it seems to break Chocolatey/Scoop. After installing programs with them the PATH seems to not be edited anymore. I just pasted that on my $profile, am I missing something?

@ropbastos do you mean that the refreshenv doesn't work anymore?
could you share the contents of your $profile please?

@LuanVSO commented on GitHub (Apr 13, 2021): > Many thanks for that, been wanting that feature for ages! > > Unfortunately, it seems to break Chocolatey/Scoop. After installing programs with them the PATH seems to not be edited anymore. I just pasted that on my $profile, am I missing something? @ropbastos do you mean that the `refreshenv` doesn't work anymore? could you share the contents of your `$profile` please?
Author
Owner

@ropbastos commented on GitHub (Apr 14, 2021):

My bad, I don't really know what went on when I made that comment. I remember running "choco install nodejs" and not having node show on path but I just tried to reproduce it and, happily, I guess x), failed. It works perfectly it seems, sorry! And many thanks to all contributors here!

@ropbastos commented on GitHub (Apr 14, 2021): My bad, I don't really know what went on when I made that comment. I remember running "choco install nodejs" and not having node show on path but I just tried to reproduce it and, happily, I guess x), failed. It works perfectly it seems, sorry! And many thanks to all contributors here!
Author
Owner

@tg21 commented on GitHub (May 5, 2021):

I am able to replicate Panes and tabs(with same working directory) in windows terminal using these steps.

  1. obtained terminal context menu item using this library Windows-terminal-context-menu. For some reason it does not work with default context menu option
    image

  2. set Starting directory of all profiles to "use parent process directory"
    image

  3. this is my key-mapping for split-pane
    { "command": { "action": "splitPane", "split": "auto", "splitMode": "duplicate" }, "keys": [ "alt+shift+d" ] },

  4. Result
    image

This works for tabs as well.

I hope this helps.
maybe devs can see how differently this library is making context menu options.
let me know if you need some more details.\

Known issues with this workaround
  • if you open terminal from start menu or its icon, then starting directory will be "C:\WINDOWS\system32>" instead of "C:\Users\UserName> "
  • Still does not keep the CWD same if you change it after opening the terminal. but will keep the initial directory(from where terminal was opened) as CWD.
@tg21 commented on GitHub (May 5, 2021): I am able to replicate Panes and tabs(with same working directory) in windows terminal using these steps. 1. obtained terminal context menu item using this library [Windows-terminal-context-menu](https://github.com/kerol2r20/Windows-terminal-context-menu). For some reason it does not work with default context menu option ![image](https://user-images.githubusercontent.com/21080598/117117542-46943e80-adad-11eb-89c8-4fc356ba8fab.png) 2. set Starting directory of all profiles to "use parent process directory" ![image](https://user-images.githubusercontent.com/21080598/117117661-6fb4cf00-adad-11eb-90d5-cc7d8a7f677f.png) 3. this is my key-mapping for split-pane `{ "command": { "action": "splitPane", "split": "auto", "splitMode": "duplicate" }, "keys": [ "alt+shift+d" ] },` 4. Result ![image](https://user-images.githubusercontent.com/21080598/117118385-54968f00-adae-11eb-90a5-ae76140c3e50.png) ### This works for tabs as well. I hope this helps.\ maybe devs can see how differently this library is making context menu options.\ let me know if you need some more details.\ ##### Known issues with this workaround - if you open terminal from start menu or its icon, then starting directory will be "C:\WINDOWS\system32>" instead of "C:\Users\UserName> " - Still does not keep the CWD same if you change it after opening the terminal. but will keep the initial directory(from where terminal was opened) as CWD.
Author
Owner

@TBBle commented on GitHub (May 5, 2021):

That approach is no different to just going into the directory in a console, and running Terminal from there.

It doesn't help this ticket at all, which is for this:

Still does not keep the CWD same if you change it after opening the terminal. but will keep the initial directory(from where terminal was opened) as CWD.

It won't interfere with it though, so if you then add "OSC9;9" to your various shells, then 'duplicate' and 'split-Duplicate' will work, but 'New tab' and 'split-new' are still to be done.

That said, that's a clever shell extension idea that solves a different, related problem.

@TBBle commented on GitHub (May 5, 2021): That approach is no different to just going into the directory in a console, and running Terminal from there. It doesn't help this ticket at all, which is for this: > Still does not keep the CWD same if you change it after opening the terminal. but will keep the initial directory(from where terminal was opened) as CWD. It won't _interfere_ with it though, so if you then add "OSC9;9" to your various shells, then 'duplicate' and 'split-Duplicate' will work, but 'New tab' and 'split-new' are [still to be done](https://github.com/microsoft/terminal/issues/3158#issuecomment-770206512). That said, that's a clever shell extension idea that solves a different, related problem.
Author
Owner

@tg21 commented on GitHub (May 5, 2021):

Yes you are absolutely correct.
while mentioning known issues in my workaround I realized this wasn't exactly what this thread was about.
But because almost all issues mentioning duplicate tabs/panes with same directory are marked duplicate of #3158 and closed. I thought I would leave it here for some like me willing to make do with this solution in the meantime.

@tg21 commented on GitHub (May 5, 2021): Yes you are absolutely correct. while mentioning known issues in my workaround I realized this wasn't exactly what this thread was about. But because almost all issues mentioning duplicate tabs/panes with same directory are marked duplicate of #3158 and closed. I thought I would leave it here for some like me willing to make do with this solution in the meantime.
Author
Owner

@Trance-Paradox commented on GitHub (Jun 15, 2021):

I want to open new terminal tab of other command lines in the same directory. For example I have a currently active tab of powershell in a specific folder. Not I want to open cmd in the same folder seperated from the current tab.

@Trance-Paradox commented on GitHub (Jun 15, 2021): I want to open new terminal tab of other command lines in the same directory. For example I have a currently active tab of powershell in a specific folder. Not I want to open cmd in the same folder seperated from the current tab.
Author
Owner

@skyline75489 commented on GitHub (Jun 15, 2021):

@Trance-Paradox I think what you looking for is #10232

@skyline75489 commented on GitHub (Jun 15, 2021): @Trance-Paradox I think what you looking for is #10232
Author
Owner

@Trance-Paradox commented on GitHub (Jun 16, 2021):

@Trance-Paradox I think what you looking for is #10232

Yes thank you

@Trance-Paradox commented on GitHub (Jun 16, 2021): > @Trance-Paradox I think what you looking for is #10232 Yes thank you
Author
Owner

@NicTanghe commented on GitHub (Jul 14, 2021):

Hello,
I wasn't sure this was specified already.
But I'd like to add this.
Any way to have a function to tell wt -w -0 nt program.exe to also run from the current directory ?

I don't want to write extra logic for saving the current directory in my rust program every time.

@NicTanghe commented on GitHub (Jul 14, 2021): Hello, I wasn't sure this was specified already. But I'd like to add this. Any way to have a function to tell `wt -w -0 nt program.exe` to also run from the current directory ? I don't want to write extra logic for saving the current directory in my rust program every time.
Author
Owner

@zadjii-msft commented on GitHub (Jul 14, 2021):

@NicTanghe try wt -w -0 nt -d . program.exe

@zadjii-msft commented on GitHub (Jul 14, 2021): @NicTanghe try `wt -w -0 nt -d . program.exe`
Author
Owner

@NicTanghe commented on GitHub (Jul 14, 2021):

Thanks 4 the lightning fast helpfulness as always :D
I thought that would only work for opening new terminal tabs.

@NicTanghe commented on GitHub (Jul 14, 2021): Thanks 4 the lightning fast helpfulness as always :D I thought that would only work for opening new terminal tabs.
Author
Owner

@touhou-ayaya commented on GitHub (Aug 27, 2021):

I add the following line on my ~/.bashrc file
cd $(cat $HOME/.my_current_path)
alias pwd='pwd|tee $HOME/.my_current_path'

when I run pwd in terminal, the current path can be recorded in .my_current_path.
now, you can openning in current path when you open a new tab or a new window.😂

@touhou-ayaya commented on GitHub (Aug 27, 2021): I add the following line on my ~/.bashrc file `cd $(cat $HOME/.my_current_path)` `alias pwd='pwd|tee $HOME/.my_current_path'` when I run `pwd` in terminal, the current path can be recorded in `.my_current_path`. now, you can openning in current path when you open a new tab or a new window.😂
Author
Owner

@Decoherence commented on GitHub (Aug 27, 2021):

Inspired by @touhou-ayaya's comment above, here's a way to open tabs in the current directory automatically (without running pwd each time).

I appended this to bottom of my ~/.zshrc file (it should also work with ~/.bashrc):

# Record the current path when changing directories
function cd() {
  builtin cd "$@" || return
  pwd > $HOME/.my_current_path
}

# Open new tabs using the current path
cd $(cat ~/.my_current_path)

This basically overrides the standard cd command so that whenever you change directories, the new path is written to $HOME/.my_current_path. The builtin prefix is required to prevent the function from recursively calling itself forever.

And the last line simply changes to that directory when opening a new tab.

I'm certainly no bash expert (is anyone, really? 😆), just wanted to share this quick solution in case someone finds it helpful.

@Decoherence commented on GitHub (Aug 27, 2021): Inspired by @touhou-ayaya's comment above, here's a way to open tabs in the current directory automatically (without running `pwd` each time). I appended this to bottom of my `~/.zshrc` file (it should also work with `~/.bashrc`): ```bash # Record the current path when changing directories function cd() { builtin cd "$@" || return pwd > $HOME/.my_current_path } # Open new tabs using the current path cd $(cat ~/.my_current_path) ``` This basically overrides the standard `cd` command so that whenever you change directories, the new path is written to `$HOME/.my_current_path`. The `builtin` prefix is required to prevent the function from recursively calling itself forever. And the last line simply changes to that directory when opening a new tab. I'm certainly no bash expert (is anyone, really? 😆), just wanted to share this quick solution in case someone finds it helpful.
Author
Owner

@liamness commented on GitHub (Aug 27, 2021):

This issue should probably be closed, given that an officially supported solution exists in a stable release (unless I'm missing something).

There is support for the OSC 9;9 escape sequence, which when set up, allows you to duplicate a tab in the same directory with ctrl+d. Yet people are still discussing hacky workarounds. I think the issue still being open is potentially confusing people.

If you use bash, put this in your .bashrc:

export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"'

If you use zsh, put this in your .zshrc:

precmd() {
  printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"
}

I use zsh personally so I've only tested the latter, but they should both work.

@liamness commented on GitHub (Aug 27, 2021): This issue should probably be closed, given that an officially supported solution exists in a stable release (unless I'm missing something). There is support for the OSC 9;9 escape sequence, which when set up, allows you to duplicate a tab in the same directory with ctrl+d. Yet people are still discussing hacky workarounds. I think the issue still being open is potentially confusing people. If you use bash, put this in your .bashrc: ``` export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"' ``` If you use zsh, put this in your .zshrc: ``` precmd() { printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")" } ``` I use zsh personally so I've only tested the latter, but they should both work.
Author
Owner

@LuanVSO commented on GitHub (Aug 27, 2021):

it's not closed because osc7 is different from osc9;9

@LuanVSO commented on GitHub (Aug 27, 2021): it's not closed because osc7 is different from osc9;9
Author
Owner

@liamness commented on GitHub (Aug 27, 2021):

The workarounds being discussed are also different from OSC 7. I never really got the impression that this issue was specifically about one particular escape sequence, but more about the functionality (opening a new tab in the same directory) regardless of how it is achieved.

Support for OSC 7 would be nice I suppose. Would be more aligned with other popular terminals like Terminal.app and GNOME Terminal. And AFAIK it wouldn't require this extra step to set up, although that may depend on which shell you happen to be using.

@liamness commented on GitHub (Aug 27, 2021): The workarounds being discussed are also different from OSC 7. I never really got the impression that this issue was specifically about one particular escape sequence, but more about the functionality (opening a new tab in the same directory) regardless of how it is achieved. Support for OSC 7 would be nice I suppose. Would be more aligned with other popular terminals like Terminal.app and GNOME Terminal. And AFAIK it wouldn't require this extra step to set up, although that may depend on which shell you happen to be using.
Author
Owner

@TBBle commented on GitHub (Aug 27, 2021):

OSC 7 support got bogged down because there are a few different conflicting specifications for it, and the main thing they have in common is that they assume the Free Desktop specification for file:// URIs, and hence had unclear or unhelpful semantics when dealing with the Windows definition of file:// URI handling, and which got worse when WSL got involved, because the Free Desktop file:// URI spec simply doesn't account for (predates?) filesystem namespaces and virtual filesystems when they share the same hostname as the physical/underlying filesystem, which is the case for pretty much any bash running on a Windows host, e.g. WSL, MSYS2, Cygwin.

OSC 9;9 has the advantage that it's already defined as a Windows-native path, so the implementation was uncontroversial, and delivered the needed functionality (informing the terminal of the shell's CWD). It also has the advantage that it won't conflict with anyone's existing Linux-native OSC 7 support scripts, e.g. when using Gnome Terminal from within WSL, OSC 7 will need to have the in-WSL path, while Windows Terminal needs the translated Windows path.

Overall, I agree that this ticket could probably be closed. For a while, people were posting OSC 9;9 implementation scripts, which was nice, but they're starting to scroll out into the "hidden items", and this is probably the wrong place to document such things anyway. https://github.com/MicrosoftDocs/terminal/issues/285 would be the right place, I guess.

#10232 is tracking the next evolution of this feature: conditional integration with "New tab/pane" support.

@TBBle commented on GitHub (Aug 27, 2021): OSC 7 support got bogged down because there are a few different conflicting specifications for it, and the main thing they have in common is that they assume the Free Desktop specification for `file://` URIs, and hence had unclear or unhelpful semantics when dealing with the Windows definition of `file://` URI handling, and which got worse when WSL got involved, because the Free Desktop `file://` URI spec simply doesn't account for (predates?) filesystem namespaces and virtual filesystems when they share the same hostname as the physical/underlying filesystem, which is the case for pretty much _any_ `bash` running on a Windows host, e.g. WSL, MSYS2, Cygwin. OSC 9;9 has the advantage that it's already defined as a Windows-native path, so the implementation was uncontroversial, and delivered the needed functionality (informing the terminal of the shell's CWD). It also has the advantage that it won't conflict with anyone's existing Linux-native OSC 7 support scripts, e.g. when using Gnome Terminal from within WSL, OSC 7 will need to have the in-WSL path, while Windows Terminal needs the translated Windows path. Overall, I agree that this ticket could probably be closed. For a while, people were posting OSC 9;9 implementation scripts, which was nice, but they're starting to scroll out into the "hidden items", and this is probably the wrong place to document such things anyway. https://github.com/MicrosoftDocs/terminal/issues/285 would be the right place, I guess. #10232 is tracking the next evolution of this feature: conditional integration with "New tab/pane" support.
Author
Owner

@bravely commented on GitHub (Sep 21, 2021):

For anyone having difficulty, I put together a a quick guide on accomplishing this(as long as you're willing to use OSC 9;9), as reading through everything here and in the related threads was pretty confusing.

@bravely commented on GitHub (Sep 21, 2021): For anyone having difficulty, I put together a [a quick guide](https://publish.obsidian.md/bravelyjake/Opening+a+Windows+Terminal+Tab+in+the+Previous+Directory) on accomplishing this(as long as you're willing to use OSC 9;9), as reading through everything here and in the related threads was pretty confusing.
Author
Owner

@Plasmadog commented on GitHub (Sep 29, 2021):

[Jan 31 2021] So now that this is working for duplicate tab and split pane w/duplicate...

Umm, is it? I'm on 1.10.2383.0 and both split and duplicate still always open in my home folder. What build should I be using to get this behaviour? (I only care about Powershell tabs)

@Plasmadog commented on GitHub (Sep 29, 2021): > [Jan 31 2021] So now that this is working for duplicate tab and split pane w/duplicate... Umm, is it? I'm on 1.10.2383.0 and both split and duplicate still always open in my home folder. What build should I be using to get this behaviour? (I only care about Powershell tabs)
Author
Owner

@TBBle commented on GitHub (Sep 30, 2021):

Have you set up our PowerShell to output OSC 9;9 data so that Windows Terminal knows the current working directory? Also, the default split command in the Windows Terminal key bindings is not 'duplicate', so you'll have to rebind that or it splits into a new copy of the profile, and won't look at the current working directory of the existing profile.

@TBBle commented on GitHub (Sep 30, 2021): Have you set up our PowerShell to output `OSC 9;9` data so that Windows Terminal knows the current working directory? Also, the default `split` command in the Windows Terminal key bindings is not 'duplicate', so you'll have to rebind that or it splits into a new copy of the profile, and won't look at the current working directory of the existing profile.
Author
Owner

@Plasmadog commented on GitHub (Sep 30, 2021):

Have you set up our PowerShell to output OSC 9;9 data so that Windows Terminal knows the current working directory? Also, the default split command in the Windows Terminal key bindings is not 'duplicate', so you'll have to rebind that or it splits into a new copy of the profile, and won't look at the current working directory of the existing profile.

Is that a documented process? I have no idea what it even means let alone how to do it, and if the position of the Windows Terminal team is that this commonly requested feature is a solved problem, then I would expect to see some reference to it in the official documentation.

@Plasmadog commented on GitHub (Sep 30, 2021): > Have you set up our PowerShell to output `OSC 9;9` data so that Windows Terminal knows the current working directory? Also, the default `split` command in the Windows Terminal key bindings is not 'duplicate', so you'll have to rebind that or it splits into a new copy of the profile, and won't look at the current working directory of the existing profile. Is that a documented process? I have no idea what it even means let alone how to do it, and if the position of the Windows Terminal team is that this commonly requested feature is a solved problem, then I would expect to see some reference to it in the official documentation.
Author
Owner

@zadjii-msft commented on GitHub (Sep 30, 2021):

It's on the todo list, see https://github.com/MicrosoftDocs/terminal/issues/285. We'd be happy to accept contributions in this space, especially since folks have plenty of different ways of doing this for plenty of different shells already.

@zadjii-msft commented on GitHub (Sep 30, 2021): It's on the todo list, see https://github.com/MicrosoftDocs/terminal/issues/285. We'd be happy to accept contributions in this space, especially since folks have plenty of different ways of doing this for plenty of different shells already.
Author
Owner

@nacitar commented on GitHub (Oct 1, 2021):

[Jan 31 2021] So now that this is working for duplicate tab and split pane w/duplicate...

Umm, is it? I'm on 1.10.2383.0 and both split and duplicate still always open in my home folder. What build should I be using to get this behaviour? (I only care about Powershell tabs)

@Plasmadog

Perhaps you, like me, have previously fixed the silly default behavior that wsl has where it starts you in %USERPROFILE% instead of $HOME, and did something like:
"commandline": "wsl.exe ~ -d Ubuntu"
in your settings.json, and it is thus overriding the default path and forcing to HOME. If you remove the ~ argument there, it will work, provided that this is indeed what you did.

EDIT: I'll leave this here for others, but the "powershell" bit means this isn't what he did.

@nacitar commented on GitHub (Oct 1, 2021): > > [Jan 31 2021] So now that this is working for duplicate tab and split pane w/duplicate... > > Umm, is it? I'm on 1.10.2383.0 and both split and duplicate still always open in my home folder. What build should I be using to get this behaviour? (I only care about Powershell tabs) @Plasmadog Perhaps you, like me, have previously fixed the silly default behavior that wsl has where it starts you in %USERPROFILE% instead of $HOME, and did something like: `"commandline": "wsl.exe ~ -d Ubuntu"` in your settings.json, and it is thus overriding the default path and forcing to HOME. If you remove the ~ argument there, it will work, provided that this is indeed what you did. EDIT: I'll leave this here for others, but the "powershell" bit means this isn't what he did.
Author
Owner

@Inch4Tk commented on GitHub (Oct 1, 2021):

For anyone trying to get it to work with Cmder/Clink.

  1. Add a my_prompt.lua file in the "config/" folder.
  2. Add the following to the file (the "\x1b]9;9;{cwd}\x1b\" part is the osc9;9 sequence, the rest is the default cmder prompt with background color fix, see https://stackoverflow.com/questions/67541540/cmder-wrong-colors-using-windows-terminal)
  3. Use the duplicateTab action in windows terminal
function custom_prompt()
  cwd = clink.get_cwd()
  prompt = "\x1b[1;32;49m{cwd} {git}{hg}{svn} \n\x1b[1;39;49m{lamb} \x1b[0m \x1b]9;9;{cwd}\x1b\\"
  new_value = string.gsub(prompt, "{cwd}", cwd)
  clink.prompt.value = string.gsub(new_value, "{lamb}", "λ")
end

clink.prompt.register_filter(custom_prompt, 1)
@Inch4Tk commented on GitHub (Oct 1, 2021): For anyone trying to get it to work with Cmder/Clink. 1. Add a my_prompt.lua file in the "config/" folder. 2. Add the following to the file (the "\x1b]9;9;{cwd}\x1b\\" part is the osc9;9 sequence, the rest is the default cmder prompt with background color fix, see https://stackoverflow.com/questions/67541540/cmder-wrong-colors-using-windows-terminal) 3. Use the duplicateTab action in windows terminal ``` function custom_prompt() cwd = clink.get_cwd() prompt = "\x1b[1;32;49m{cwd} {git}{hg}{svn} \n\x1b[1;39;49m{lamb} \x1b[0m \x1b]9;9;{cwd}\x1b\\" new_value = string.gsub(prompt, "{cwd}", cwd) clink.prompt.value = string.gsub(new_value, "{lamb}", "λ") end clink.prompt.register_filter(custom_prompt, 1) ```
Author
Owner

@s-celles commented on GitHub (Oct 21, 2021):

As mentionned in https://github.com/microsoft/terminal/issues/10232#issuecomment-948303453 I'm looking for an "out of the box" solution to have duplicated tabs in the same current directory then source tab.

@s-celles commented on GitHub (Oct 21, 2021): As mentionned in https://github.com/microsoft/terminal/issues/10232#issuecomment-948303453 I'm looking for an "out of the box" solution to have duplicated tabs in the same current directory then source tab.
Author
Owner

@TBBle commented on GitHub (Oct 22, 2021):

Since there's no code work left to do here (https://github.com/MicrosoftDocs/terminal/issues/285 and #10232 exist for the remaining work), perhaps it's time to close this ticket?

Alternatively, perhaps one final improvement to bring us closer to "out-of-the-box" would be to make the default for the splitPane action be "duplicate" instead of the currently-unnamed approach, if no profile is provided. That would certainly remove the keybinding overrides I'm carrying, and I think be less-surprising for users who've set up OSC9;9 in their shells.

It's kind-of weird that splitPane takes both a profile and a duplicate flag separately, and the default behaviour is neither of them set, and I don't know which one wins if you set both.

Perhaps that should be a new ticket though, but I don't feel strongly enough about it to create that ticket right now. ^_^ (I also don't use split very often, so am probably not the right person to make a use-case-based change proposal)

@TBBle commented on GitHub (Oct 22, 2021): Since there's no code work left to do here (https://github.com/MicrosoftDocs/terminal/issues/285 and #10232 exist for the remaining work), perhaps it's time to close this ticket? Alternatively, perhaps one final improvement to bring us closer to "out-of-the-box" would be to make the default for the [`splitPane` action](https://docs.microsoft.com/en-au/windows/terminal/customize-settings/actions#split-a-pane) be "duplicate" instead of the currently-unnamed approach, if no `profile` is provided. That would certainly remove the keybinding overrides I'm carrying, and I think be less-surprising for users who've set up `OSC9;9` in their shells. It's kind-of weird that `splitPane` takes both a profile and a duplicate flag separately, and the default behaviour is neither of them set, and I don't know which one wins if you set _both_. Perhaps that should be a new ticket though, but I don't feel strongly enough about it to create that ticket right now. ^_^ (I also don't use split very often, so am probably not the right person to make a use-case-based change proposal)
Author
Owner

@zadjii-msft commented on GitHub (Oct 27, 2021):

I wouldn't totally agree with the assertion that there's no work to do here. IIRC, after the discussion we had in #8214, I think the plan was to do the following:

  • start by implementing OSC9;9 because we can be reasonably sure those are windows paths
  • do a heuristic (guessing) path translation for OSC7. We'd need to know when a profile is a WSL profile, and when it is, we'd translate OSC7 paths back to Windows paths (internally).
    • Non-WSL profiles unfortunately wouldn't have the benefit of the doubt. We deferred coming up with a plan for those for now. Our goal was to better support first-party partners for now, and if someone had a clever solution for git bash, etc, in the future, we'd do that too. (i.e. some sort of setting)

#11625 does a lot of the work for the second point here. that plumbs through the profile source all the way through to the control. Now we'd need to also plumb through some sort of property with the distro name, so we can do the WSL -> Windows translation as well. Fortunately, we could silently upgrade the distro generators to include that property, so that they will add it by default for everyone.

@zadjii-msft commented on GitHub (Oct 27, 2021): I wouldn't totally agree with the assertion that there's no work to do here. IIRC, after the discussion we had in #8214, I think the plan was to do the following: * start by implementing `OSC9;9` because we can be reasonably sure those are windows paths * do a heuristic (guessing) path translation for `OSC7`. We'd need to know when a profile is a WSL profile, and when it is, we'd translate `OSC7` paths back to Windows paths (internally). * Non-WSL profiles unfortunately wouldn't have the benefit of the doubt. We deferred coming up with a plan for those for now. Our goal was to better support first-party partners for now, and if someone had a clever solution for git bash, etc, in the future, we'd do that too. (i.e. some sort of setting) #11625 does a lot of the work for the second point here. that plumbs through the profile source all the way through to the control. Now we'd need to also plumb through some sort of property with the distro name, so we can do the WSL -> Windows translation as well. Fortunately, we could silently upgrade the distro generators to include that property, so that they will add it by default for everyone.
Author
Owner

@TBBle commented on GitHub (Oct 27, 2021):

Ah, fair nuff. I had 100% forgotten about that discussion (2020 wasn't real...), and that OSC 7 has a path forward.

That said, this ticket has accumulated a lot of stuff that either isn't super-relevant after that discussion and its resolution, or is OSC 9;9 specific (or is actually looking for the feature in the other tickets I linked in my earlier post). Since the core "profiles have a CWD" and the easy-to-unconditionally-enable "use the CWD when duplicating tabs" work is done, I would track things like "hook OSC 7 to set the profile CWD when we know it's WSL" as a separate ticket, because that's how I model it mentally.

But it's not my project, so track the work as is best for you and the team to deliver the goods. ^_^

@TBBle commented on GitHub (Oct 27, 2021): Ah, fair nuff. I had 100% forgotten about that discussion (2020 wasn't real...), and that OSC 7 has a path forward. That said, this ticket has accumulated a lot of stuff that either isn't super-relevant after that discussion and its resolution, or is OSC 9;9 specific (or is actually looking for the feature in the other tickets I linked in my earlier post). Since the core "profiles have a CWD" and the easy-to-unconditionally-enable "use the CWD when duplicating tabs" work is done, _I_ would track things like "hook OSC 7 to set the profile CWD when we know it's WSL" as a separate ticket, because that's how I model it mentally. But it's not my project, so track the work as is best for you and the team to deliver the goods. ^_^
Author
Owner

@amzon-ex commented on GitHub (Nov 3, 2021):

Proposed technical implementation details (optional)

Hit the new tab hotkey, the new terminal should then be in the same folder as the previouse.

Any updates on work (possibly) going on regarding this functionality and/or any available workarounds? There is a way to do it like

wt -w 0 -p <profile-name> -d .

But, more elegant ways?

There are so many different topics discussed in this thread that I cannot figure out what to look for.

@amzon-ex commented on GitHub (Nov 3, 2021): > # Proposed technical implementation details (optional) > Hit the new tab hotkey, the new terminal should then be in the same folder as the previouse. Any updates on work (possibly) going on regarding this functionality and/or any available workarounds? There is a way to do it like ``` wt -w 0 -p <profile-name> -d . ``` But, more elegant ways? There are so many different topics discussed in this thread that I cannot figure out what to look for.
Author
Owner

@maximosdrr commented on GitHub (Nov 7, 2021):

This issue should probably be closed, given that an officially supported solution exists in a stable release (unless I'm missing something).

There is support for the OSC 9;9 escape sequence, which when set up, allows you to duplicate a tab in the same directory with ctrl+d. Yet people are still discussing hacky workarounds. I think the issue still being open is potentially confusing people.

If you use bash, put this in your .bashrc:

export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"'

If you use zsh, put this in your .zshrc:

precmd() {
  printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"
}

I use zsh personally so I've only tested the latter, but they should both work.

Thanks, it worked just fine for me <3

@maximosdrr commented on GitHub (Nov 7, 2021): > This issue should probably be closed, given that an officially supported solution exists in a stable release (unless I'm missing something). > > There is support for the OSC 9;9 escape sequence, which when set up, allows you to duplicate a tab in the same directory with ctrl+d. Yet people are still discussing hacky workarounds. I think the issue still being open is potentially confusing people. > > If you use bash, put this in your .bashrc: > > ``` > export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"' > ``` > > If you use zsh, put this in your .zshrc: > > ``` > precmd() { > printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")" > } > ``` > > I use zsh personally so I've only tested the latter, but they should both work. Thanks, it worked just fine for me <3
Author
Owner

@robsonsobral commented on GitHub (Nov 11, 2021):

Weirdly, this stopped working for me.

@robsonsobral commented on GitHub (Nov 11, 2021): Weirdly, this stopped working for me.
Author
Owner

@JelteF commented on GitHub (Nov 11, 2021):

@robsonsobral if you started using Windows 11, then you don't need wslpath anymore if you're using WSL. The normal linux path is what you can provide in the printf now. So this should work:

export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$PWD"
@JelteF commented on GitHub (Nov 11, 2021): @robsonsobral if you started using Windows 11, then you don't need `wslpath` anymore if you're using WSL. The normal linux path is what you can provide in the printf now. So this should work: ``` export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$PWD" ```
Author
Owner

@robsonsobral commented on GitHub (Nov 11, 2021):

Thank you, @JelteF , but I'm not using WSL neither Windows 11.

@robsonsobral commented on GitHub (Nov 11, 2021): Thank you, @JelteF , but I'm not using WSL neither Windows 11.
Author
Owner

@robsonsobral commented on GitHub (Nov 12, 2021):

I'm so dumb! I forgot I've installed Starship! Now, I need to find how to enable things again.

@robsonsobral commented on GitHub (Nov 12, 2021): I'm so dumb! I forgot I've installed [Starship](https://starship.rs/)! Now, I need to find how to enable things again.
Author
Owner

@TBBle commented on GitHub (Nov 12, 2021):

For Starship, what you need will be very similar to this recipe. There, they're passing the current directory (and possibly some other text) into OSC 0, so it's pretty close to what you already have, e.g., in the PowerShell recipe replace

  $host.ui.Write("`e]0; PS> $env:USERNAME@$env:COMPUTERNAME`: $pwd `a")

with

  $host.ui.Write("`e]9;9;$pwd`a")

If you're using bash from cygwin, MSYS2, or Git For Windows, then it'll be very similar to the WSL recipe give above, but use cygpath -w instead of wslpath -m, i.e. replace

    echo -ne "\033]0; $(basename "$PWD") \007"

with

    echo -ne "\033]9;9;$(cygpath -w "$PWD")\007"

And of course, if some awesome person wanted to teach Starship to emit this sequence (and maybe OSC 7 while you're there), that would be at least 20% cooler.

@TBBle commented on GitHub (Nov 12, 2021): For Starship, what you need will be very similar to [this recipe](https://starship.rs/advanced-config/#change-window-title). There, they're passing the current directory (and possibly some other text) into OSC `0`, so it's pretty close to what you already have, e.g., in the PowerShell recipe replace ``` $host.ui.Write("`e]0; PS> $env:USERNAME@$env:COMPUTERNAME`: $pwd `a") ``` with ``` $host.ui.Write("`e]9;9;$pwd`a") ``` If you're using bash from cygwin, MSYS2, or Git For Windows, then it'll be very similar to the WSL recipe give above, but use `cygpath -w` instead of `wslpath -m`, i.e. replace ``` echo -ne "\033]0; $(basename "$PWD") \007" ``` with ``` echo -ne "\033]9;9;$(cygpath -w "$PWD")\007" ``` And of course, if some awesome person wanted to teach Starship to emit this sequence (and maybe OSC 7 while you're there), that would be at least 20% cooler.
Author
Owner

@shivjm commented on GitHub (Nov 12, 2021):

I'm so dumb! I forgot I've installed Starship! Now, I need to find how to enable things again.

In case you’re using PowerShell, this is what works for me to both register the working directory and update the window title:

Invoke-Expression (&starship init powershell)

# https://github.com/starship/starship/issues/2585#issuecomment-821791006
$script:oldPrompt = $function:prompt

function prompt {
    $pp = $pwd.ProviderPath
    Write-Host -NoNewline "$([char]27)]9;9;`"$pp`"$([char]7)"
    & $script:oldPrompt

    $Host.UI.RawUI.WindowTitle = "PS: $(Split-Path $pp -Leaf)"
}
@shivjm commented on GitHub (Nov 12, 2021): > I'm so dumb! I forgot I've installed [Starship](https://starship.rs/)! Now, I need to find how to enable things again. In case you’re using PowerShell, this is what works for me to both register the working directory and update the window title: ```pwsh Invoke-Expression (&starship init powershell) # https://github.com/starship/starship/issues/2585#issuecomment-821791006 $script:oldPrompt = $function:prompt function prompt { $pp = $pwd.ProviderPath Write-Host -NoNewline "$([char]27)]9;9;`"$pp`"$([char]7)" & $script:oldPrompt $Host.UI.RawUI.WindowTitle = "PS: $(Split-Path $pp -Leaf)" } ```
Author
Owner

@robsonsobral commented on GitHub (Nov 12, 2021):

Thank you so much, @TBBle and @shivjm !

Couldn't we add all these recipes to docs?

@robsonsobral commented on GitHub (Nov 12, 2021): Thank you so much, @TBBle and @shivjm ! Couldn't we add all these recipes to docs?
Author
Owner

@shivjm commented on GitHub (Nov 12, 2021):

Couldn't we add all these recipes to docs?

I’d certainly love to see that! Note that the just-released Starship v1.0.0 supports a PowerShell pre-command. I adapted the example from the website:

function Invoke-Starship-PreCommand {
    $pp = $pwd.ProviderPath
    Write-Host -NoNewline "`e]9;9;`"$pp`"`a"
    $host.ui.Write("`e]0; PS> $(Split-Path $pp -Leaf) `a")
}

Invoke-Expression (&starship init powershell)
@shivjm commented on GitHub (Nov 12, 2021): > Couldn't we add all these recipes to docs? I’d certainly love to see that! Note that the just-released Starship v1.0.0 supports a PowerShell pre-command. I adapted [the example from the website](https://starship.rs/advanced-config/#change-window-title): ```powershell function Invoke-Starship-PreCommand { $pp = $pwd.ProviderPath Write-Host -NoNewline "`e]9;9;`"$pp`"`a" $host.ui.Write("`e]0; PS> $(Split-Path $pp -Leaf) `a") } Invoke-Expression (&starship init powershell) ```
Author
Owner

@TBBle commented on GitHub (Nov 13, 2021):

Couldn't we add all these recipes to docs?

The docs don't exist yet, there's a ticket at https://github.com/MicrosoftDocs/terminal/issues/285 to put something together, but it's not trivial, or at least no one's attempted it yet, AFAIK, due to the wide variety of shells, prompt automation scripts, and general system setups people use.

@TBBle commented on GitHub (Nov 13, 2021): > Couldn't we add all these recipes to docs? The docs don't exist yet, there's a ticket at https://github.com/MicrosoftDocs/terminal/issues/285 to put something together, but it's not trivial, or at least no one's attempted it yet, AFAIK, due to the wide variety of shells, prompt automation scripts, and general system setups people use.
Author
Owner

@shinebayar-g commented on GitHub (Dec 6, 2021):

Thanks to above users. This works on Windows 10/11 + Zsh.

# ~/.zshrc
precmd() {
  printf "\e]9;9;%s\e\\" "$PWD"
}
@shinebayar-g commented on GitHub (Dec 6, 2021): Thanks to above users. This works on Windows 10/11 + Zsh. ```zsh # ~/.zshrc precmd() { printf "\e]9;9;%s\e\\" "$PWD" } ```
Author
Owner

@nova77 commented on GitHub (Dec 30, 2021):

Not sure what happened, but with Windows Terminal (Ubuntu + bash) 1.11.3471.0 the "OSC 9;9 escape" no longer seem to be working.
UPDATE: it seems to be an issue with oh-my-posh.
UPDATE2: this has been fixed in https://github.com/JanDeDobbeleer/oh-my-posh/pull/1516. If you suffer from the same problem, get the latest oh-my-posh binary (thanks Inu!)

@nova77 commented on GitHub (Dec 30, 2021): Not sure what happened, but with Windows Terminal (Ubuntu + bash) 1.11.3471.0 the "OSC 9;9 escape" no longer seem to be working. UPDATE: it seems to be an issue with oh-my-posh. UPDATE2: this has been fixed in https://github.com/JanDeDobbeleer/oh-my-posh/pull/1516. If you suffer from the same problem, get the latest oh-my-posh binary (thanks [Inu](https://github.com/lnu)!)
Author
Owner

@nacitar commented on GitHub (Jan 6, 2022):

Not sure what happened, but with Windows Terminal (Ubuntu + bash) 1.11.3471.0 the "OSC 9;9 escape" no longer seem to be working. UPDATE: it seems to be an issue with oh-my-posh. UPDATE2: this has been fixed in JanDeDobbeleer/oh-my-posh#1516. If you suffer from the same problem, get the latest oh-my-posh binary (thanks Inu!)

Mine stopped working as well, and I wasn't sure what was amiss... but MANY examples use $(wslpath -m "$PWD") or equivalent, and indeed I had implemented this feature using that approach as well. If you look at the change made by oh-my-posh, it simply started using $PWD without "wslpath -m" processing it. Removing this from my own fixed the issue as well.

I don't know that I'd call this a bug in oh-my-posh, it WORKED previously with this approach, so there was some sort of behavioral change in windows terminal along the way too...

my own fix commit

@nacitar commented on GitHub (Jan 6, 2022): > Not sure what happened, but with Windows Terminal (Ubuntu + bash) 1.11.3471.0 the "OSC 9;9 escape" no longer seem to be working. UPDATE: it seems to be an issue with oh-my-posh. UPDATE2: this has been fixed in [JanDeDobbeleer/oh-my-posh#1516](https://github.com/JanDeDobbeleer/oh-my-posh/pull/1516). If you suffer from the same problem, get the latest oh-my-posh binary (thanks [Inu](https://github.com/lnu)!) Mine stopped working as well, and I wasn't sure what was amiss... but MANY examples use $(wslpath -m "$PWD") or equivalent, and indeed I had implemented this feature using that approach as well. If you look at the change made by oh-my-posh, it simply started using $PWD without "wslpath -m" processing it. Removing this from my own fixed the issue as well. I don't know that I'd call this a bug in oh-my-posh, it WORKED previously with this approach, so there was some sort of behavioral change in windows terminal along the way too... [my own fix commit](https://github.com/nacitar/bashrc/commit/0e39d87abccf24a7ca44b7ec79ff4c95a8a5431a)
Author
Owner

@dotnetCarpenter commented on GitHub (Feb 9, 2022):

In case you missed it, there is a tutorial on how to open a new tab/split pane in the same directory at https://docs.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory

As far as I can tell, the fix does not involve OSC 7 but I am guessing that 90% of people here are more interested in opening a new terminal with the same directory, than the technical details. In that regard, I think this issue can be closed as solved.

I have followed the tutorial and it is working in my WSL2 Ubuntu setup.

@dotnetCarpenter commented on GitHub (Feb 9, 2022): In case you missed it, there is a tutorial on how to open a new tab/split pane in the same directory at https://docs.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory As far as I can tell, the fix does not involve OSC 7 but I am guessing that 90% of people here are more interested in opening a new terminal with the same directory, than the technical details. In that regard, I think this issue can be closed as solved. I have followed the tutorial and it is working in my WSL2 Ubuntu setup.
Author
Owner

@zadjii-msft commented on GitHub (Feb 9, 2022):

In that regard, I think this issue can be closed as solved

Meh, in my opinion, I'd like to keep it open. As I discussed, I do still want to make this sequence work as well.

THAT BEING SAID

Yea, basically everything you could want from OSC7 will work just as well with OSC9;9. The difference is absolutely technical nitpicking 😄

for the folks in the back

Go read this guide: Opening a tab/pane in the same directory in Windows Terminal

thanks to everyone in this thread who's recipes I was able to use to help write that ☺️

@zadjii-msft commented on GitHub (Feb 9, 2022): > In that regard, I think this issue can be closed as solved Meh, in my opinion, I'd like to keep it open. [As I discussed](https://github.com/microsoft/terminal/issues/3158#issuecomment-952839907), I do still want to make this sequence work as well. **THAT BEING SAID** Yea, basically everything you could want from OSC7 will work just as well with OSC9;9. The difference is absolutely technical nitpicking 😄 _for the folks in the back_ # Go read this guide: [Opening a tab/pane in the same directory in Windows Terminal](https://docs.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory) _thanks to everyone in this thread who's recipes I was able to use to help write that ☺️_
Author
Owner

@nephewtom commented on GitHub (Feb 11, 2022):

Go read this guide: Opening a tab/pane in the same directory in Windows Terminal

thanks to everyone in this thread who's recipes I was able to use to help write that ☺️

Ok, I am a folk in the back...
I tried those solutions for CMD and WSL, and only the WSL one works for me.
I am following exactly the instructions steps for Command Prompt: cmd.exe :

This works:
set PROMPT=$e]9;9;$P$e\%PROMPT%

But this one fails:
setx PROMPT %PROMPT%

So, I quoted it:
image

But still not getting duplicated tabs on the same path, neither split panes (with splitMode duplicate) on the same path.
Am I forgetting something?

Best Regards.

@nephewtom commented on GitHub (Feb 11, 2022): > > # Go read this guide: [Opening a tab/pane in the same directory in Windows Terminal](https://docs.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory) > _thanks to everyone in this thread who's recipes I was able to use to help write that ☺️_ Ok, I am a folk in the back... I tried those solutions for CMD and WSL, and only the WSL one works for me. I am following exactly the instructions steps for **Command Prompt: cmd.exe** : This works: `set PROMPT=$e]9;9;$P$e\%PROMPT% ` But this one fails: `setx PROMPT %PROMPT% ` So, I quoted it: ![image](https://user-images.githubusercontent.com/2485147/153681788-da4e61ae-bde1-488a-a73f-585da984eb91.png) But still not getting duplicated tabs on the same path, neither split panes (with splitMode duplicate) on the same path. Am I forgetting something? Best Regards.
Author
Owner

@TBBle commented on GitHub (Feb 11, 2022):

I'm pretty sure clink is your problem here, as without it, both commands worked for me as per the instructions. Somewhere in the hidden comments of this ticket, there was a note that clink was interfering with the relevant ANSI codes, and I don't believe it was ever resolved.

My guess would be that it's eating the ANSI codes, so the OSC command is never seen by Windows Terminal.

For the setx issue, it's probably because a " " has ended up in your prompt env-var (I would guess that clink lives in your prompt already). So the instructions should be updated to quote the %PROMPT% as you have done. I was able to reproduce this problem by manually putting a space into my local PROMPT var, so it's not a clink problem per-se, but I guess in your case, clink is why the space is there, even though it's not visible in the displayed prompt.

You could echo %PROMPT% to confirm this.

Ah, someone did get it working with clink in the end: https://github.com/microsoft/terminal/issues/3158#issuecomment-932529090. Looks like you need to do the config in clink's settings, as it's probably using the PROMPT env-var itself.

Ah, yes. Per the docs

Before Clink displays the prompt it filters the prompt through Lua so that the prompt can be customized.

and

To help with [readline], Clink automatically detects most standard ANSI escape codes (and most of ConEmu's non-standard escape codes) and the BEL character (^G, audible bell) and surrounds them with \001 (^A) and \002 (^B) characters.

So yeah, clink is destructively (in our case) filtering the PROMPT env-var, but per the fix above, doesn't damage ANSI codes in the prompt when done in Lua.

Edit: Note, those doc links turn out to be from a fork of Clink. The original version hasn't had a release since 2017, nor even a commit since 2018, so it may be that the forked version I got those docs from does work correctly (i.e. not mangle the ANSI codes) even if using %PROMPT% rather than Lua.

Last edit: Yeah, turns out to be a reported issue in the 0.4.9 version of clink, and fixed in the forked version.

@TBBle commented on GitHub (Feb 11, 2022): I'm pretty sure `clink` is your problem here, as without it, both commands worked for me as per the instructions. Somewhere in the hidden comments of this ticket, [there was a note that clink was interfering with the relevant ANSI codes](https://github.com/microsoft/terminal/issues/3158#issuecomment-802619821), and [I don't believe it was ever resolved](https://github.com/microsoft/terminal/issues/3158#issuecomment-803197298). My guess would be that it's eating the ANSI codes, so the OSC command is never seen by Windows Terminal. For the `setx` issue, it's probably because a " " has ended up in your prompt env-var (I would guess that clink lives in your prompt already). [So the instructions should be updated to quote the `%PROMPT%` as you have done](https://github.com/MicrosoftDocs/terminal/pull/502). I was able to reproduce this problem by manually putting a space into my local `PROMPT` var, so it's not a clink problem per-se, but I guess in _your_ case, `clink` is why the space is there, even though it's not visible in the displayed prompt. You could `echo %PROMPT%` to confirm this. Ah, someone did get it working with clink in the end: https://github.com/microsoft/terminal/issues/3158#issuecomment-932529090. Looks like you need to do the config in clink's settings, as it's probably using the `PROMPT` env-var itself. Ah, yes. [Per the docs](https://chrisant996.github.io/clink/clink.html#customizing-the-prompt) > Before Clink displays the prompt it filters the prompt through [Lua](https://chrisant996.github.io/clink/clink.html#extending-clink) so that the prompt can be customized. and > To help with [readline], Clink automatically detects most standard ANSI escape codes (and most of ConEmu's non-standard escape codes) and the BEL character (^G, audible bell) and surrounds them with \001 (^A) and \002 (^B) characters. So yeah, clink is destructively (in our case) filtering the `PROMPT` env-var, but per the fix above, doesn't damage ANSI codes in the prompt when done in Lua. Edit: Note, those doc links turn out to be from [a fork of Clink](https://github.com/chrisant996/clink). The [original version](https://github.com/mridgers/clink) hasn't had a release since 2017, nor even a commit since 2018, so it may be that the forked version I got those docs from _does_ work correctly (i.e. not mangle the ANSI codes) even if using `%PROMPT%` rather than Lua. Last edit: Yeah, turns out to be [a reported issue](https://github.com/mridgers/clink/issues/487) in the 0.4.9 version of clink, and fixed in the forked version.
Author
Owner

@nephewtom commented on GitHub (Feb 12, 2022):

Ok, that makes sense, and clink came to my mind when it didn't work.
Thanks for taking the time to answer. 🙏
I am using clink's fork now and everything works.
Hurrah! 🥇

@nephewtom commented on GitHub (Feb 12, 2022): Ok, that makes sense, and clink came to my mind when it didn't work. Thanks for taking the time to answer. 🙏 I am using clink's fork now and everything works. Hurrah! 🥇
Author
Owner

@falkenhawk commented on GitHub (Feb 18, 2022):

But this one fails: setx PROMPT %PROMPT%

This worked for me:

setx PROMPT "%PROMPT%"
@falkenhawk commented on GitHub (Feb 18, 2022): > But this one fails: `setx PROMPT %PROMPT% ` This worked for me: ``` setx PROMPT "%PROMPT%" ```
Author
Owner

@MonstraG commented on GitHub (Mar 4, 2022):

It seems I'm also one of the folks in the back.

Followed the guide, were not able to just create the profile file with notepad $PROFILE.AllUsersAllHosts as for some reason, even elevated notepad cannot save things there, in WindowsApps\ps... folder (or elevated terminal doesn't start notepad elevated?).

Had to settle for $PROFILE.CurrentUserAllHosts, and it did sort of work, with a side effect.

When opening a new tab in WSL, instead of username@PC-NAME:~, I get PS Microsoft.PowerShell.Core\FileSystem::\\wsl.localhost\Ubuntu-20.04\home\username, as current path, which I guess is technically correct, but not what I want. Any solutions to that?

@MonstraG commented on GitHub (Mar 4, 2022): It seems I'm also one of the folks in the back. Followed the guide, were not able to just create the profile file with `notepad $PROFILE.AllUsersAllHosts` as for some reason, even elevated notepad cannot save things there, in `WindowsApps\ps...` folder (or elevated terminal doesn't start notepad elevated?). Had to settle for `$PROFILE.CurrentUserAllHosts`, and it did sort of work, with a side effect. When opening a new tab in WSL, instead of `username@PC-NAME:~`, I get `PS Microsoft.PowerShell.Core\FileSystem::\\wsl.localhost\Ubuntu-20.04\home\username`, as current path, which I guess is technically correct, but not what I want. Any solutions to that?
Author
Owner

@TBBle commented on GitHub (Mar 4, 2022):

Yeah, $PROFILE.AllUsersAllHosts seems like the wrong directory, that'll be in the PowerShell installation directory; generally "AllUsers" is only for system admins to set (depending on how you installed PowerShell, it might be limited to TrustedInstaller). so for personal settings you want "CurrentUser" versions.

That said, I put all these settings directly in $PROFILE and it works fine for me, since I probably don't want these settings to apply to, e.g. VSCode's integrated terminal. (Or maybe I do, if they also support OSC;9;9... Huh, I need to think about that.)

@TBBle commented on GitHub (Mar 4, 2022): Yeah, `$PROFILE.AllUsersAllHosts` seems like the wrong directory, that'll be in the PowerShell installation directory; generally "AllUsers" is only for system admins to set (depending on how you installed PowerShell, it might be limited to `TrustedInstaller`). so for personal settings you want "CurrentUser" versions. That said, I put all these settings directly in `$PROFILE` and it works fine for me, since I probably don't want these settings to apply to, e.g. VSCode's integrated terminal. (Or maybe I do, if they also support `OSC;9;9`... Huh, I need to think about that.)
Author
Owner

@JahzVH commented on GitHub (May 9, 2022):

This works for Git Bash
export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(cygpath -w "$PWD")"'

@JahzVH commented on GitHub (May 9, 2022): This works for Git Bash `export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(cygpath -w "$PWD")"'`
Author
Owner

@RedFour commented on GitHub (May 17, 2022):

The guide for WSL does not work for me.

I'm on Windows 11 using WSL 2 and oh-my-posh.

I've added the following to the end of my bashrc file

PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND; "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"'

I get the following error when I refresh my terminal:

-bash: PROMPT_COMMAND: line 0: syntax error near unexpected token `;'
-bash: PROMPT_COMMAND: line 0: `_omp_hook; ; printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"'
@RedFour commented on GitHub (May 17, 2022): The guide for WSL does not work for me. I'm on Windows 11 using WSL 2 and oh-my-posh. I've added the following to the end of my bashrc file ``` PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND; "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"' ``` I get the following error when I refresh my terminal: ``` -bash: PROMPT_COMMAND: line 0: syntax error near unexpected token `;' -bash: PROMPT_COMMAND: line 0: `_omp_hook; ; printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"' ```
Author
Owner

@TBBle commented on GitHub (May 17, 2022):

@RedFour

I guess that the problem is that whatever adds _omp_hook to PROMPT_COMMAND earlier included a trailing semicolon, and the guide's command assumes that an existing PROMPT_COMMAND doesn't do that, so it adds one before its new command, and this double-semicolon with no command between then is what bash's objecting to.

So remove the semicolon after PROMPT_COMMAND, i.e.

PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"'

I reckon this is a bug in oh-my-posh's bash support, because it assumes PROMPT_COMMAND is already set and blindly adds the semicolon.

You'd also find if you put the unchanged PROMPT_COMMAND line from the Windows Terminal docs before the oh-my-posh setup line in your .bashrc, it works fine, as the Windows Terminal docs' command handles "No PROMPT_COMMAND set" correctly, and oh-my-posh will then prepend to that correctly.

All that said, oh-my-posh has built-in OSC9;9 support, so you probably don't need this command at all, just set osc99 to true in your config and it'll include it without needing to modify your bash config (or anywhere else you're using oh-my-posh).

@TBBle commented on GitHub (May 17, 2022): @RedFour I _guess_ that the problem is that whatever adds `_omp_hook` to `PROMPT_COMMAND` earlier included a trailing semicolon, and the guide's command assumes that an existing `PROMPT_COMMAND` doesn't do that, so it adds one before its new command, and this double-semicolon with no command between then is what bash's objecting to. So remove the semicolon after `PROMPT_COMMAND`, i.e. ``` PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"' ``` I reckon this is a bug in [oh-my-posh's bash support](https://github.com/JanDeDobbeleer/oh-my-posh/blob/main/src/shell/scripts/omp.bash#L34), because it _assumes_ `PROMPT_COMMAND` is already set and blindly adds the semicolon. You'd also find if you put the unchanged `PROMPT_COMMAND` line from the Windows Terminal docs _before_ the oh-my-posh setup line in your .bashrc, it works fine, as the Windows Terminal docs' command handles "No PROMPT_COMMAND set" correctly, and oh-my-posh will then prepend to that correctly. All that said, oh-my-posh has built-in OSC9;9 support, so you probably don't need this command at all, [just set `osc99` to `true` in your config](https://ohmyposh.dev/docs/configuration/overview#general-settings) and it'll include it without needing to modify your bash config (or anywhere else you're using oh-my-posh).
Author
Owner

@RedFour commented on GitHub (May 17, 2022):

Thanks @TBBle for explaining how to fix it.

After following your suggestions, I had to do the following changes to get it working for me.

  1. I had to remove wslpath -w from that line for bashrc file:
PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND "}'printf "\e]9;9;%s\e\\" "$PWD"'
  1. I had to change my Windows Terminal profile settings.
    Command line to use wsl.exe instead of Ubuntu.exe
    Starting directory to \\wsl.localhost\Ubuntu\home\<username>

https://github.com/microsoft/WSL/issues/6995 has more information on Windows Terminal unable to start in a linux path.

In the end I used the osc99 option in my oh-my-posh config instead of adding that extra line in the bashrc. Changing the Windows Terminal profile setting was also necessary with the oh-my-posh config option.

@RedFour commented on GitHub (May 17, 2022): Thanks @TBBle for explaining how to fix it. After following your suggestions, I had to do the following changes to get it working for me. 1. I had to remove `wslpath -w` from that line for bashrc file: ``` PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND "}'printf "\e]9;9;%s\e\\" "$PWD"' ``` 2. I had to change my Windows Terminal profile settings. **Command line** to use `wsl.exe` instead of `Ubuntu.exe` **Starting directory** to `\\wsl.localhost\Ubuntu\home\<username>` https://github.com/microsoft/WSL/issues/6995 has more information on Windows Terminal unable to start in a linux path. In the end I used the osc99 option in my oh-my-posh config instead of adding that extra line in the bashrc. Changing the Windows Terminal profile setting was also necessary with the oh-my-posh config option.
Author
Owner

@zadjii-msft commented on GitHub (May 17, 2022):

2. Command line to use wsl.exe instead of Ubuntu.exe

Ah yes, that's something we need to work through with Canonical. Ubuntu.exe seemingly totally disregards the startingDirectory, which helps power this.

@zadjii-msft commented on GitHub (May 17, 2022): > 2\. **Command line** to use `wsl.exe` instead of `Ubuntu.exe` Ah yes, that's something we need to work through with Canonical. `Ubuntu.exe` seemingly totally disregards the `startingDirectory`, which helps power this.
Author
Owner

@dotnetCarpenter commented on GitHub (May 18, 2022):

Dang! For some reason the solution from https://docs.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory stopped working in Windows Terminal 1.13.10983.0 (or before). It's working for window splitting (panes) but not for new tabs.

Using the Ubuntu image.

@dotnetCarpenter commented on GitHub (May 18, 2022): Dang! For some reason the solution from https://docs.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory stopped working in Windows Terminal 1.13.10983.0 (or before). It's working for window splitting (panes) but not for new tabs. _Using the Ubuntu image._
Author
Owner

@TBBle commented on GitHub (May 19, 2022):

Are you using "new tab" or "duplicate tab". The former doesn't carry the working directory over.

@TBBle commented on GitHub (May 19, 2022): Are you using "new tab" or "duplicate tab". The former doesn't carry the working directory over.
Author
Owner

@tristanbarcelon commented on GitHub (May 26, 2022):

Are you using "new tab" or "duplicate tab". The former doesn't carry the working directory over.

I'm using new tab. Turns out the profile needs to properly escape single slash on Server 2022, something I didn't have to do in Windows 10/11. Fix mentioned by nuixtech fixed the issue. I have terminal installed on Windows 11 and Server 2022 (using the win10 msixbundle). This is how Ubuntu-20.04 profile looks on Windows 11.

image

On Server 2022, this is how it looks.

image
@tristanbarcelon commented on GitHub (May 26, 2022): > Are you using "new tab" or "duplicate tab". The former doesn't carry the working directory over. I'm using new tab. Turns out the profile needs to properly escape single slash on Server 2022, something I didn't have to do in Windows 10/11. Fix mentioned by [nuixtech]( https://twitter.com/nunixtech/status/1529777613979492354?s=20&t=UO1Lrv6paWpLx2sNhWsDgw) fixed the issue. I have terminal installed on Windows 11 and Server 2022 (using the win10 msixbundle). This is how Ubuntu-20.04 profile looks on Windows 11. <img width="856" alt="image" src="https://user-images.githubusercontent.com/5810165/170541834-b9c60ec5-b339-42eb-a34a-33750e25affb.png"> On Server 2022, this is how it looks. <img width="856" alt="image" src="https://user-images.githubusercontent.com/5810165/170542329-a9bd809e-3b4e-42a1-bd70-481e302ff11f.png">
Author
Owner

@TBBle commented on GitHub (May 27, 2022):

I don't understand how that makes a difference (because that path should be processed by Terminal, well before WSL sees it), but it might be worth opening as a separate specific bug report so it can be fixed in the code that auto-generates the profile, or if there's a bug elsewhere in Terminal causing this issue, that can be fixed instead.

@TBBle commented on GitHub (May 27, 2022): I don't understand how that makes a difference (because that path should be processed by Terminal, well before WSL sees it), but it might be worth opening as a separate specific bug report so it can be fixed in the code that auto-generates the profile, or if there's a bug elsewhere in Terminal causing this issue, that can be fixed instead.
Author
Owner

@codtiger commented on GitHub (Oct 13, 2022):

Are there any updates on this ? I managed to make it work for "duplicate tab" by changing ubuntu.exe to wsl.exe -d Ubuntu in the profile section but it still does not work on new tab:(

@codtiger commented on GitHub (Oct 13, 2022): Are there any updates on this ? I managed to make it work for "duplicate tab" by changing `ubuntu.exe` to `wsl.exe -d Ubuntu` in the profile section but it still does not work on new tab:(
Author
Owner

@InvisibleProgrammer commented on GitHub (Jan 6, 2023):

@codtiger , thank you for your answer. It saved me :D

One additional detail: with default settings, when I change ubuntu.exe to wsl.exe -d Ubuntu, the starting directory becomes the /mnt/c/WINDOWS/system32. To fix that, I've changed starting directory to ~:

                "startingDirectory": "~",
@InvisibleProgrammer commented on GitHub (Jan 6, 2023): @codtiger , thank you for your answer. It saved me :D One additional detail: with default settings, when I change `ubuntu.exe` to `wsl.exe -d Ubuntu`, the starting directory becomes the `/mnt/c/WINDOWS/system32`. To fix that, I've changed starting directory to `~`: ```json "startingDirectory": "~", ```
Author
Owner

@nileshgr commented on GitHub (Mar 13, 2023):

@codtiger @tristanbarcelon was irritated by this problem, thanks for the suggestions! 😄

@nileshgr commented on GitHub (Mar 13, 2023): @codtiger @tristanbarcelon was irritated by this problem, thanks for the suggestions! 😄
Author
Owner

@alkorlos commented on GitHub (May 27, 2023):

Good day!

I am using:
Windows 10 22H2
Windows Terminal 1.16.10261.0
Ubuntu 22.04.2 LTS

Following this instruction Tutorial: Opening a tab or pane in the same directory in Windows Terminal added to .bash_profile line

PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND; "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"'

After that, Windows Terminal began to remember directories, thanks!

But other problems arose, for example, nvm broke
Command 'nvm' not found

Adding these lines to .bash_profile helped fix this problem

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

I decided to write this comment because neither in the article Tutorial: Opening a tab or pane in the same directory in Windows Terminal nor in this issue did I see that adding this line

PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND; "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"'

to .bash_profile may cause additional problems.

nvm is the first thing I tried to use, most likely there are more such problems. Did I do something wrong when I edited .bash_profile? Or is it known that adding this line breaks paths or something like that?

@alkorlos commented on GitHub (May 27, 2023): Good day! I am using: Windows 10 22H2 Windows Terminal 1.16.10261.0 Ubuntu 22.04.2 LTS Following this instruction [Tutorial: Opening a tab or pane in the same directory in Windows Terminal](https://learn.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory) added to `.bash_profile` line ```bash PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND; "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"' ``` After that, Windows Terminal began to remember directories, thanks! But other problems arose, for example, nvm broke `Command 'nvm' not found` Adding these lines to `.bash_profile` helped fix this problem ```bash export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion ``` I decided to write this comment because neither in the article [Tutorial: Opening a tab or pane in the same directory in Windows Terminal](https://learn.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory) nor in this issue did I see that adding this line ```bash PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND; "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"' ``` to `.bash_profile` may cause additional problems. nvm is the first thing I tried to use, most likely there are more such problems. Did I do something wrong when I edited `.bash_profile`? Or is it known that adding this line breaks paths or something like that?
Author
Owner

@TBBle commented on GitHub (May 27, 2023):

That line definitely shouldn't have broken stuff you described. It's not obvious how nvm was working, but my best-guess is that you actually newly created the .bash_profile, and now bash is running that instead of some other file, like .profile, and your existing NVM setup was in that. This site suggests that this is the case, but I haven't looked myself. This answer suggests that maybe it's .bashrc that is no longer being read, but that's older than Ubuntu 22.04.

If that's the case, then you could either add the PROMPT_COMMAND to .profile (or whatever it is) and delete the newly-created .bash_profile, or add something like source ~/.profile to the start of your .bash_profile.

@TBBle commented on GitHub (May 27, 2023): That line definitely shouldn't have broken stuff you described. It's not obvious how nvm was working, but my best-guess is that you actually newly created the `.bash_profile`, and now bash is running that instead of some other file, like `.profile`, and your existing NVM setup was in that. [This site](https://fostips.com/add-to-path-ubuntu/#rb-bash_profile-bash_login-profile) suggests that this is the case, but I haven't looked myself. [This answer](https://superuser.com/a/1546531) suggests that maybe it's `.bashrc` that is no longer being read, but that's older than Ubuntu 22.04. If that's the case, then you could either add the `PROMPT_COMMAND` to `.profile` (or whatever it is) and delete the newly-created `.bash_profile`, or add something like `source ~/.profile` to the start of your `.bash_profile`.
Author
Owner

@alkorlos commented on GitHub (May 27, 2023):

Thank you!

Important clarification — I did not do anything unusual, on the contrary, yesterday I performed a clean installation of Ubuntu 22.04.2 LTS.
After a clean install, I installed only nvm. After that of the files listed here: .bash_profile, .bash_login, .profile, only exists .profile. File .bash_profile I created, as it was written here. In addition to the problem with nvm, there was a problem with colors, but I did not betray this.

Indeed, adding PROMPT_COMMAND to the .profile and deleting .bash_profile helped.

Thanks again! Cheers!

@alkorlos commented on GitHub (May 27, 2023): Thank you! Important clarification — I did not do anything unusual, on the contrary, yesterday I performed a clean installation of `Ubuntu 22.04.2 LTS`. After a clean install, I installed only `nvm`. After that of the files listed [here](https://fostips.com/add-to-path-ubuntu/#rb-bash_profile-bash_login-profile): `.bash_profile`, `.bash_login`, `.profile`, only exists `.profile`. File `.bash_profile` I created, as it was written [here](https://learn.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory). In addition to the problem with `nvm`, there was a problem with [colors](https://superuser.com/questions/1545052/wsl2-no-longer-starting-with-bash-colors/1546531#1546531), but I did not betray this. Indeed, adding `PROMPT_COMMAND` to the `.profile` and deleting `.bash_profile` helped. Thanks again! Cheers!
Author
Owner

@TBBle commented on GitHub (May 28, 2023):

Okay, so it might make sense to add a note to the docs along the lines of "If .bash_profile does not exist, but .profile does, add the line there instead", to avoid confusion for the default Ubuntu 22.04 setup and any similar situations.

The current instructions do not say to create the file, but in this situation, it's a reasonable guess that happens to do the wrong thing.

I note the MINGW instructions use .bashrc instead, which won't have this problem. That's maybe a better choice, as it's specifically for interactive shells, IIUC.

@TBBle commented on GitHub (May 28, 2023): Okay, so it might make sense to add a note to the docs along the lines of "If `.bash_profile` does not exist, but `.profile` does, add the line there instead", to avoid confusion for the default Ubuntu 22.04 setup and any similar situations. The current instructions do not say to create the file, but in this situation, it's a reasonable guess that happens to do the wrong thing. I note the MINGW instructions use `.bashrc` instead, which won't have this problem. That's maybe a better choice, as it's specifically for interactive shells, IIUC.
Author
Owner

@daviewales commented on GitHub (Jun 9, 2023):

The creator of powerlevel10k has created a Zsh plugin for this.
He claims it "...achieves the same thing as the code snippet in the official Windows Terminal documentation but with fewer bugs and better performance".

Linking it here for visibility:
https://github.com/romkatv/windows-terminal-zsh-integration

@daviewales commented on GitHub (Jun 9, 2023): The creator of powerlevel10k has created a Zsh plugin for this. He claims it "...achieves the same thing as the [code snippet](https://learn.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory#zsh) in the official Windows Terminal documentation but with fewer bugs and better performance". Linking it here for visibility: https://github.com/romkatv/windows-terminal-zsh-integration
Author
Owner

@TBBle commented on GitHub (Jun 9, 2023):

I don't know the zsh ecosystem, but is that plugin widely-suitable-enough to be added as a preferred option to the Windows Terminal docs?

It's clearly too-long to inline into the docs (and is doing a lot more than the one-liner does, such as caching, some TMUX-specific magic and for some reason using wslpath -am and mangling the output rather than wslpath -w), but if general zsh users can do an extra git clone over the current docs and get a much better result, then it seems like an easy win to me.

If zsh plugin managers are commonly used, then that's even better, IMHO.

The main concern I envisage is making the docs dependent on an external site.

@TBBle commented on GitHub (Jun 9, 2023): I don't know the zsh ecosystem, but is that plugin widely-suitable-enough to be added as a preferred option to the Windows Terminal docs? It's clearly too-long to inline into the docs (and is doing a _lot_ more than the one-liner does, such as caching, some TMUX-specific magic and for some reason using `wslpath -am` and mangling the output rather than `wslpath -w`), but if general zsh users can do an extra `git clone` over the current docs and get a much better result, then it seems like an easy win to me. If zsh plugin managers are commonly used, then that's even better, IMHO. The main concern I envisage is making the docs dependent on an external site.
Author
Owner

@Lajdre commented on GitHub (Jul 6, 2023):

In regard to comments made by alkorlos and TBBle.
This might help somebody in the future:

  • TL;DR:
    • remove potential "cd ~" or "cd ~/my-preferred-starting-dir" from .bashrc
    • remove .bash_profile if using .profile (then move PROMPT_COMMAND to .profile or .bashrc)
  1. On a few forums on the Internet it is advised to put "cd ~" or some variation of this in .bashrc to change the starting directory. This can be overlooked and will obviously make PROMPT_COMMAND not produce the desired result.

  2. If you did not have .bash_profile and you created it, as it was written here, PROMPT_COMMAND will work, given you put it in .bash_profile, however this will also "skip" your "config" (.bashrc and .profile). .bashrc is not "loaded" by default. .profile is responsible for that, but it is also not always "loaded".

First few lines of .profile:

# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.

Solutions:

  • copy the contents of .profile to .bash_profile. e.g.
...
# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
	. "$HOME/.bashrc"
    fi
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/.local/bin" ] ; then
    PATH="$HOME/.local/bin:$PATH"
fi
...

or

  • remove .bash_profile and put PROMPT_COMMAND in either .profile or .bashrc
@Lajdre commented on GitHub (Jul 6, 2023): In regard to comments made by alkorlos and TBBle. This might help somebody in the future: - TL;DR: * remove potential "cd ~" or "cd ~/my-preferred-starting-dir" from ```.bashrc``` * remove ```.bash_profile``` if using ```.profile``` (then move PROMPT_COMMAND to ```.profile``` or ```.bashrc```) 1. On a few forums on the Internet it is advised to put "cd ~" or some variation of this in ```.bashrc``` to change the starting directory. This can be overlooked and will obviously make PROMPT_COMMAND not produce the desired result. 2. If you did not have ```.bash_profile``` and you created it, as it was written [here](https://learn.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory), PROMPT_COMMAND will work, given you put it in ```.bash_profile```, however this will also "skip" your "config" (```.bashrc``` and ```.profile```). ```.bashrc``` is not "loaded" by default. ```.profile``` is responsible for that, but it is also not always "loaded". First few lines of ```.profile```: ``` # ~/.profile: executed by the command interpreter for login shells. # This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login # exists. ``` Solutions: * copy the contents of ```.profile``` to ```.bash_profile```. e.g. ``` ... # if running bash if [ -n "$BASH_VERSION" ]; then # include .bashrc if it exists if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc" fi fi # set PATH so it includes user's private bin if it exists if [ -d "$HOME/bin" ] ; then PATH="$HOME/bin:$PATH" fi # set PATH so it includes user's private bin if it exists if [ -d "$HOME/.local/bin" ] ; then PATH="$HOME/.local/bin:$PATH" fi ... ``` or * remove ```.bash_profile``` and put PROMPT_COMMAND in either ```.profile``` or ```.bashrc```
Author
Owner

@deadcoder0904 commented on GitHub (Jan 16, 2024):

why is this not implemented even 5 years later?

i don't think this is unreasonable for any web developer working on a project that requires to spin up >2 scripts in the same directory.

@deadcoder0904 commented on GitHub (Jan 16, 2024): why is this not implemented even 5 years later? i don't think this is unreasonable for any web developer working on a project that requires to spin up >2 scripts in the same directory.
Author
Owner

@zadjii-msft commented on GitHub (Jan 16, 2024):

Well, I mean, it has and it hasn't.

You've been able to use shell integration to open a new tab/pane in the same CWD for a couple years now, using OSC9;9. (osc9;9 was originally tracked in #8166) This thread is technically tracking a similar escape sequence, OSC7, which we haven't had a chance to come back around on yet (because it's got some trickier edge cases with WSL distros). #8214 (linked earlier in this thread) has some of the most complete discussion on the whole problem space.

Alas, automagic CWD detection (like linux) will almost certainly never work, as some shells (cough powershell) don't actually set their CWD.

Then there's of course the potential for automatically modifying people's prompts, such that shell integration is automatically enabled for them. This is definitely something that I want to investigate going forward, maybe sometime next year. But I doubt that'll work for everyone or every shell.

@zadjii-msft commented on GitHub (Jan 16, 2024): Well, I mean, it has and it hasn't. You've been able to use [shell integration](https://learn.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory) to open a new tab/pane in the same CWD for a couple years now, using `OSC9;9`. (osc9;9 was originally tracked in #8166) _This thread_ is technically tracking a similar escape sequence, `OSC7`, which we haven't had a chance to come back around on yet (because it's got some trickier edge cases with WSL distros). #8214 (linked earlier in this thread) has some of the most complete discussion on the whole problem space. Alas, automagic CWD detection (like linux) will almost certainly never work, as some shells (_cough_ powershell) don't actually set their CWD. Then there's of course the potential for automatically modifying people's prompts, such that shell integration is automatically enabled for them. This is definitely something that I want to investigate going forward, maybe sometime next year. But I doubt that'll work for everyone or every shell.
Author
Owner

@ewlondon commented on GitHub (Feb 10, 2024):

I know this is an old topic but I just wanted to say for anyone trying to get split panes to same directory using GitBash in 2024, adding this line to .bashrc finally worked for me. The previously listed command by JahzVH was not working correctly for me and would give an error ping every time a prompt was input into terminal.

PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND "}'printf "\e]9;9;%s\e\\" "$(cygpath -w "$PWD")"'

@ewlondon commented on GitHub (Feb 10, 2024): I know this is an old topic but I just wanted to say for anyone trying to get split panes to same directory using GitBash in 2024, adding this line to .bashrc finally worked for me. The previously listed command by **JahzVH** was not working correctly for me and would give an error ping every time a prompt was input into terminal. `PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND "}'printf "\e]9;9;%s\e\\" "$(cygpath -w "$PWD")"'`
Author
Owner

@Daydreamer-riri commented on GitHub (Aug 18, 2024):

Hi @zadjii-msft , you mentioned shell integration which works fine in Powershell, but when I configure my wsl / zsh using the method described in it, the root directory still opens when I split the pane. I'm trying to understand if I'm missing something?

image
image
image

@Daydreamer-riri commented on GitHub (Aug 18, 2024): Hi @zadjii-msft , you mentioned [shell integration](https://learn.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory) which works fine in Powershell, but when I configure my wsl / zsh using the method described in it, the root directory still opens when I split the pane. I'm trying to understand if I'm missing something? ![image](https://github.com/user-attachments/assets/da73c2fb-9ae3-4bf6-8630-d7d91ea5291c) ![image](https://github.com/user-attachments/assets/6ff234d5-f0b4-4ddf-ab76-0149ff4d3e37) ![image](https://github.com/user-attachments/assets/9e76b23c-d82a-4c1d-ac5f-ae8162c519e6)
Author
Owner

@TBBle commented on GitHub (Aug 18, 2024):

@Daydreamer-riri I'd suggest checking what settings are used to launch WSL. I don't know if it's still the default, but IIRC it used to default to including a path on the command line (so it wouldn't start in C:\Windows\System32), and that would override the path provided by this feature.

Also worth checking if you haven't already that nothing else in your zsh startup scripts are changing the current directory, e.g., see point 1 of https://github.com/microsoft/terminal/issues/3158#issuecomment-1624390767.

For example, this Ubuntu WSL config block works for me with the bash setup from the shell integration docs:

            {
                "guid": "{2c4de342-38b7-51cf-b940-2309a097f518}",
                "hidden": false,
                "icon": "C:/Program Files/WindowsApps/CanonicalGroupLimited.UbuntuonWindows_2004.2022.1.0_x64__79rhkp1fndgsc/Assets/Square44x44Logo.altform-unplated_targetsize-256.png",
                "name": "Ubuntu",
                "source": "Windows.Terminal.Wsl",
                "startingDirectory": "//wsl$/Ubuntu/home/paulh"
            },

If changing the startingDirectory value changes the start directory successfully, then your zsh startup scripts are not overriding the directory set by this feature, at least, as that's the value this feature overrides.

@TBBle commented on GitHub (Aug 18, 2024): @Daydreamer-riri I'd suggest checking what settings are used to launch WSL. I don't know if it's still the default, but IIRC it used to default to including a path on the command line (so it wouldn't start in `C:\Windows\System32`), and that would override the path provided by this feature. Also worth checking if you haven't already that nothing else in your zsh startup scripts are changing the current directory, e.g., see point 1 of https://github.com/microsoft/terminal/issues/3158#issuecomment-1624390767. For example, this Ubuntu WSL config block works for me with the bash setup from the shell integration docs: ``` { "guid": "{2c4de342-38b7-51cf-b940-2309a097f518}", "hidden": false, "icon": "C:/Program Files/WindowsApps/CanonicalGroupLimited.UbuntuonWindows_2004.2022.1.0_x64__79rhkp1fndgsc/Assets/Square44x44Logo.altform-unplated_targetsize-256.png", "name": "Ubuntu", "source": "Windows.Terminal.Wsl", "startingDirectory": "//wsl$/Ubuntu/home/paulh" }, ``` If changing the `startingDirectory` value changes the start directory successfully, then your zsh startup scripts are not overriding the directory set by this feature, at least, as that's the value this feature overrides.
Author
Owner

@Daydreamer-riri commented on GitHub (Aug 19, 2024):

‌‌Hi @TBBle, the settings in my Terminal are:
image

I found something interesting: when I use the former (which is, the source is Windows.Terminal.Wsl), the path can be duplicate correctly. But it is hidden by default and the latter is used by default. The latter cannot duplicate the path correctly. Is this perhaps a bug?

@Daydreamer-riri commented on GitHub (Aug 19, 2024): ‌‌Hi @TBBle, the settings in my Terminal are: ![image](https://github.com/user-attachments/assets/91f895ea-2dac-4c70-b9c6-09d69eec4933) I found something interesting: when I use the former (which is, the source is `Windows.Terminal.Wsl`), the path can be duplicate correctly. But it is hidden by default and the latter is used by default. The latter cannot duplicate the path correctly. Is this perhaps a bug?
Author
Owner

@TBBle commented on GitHub (Aug 19, 2024):

Try adding a manual commandLine to the non-working profile, something like C:\Windows\System32\wsl.exe -d Ubuntu-24.04. I don't know what command line that dynamic profile source is actually providing on your machine, but my guess it it hard-codes the starting directory in some way. (You could also try adding a startingDirectory value to it (~ should work), since the Windows.Terminal.Wsl profile source generates one by default, but that shouldn't make a difference, and my research below suggests that it's the command-line.)

Anyway, I did some more digging: I have a different Ubuntu build installed (CanonicalGroupLimited.UbuntuonWindows_2004.2022.1.0_x64__79rhkp1fndgsc) but I checked its snippet (with this process), and it apparently just runs ubuntu.exe, which does (or at least used to) override startingDirectory and hence is incompatible with this feature, so I'm fairly confident this is the problem.

If you confirm that adding a commandLine entry fixes the starting directory, then it's an issue specific to the Ubuntu-provided snippets (or a behaviour choice in their ubuntu.exe launcher, probably the false in this line, which was inherited from MS's template launcher project originally implemented by a familiar author) and you would need to raise it as a ticket with them to fix in some way. You're welcome to link or quote this comment in any such issue you raise.

Edit: Gah. Turns out we already have a bug in this repo for this issue, #12961, which provides a simpler commandLine value to use: ubuntu run. That possibly should be the default command in the Ubuntu snippet... along with startingDirectory value ~ as used by the WSL profile generator. So still an Ubuntu issue to fix, but not a difficult one.


In short, I think this will work to fix your issue: In the second profile, add the following two lines to the start:

"commandLine": "ubuntu.exe run",
"startingDirectory": "~",
@TBBle commented on GitHub (Aug 19, 2024): Try adding a manual commandLine to the non-working profile, something like `C:\Windows\System32\wsl.exe -d Ubuntu-24.04`. I don't know what command line that dynamic profile source is actually providing on your machine, but my guess it it hard-codes the starting directory in some way. (You could also try adding a `startingDirectory` value to it (`~` should work), since the `Windows.Terminal.Wsl` profile source generates one by default, but that _shouldn't_ make a difference, and my research below suggests that it's the command-line.) Anyway, I did some more digging: I have a different Ubuntu build installed (`CanonicalGroupLimited.UbuntuonWindows_2004.2022.1.0_x64__79rhkp1fndgsc`) but I checked its snippet ([with this process](https://superuser.com/a/1737981)), and it apparently just runs ubuntu.exe, which does (or at least [used to](https://github.com/microsoft/WSL/issues/6995#issuecomment-1281552037)) override `startingDirectory` and hence is incompatible with this feature, so I'm fairly confident this is the problem. If you confirm that adding a `commandLine` entry fixes the starting directory, then it's an issue specific to the [Ubuntu-provided snippets](https://github.com/search?q=%22commandLine%22+repo%3Aubuntu%2FWSL+language%3AJSON&type=code&l=JSON) (or a behaviour choice in their ubuntu.exe launcher, [probably the `false` in this line](https://github.com/ubuntu/WSL/blob/main/DistroLauncher/DistroLauncher.cpp#L152), which was inherited from [MS's template launcher project](https://github.com/microsoft/WSL-DistroLauncher/blob/master/DistroLauncher/DistroLauncher.cpp#L120) originally implemented [by a familiar author](https://github.com/ubuntu/WSL/commit/5bc5c8d7a239ea2203f9326bb158a4f7dcb6c8ce#diff-b4ab2df346a855bff484ad7535f2d930b345a1fbc50030231d3383dfc0e79718R167)) and you would need to raise it as a ticket [with them](https://github.com/ubuntu/WSL) to fix in some way. You're welcome to link or quote this comment in any such issue you raise. Edit: Gah. Turns out we already have a bug in this repo for this issue, #12961, which provides [a simpler `commandLine` value to use](https://github.com/microsoft/terminal/issues/12961#issuecomment-1570584225): `ubuntu run`. That _possibly_ should be the default command in the Ubuntu snippet... along with `startingDirectory` value `~` as used by [the WSL profile generator](https://github.com/microsoft/terminal/blob/9b21b78feea9ff0a0b9ff2c8fa4b4aa5602d3889/src/cascadia/TerminalSettingsModel/WslDistroGenerator.cpp#L59-L66). So still an Ubuntu issue to fix, but not a difficult one. ---- In short, I think this will work to fix your issue: In the second profile, add the following two lines to the start: ```json "commandLine": "ubuntu.exe run", "startingDirectory": "~", ```
Author
Owner

@Daydreamer-riri commented on GitHub (Aug 19, 2024):

‌‌Thank you very much for your survey. It's incredible to have accomplished so much work in such a short time.

However, after I added these two lines to the configuration, everything behaved the same as before, with no improvement.

@Daydreamer-riri commented on GitHub (Aug 19, 2024): ‌‌Thank you very much for your survey. It's incredible to have accomplished so much work in such a short time. However, after I added these two lines to the configuration, everything behaved the same as before, with no improvement.
Author
Owner

@zadjii-msft commented on GitHub (Aug 19, 2024):

Did you set "commandline"? or "commandLine"? (note the capital L)

The setup from the docs Works On My Machine when I don't use the profile that Canonical provides, and use the built-in WSL profiles instead:

Using the canonical profile: ("commandline": "ubuntu2204.exe")
image

Using the built-in dynamic profile: ("commandline": "C:\WINDOWS\system32\wsl.exe -d Ubuntu-22.04")
image

@zadjii-msft commented on GitHub (Aug 19, 2024): Did you set `"commandline"`? or `"commandLine"`? (note the capital `L`) The setup from the docs Works On My Machine when I _don't_ use the profile that Canonical provides, and use the built-in WSL profiles instead: Using the canonical profile: (`"commandline": "ubuntu2204.exe"`) ![image](https://github.com/user-attachments/assets/bcacc49d-b408-4705-9316-6d1416329d30) Using the built-in dynamic profile: (`"commandline": "C:\WINDOWS\system32\wsl.exe -d Ubuntu-22.04"`) ![image](https://github.com/user-attachments/assets/a564f7bf-0103-45ea-9456-4c1de27a0ba3)
Author
Owner

@Daydreamer-riri commented on GitHub (Aug 19, 2024):

‌‌‌I have not set up "commandline". The configuration was automatically generated after installing WSL:

{
    "colorScheme": "Chester",
    "guid": "{acbafd15-cbbb-5bb3-8a61-bed446ff4b83}",
    "hidden": false,
    "name": "Ubuntu 24.04 LTS",
    "opacity": 95,
    "source": "CanonicalGroupLimited.Ubuntu24.04LTS_79rhkp1fndgsc"
}

When I set the source to Windows.Terminal.Wsl, the documentation works.

@Daydreamer-riri commented on GitHub (Aug 19, 2024): ‌‌‌I have not set up "commandline". The configuration was automatically generated after installing WSL: ```json { "colorScheme": "Chester", "guid": "{acbafd15-cbbb-5bb3-8a61-bed446ff4b83}", "hidden": false, "name": "Ubuntu 24.04 LTS", "opacity": 95, "source": "CanonicalGroupLimited.Ubuntu24.04LTS_79rhkp1fndgsc" } ``` When I set the `source` to `Windows.Terminal.Wsl`, the documentation works.
Author
Owner

@TBBle commented on GitHub (Aug 19, 2024):

Yes, that works because by changing the source, you're changing the profile you're inheriting from Ubuntu's one, to the built-in profile that includes the two lines I shared. If you do that, you may as well just unhide the actual profile generated by Windows Terminal, and hide the Ubuntu-generated one, to avoid any risk of confusion in-future. (If you go this way, you can add Ubuntu to the list of profile generators to ignore, and then remove that generated profile entirely, for a cleaner config file.)

Can you share the version of that profile with the two lines I provided added, that wasn't working, so if we can see if there's anything else needed?

I expect this should work, is that what you had?

{
    "commandLine": "ubuntu2204.exe run",
    "startingDirectory": "~",
    "colorScheme": "Chester",
    "guid": "{acbafd15-cbbb-5bb3-8a61-bed446ff4b83}",
    "hidden": false,
    "name": "Ubuntu 24.04 LTS",
    "opacity": 95,
    "source": "CanonicalGroupLimited.Ubuntu24.04LTS_79rhkp1fndgsc"
}
@TBBle commented on GitHub (Aug 19, 2024): Yes, that works because by changing the source, you're changing the profile you're inheriting from Ubuntu's one, to the built-in profile that includes the two lines I shared. If you do that, you may as well just unhide the actual profile generated by Windows Terminal, and hide the Ubuntu-generated one, to avoid any risk of confusion in-future. (If you go this way, you can add Ubuntu to the list of profile generators to ignore, and then remove that generated profile entirely, for a cleaner config file.) Can you share the version of that profile with the two lines I provided added, that wasn't working, so if we can see if there's anything else needed? I expect this should work, is that what you had? ```json { "commandLine": "ubuntu2204.exe run", "startingDirectory": "~", "colorScheme": "Chester", "guid": "{acbafd15-cbbb-5bb3-8a61-bed446ff4b83}", "hidden": false, "name": "Ubuntu 24.04 LTS", "opacity": 95, "source": "CanonicalGroupLimited.Ubuntu24.04LTS_79rhkp1fndgsc" } ```
Author
Owner

@Daydreamer-riri commented on GitHub (Aug 19, 2024):

Yes, that works because by changing the source, you're changing the profile you're inheriting from Ubuntu's one, to the built-in profile that includes the two lines I shared. If you do that, you may as well just unhide the actual profile generated by Windows Terminal, and hide the Ubuntu-generated one, to avoid any risk of confusion in-future. (If you go this way, you can add Ubuntu to the list of profile generators to ignore, and then remove that generated profile entirely, for a cleaner config file.)

Can you share the version of that profile with the two lines I provided added, that wasn't working, so if we can see if there's anything else needed?

I expect this should work, is that what you had?

{
    "commandline": "ubuntu2204.exe run",
    "startingDirectory": "~",
    "colorScheme": "Chester",
    "guid": "{acbafd15-cbbb-5bb3-8a61-bed446ff4b83}",
    "hidden": false,
    "name": "Ubuntu 24.04 LTS",
    "opacity": 95,
    "source": "CanonicalGroupLimited.Ubuntu24.04LTS_79rhkp1fndgsc"
}

Sorry, the configuration you provided works, the reason I said it didn't work before was because I filled in the name of the executable wrong (my ubuntu version is 2404 but I wrote 2204). The only problem with it now is that my wsl default directory becomes my Windows user directory instead of the user directory in wsl.

image

When I set commandline to wsl.exe -d Ubuntu-22.04:

image

@Daydreamer-riri commented on GitHub (Aug 19, 2024): > Yes, that works because by changing the source, you're changing the profile you're inheriting from Ubuntu's one, to the built-in profile that includes the two lines I shared. If you do that, you may as well just unhide the actual profile generated by Windows Terminal, and hide the Ubuntu-generated one, to avoid any risk of confusion in-future. (If you go this way, you can add Ubuntu to the list of profile generators to ignore, and then remove that generated profile entirely, for a cleaner config file.) > > Can you share the version of that profile with the two lines I provided added, that wasn't working, so if we can see if there's anything else needed? > > I expect this should work, is that what you had? > > ```json > { > "commandline": "ubuntu2204.exe run", > "startingDirectory": "~", > "colorScheme": "Chester", > "guid": "{acbafd15-cbbb-5bb3-8a61-bed446ff4b83}", > "hidden": false, > "name": "Ubuntu 24.04 LTS", > "opacity": 95, > "source": "CanonicalGroupLimited.Ubuntu24.04LTS_79rhkp1fndgsc" > } > ``` Sorry, the configuration you provided works, the reason I said it didn't work before was because I filled in the name of the executable wrong (my ubuntu version is 2404 but I wrote 2204). The only problem with it now is that my wsl default directory becomes my Windows user directory instead of the user directory in wsl. ![image](https://github.com/user-attachments/assets/d0599c8c-e579-45fa-8f67-6d6315da732a) When I set commandline to `wsl.exe -d Ubuntu-22.04`: ![image](https://github.com/user-attachments/assets/d9d283cc-f8af-4e31-ade0-29fe458db44a)
Author
Owner

@TBBle commented on GitHub (Aug 19, 2024):

Ah yeah, sorry about getting the number wrong. I originally typed "2004" out of habit, and fixed it looking at the example in the other ticket, not your settings. >_<

Anyway, I'd go with the wsl.exe -d Ubuntu-22.04 command-line setting then. That should be all the launcher is doing underneath, after the first-run setup anyway.

Otherwise, you can also put your real desired startup directory in the startingDirectory parameter, e.g., you can see in my earlier example I use //wsl$/Ubuntu/home/paulh which is /home/paulh inside the Ubuntu WSL install. If you navigate to \\wsl$ in Windows Explorer, you should be able to get the correct path to use by browsing in there, but I assume it'll be something like \\wsl$\Ubuntu-2404\home\<yourWSLAccountName>. (My use of / is probably legacy here and only works with wsl.exe, \-based paths like you'd copy from Explorer should work, but remember to double the backslashes if you're editing the JSON directly. I just changed mine to use \ and it works fine.) Easier method: Go into the directory in WSL that you want to be your starting directory, and run wslpath -w "$PWD". Put that in your config; if you're editing JSON directly, double the backslashes.

Sadly, it turns out Windows Terminal makes the ~ starting directory work by specifically looking for wsl.exe on the command line and otherwise turns it into USERPROFILE as you have discovered. There's a separate hack that specifically looks for the source Windows.Terminal.Wsl (used for drag-and-drop support AFAICT, see #17691) so clearly some outstanding work to be done to make this all work nicely out-of-the-box for WSL profiles/launchers other than the built-in default WSL profile generator.

@TBBle commented on GitHub (Aug 19, 2024): Ah yeah, sorry about getting the number wrong. I originally typed "2004" out of habit, and fixed it looking at the example in the other ticket, not your settings. >_< Anyway, I'd go with the `wsl.exe -d Ubuntu-22.04` command-line setting then. That should be all the launcher is doing underneath, after the first-run setup anyway. Otherwise, you can also put your real desired startup directory in the `startingDirectory` parameter, e.g., you can see in my earlier example I use `//wsl$/Ubuntu/home/paulh` which is `/home/paulh` inside the Ubuntu WSL install. ~~If you navigate to `\\wsl$` in Windows Explorer, you should be able to get the correct path to use by browsing in there, but I assume it'll be something like `\\wsl$\Ubuntu-2404\home\<yourWSLAccountName>`. (My use of `/` is probably legacy here and only works with wsl.exe, `\`-based paths like you'd copy from Explorer should work, but remember to double the backslashes if you're editing the JSON directly. I just changed mine to use `\` and it works fine.)~~ Easier method: Go into the directory in WSL that you want to be your starting directory, and run `wslpath -w "$PWD"`. Put that in your config; if you're editing JSON directly, double the backslashes. Sadly, it turns out Windows Terminal makes the `~` starting directory work [by specifically looking for wsl.exe on the command line](https://github.com/microsoft/terminal/blob/735ef2823ed72d80ce91df0176646979e4568831/src/types/utils.cpp#L1017-L1021) and otherwise turns it into `USERPROFILE` as you have discovered. There's [a separate hack](https://github.com/microsoft/terminal/blob/faf21acbc7d67f4689bad21695439de129a221a0/src/cascadia/TerminalControl/ControlInteractivity.cpp#L728-L739) that specifically looks for the source `Windows.Terminal.Wsl` (used for drag-and-drop support AFAICT, see #17691) so clearly some outstanding work to be done to make this all work nicely out-of-the-box for WSL profiles/launchers other than the built-in default WSL profile generator.
Author
Owner

@Daydreamer-riri commented on GitHub (Aug 19, 2024):

Thank you! Thanks for your guidance.

I think it should be stated in the documentation that “Opening a tab or pane in the same directory” requires some extra work when using the default generated "source": ‘CanonicalGroupLimited... profile”.

Hopefully this will help more people.

@Daydreamer-riri commented on GitHub (Aug 19, 2024): Thank you! Thanks for your guidance. I think it should be stated in the documentation that “Opening a tab or pane in the same directory” requires some extra work when using the default generated `"source": ‘CanonicalGroupLimited...` profile”. Hopefully this will help more people.
Author
Owner

@TBBle commented on GitHub (Aug 20, 2024):

I think it should be stated in the documentation that “Opening a tab or pane in the same directory” requires some extra work when using the default generated "source": ‘CanonicalGroupLimited... profile”.

The problem is the "source": ‘CanonicalGroupLimited... profile” is not part of Windows Terminal, so I'd suggest you raise a suggestion with the project providing that source (https://github.com/ubuntu/WSL) to change it to work "better", or better-document the effect their profile has on Windows Terminal, and any extra steps the user needs to take to make it work.

There's some work that could be done in Windows Terminal, but it wouldn't be Ubuntu-specific and would require coordination with any such WSL distributions in their profile contributions too.

@TBBle commented on GitHub (Aug 20, 2024): > I think it should be stated in the documentation that “Opening a tab or pane in the same directory” requires some extra work when using the default generated `"source": ‘CanonicalGroupLimited...` profile”. The problem is the `"source": ‘CanonicalGroupLimited...` profile” is not part of Windows Terminal, so I'd suggest you raise a suggestion with the project providing that source (https://github.com/ubuntu/WSL) to change it to work "better", or better-document the effect their profile has on Windows Terminal, and any extra steps the user needs to take to make it work. There's some work that could be done in Windows Terminal, but it wouldn't be Ubuntu-specific and would require coordination with any such WSL distributions in their profile contributions too.
Author
Owner

@Lyton505 commented on GitHub (Oct 21, 2024):

Hi @Daydreamer-riri mentioned CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc being faulty. I am also observing the same behaviour. How did you change it to Windows.Terminal.Wsl Whenever I try to change it in settings.json, I get the following error:

Could not find your default profile in your list of profiles - using the first profile. Check to make sure the "defaultProfile" matches the GUID of one of your profiles.
@Lyton505 commented on GitHub (Oct 21, 2024): Hi @Daydreamer-riri mentioned `CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc` being faulty. I am also observing the same behaviour. How did you change it to `Windows.Terminal.Wsl` Whenever I try to change it in `settings.json`, I get the following error: ``` Could not find your default profile in your list of profiles - using the first profile. Check to make sure the "defaultProfile" matches the GUID of one of your profiles. ```
Author
Owner

@glokta1 commented on GitHub (Feb 9, 2025):

@TBBle Thank you very much! <3 I was encountering the same issue with the official documentation not working and your solution fixed it

@glokta1 commented on GitHub (Feb 9, 2025): @TBBle Thank you very much! <3 I was encountering the same issue with the official documentation not working and your solution fixed it
Author
Owner

@0anton commented on GitHub (Mar 17, 2025):

I cannot get terminal tab split into the current directory working. I've tried many options:

  • Preview vs Standard Terminal
  • invoking as "wsl.exe" and "ubuntu2204.exe run"
  • trying different distributions, like "Ubuntu-22.04", "Ubuntu-24.04 LTS".
           {
                "commandline": "wsl.exe -d Ubuntu-22.04",
                "guid": "{097c520d-465f-47f8-857c-3007477a556b}",
                "hidden": false,
                "name": "Ubuntu 22.04",
                "opacity": 95,
                "startingDirectory": "~"
            }
$ echo $PROMPT_COMMAND
printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"

Image

Windows Terminal
Version: 1.21.10351.0
Windows Terminal Preview
Version: 1.23.10732.0`

How can I troubleshoot what exactly is broken?
I've have two other Windows devices - on them the same works perfectly. I'm replicating the profiles one-to-one - and on the affected host the path is simply not taken over...

@0anton commented on GitHub (Mar 17, 2025): I cannot get terminal tab split into the current directory working. I've tried many options: - Preview vs Standard Terminal - invoking as "wsl.exe" and "ubuntu2204.exe run" - trying different distributions, like "Ubuntu-22.04", "Ubuntu-24.04 LTS". ``` { "commandline": "wsl.exe -d Ubuntu-22.04", "guid": "{097c520d-465f-47f8-857c-3007477a556b}", "hidden": false, "name": "Ubuntu 22.04", "opacity": 95, "startingDirectory": "~" } ``` ``` $ echo $PROMPT_COMMAND printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")" ``` ![Image](https://github.com/user-attachments/assets/53d8090d-75be-44d2-9d71-c4b281222858) ``` Windows Terminal Version: 1.21.10351.0 ``` ``` Windows Terminal Preview Version: 1.23.10732.0` ``` How can I troubleshoot what exactly is broken? I've have two other Windows devices - on them the same works perfectly. I'm replicating the profiles one-to-one - and on the affected host the path is simply not taken over...
Author
Owner

@nacitar commented on GitHub (Apr 7, 2025):

I cannot get terminal tab split into the current directory working. I've tried many options:

  • Preview vs Standard Terminal
  • invoking as "wsl.exe" and "ubuntu2204.exe run"
  • trying different distributions, like "Ubuntu-22.04", "Ubuntu-24.04 LTS".
           {
                "commandline": "wsl.exe -d Ubuntu-22.04",
                "guid": "{097c520d-465f-47f8-857c-3007477a556b}",
                "hidden": false,
                "name": "Ubuntu 22.04",
                "opacity": 95,
                "startingDirectory": "~"
            }
$ echo $PROMPT_COMMAND
printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"

Image

Windows Terminal
Version: 1.21.10351.0
Windows Terminal Preview
Version: 1.23.10732.0`

How can I troubleshoot what exactly is broken? I've have two other Windows devices - on them the same works perfectly. I'm replicating the profiles one-to-one - and on the affected host the path is simply not taken over...

Just use "$PWD" in your prompt command, not "$(wslpath -w "$PWD")"

EDIT: and probably remove the starting directory bit too.

@nacitar commented on GitHub (Apr 7, 2025): > I cannot get terminal tab split into the current directory working. I've tried many options: > > * Preview vs Standard Terminal > * invoking as "wsl.exe" and "ubuntu2204.exe run" > * trying different distributions, like "Ubuntu-22.04", "Ubuntu-24.04 LTS". > > ``` > { > "commandline": "wsl.exe -d Ubuntu-22.04", > "guid": "{097c520d-465f-47f8-857c-3007477a556b}", > "hidden": false, > "name": "Ubuntu 22.04", > "opacity": 95, > "startingDirectory": "~" > } > ``` > > ``` > $ echo $PROMPT_COMMAND > printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")" > ``` > > ![Image](https://github.com/user-attachments/assets/53d8090d-75be-44d2-9d71-c4b281222858) > > ``` > Windows Terminal > Version: 1.21.10351.0 > ``` > > ``` > Windows Terminal Preview > Version: 1.23.10732.0` > ``` > > How can I troubleshoot what exactly is broken? I've have two other Windows devices - on them the same works perfectly. I'm replicating the profiles one-to-one - and on the affected host the path is simply not taken over... Just use "$PWD" in your prompt command, not "$(wslpath -w "$PWD")" EDIT: and probably remove the starting directory bit too.
Author
Owner

@0anton commented on GitHub (Apr 7, 2025):

thanks for the hint, @nacitar

I've tried w/o wslpath like:

printf "\e]9;9;%s\e\\" "$PWD"

it didn't work unfortunately:

Image

what do you mean exactly with remove the starting directory bit too?

@0anton commented on GitHub (Apr 7, 2025): thanks for the hint, @nacitar I've tried w/o _wslpath_ like: ``` printf "\e]9;9;%s\e\\" "$PWD" ``` it didn't work unfortunately: ![Image](https://github.com/user-attachments/assets/a6e01252-01b2-40c8-b4d1-7c5ecf9714e8) what do you mean exactly with _remove the starting directory bit too_?
Author
Owner

@nacitar commented on GitHub (Apr 7, 2025):

thanks for the hint, @nacitar

I've tried w/o wslpath like:

printf "\e]9;9;%s\e\\" "$PWD"

it didn't work unfortunately:

Image

what do you mean exactly with remove the starting directory bit too?

In your windows terminal settings:

            "startingDirectory": "~"

I can confirm that mine works without that present and using PWD directly like I suggested. My guess is that is overriding it.

... also make sure you're using duplicateTab

@nacitar commented on GitHub (Apr 7, 2025): > thanks for the hint, [@nacitar](https://github.com/nacitar) > > I've tried w/o _wslpath_ like: > > ``` > printf "\e]9;9;%s\e\\" "$PWD" > ``` > > it didn't work unfortunately: > > ![Image](https://github.com/user-attachments/assets/a6e01252-01b2-40c8-b4d1-7c5ecf9714e8) > > what do you mean exactly with _remove the starting directory bit too_? In your windows terminal settings: "startingDirectory": "~" I can confirm that mine works without that present and using PWD directly like I suggested. My guess is that is overriding it. ... also make sure you're using duplicateTab
Author
Owner

@0anton commented on GitHub (Apr 8, 2025):

Thank you a lot @nacitar!

I'm unsure what has worked at the end, but this combination "does the needful":

I had to ensure I'm using duplicate pane: action

        {
            "command": 
            {
                "action": "splitPane",
                "split": "auto",
                "splitMode": "duplicate"
            },
            "id": "User.splitPane.A6751878"
        },

Simplified PROMPT_COMMAND version with just $PWD works actually fine, so I've started using it:

$ echo $PROMPT_COMMAND
printf "\e]9;9;%s\e\\" "$PWD"

startingDirectory set to "current dir":

   {
                "colorScheme": "One Half Dark",
                "commandline": "wsl.exe -d Ubuntu-24.04",
                "guid": "{acbafd15-cbbb-5bb3-8a61-bed446ff4b83}",
                "hidden": false,
                "name": "Ubuntu 24.04 LTS 1",
                "opacity": 95,
                "startingDirectory": "~",
                "useAcrylic": false
            }

With all this I indeed can duplicate tab to the same dir, which saves a lot of time to me! Resolved to me.

@0anton commented on GitHub (Apr 8, 2025): Thank you a lot @nacitar! I'm unsure what has worked at the end, but this combination "does the needful": I had to ensure I'm using duplicate pane: action ``` { "command": { "action": "splitPane", "split": "auto", "splitMode": "duplicate" }, "id": "User.splitPane.A6751878" }, ``` Simplified `PROMPT_COMMAND` version with just `$PWD` works actually fine, so I've started using it: ``` $ echo $PROMPT_COMMAND printf "\e]9;9;%s\e\\" "$PWD" ``` _startingDirectory_ set to "current dir": ``` { "colorScheme": "One Half Dark", "commandline": "wsl.exe -d Ubuntu-24.04", "guid": "{acbafd15-cbbb-5bb3-8a61-bed446ff4b83}", "hidden": false, "name": "Ubuntu 24.04 LTS 1", "opacity": 95, "startingDirectory": "~", "useAcrylic": false } ``` With all this I indeed can duplicate tab to the same dir, which saves a lot of time to me! Resolved to me.
Author
Owner

@hktkqj commented on GitHub (Apr 9, 2025):

For those struggling to duplicate/split WSL tabs in same diretory, please ensure that the startup command line for the distribution profile uses wsl -d <distro> instead of ubuntu2204.exe like executable, as for some reason this affects the passing of the CWD.

@hktkqj commented on GitHub (Apr 9, 2025): For those struggling to duplicate/split WSL tabs in same diretory, please ensure that the startup command line for the distribution profile uses `wsl -d <distro>` instead of `ubuntu2204.exe` like executable, as for some reason this affects the passing of the CWD.
Author
Owner

@working-name commented on GitHub (Apr 19, 2025):

For those struggling to duplicate/split WSL tabs in same diretory, please ensure that the startup command line for the distribution profile uses wsl -d <distro> instead of ubuntu2204.exe like executable, as for some reason this affects the passing of the CWD.

Right, or this default junk somehow generated:

C:\Windows\system32\wsl.exe --distribution-id {4ad8391d-7793-4fea-90d6-767b6df60ba0} --cd ~

Remove --cd ~, that forces to always cd into the linux user's home folder.

Thanks @0anton

@working-name commented on GitHub (Apr 19, 2025): > For those struggling to duplicate/split WSL tabs in same diretory, please ensure that the startup command line for the distribution profile uses `wsl -d <distro>` instead of `ubuntu2204.exe` like executable, as for some reason this affects the passing of the CWD. Right, or this default junk somehow generated: ``` C:\Windows\system32\wsl.exe --distribution-id {4ad8391d-7793-4fea-90d6-767b6df60ba0} --cd ~ ``` Remove --cd ~, that forces to always cd into the linux user's home folder. Thanks @0anton
Author
Owner

@pavangayakwad commented on GitHub (May 3, 2025):

This is a commonsense and the most useful UX, really disappointed to see that it is not implemented till date. I just also wish Terminal remember its previous state when re-opened.

@pavangayakwad commented on GitHub (May 3, 2025): This is a commonsense and the most useful UX, really disappointed to see that it is not implemented till date. I just also wish Terminal remember its previous state when re-opened.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/terminal#4405