- How to open a file from the integrated terminal in Visual Studio Code?
- 6 Answers 6
- Not the answer you’re looking for? Browse other questions tagged visual-studio-code or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- Начало работы с Windows Terminal
- Установка
- Требования
- Windows Terminal Preview
- Windows Terminal
- Первый запуск
- Профили
- Дефолтный профиль
- Добавление нового профиля
- Структура Settings.json
- Базовая кастомизация
- Цветовая схема
- Начертание шрифта
- Open text file and program shortcut in a Windows batch file
- 12 Answers 12
- What is Windows Terminal?
- Multiple profiles supporting a variety of command line applications
- Customized schemes and configurations
- Custom actions
- Unicode and UTF-8 character support
- GPU accelerated text rendering
- Background image support
- Command line arguments
- How to open a terminal quickly from a file explorer at a folder in Windows 7?
- 7 Answers 7
- Update for Windows 10 when CMD was replaced by PowerShell:
How to open a file from the integrated terminal in Visual Studio Code?
Is there a way of opening a file from the terminal in Visual Studio Code that opens in the same vscode instance that runs the terminal? Similar to c9 tool in Cloud9.
I’m aware of the code tool, but when you run code something.php from the integrated terminal it opens a new vscode instance, which is not what I want.
6 Answers 6
You can use -r or —reuse-window command line option.
in the version 1.31.0 that I have installed, on Windows 7, the only way I found to do this is to e.g. change the file associations in system so that .cproj and .cs files are opened by Visual Studio Code by default, and type «filename.cs» in Terminal to open file by that name in the same window. -r option is not working for the first call (opens a new window), but with each subsequent call that same window is correctly reused. ok can’t get to open whole directories this way — it’s a bit shoddy anyway. probably it would be more convenient to use an outside shell and work with «-r» option
I tried it on Win10 and on Linux (Ubuntu)
Not the answer you’re looking for? Browse other questions tagged visual-studio-code or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Начало работы с Windows Terminal
Привет, Хабр! Сегодня делимся гайдом по началу работы с Windows Terminal. Да, поскольку он о начале работы с инструментом, в основном в материале описываются какие-то базовые моменты. Но я думаю, что и профессионалы смогут подчерпнуть для себя что-то полезное, как минимум из списка полезных ссылок в конце статьи. Заглядывайте под кат!
Установка
Windows Terminal доступен в двух разных сборках: Windows Terminal и Windows Terminal Preview. Обе сборки доступны для загрузки в Microsoft Store и на странице выпусков GitHub.
Требования
Для запуска любой сборки Windows Terminal на вашем компьютере должна быть установлена Windows 10 1903 или более поздняя версия.
Windows Terminal Preview
Windows Terminal
Терминал Windows — это основная сборка продукта. Функции, которые поступают в Windows Terminal Preview, появляются в Windows Terminal через месяц эксплуатации. Это позволяет проводить обширное тестирование ошибок и стабилизацию новых функций. Эта сборка предназначена для тех, кто хочет получить функции после того, как они были изучены и протестированы сообществом Preview.
Первый запуск
После установки терминала вы можете запустить приложение и сразу приступить к работе с командной строкой. По умолчанию терминал включает профили Windows PowerShell, Command Prompt и Azure Cloud Shell в раскрывающемся списке. Если на вашем компьютере установлены дистрибутивы Подсистемы Windows для Linux (WSL), они также должны динамически заполняться как профили при первом запуске терминала.
Профили
Профили действуют как различные среды командной строки, которые вы можете настраивать внутри терминала. По умолчанию в каждом профиле используется отдельный исполняемый файл командной строки, однако вы можете создать столько профилей, сколько захотите, используя один и тот же исполняемый файл. Каждый профиль может иметь свои собственные настройки, которые помогут вам различать их и добавить в каждый свой собственный стиль.
Дефолтный профиль
При первом запуске Windows Terminal в качестве профиля по умолчанию устанавливается Windows PowerShell. Профиль по умолчанию — это профиль, который всегда открывается при запуске терминала, и это профиль, который открывается при нажатии кнопки новой вкладки. Вы можете изменить профиль по умолчанию, установив «defaultProfile» на имя вашего предпочтительного профиля в файле settings.json.
Добавление нового профиля
Новые профили можно добавлять динамически с помощью терминала или вручную. Терминал Windows автоматически создаст профили для распределений PowerShell и WSL. Эти профили будут иметь свойство «source», которое сообщает терминалу, где он может найти соответствующий исполняемый файл.
Если вы хотите создать новый профиль вручную, вам просто нужно сгенерировать новый «guid», указать «name» и предоставить исполняемый файл для свойства «commandline».
Примечание. Вы не сможете скопировать свойство «source» из динамически созданного профиля. Терминал просто проигнорирует этот профиль. Вам нужно будет заменить «source» на «commandline» и предоставить исполняемый файл, чтобы дублировать динамически созданный профиль.
Структура Settings.json
В Терминал Windows включены два файла настроек. Один из них — defaults.json, который можно открыть, удерживая клавишу Alt и нажав кнопку «Настройки» в раскрывающемся списке. Это неизменяемый файл, который включает в себя все настройки по умолчанию, которые поставляются с терминалом. Второй файл — settings.json, в котором вы можете применить все свои пользовательские настройки. Доступ к нему можно получить, нажав кнопку «Настройки» в раскрывающемся меню.
Файл settings.json разделен на четыре основных раздела. Первый — это объект глобальных настроек, который находится в верхней части файла JSON внутри первого <. Примененные здесь настройки повлияют на все приложение.
Следующим основным разделом файла является объект «profiles». Объект «profiles» разделен на два раздела: «defaults» и «list». Вы можете применить настройки профиля к объекту «defaults», и они будут применяться ко всем профилям в вашем «list». «list» содержит каждый объект профиля, который представляет профили, описанные выше, и это элементы, которые появляются в раскрывающемся меню вашего терминала. Настройки, примененные к отдельным профилям в «списке», имеют приоритет над настройками, примененными в разделе «defaults».
Далее в файле расположен массив «schemes». Здесь можно разместить собственные цветовые схемы. Отличный инструмент, который поможет вам создать свои собственные цветовые схемы, — это terminal.sexy.
Наконец, в нижней части файла находится массив «actions». Перечисленные здесь объекты добавляют действия в ваш терминал, которые можно вызывать с клавиатуры и/или находить внутри палитры команд.
Базовая кастомизация
Вот несколько основных настроек, которые помогут вам начать настройку вашего терминала.
Одна из самых популярных настроек — настраиваемое фоновое изображение. Это настройка профиля, поэтому ее можно либо поместить внутри объекта «defaults» внутри объекта «profiles», чтобы применить ко всем профилям, либо внутри определенного объекта профиля.
Параметр «backgroundImage» принимает расположение файла изображения, которое вы хотите использовать в качестве фона вашего профиля. Допустимые типы файлов: .jpg, .png, .bmp, .tiff, .ico и .gif.
Цветовая схема
Список доступных цветовых схем можно найти на нашем сайте документации. Цветовые схемы применяются на уровне профиля, поэтому вы можете поместить настройку внутри «значений по умолчанию» или в конкретный объект профиля.
Этот параметр принимает название цветовой схемы. Вы также можете создать свою собственную цветовую схему и поместить ее в список «schemes», а затем установить в настройках профиля имя этой новой схемы, чтобы применить ее.
Начертание шрифта
По умолчанию Windows Terminal использует Cascadia Mono в качестве шрифта. Начертание шрифта — это настройка уровня профиля. Вы можете изменить шрифт, установив «fontFace» на имя шрифта, который вы хотите использовать.
Совет: Терминал Windows также поставляется с начертанием шрифта Cascadia Code, который включает программные лигатуры (см. Gif ниже). Если вы используете Powerline, Cascadia Code также поставляется в PL-версии, которую можно загрузить с GitHub.
Open text file and program shortcut in a Windows batch file
I have two files in the same folder that I’d like to run. One is a .txt file, and the other is the program shortcut to an .exe . I’d like to make a batch file in the same location to open the text file and the shortcut then close the batch file (but the text file and program remain open).
I tried this with no luck:
Also didn’t work:
12 Answers 12
I was able to figure out the solution:
This would have worked too. The first quoted pair are interpreted as a window title name in the start command.
Don’t put quotes around the name of the file that you are trying to open; start «myfile.txt» opens a new command prompt with the title myfile.txt , while start myfile.txt opens myfile.txt in Notepad. There’s no easy solution in the case where you want to start a console application with a space in its file name, but for other applications, start «» «my file.txt» works.
The command-line syntax for opening a text file is:
File types supported by this command include (but are not limited to): .doc, .txt, .html, .log
If the contents is too long, you can add «|more» after «type filename.txt», and it will pause after each screen; to end the command before the end of the file, you can hold Ctrl + C .
to open the file.
Another example is
You can also do:
The C:\Users\kemp\Install\ is your PATH. The Text1.txt is the FILE.
«location of notepad file» > notepad Filename
C:\Users\Desktop\Anaconda> notepad myfile
In some cases, when opening a LNK file it is expecting the end of the application run.
In such cases it is better to use the following syntax (so you do not have to wait the end of the application):
To open a TXT file can be in the way already indicated (because notepad.exxe not interrupt the execution of the start command)
The command start [filename] opened the file in my default text editor.
This command also worked for opening a non-.txt file.
If you are trying to open an application such as Chrome or Microsoft Word use this:
And repeat this for all of the applications you want to open.
What is Windows Terminal?
Windows Terminal is a modern terminal application for users of command-line tools and shells like Command Prompt, PowerShell, and Windows Subsystem for Linux (WSL). Its main features include multiple tabs, panes, Unicode and UTF-8 character support, a GPU accelerated text rendering engine, and the ability to create your own themes and customize text, colors, backgrounds, and shortcuts.
Multiple profiles supporting a variety of command line applications
Any application that has a command line interface can be run inside Windows Terminal. This includes everything from PowerShell and Command Prompt to Azure Cloud Shell and any WSL distribution such as Ubuntu or Oh-My-Zsh.
Customized schemes and configurations
You can configure your Windows Terminal to have a variety of color schemes and settings. To learn how to make your own color scheme, visit the Color schemes page. You can also find custom Terminal configurations in the Custom terminal gallery.
Custom actions
There are a variety of custom commands you can use in Windows Terminal to have it feel more natural to you. If you don’t like a particular keyboard shortcut, you can change it to whatever you prefer.
For example, the default shortcut to copy text from the command line is ctrl+shift+c . You can change this to ctrl+1 or whatever you prefer. To open a new tab, the default shortcut is ctrl+shift+t , but maybe you want to change this to ctrl+2 . The default shortcut to flip between the tabs you have open is ctrl+tab , this could be changed to ctrl+- and used to create a new tab instead.
You can learn about customizing shortcuts on the Actions page.
Unicode and UTF-8 character support
Windows Terminal can display Unicode and UTF-8 characters such as emoji and characters from a variety of languages.
GPU accelerated text rendering
Windows Terminal uses the GPU to render its text, thus providing improved performance over the default Windows command line experience.
Background image support
You can have background images and gifs inside your Windows Terminal window. Information on how to add background images to your profile can be found on the Profile — Appearance page.
Command line arguments
You can set Windows Terminal to launch in a specific configuration using command line arguments. You can specify which profile to open in a new tab, which folder directory should be selected, open the terminal with split window panes, and choose which tab should be in focus.
For example, to open Windows Terminal from PowerShell with three panes, with the left pane running a Command Prompt profile and the right pane split between your PowerShell and your default profile running WSL, enter:
Learn how to set up command-line arguments on the Command line arguments page.
How to open a terminal quickly from a file explorer at a folder in Windows 7?
This can be done easily in Ubuntu, just right click and open Terminal. It is very inconvenient to open cmd.exe then cd to the folder.
So, how do I open a terminal quickly from a file explorer at a folder?
7 Answers 7
- Hold Shift + Right Click the folder you want it opened on, and click «open command window here«. That should do the trick!
OR
- You can also type cmd into the Windows File Explorer address bar (use Ctrl+L to focus the address bar) and press Enter to open the shell.
You can type cmd in Windows Explorer’s location bar (which you can edit with the keyboard shortcut Alt + D ); it will open a terminal upon pressing Enter .
Personally I use a voice command in Dragon NaturallySpeaking that takes care of it:
Press Ctrl+L. This will allow you to edit the location bar address of the file explorer. Type ‘cmd’ and press enter. This will open command prompt in current folder.
As I don’t have access to any Win7 machine right now i’ll give you 2 answers, one that I know that works in winXP and one that I found but don’t know if it works in Win7.
Just import the below *.reg file (or copy from the MSDN blog above)
Update for Windows 10 when CMD was replaced by PowerShell:
For quite some time, there is a PowerShell module called OpenHere that gives you granular options to control this functionality.
All you need is to copy paste this into PowerShell with elevated rights:
and start to explore the Set-OpenHereShortcut function.