MacOS X: как получить удобный ярлык «Открыть эту папку в iTerm»?

10542
Malax

Я думаю, что в заголовке указано именно то, что я хочу сделать. Мне нужен ярлык или даже кнопка в Finder, которая запускает новую вкладку iTerm и изменяет местоположение на местоположение, открытое в Finder. Что-то вроде open .наоборот. :-)

Спасибо малакс

11

9 ответов на вопрос

10
bulljit

Этот яблочный скрипт работает для меня:

-- script was opened by click in toolbar on run tell application "Finder" try set currFolder to (folder of the front window as string) on error set currFolder to (path to desktop folder as string) end try end tell CD_to(currFolder, false) end run  -- script run by draging file/folder to icon on open (theList) set newWindow to false repeat with thePath in theList set thePath to thePath as string if not (thePath ends with ":") then set x to the offset of ":" in (the reverse of every character of thePath) as string set thePath to (characters 1 thru -(x) of thePath) as string end if CD_to(thePath, newWindow) set newWindow to true -- create window for any other files/folders end repeat return end open  -- cd to the desired directory in iterm on CD_to(theDir, newWindow) set theDir to quoted form of POSIX path of theDir as string tell application "iTerm" activate delay 1 -- talk to the first terminal  try set myterm to the first terminal on error set myterm to (make new terminal) end try  tell myterm try -- launch a default shell in a new tab in the same terminal  launch session "Default Session" on error display dialog "There was an error creating a new tab in iTerm." buttons {"OK"} end try tell the last session try -- cd to the finder window write text "cd " & theDir on error display dialog "There was an error cding to the finder window." buttons {"OK"} end try end tell end tell end tell end CD_to 
Я думаю, что это должен быть принятый ответ. dhilipsiva 10 лет назад 1
8
Ross

Используя другие ответы на этой странице, я создал приложение, которое можно перетаскивать на панель задач поиска.

Вы можете скачать его здесь: https://github.com/rc1/iTermTo

Отличная работа! Работает отлично. Это должен быть принятый ответ. rcd 10 лет назад 1
Я согласен - кажется, работает отлично. Скачать почтовый индекс. Перетащите приложение в папку «Приложения» для установки. Перетащите приложение на панель инструментов поиска для удобного ярлыка. justingordon 10 лет назад 1
5
Forgotten Semicolon

Здесь есть открытый терминал AppleScript, который вы можете изменить, чтобы вместо этого вызывать iTerm. Этот пост MacOSXHints должен быть полезным.

(Я не на своем Mac, в противном случае я бы протестировал его.)

2
Lloyd Dewolf

Взгляните на cdtoпроект, размещенный на https://github.com/jbtule/cdto "Приложение панели инструментов Finder, чтобы открыть текущий каталог в Терминале (или iTerm, X11). Это приложение разработано (включая его значок) для размещения в панель инструментов окна поиска. "

Но он открывает два окна iTerms, что очень раздражает через некоторое время. Mike Lischke 10 лет назад 0
2
Brad Cupit

Это встроено в iTerm2 начиная с версии 3.1.0.

Чтобы использовать функциональность:
в Finder щелкните правой кнопкой мыши папку -> Службы -> Новое окно iTerm2 Здесь

Примечание: Servicesподменю находится в самом низу контекстного меню.

Ссылка
По этой ссылке нажмите Показать старые версии, затем в iTerm2 3.1.0 нажмите Показать список изменений и найдите службы, вы найдете это:

Добавить поддержку для поиска услуг. Вы можете щелкнуть правой кнопкой мыши в Finder, чтобы запустить iTerm2 в этом месте.

1
Ioannis Filippidis

Just for completeness, before finding this question what worked for me was:

  • adapted new_tab.sh (AppleScript issued by bash script) to an AppleScript-only solution.
  • then from the Applescript Editor-> File-> Export-> File Format = .app.
  • drag & dropped the .app to Finder's toolbar.

This results in a Finder toolbar button which opens the current directory in new iTerm2 tab. XtraFinder offers such a button, but it opens new windows.

A similar solution using services can be found here, which links to even more related AppleScript solutions:

My adapted AppleScript is:

try tell application "iTerm2" tell the last terminal launch session "Default Session" tell the last session tell i term application "Finder" set cur_dir to (the target of the front Finder window) as string end tell set cur_dir to POSIX path of cur_dir write text "cd " & cur_dir end tell end tell end tell end try 

This solution was commented in this button-related thread.

Thanks to the iTermTo answer above.

1
fikovnik

I guess it is because the internals of iTerm has changed, but none of the solutions worked for me. What did was the following code:

tell application "Finder" set cur_dir to POSIX path of ((the target of the front Finder window) as string) end tell tell application "iTerm" tell (create window with default profile) write current session text "cd " & quoted form of cur_dir end tell end tell 

Or using Automator as a finder service:

on run tell application "Finder" set cur_dir to POSIX path of (input as string) end tell tell application "iTerm" tell (create window with default profile) write current session text "cd " & quoted form of cur_dir end tell end tell end run 
0
coto

С iTerm:

Iterm Preferences и вкладка Under Profiles, перейдите в подвкладку General, установите для Working Directory значение «Повторное использование каталога предыдущего сеанса».

0
user495470

Вот упрощенный скрипт, который всегда открывает новую вкладку (как скрипт bulljit):

try tell application "Finder" if number of Finder windows is 0 then set p to POSIX path of (desktop as alias) else set p to POSIX path of (target of Finder window 1 as alias) end if end tell tell application "iTerm" reopen tell current terminal tell (launch session "Default Session") write text "cd " & quoted form of p end tell end tell activate end tell end try 

Если вы хотите, чтобы скрипт повторно использовал существующие вкладки, замените tell current terminalблок примерно так:

tell current session of current terminal write text "cd " & quoted form of p end tell 

Но это не сработает, если, например, текущий сеанс занят или выполняется процесс less или vim.

Оборачивание скрипта в блок try делает его молча неудачным. reopenоткрывает новое окно терминала, если нет видимых окон или если, например, открыто только окно настроек. У Finder также есть insertion locationсвойство, которое обычно находится target of Finder window 1на рабочем столе. Но есть ошибка в 10.7 и позже, когда она часто ссылается на какое-то другое окно, а не на переднее окно.

Некоторые потенциальные проблемы со скриптом bulljit:

  • У него задержка в одну секунду. Я не знаю, нужно ли это для чего-то, но мне не нужно было задержек при тестировании этого скрипта.
  • Если вы настроили iTerm на открытие новых окон в полноэкранном режиме, а открытых окон нет, открывается не полноэкранное окно.
  • Он говорит Finder, чтобы получить путь front window( window 1), который может быть информационным окном или окном настроек. Finder window 1всегда будет окно браузера файлов.
  • Он меняет каталог на, /если переднее окно Finder отображает представление, у которого нет пути (например, представление сети).

Я предпочитаю просто использовать такую ​​функцию:

cf () { c "$(osascript -e 'tell application "Finder" POSIX path of (target of Finder window 1 as alias end tell)' 2> /dev/null)" }