Перейти к содержимому

Как настроить терминал в phpstorm

  • автор:

Terminal

PhpStorm includes an embedded terminal emulator for working with your command-line shell from inside the IDE. Use it to run Git commands, set file permissions, and perform other command-line tasks without switching to a dedicated terminal application.

Initially, the terminal emulator runs with your default system shell, but it supports many other shells, such as Windows PowerShell, Command Prompt cmd.exe , sh , bash , zsh , csh , and so on. For information about changing the shell, see Configure the terminal emulator.

Open the Terminal tool window

From the main menu, select View | Tool Windows | Terminal or press Alt+F12 .

By default, the terminal emulator runs with the current directory set to the root directory of the current project. For information about changing the default start directory, see Configure the terminal emulator.

Right-click any file (for example, in the Project tool window or any open editor tab) and select Open in Terminal to open the Terminal tool window with a new session in the directory of that file.

You can open the terminal as an editor tab: right-click the Terminal tool window header and select Move to Editor .

Start a new session

Click on the toolbar to start a new session in a separate tab.

To run multiple sessions inside a tab, right-click the tab and select Split Right or Split Down in the context menu.

The Terminal saves tabs and sessions when you close the project or PhpStorm. It preserves tab names, the current working directory, and even the shell history.

To close a tab, click on the Terminal toolbar or right-click the tab and select Close Tab from the context menu.

Press Alt+Right and Alt+Left to switch between active tabs. Alternatively, you can press Alt+Down to see the list of all terminal tabs.

To rename a tab, right-click the tab and select Rename Session from the context menu.

Just like with system terminal tabs, you can rename PhpStorm Terminal tabs programmatically. For example, use title MyTitle if your interpreter is Windows Command Prompt or echo -en "\033]0;MyTitle\a" for bash and zsh.

Search in terminal

To search for a certain string in a Terminal session, press Ctrl+F . This searches all text in the session: the prompt, commands, and output.

Configure the terminal emulator

Press Ctrl+Alt+S to open the IDE settings and select Tools | Terminal .

Project Settings

These settings affect the terminal only for the current project:

Specify the working directory where every new shell session should start. By default, it starts in the root directory of the current project.

Specify custom environment variables for every new shell session.

Application Settings

These settings affect the terminal in any project that you open with the current PhpStorm instance.

Specify the shell that will run by default. PhpStorm should automatically detect the default shell based on your environment. Here are some examples of different shells:

Bash for Windows: bash.exe

Command Prompt: cmd.exe

Cygwin: "C:\cygwin\bin\bash.exe" —login -i

Default Tab name

Specify the default name for new tabs.

Play the bell sound on various events.

Close session when it ends

Close the current session when the corresponding process ends (for example, by kill ).

Enable the mouse pointer support in the embedded local terminal.

Copy to clipboard on selection

Copy text selected in the terminal to the clipboard.

Paste on middle mouse button click

Paste clipboard contents by clicking the middle mouse button.

Override IDE shortcuts

Use shell-specific shortcuts instead of IDE shortcuts when the Terminal tool window is active.

Click Configure terminal keybindings to open the Keymap settings page and configure the shortcuts that are available int the Terminal tool window under Plugins | Terminal . For example, Switch Focus to Editor is mapped to Escape by default, which means that if you don’t override the IDE shortcuts, Escape will switch focus from the terminal to the editor.

Integrate the terminal with the system shell to properly keep track of your command history for sessions and load a custom config file with required environment variables.

Shell integration works for sh , bash , zsh , and fish shells.

Highlight HTTP links in the terminal and make them clickable.

Use Option as Meta key

On macOS, use the Option key as the Meta key.

Run Commands using IDE

Detect and highlight commands that can be used as IDE features instead of running them in the terminal and reading console output.

When enabled, instead of pressing Enter , which runs the command in the terminal, press Ctrl+Enter to open the corresponding GUI element. For more information, see Run IDE features from the terminal.

Select the shape of the cursor: block, underline, or vertical.

The embedded terminal emulator also inherits the following IDE settings:

On the Keymap page, you can configure the copy Ctrl+C and paste Ctrl+V shortcuts.

On the Editor | General | Appearance page, you can configure blinking frequency for the caret. The Terminal does not inherit the Use block caret option because there is a separate option for that: Cursor shape.

On the Editor | Color Scheme | Console Font page, you can configure line spacing and fonts.

On the Editor | Color Scheme | Console Colors page, you can configure font colors.

On the Editor | Color Scheme | General page, you can configure the selection foreground and background colors.

Run IDE features from the terminal

Instead of running a specific command in the integrated terminal and reading console output, you can use the relevant IDE feature, like a tool window or a dialog that implements this functionality. For example, the diff viewer actually runs the diff command in the system shell to produce results. Another example is the Log tab in the Git tool window, which is based on the output of the git log command.

Open the Log tab of the Git tool window from the terminal

Type a supported command in the terminal and notice how it is highlighted.

Instead of pressing Enter , which runs the command in the terminal, press Ctrl+Enter to open the corresponding GUI element. In this example, it will open the Log tab of the Git tool window and filter commits for the docker branch.

If you want to disable this feature, click on the title bar of the Terminal window and clear the Run Commands using IDE option. Alternatively, clear Run Commands using IDE on the Tools | Terminal page of the IDE settings Ctrl+Alt+S .

Using Git Bash with PhpStorm

This morning I felt there should be more to the terminal in JetBrain’s PHPStorm IDE and it turns out I was right.

Full disclosure, I’ve come to prefer the *nix style command line interface to Windows and that’s reflected in my choice to continue using Git Bash on my work PC (it’s a Lenovo Thinkpad with 64-bit Windows 10).

So, back to the subject of this post, I did a bit of googling and full credit to https://bobsguides.com/blog.html/2014/10/23/git-bash-inside-phpstorm/ as I found the fastest way to switch the default terminal used by PhpStorm.

So make the switch, just go to:

Once here, change the “Shell Path” to:

For a 32-bit system, use

or the equivalent path to your git-shell installation.

The -login switch informs the program to run it’s configuration files and the -i switch informs the program that you want the interactive mode.

Настроить консоль phpStorm, чтобы были доступны unix-команды (как в Git bash)

Почему в command line tool phpStorm не работают команды ls , pwd , mkdir и др.?

В обычной cmd эти команды тоже не работают. Зато в консоли git bash работают. php, git, composer — работают везде. Но это, я так понимаю, потому что прописано в переменной PATH .

В чем отличие консольных утилит и как сделать так, чтобы команды работали?

Nick Volynkin's user avatar

Деня Деня's user avatar

По-умолчанию терминалом для PhpStorm является стандартный терминал windows cmd.exe . Для того чтобы настроить в PhpStorm bash терминал нужно изменить соответствующую настройку:

Phpstorm git bash terminal

-login и -i нужны для загрузки конфигурационных файлов и включения интерактивного режима.

Встроенный SSH клиент в PhpStorm

В этом руководстве описываются особенности использования встроенного SSH клиента в PhpStorm и удалённая работа с внешними инструментами по SSH.

Все действия, описанные здесь, были воспроизведены с корректными ожидаемыми результатами на PhpStorm 2016.2 под OS Windows 10 x64 Pro. Прежде чем продолжить, убедись, что у тебя есть доступ к какому-нибудь серверу по SSH.

SSH — это утилита и защищённый сетевой протокол для удалённого доступа к операционной системе компьютера, является основным средством для администрирования. С его помощью можно передавать, изменять файлы и каталоги, перезагружать сервер и многое другое.

Изучение основ использования протокола SSH и одноимённой утилиты не входит в рамки данного руководства.

1. Использование встроенного SSH клиента

Чтобы начать работу со встроенным SSH клиентом в PhpStorm тебе необходимо запустить SSH соединение. Для этого с помощью главного меню IDE выбери пункт [Tools → Start SSH session. ] . Откроется список Select host to connect (выбери хост для подключения).

PhpStorm: список "Select host to connect"

Если ранее ты уже настраивал, например, деплой, то увидишь существующие подключения в списке, в данном случае это dev и prod. Чтобы создать новое подключение и сохранить его конфигурацию, перейди через пункт главного меню IDE [Tools → Deployment → Configuration. ] в диалоговое окно Deployment . Все созданные здесь подключения с типом соединения SFTP далее будут отображаться в списке Select host to connect .

Чтобы создать одноразовое подключение, выбери пункт Edit credentials. (изменить учётные данные), откроется диалоговое окно SSH Session , как на скриншоте ниже. В нём укажи всю информацию о подключении: хост (локальный или удалённый), порт, имя пользователя и пароль.

PhpStorm: окно "SSH Session"

После ввода необходимых данных и нажатия кнопки ОК запускается SSH сессия в отдельной вкладке окна инструмента Terminal , в нижней панели окна инструментов.

PhpStorm: окно инструмента "Terminal"

Что можно делать в SSH сессии? Как обычно, в интерактивной сессии можно: запускать удалённо любые команды, копировать и вставлять, прокручивать историю команд с помощью клавиш со стрелками вверх и вниз.

2. Работа с внешним инструментом по SSH

Теперь определи внешний инструмент, который будет, например, показывать календарь и выполнять команду по SSH.

2.1. Настройка внешнего инструмента для доступа по SSH

С помощью пункта главного меню IDE [File → Settings. → Tools → Remote SSH External Tools] ты попадёшь в нужный подраздел, где с помощью кнопки, в форме плюсика, на панели инструментов ты можешь создать новый удалённый инструмент.

Дополнительные сведения по вопросу создания нового удалённого инструмента ты можешь получить из следующей справки PhpStorm: Внешние SSH инструменты.

В диалоговом окне Create Tool (скриншот ниже) укажи параметры нового инструмента:

  • Поле Name — это видимое имя нового инструмента.
  • Необязательное поле Description — это какое-нибудь осмысленное описание инструмента.
  • Необязательное поле Group — это имя группы, которая будет создана в меню Tools , и новый внешний SSH инструмент будет расположен в этой группе.
  • Область Tool Settings содержит все настройки для инструмента, который будет выполняться удалённо. На скриншоте ниже используется Bash команда cal . Поле Arguments (аргументы) и поле Working directory (рабочий каталог) не обязательны к заполнению. Также ты можешь использовать макросы для ввода параметров инструмента.
  • Область Connection settings содержит различные переключатели. Используй переключатель Deployment server и выбери из списка пункт Select server on every run . Он означает, что каждый раз при запуске удалённого инструмента, необходимо выбирать какое подключение к серверу будет использовано.

Нажми кнопку ОК , чтобы закрыть диалоговое окно Create Tool (создать инструмент) и вернуться в подраздел Remote SSH External Tools . Теперь в нём ты увидишь новый инструмент в списке.

PhpStorm: окно настроек раздела "Remote SSH External Tools"

2.2. Запуск внешнего инструмента по SSH

После создания или настройки инструмента он отобразится в ранее указанном меню. В данном случае это меню Tools , также инструмент будет находиться в группе, определённой ранее.

Используй пункт главного меню PhpStorm [Tools → Auxiliary Tools → show calendar] и посмотри, что получится. После клика выбери существующее подключение или укажи параметры для одноразового подключения. Сделай правильный выбор.

И, наконец, ты увидишь календарь!

PhpStorm: окно инструмента "Run"

3. О встроенном локальном терминале *

Терминал в PhpStorm под Windows по умолчанию использует интерпретатор командной строки Cmd.exe. Функциональность встроенного локального терминала можно увеличить с помощью, использования Git Bash, ты ведь наверняка используешь Git. Если всё так, то с помощью пункта главного меню IDE [File → Settings. → Tools → Terminal] перейди в настройки подраздела Terminal . В нём есть параметр Shell path (путь к шеллу), в секции Application settings (настройки приложения), значение которого тебе нужно изменить, например, на следующее:

Дополнительную информацию по улучшению функциональности терминала ты можешь найти в материалах 2-х последних ссылок блока Источники и дополнительные материалы данного руководства.

Пункт является опциональным при изучении руководства: Встроенный SSH клиент в PhpStorm.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *