Neovim, how to jump back to a terminal - neovim

help terminal-input said
To use `ALT+{h,j,k,l}` to navigate windows from any mode: >
:tnoremap <A-h> <C-\><C-N><C-w>h
:tnoremap <A-j> <C-\><C-N><C-w>j
:tnoremap <A-k> <C-\><C-N><C-w>k
:tnoremap <A-l> <C-\><C-N><C-w>l
:inoremap <A-h> <C-\><C-N><C-w>h
:inoremap <A-j> <C-\><C-N><C-w>j
:inoremap <A-k> <C-\><C-N><C-w>k
:inoremap <A-l> <C-\><C-N><C-w>l
:nnoremap <A-h> <C-w>h
:nnoremap <A-j> <C-w>j
:nnoremap <A-k> <C-w>k
:nnoremap <A-l> <C-w>l
.
Thus I add these shortcut maps into my init file. And when a terminal is open, i type <A-j>, the cursor jumped from the terminal into the normal interface (The terminal interface does not close.). i want jump back to the terminal interface. However, all the shortcuts do not work. They only jump across windows.

:) i wanted the same thing i searched online to learn how to write a custom function around buffers, then came with this:
function SwitchToTerm()
let term_bufs = getbufinfo({'buflisted':1})
let curr_buf = bufnr('%')
call filter(term_bufs, 'v:val.name =~ "^term"')
call filter(term_bufs, 'v:val.bufnr != ' . curr_buf)
call map(term_bufs, { _, e -> ({"nr": e.bufnr, "lu": e.lastused}) })
if bufname('%') =~ "^term"
call sort(term_bufs, { b1, b2 -> b1.lu - b2.lu })
else
call sort(term_bufs, { b1, b2 -> b2.lu - b1.lu })
endif
exec "b " . term_bufs[0].nr
endfunction
nnoremap <silent> <Leader>t :call SwitchToTerm()<cr>
in my ~/.vimrc and using Neovim but not sure if that matters. It is supposed to go to the most recently used buffer, then continuously cycle through terminal buffers if already on at a terminal. I switch to BufExplorer a lot to visit another file, and the last terminal becomes iffy there... but switching buffers directly from the command line works fine.

Related

How to include specific hidden file/folder in search result when using telescope.nvim?

I'm using neovim and Telescope as a finder (find_files, live_grep, file_browser), by default Telescope is ignoring hidden files and files included in .gitignore - how can I add exception (e.g. .gitlab-ci file/folder) to this list? so Telescope will still ignore hidden files except .gitlab-ci file/folder?
Use default filter ignore pattern for that like that
telescope.setup {
....
defaults = {
....
file_ignore_patterns = {
"node_modules", "build", "dist", "yarn.lock"
},
}
}
I know you can find this in someone's vimrc files or telescope docs. But may help some newbies.
Telescope uses ripgrep to search through files. By default, ripgrep ignores several groups of files, including hidden files (dotfiles) and files ignored by git. Adding --no-ignore-vcs and --hidden flags will make it to search through those files.
Arguments for ripgrep can be configured via defaults.vimgrep_arguments.
In your case, to search through hidden files, which are not in .gitignore --hidden flag should be added:
require('telescope').setup{
defaults = {
vimgrep_arguments = {
'rg',
'--color=never',
'--no-heading',
'--with-filename',
'--line-number',
'--column',
'--smart-case',
'--hidden',
},
}
You can always test the command from the terminal before changing the Telescope configuration:
rg ... --hidden <search string>
As --hidden will enable search through all hidden files, you might want to look into .ignore or .rgignore files. They tell ripgrep which files to ignore during search. See ripgrep's documentation for more info.
After several weeks of intense reading and testing, I have found the for me easiest solution here.
In order to find HIDDEN FILES, I have added the following lines to
.config/nvim/init.vim
nnoremap fff <cmd>Telescope find_files <cr>
nnoremap ffh <cmd>Telescope find_files hidden=true<cr>
When yo launch Neovim UI, pressing fff pops up the Telescope find_file screen, and when you press ffh, you can search for HIDDEN files.
To search for hidden files in LIVE_GREP, the work was a bit more difficult.
From my perspective, the most elegant solution is to first create the following file : .config/nvim/lua/find_hidden.lua
Inside goes :
local telescope = require("telescope")
local telescopeConfig = require("telescope.config")
-- Clone the default Telescope configuration
local vimgrep_arguments = { unpack(telescopeConfig.values.vimgrep_arguments) }
-- I want to search in hidden/dot files.
table.insert(vimgrep_arguments, "--hidden")
-- I don't want to search in the `.git` directory.
table.insert(vimgrep_arguments, "--glob")
table.insert(vimgrep_arguments, "!**/.git/*")
telescope.setup({
defaults = {
-- `hidden = true` is not supported in text grep commands.
hidden = true,
vimgrep_arguments = vimgrep_arguments,
},
pickers = {
find_files= {
hidden = true,
-- `hidden = true` will still show the inside of `.git/` as it's not `.gitignore`d.
find_command = { "rg", "--files", "--hidden", "--glob", "!**/.git/*" },
},
},
})
----- This activates the search for hidden files in live_grep
require("telescope").setup {
pickers = {
live_grep = {
additional_args = function(_ts)
return {"--hidden"}
end
},
},
}
The add the following the following lines to your init.vim :
:lua require('find_hidden')
nnoremap gre <cmd>Telescope live_grep <cr>
To sum it up: with the find_hidden.lua file and the following lines in your init.vim, you can easily search for hidden and non-hidden files both in telescope_find_files and telescope_live_grep :
:lua require('find_hidden')
nnoremap fff <cmd>Telescope find_files <cr>
nnoremap ffh <cmd>Telescope find_files hidden=true<cr>
nnoremap gre <cmd>Telescope live_grep <cr>

How to fold all open editors in visual studio code using a script

I would like to be able to create/write a command to fold all code in all open editors within visual studio code.
I believe I am very close.
I am using the "script commands" extension written by Marcel J. Kloubert
When I use the following script with 7 or so open editors in a single group. I achieve the following:
The open editor (at the time of execution) has its code folded
VSC will loop over the open editors
No other editor has its code folded
The script I am using:
// Fold all code in all open editors.
function execute(args) {
// Obtain access to vscode
var vscode = args.require('vscode');
// Set number of open editors... (future: query vscode for number of open editors)
var numOpenEditor = 20;
// Loop for numOpenEditor times
for (var i = 0; i <= numOpenEditor; i++){
// Fold the current open editor
vscode.commands.executeCommand('editor.foldAll');
// Move to the next editor to the right
vscode.commands.executeCommand('workbench.action.nextEditor');
// Loop message
var statusString = 'Loop ->' + i
// print message
vscode.window.showErrorMessage(statusString);
}
}
// Script Commands must have a public execute() function to work.
exports.execute = execute;
I have made an interesting observation, when I use the above script with 7 or so open editors with two groups or more. Something about switching to a new group will allow the command editor.foldAll to work. Note, that if a group has multiple editors, the only editor to fold its code is the open editor in the group. Thus, all other editors will not fold.
I also thought that maybe... the script needed to slow down, so I added a function to pause on every iteration. This did not turn out to work either.
Any help would be great!
You just need to make this function async and wait for the executeCommand calls to complete before moving on:
// Fold all code in all open editors.
async function execute(args) {
// Obtain access to vscode
var vscode = args.require('vscode');
// Set number of open editors... (future: query vscode for number of open editors)
var numOpenEditor = 5;
// Loop for numOpenEditor times
for (var i = 0; i <= numOpenEditor; i++) {
// Fold the current open editor
await vscode.commands.executeCommand('editor.foldAll');
// Move to the next editor to the right
await vscode.commands.executeCommand('workbench.action.nextEditor');
// Loop message
var statusString = 'Loop ->' + i
// print message
vscode.window.showErrorMessage(statusString);
}
}
// Script Commands must have a public execute() function to work.
exports.execute = execute;

How to insert text into terminal buffer of nvim by :normal command?

In a normal buffer of nvim, the following ex command works.
:normal! GAabcd
This adds the text "abcd" to the current normal buffer.
But in a terminal buffer of nvim, the above ex command doesn't work!
:normal! GAabcd
This just converts the terminal buffer into '-- TERMINAL --' mode and the "abcd" isn't added!
Why isn't the text added? How can I accomplish that?
I digged the neovim sources and maybe found the answer by myself.
In edit funtion of edit.c, there is the following comment.
bool edit(int cmdchar, bool startln, long count)
{
if (curbuf->terminal) {
if (ex_normal_busy) {
// Do not enter terminal mode from ex_normal(), which would cause havoc
// (such as terminal-mode recursiveness). Instead set a flag to force-set
// the value of `restart_edit` before `ex_normal` returns.
restart_edit = 'i';
force_restart_edit = true;
} else {
terminal_enter();
}
return false;
}
...
I think it means that it's not possible to enter terminal mode(insert mode) while processing normal commands in ex-mode. Therefore the text 'abcd' wasn't added in terminal mode but was just processed as normal commands.
Your answer is correct in that it's not possible to append text using :normal! GAfoo. However, in the interests of answering your last question, you can do this:
:normal! "0p
So if you happen to have what you need in a register, you can always paste it.

Adding keyboard shortcuts for move cell up and move cell down

I am trying to add the Cntl+K and Cntl+J shortcuts to move cells up and down quickly. I viewed the issue on Github here for adding the shortcuts and found what looked to be a workable answer:
"For those (like me) who liked this shortcut, add this to your ~/.ipython/profile_default/static/custom/custom.js:
$([IPython.events]).on("app_initialized.NotebookApp", function () {
IPython.keyboard_manager.command_shortcuts.add_shortcut('ctrl-k', function (event) {
IPython.notebook.move_cell_up();
return false;
});
IPython.keyboard_manager.command_shortcuts.add_shortcut('ctrl-j', function (event) {
IPython.notebook.move_cell_down();
return false;
});
});
"
But my users/{my name}/.ipython/profile_default directory did not have a static folder. I tried adding the missing folders and custom.js file, and reopened Anaconda prompt, but this did not add the missing shortcuts.
Another answer had the same issue:
"Use the following:
$ cat ~/.jupyter/custom/custom.js
define(["base/js/namespace"], function(Jupyter){
console.info('Binding Ctrl-J/K to move cell up/down');
Jupyter.keyboard_manager.command_shortcuts.add_shortcut('Ctrl-k','jupyter-notebook:move-cell-up');
Jupyter.keyboard_manager.command_shortcuts.add_shortcut('Ctrl-j','jupyter-notebook:move-cell-down');
});
"
This answer also did not work (adding the missing folder and custom.js file did not work).
As proposed in the official doc (got with the "Help>Notebook" menu action),
you could try first in a live notebook. The browser javascript console helps too.
I tried:
%%javascript
IPython.keyboard_manager.command_shortcuts.add_shortcut('Ctrl-k','jupyter-notebook:move-cell-up');
// replacing IPython with Jupyter should work as well:
Jupyterkeyboard_manager.command_shortcuts.add_shortcut('Ctrl-j','jupyter-notebook:move-cell-down');
It works but, just as when clicking on the corresponding toolbar button, the console warns about deprecation
in favor of IPython.notebook.move_selection_up() .
The string "jupyter-notebook:move-cell-up" refers to the same action.
So I suppose a reasonnable thing to do is to redefine it from scratch:
IPython.keyboard_manager.command_shortcuts.add_shortcut('Ctrl-k', {
help : 'move up selected cells',
help_index : 'jupyter-notebook:move-selection-up',
handler : function (event) {
IPython.notebook.move_selection_up();
return false;
}}
);
IPython.keyboard_manager.command_shortcuts.add_shortcut('Ctrl-j', {
help : 'move down selected cells',
help_index : 'jupyter-notebook:move-selection-down',
handler : function (event) {
IPython.notebook.move_selection_down();
return false;
}}
);
After executing the notbook cell (or the code in your browser console), it should
be active and you can experiment with it.
Once happy, check the path of your jupyter profile with !jupyter --config, and from there
you'd know where to copy your code : <profile>/static/custom/custom.js
so that it would be active in next jupyter sessions.

Automatically open the Safari Debugger when the iPhone Simulator is launched

The iOS web debugger in Safari is the bee's knees, but it closes every time the Simulator is restarted. Not only is it annoying to re-open it from the menu after every build, but it makes it tricky to debug any behavior that happens during startup.
Is there a way to set up a trigger in Xcode to automatically open the Safari debugger after every build, or perhaps a way to build a shell script or Automator action to do a build and immediately open the debugger?
This is a partial solution. This opens the debug window of Safari with one click which is a lot better but not automatic.
Open Script Editor on your mac (Command + Space Bar and type in Script Editor)
Paste in this code:
-- `menu_click`, by Jacob Rus, September 2006
--
-- Accepts a list of form: `{"Finder", "View", "Arrange By", "Date"}`
-- Execute the specified menu item. In this case, assuming the Finder
-- is the active application, arranging the frontmost folder by date.
on menu_click(mList)
local appName, topMenu, r
-- Validate our input
if mList's length < 3 then error "Menu list is not long enough"
-- Set these variables for clarity and brevity later on
set {appName, topMenu} to (items 1 through 2 of mList)
set r to (items 3 through (mList's length) of mList)
-- This overly-long line calls the menu_recurse function with
-- two arguments: r, and a reference to the top-level menu
tell application "System Events" to my menu_click_recurse(r, ((process appName)'s ¬
(menu bar 1)'s (menu bar item topMenu)'s (menu topMenu)))
end menu_click
on menu_click_recurse(mList, parentObject)
local f, r
-- `f` = first item, `r` = rest of items
set f to item 1 of mList
if mList's length > 1 then set r to (items 2 through (mList's length) of mList)
-- either actually click the menu item, or recurse again
tell application "System Events"
if mList's length is 1 then
click parentObject's menu item f
else
my menu_click_recurse(r, (parentObject's (menu item f)'s (menu f)))
end if
end tell
end menu_click_recurse
menu_click({"Safari", "Develop", "Simulator", "index.html"})
Once the simulator has opened, click run on your script (you might need to allow the script editor in the settings the first time).
(Optional) You can save your the scripts as an app so that you don't have to have the script editor open.
There is question that should be marked a duplicate that describes using setTimeout() to give you enough time to switch windows over to Safari and set a breakpoint.
Something like this, where startMyApp is the bootstrap function of your app:
setTimeout(function () {
startMyApp();
}, 20000);
It is super ghetto, but does work. I've submitted a feature request via http://www.apple.com/feedback/safari.html too to close the loop.
Extending upon the #Prisoner's answer, if you use WKWebView you could:
let contentController:WKUserContentController = WKUserContentController()
let pauseForDebugScript = WKUserScript(source: "window.alert(\"Go, turn on Inspector, I'll hold them back!\")",
injectionTime: WKUserScriptInjectionTime.AtDocumentStart,
forMainFrameOnly: true)
contentController.addUserScript(pauseForDebugScript)
let config = WKWebViewConfiguration()
config.userContentController = contentController
//Init browser with configuration (our injected script)
browser = WKWebView(frame: CGRect(x:0, y:0, width: view.frame.width, height: containerView.frame.height), configuration:config)
also important thing is to implement alert handler from WKUIDelegate protocol
//MARK: WKUIDelegate
func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String,
initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) {
let alertController = UIAlertController(title: message, message: nil,
preferredStyle: UIAlertControllerStyle.Alert);
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel) {
_ in completionHandler()}
);
self.presentViewController(alertController, animated: true, completion: {});
}
and one little thing just in case you could have an UIAlertController:supportedInterfaceOrientations was invoked recursively error add following extension (From this SO Answer)
extension UIAlertController {
public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
public override func shouldAutorotate() -> Bool {
return false
}
}
Combining Tom's answer with my solution, first do the following:
Create an application as Tom describes above
In "System Preferences -> Security & Privacy -> Privacy -> Accessibility" add your new Script Applicaiton and make sure it is allowed to control your computer
Now, I'm using cordova and from the command line the following builds, runs emulator and opens safari debug console:
cordova build ios; cordova emulate ios; open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app; sleep 1 ; open /PATH/TO/OpenDevelop.app/
Make sure to replace /PATH/TO/ with the appropriate path to where you saved your script.
Humm,I don't think you can do that,but you can just "CTRL+R" in the web debugger.