Open files in existing Gvim in multiple (new) tabs - bash

I have put some aliases in my .bashrc to open a group of project files in gvim, each in their own tab:
gvim -p <list of file names using absolute paths>
This is all well and good, except there are several groups of files I might want to move between at any given time (my current project uses Ruby on Rails, so that explains that). What would be really awesome is if I could append the new tabs to an existing instance of gvim. In my last position I worked on Vista; I got around this by opening a bunch of empty tabs in gvim, which allowed me to right-click on a filename and choose "Open in existing No-Name gvim." Now I use Ubuntu and there's no such thing on the context menu. Is there any way to do this from the command line?

If vim is compiled with the clientserver option, you can do it. Start your vim instance with the following flag:
$ gvim --servername GVIM # GVIM is the server name. It can be anything.
To open more tabs in this instance, you can run the command:
$ gvim --servername GVIM --remote-tab file1 file2 file3 ...
The clientserver feature in vim is very handy. It's not limited to opening files; it can be used to send any command to vim using the command-line. For example, to close a vim instance remotely, you can use:
$ gvim --servername GVIM --remote-send '<Esc>:wqa<CR>'

From inside of Gvim, type :tabe {file_name}. This opens the named file in a new tab. If you aren't fond of typing long filenames, try this:
:tabnew
:e .
This will open a new, blank tab page and open a file browser. You can mouse click your way around or use the keyboard. Click or hit the enter key on the file you want to open it. Try using the keyboard to position the cursor over the file you want to open and then hit 't'. This opens the selected file in a new tab, keeping the file browser open in the first tab. This might be a fast way to open a bunch of files.
There are a whole lot of things you can do with tab pages that might make life easier. To get to the relevant section in Vim's on line help manual, type :h tabpage.

Want your Windows context menu to allow you to open files in a new tab of the currently open gvim window?
Save this as as a file called temp.reg and double-click it to add the settings to your registry. Be sure to modify the path to vim if yours is different.
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\*\Shell\Open with &Vim]
[HKEY_CLASSES_ROOT\*\Shell\Open with &Vim\command]
#="\"C:\\Program Files (x86)\\Vim\\vim73\\gvim.exe\" -p --remote-tab-silent \"%1\" \"%*\""
You will now have a context menu like this:

Linux users may use this kind of script:
#!/bin/bash
ANS=`pgrep -fx "gvim --servername GVIM"`
echo $#
if [[ ! $ANS ]]; then
gvim --servername GVIM
fi
if [[ $1 ]]; then
gvim --servername GVIM --remote-tab "${#}"
fi
And then edit gvim.desktop file for using this script:
Exec=/home/user/bin/my_gvim_script.sh %F

There is a way:
n*.cpp|tab ba
or if you like to split:
n*.cpp|sba
If you wish to know more:
:help ba
and I don't know what is n , but it would not work without it.

Here is my gvim start-up script. It is an extension of previous answers. It ensures only one gvim instance will run when gvim is called under all circumstances:
gvim is called without filename when no gvim instance is running; gvim is started.
gvim is called without filename in the presence of a gvim instance; an empty new tab is opened.
gvim is called with a filename with or without a gvim instance; a tab is opened showing the file.
This will mimic the standard behaviour of other editors.
#!/bin/bash
exec=/usr/bin/gvim #the path to gvim
if [ $# -eq 0 ]
then # no filename given
if [ -z $($exec --serverlist) ]
then # no filename given and no gvim instance
$exec -f --servername GVIM > /dev/null 2>&1
else # no filename given, but a gvim instance exists
$exec -f --servername GVIM --remote-send ':tabnew<CR>' > /dev/null 2>&1
fi
else # filenames given
$exec -f --servername GVIM --remote-tab "$#" > /dev/null 2>&1
fi

Related

How to start emacs from the terminal with an emacs command that runs soon after emacs is opened

Is there a way to launch Emacs from terminal and execute some Emacs command automatically soon after Emacs is launched (the command to be executed inside of emacs is provided along with the Emacs-launching command executed from the shell.)
What I want to do exactly is to have a command to launch Emacs and then open a new empty buffer and activate org mode inside of this buffer.
I want something that might look like this
emacs -fs --command="evil-buffer-new && org-mode"
I want the -fs flag because I want Emacs to open in full-screen in this case.
Update
--eval flag didn't work. Forget about evil-buffer-new, I have tried something as simple as:
emacs --eval="(org-mode)" txt.txt
txt.txt is an empty text file created before executing the above command (and please don't ask me why I didn't use .org file extension).
after Emacs opened, org-mode wasn't active. I had to run pp-eval-expression then (org-mode) to activate it, and then it worked.
Am I missing something here? How about rephrasing the question like this:
How to open an empty text file (having .txt file extension) with Emacs from the terminal and have org-mode activated in that buffer automatically?
See C-hig (emacs)Action Arguments or even just run emacs --help -- there are several options for loading and evaluating arbitrary code.
--command="evil-buffer-new && org-mode"
More like:
--eval="(progn (evil-buffer-new) (org-mode))"
But you'll have to figure it out for yourself, because I don't know what evil-buffer-new is specifically.
You told an empty file is created before emacs is started. But instead of an empty file could you create a file with file-local mode variable specifying the org mode ? For example with bash:
#!/bin/bash
cat <<EOF >> "$1"
; -*- mode: Org;-*-
EOF
emacs "$1" &
Now the mode is always resolved correctly with normal major mode selection procedure.

Can I open a file with geany from the terminal

I know there is a shortcut to open a file with sublime text from the terminal but id there something similar with geany, the only info I can find online about it is opening a file from geany to the terminal.
If Geany is inside your path, just call geany <file>. This should work on every platform, Geany is running.
Out of Geany's man page:
SYNOPSIS
geany [option] [+number] [files ...]
This will open files either in a new session or, if already a session of Geany is running, inside the existing one.
A file can be given as space separated list and might take even line numbers:
files ...
A space-separated list of filenames. Absolute and relative
filenames can be used. Geany also recognises line and column
information when appended to the filename with colons, e.g.
"geany foo.bar:10:5" will open the file foo.bar and place the
cursor in line 10 at column 5.
You can use open:
open [PATH_TO_FILE] -a [PATH_TO_GEANY_APP]
The a option defines which application to use.
To make this shorter, create an alias:
Something like echo 'alias geany="open $1 -a [PATH_TO_GEANY_APP]"' >> ~/.bash_profile && chmod u+x ~/.bash_profile. Then open a new Terminal window and type geany [path_to_file].

Delete specific line from Zsh history

I'd like to remove a specific entry in my Zsh history.
Zsh's fc and history don't have any options to delete entries. I've tried looking for the ~/.zhistory but that doesn't exist. How can I go about finding the location of the history file and remove the entry?
You are looking in wrong File. Look at ~/.zsh_history not ~/.zhistory To view in which file your history is saved:
echo $HISTFILE
And delete:
rm $HISTFILE
Clearing Zsh History (oh-my-zsh)
close, quit and re-open iTerm
run nano .zsh_history
use the arrow keys to navigate to the part of your history you'd like to delete.
use the delete key to remove all unwanted history logs.
Once you've removed everything you'd like to remove, select control X to Exit.
You'll be prompted to Save the changes. If you're happy with your changes click shift Y.
You'll be asked where you'd like to save your changes. Select control T to save to File.
navigate to your .zsh_profile with your arrow keys and press enter.
Quit and restart iTerm.
type history to confirm the deletions.
You've successfully cleared your Zsh history.
osxterminalzshoh-my-zsh
Clear zsh history on unix systems.
echo "" > ~/.zsh_history & exec $SHELL -l
open ~/.zshrc
add the following line
alias clear_history='echo "" > ~/.zsh_history & exec $SHELL -l'
Save and close the file
Close the console or type zsh
if you to see the result directly, but this will open another zsh shell in the old one
Now you can clear the console typing clear_history
All the previous answers are good, this is simply the solution that worked for me.
You can use these commands to open the ZSH command's history(When you are in the home or ~ directory) and assume that you know how to use vim or nano :
nano ~/.zsh_history
vim ~/.zsh_history
open ~/.zsh_history
then you can delete the lines you want manually and save the file.
and if your zsh_history list is too long, for convenience use this:
enable mouse move and line numbering in the Vim environment by adding this to .vimrc:
open .vimrc:
vim ~/.vimrc
add these to .vimrc and save it(press ESC, enter ":" , write wq, and press enter):
:set number
set mouse=a
use the mouse to scroll easily in zsh_history by using Vim.
if you want to enable copy in Vim use holding shift on the keyboard.
read this for more info
https://www.techrepublic.com/article/how-to-effectively-clear-your-bash-history/
TL;DR
cat /dev/null > ~/.zsh_history
Type and run at the zsh command line, openĀ ~/.zsh_history (This opens TextEdit on my Mac.)
Delete any lines in the file
Save and close the file
Close/Exit the Zsh completely and restart the Zsh (this step is important!)
Now, open zsh and the history command does not show the lines that you deleted
This function will remove any one line you want from your Zsh history, no questions asked:
# Accepts one history line number as argument.
# Alternatively, you can do `dc -1` to remove the last line.
dc () {
# Prevent the specified history line from being saved.
local HISTORY_IGNORE="${(b)$(fc -ln $1 $1)}"
# Write out history to file, excluding lines that match `$HISTORY_IGNORE`.
fc -W
# Dispose of the current history and read the new history from file.
fc -p $HISTFILE $HISTSIZE $SAVEHIST
# TA-DA!
print -r "Deleted '$HISTORY_IGNORE' from history."
}
If you additionally want to prevent all dc commands from being written to history, add the following in your ~/.zshrc file:
zshaddhistory() {
[[ $1 != 'dc '* ]]
}
Alternatively, for a comprehensive, out-of-the-box solution, use my Zsh Hist plugin.
E.g. with vim you can easily delete the last n lines like this:
Open file: vim ~/.zsh_history
Go to the bottom of the file: G
Mark lines: V -> move up with arrow key
Delete: d
Write & quit: :wq
Or you can just navigate with the cursor and delete any particular line with dd
Open .zsh_history with your favourite editor and save keystrokes.
e.g. subl .zsh_history will open up history in Sublime editor and then delete whatever you want.
You can use TextEdit or other editors also.
This worked for me:
LC_ALL=C sed -i '' '/line/d' $HISTFILE
Replace "line" with what you want deleted.
From this answer:
https://stackoverflow.com/posts/13661794/revisions
For ZSH
To locate the history file do :
echo $HISTFILE
Then simply edit the file and remove any lines you wish to be gone as you would with history -d id.
Save the file.
Open a new terminal and you should see that there is nothing to see anymore !
However I am amazed that history -d does not exists. If it does exists it's well hidden.

How can I create and open a file from terminal with a single command?

To create a file from terminal I type the following...
$ touch filename.py
To open the file I just created from terminal, I then type...
$ open filename.py
I'm curious to know if there is a terminal command that does both...create and then open (I'm super lazy).
in .bashrc
lazytouch()
{
touch $1
open $1
}
then type
$ lazytouch anything.really
This is as lazy as one can get:
$ echo "your text" > myfile.txt
Simplest way to do this is
touch filename; open filename
Example
touch myfile.py; open myfile.py
What I do when I want to create a file, edit it and just save it is I type vim at the terminal. vim is a text editor. If you just type in vim you would see the text editor.
But if you type for instance vim example.txt you open vim and from then on you are working in the file you created. The file does not get saved until you say so. So by pressing i you enter the edit mode of vim. Allowing you to put text in the file. If you want to save just enter escape followed by :w, meaning you are saving the file with the name you have it to it, so for this example it would be example.txt. After you saved it, everything you type after pressing Esc is shown left down in the screen, simple type :q to quite it.
If you realise you do not really want to save the file you can just type :q! and if you were currently in the editing mode, meaning you were typing something, you just press Esc once followed by :q!.
So short summary:
vim example.txt (opens the editor if saved it will use the given name)
s (will enable edit mode, you can write stuff)
Esc (when you want to stop editing)
:w (save the file)
:q (quit the file, only usable when saved!)
:q! (discard the save and just exit the file)
you can use the following to create a file named "filename.py", insert "Hello World" into the file and then open the file,
$ echo "Hello World" > filename.py && open filename.py
On a Mac to create a lazytouch function to create and open a file in one line you have to edit .bashrc. You might have to first create it. Beware if you are a novice programmer. Some of these commands might require you to prepend sudo for permission to create and save. Enter these commands in terminal.
$ cd ~
$ touch .bashrc
$ open .bash_profile
Enter this profile in .bash_profile to check for .bashrc
# To get aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
Remember to save .bash_profile. Then in bash do this.
$ open .bashrc
Enter this text in the .bashrc
# .bashrc
# User specific aliases and functions
lazytouch() {
touch $1
open $1
}
Remember to save .bashrc
Now you can cd to any folder then create and open a file with one line.
$ lazytouch anything.really
you can use:
cat -> youNewFile.someExtension
Example:
cat -> myNewFile.txt
After you are done press Ctrl + d to save or Ctrl + c to abort (but in this case it's gonna save an empty file.
The redirection operator ( > ) will create the file if it doesn't already exists in your folder and you will be able to edit it right a way through the terminal.

How to launch GUI Emacs from command line in OSX?

How do I launch GUI Emacs from the command line in OSX?
I have downloaded and installed Emacs from http://emacsformacosx.com/.
I'll accept an answer fulfilling all of the following criteria:
The emacs window opens in front of my terminal window.
Typing "emacs" launches a GUI Emacs window. Finding files in that window will default to looking in the directory from where I started Emacs.
Typing "emacs foo.txt" when foo.txt exists launches a GUI Emacs window with foo.txt loaded.
Typing "emacs foo.txt" when foo.txt does not exist launches a GUI Emacs window with an empty text buffer named "foo.txt". Doing ^X^S in that buffer will save foo.txt in the directory from where I started Emacs.
Call the following script "emacs" and put it in your PATH somewhere:
#!/bin/sh
/Applications/Emacs.app/Contents/MacOS/Emacs "$#"
That covers #2, #3, and #4.
For #1, put this somewhere in your .emacs file:
(x-focus-frame nil)
The emacsformacosx.com site now has a How-To page, which is where the top snippet came from. There's more info there about running emacsclient and hooking Emacs up to git mergetool.
In your shell, alias the command 'emacs' to point to the OSX emacs application
In my shell (running the default bash), I have the following (in my .bashrc)
alias emacs='open -a /Applications/Emacs.app $1'
Then, typing emacs on the command line starts the emacs application.
I would, however, recommend that you open a copy of emacs and just keep it up and running. If that's the case, and you want to load a file into an existing copy of emacs, you can use the emacsclient by placing the following in your .bashrc:
alias ec='/Applications/Emacs.app/Contents/MacOS/bin/emacsclient'
Then add the following to your .emacs file to start the emacs server (which receives the emacsclient calls)
;;========================================
;; start the emacsserver that listens to emacsclient
(server-start)
Then you can type
ec .bashrc
to load a copy of .bashrc into an existing emacs session!
This improves on David Caldwell's answer by starting Emacs in the background:
#!/bin/sh
$(/Applications/Emacs.app/Contents/MacOS/Emacs "$#") &
As stated in the other answer, this covers #2, #3, and #4. For #1, put this somewhere in your .emacs file: (x-focus-frame nil).
Note that the following does not work for me -- it does not start Emacs in a directory specified on the command line (e.g. emacs .)
# NOT RECOMMENDED
#!/bin/sh
/Applications/Emacs.app/Contents/MacOS/Emacs "$#" &
I assume you either:
Start the emacs daemon on login
Have (server-start) in your .emacs
Don't mind having lots of separate copies of emacs running
If so, then I think this satisfies the original four criteria, plus one more:
The emacs window opens in front of my terminal window.
it will always open to the foreground (with x-focus-frame).
Typing "emacs" launches a GUI Emacs window. Finding files in that window will default to looking in the directory from where I started Emacs.
It will open an existing emacs window in dired mode.
Typing "emacs foo.txt" when foo.txt exists launches a GUI Emacs window with foo.txt loaded.
If emacs is already running and has a server, then it will open in the existing window and come to the foreground.
Typing "emacs foo.txt" when foo.txt does not exist launches a GUI Emacs window with an empty text buffer named "foo.txt". Doing ^X^S in that buffer will save foo.txt in the directory from where I started Emacs.
Correct.
One extra:
Control returns to the terminal session immediately after typing the command.
~/bin/emacs
#!/bin/bash
EMACSPATH=/Applications/Emacs.app/Contents/MacOS
# Check if an emacs server is available
# (by checking to see if it will evaluate a lisp statement)
if ! (${EMACSPATH}/bin/emacsclient --eval "t" 2> /dev/null > /dev/null )
then
# There is no server available so,
# Start Emacs.app detached from the terminal
# and change Emac's directory to PWD
nohup ${EMACSPATH}/Emacs --chdir "${PWD}" "${#}" 2>&1 > /dev/null &
else
# The emacs server is available so use emacsclient
if [ -z "${#}" ]
then
# There are no arguments, so
# tell emacs to open a new window
${EMACSPATH}/bin/emacsclient --eval "(list-directory \"${PWD}\")"
else
# There are arguments, so
# tell emacs to open them
${EMACSPATH}/bin/emacsclient --no-wait "${#}"
fi
# Bring emacs to the foreground
${EMACSPATH}/bin/emacsclient --eval "(x-focus-frame nil)"
fi
On Mountain Lion, I am using Yamamoto Mitsuharu's port https://github.com/railwaycat/emacs-mac-port with the following alias:
alias emacs=/Applications/Emacs.app/Contents/MacOS/Emacs
and it satisfies all of your criteria.
Just built emacs with homebrew package manager according to this guide:
http://www.emacswiki.org/emacs/EmacsForMacOS
with brew install --cocoa emacs
After that one should launch the .app version to get gui, which in my case was /usr/local/Cellar/emacs/24.3/Emacs.app/Contents/MacOS/Emacs
Further improving on David James' response the following works for me:
Per instructions to open a file from a terminal found at http://www.emacswiki.org/emacs/EmacsForMacOS#toc20
open -a /Applications/Emacs.app <file-name>
combining this with David Jame's response I've created the following emax bash script and placed it in my path at ~/bin
#!/bin/bash
(open -a /Applications/Emacs.app "$#") &
Caveat: in order to get emacs to open the current directory in Dired by name mode, you need to use
emax .
Environment:
OS X Yosemite Version 10.10.2
GNU Emacs 24.4.2 (x86_64-apple-darwin14.0.0, NS apple-appkit-1343.14)
of 2014-11-13
Simple solution...
A lot of very complex solutions to this problem are posted here. That's fair because it seems non-trivial.
However, this solution works really well for me.
ec() {
emacsclient -n $# 2> /dev/null
if [[ $? == 1 ]]; then
open -a Emacs.app -- $#
fi
}
Usage
ec file [...]
Let's unpack what's happening:
pass all the ec arguments to emacsclient and don't (-n) wait for emacs before continuing.
If Emacs is already running, we're all done and you're editing.
swallow up the error message posted by emacsclient when there's no emacs running. (2> /dev/null)
Manually handle the exit code 1 ([[ $? == 1 ]])
open Emacs.app and pass file arguments to it (paths will be correctly opened.)
You're all done, and Emacs has opened your files.
The other answers here didn't quite work for me. In particular, on my machine, the bash script
#!/bin/sh
/Applications/Emacs.app/Contents/MacOS/Emacs "$#"
always opens emacs in the home directory. To get it to open in the current working directory, I had to do
#!/bin/sh
/Applications/Emacs.app/Contents/MacOS/Emacs "$PWD/$#"
instead.
Compile Emacs according to the following steps:
./configure --with-x --prefix=/usr
make
sudo make install
And your done! It may help to download and install XQuartz, but that's just my opinion.
This is my script for open emacs/emacsclient on osx.
#!/bin/bash
# Ensure (server-start) is added in your emacs init script.
EMACS=/Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs
EMACSCLIENT=/Applications/Macports/Emacs.app/\
Contents/MacOS/bin/emacsclient
# test if client already exsit.
$EMACSCLIENT -e "(frames-on-display-list)" &>/dev/null
# use emacsclient to connect existing server.
if [ $? -eq 0 ]; then
$EMACSCLIENT -n "$#"
# open emacs.app instead.
else
`$EMACS "$#"` &
fi
In all of the above when using "open" - make sure you use the "--args" option
Do not do this:
alias emacs='open -a /Applications/Emacs.app $1'
Instead this:
alias emacs='open -a /Applications/Emacs.app --args $1'
the --args option prevents "open" from consuming various options intended for Emacs.
The top answer is good, but I wanted the emacs process to run in the background so I could still use my shell. This answer appeared to do what I wanted, but didn't start emacs in the right directory, meaning absolute paths were required (or hacks to append pwd to the paths which wouldn't work in all cases). Furthermore, simply using & meant that if I killed the terminal, emacs would also be killed.
I decided to use screen and a bash function, and the following solution works for me on macOS 10.15.6 and emacs 26.2 installed with brew:
function emacs() {
screen -d -m /Applications/Emacs.app/Contents/MacOS/Emacs "$#"
}
For the meaning of the -d -m command line flags, they have a special meaning when used together and so can essentially be thought of as one command line flag. The explanation is in the manpage:
Start screen in "detached" mode. This creates a new session but doesn't attach to it. This is useful for system startup scripts.
open_emacs() {
num=$(ps aux | grep -E "[E]macs-x86_64-10_14 --|[e]macs --" | wc -l)
if [ $num -eq 0 ]; then
echo "## starting emacs"
# Run in a subshell to remove notifications and close STDOUT and STDERR:
(&>/dev/null emacsclient -t -q &)
fi
}
alias e="open_emacs"
Following line (&>/dev/null emacsclient -t -q &) will start the emacs daemon if it is not running on the background.
macOS may have defined the app name starting with E (ex: Emacs-x86_64-10_14.app), based on that you can check whether the emacs daemon running on the background or not.
Just want to update a response to this question. Since it is still a relevant question, but now there is an easier solution:
brew install --cask emacs
When this installs Emacs, it does the behavior you requested, without further intervention. It even runs the Emacs Server on startup.
Files installed/linked by default:
ebrowse -> /Applications/Emacs.app/Contents/MacOS/bin/ebrowse
emacs -> /Applications/Emacs.app/Contents/MacOS/Emacs
emacsclient -> /Applications/Emacs.app/Contents/MacOS/bin/emacsclient
etags -> /Applications/Emacs.app/Contents/MacOS/bin/etags
BTW, this is now a recommended way of installing Emacs on MacOS:
https://www.gnu.org/software/emacs/download.html#nonfree

Resources