have neovim use both tmux buffers & system clipboard as both registers - buffer

I'm fairly new to neovim (nvim) so forgive my lack of knowledge, many questions are similar to mine, but not quite the same.
I would like this:
by default should cut/copy to a buffer, not system clipboard.
it's other register (I think its +, please correct me if its *!) should go to the system clipboard.
I have done some research but nothing (so far) is working for me.
Info:
I use tmux so pushing to tmux buffers.
I'm away from home, so currently using termux so termux-clipboard-get/set
Here is what I thought would work in my case:
let g:clipboard = {
\ 'name': 'TmuxTermux',
\ 'copy': {
\ '*': ['tmux', 'load-buffer', '-'],
\ '+': ['termux-clipboard-set'],
\ },
\ 'paste': {
\ '*': ['tmux', 'save-buffer', '-'],
\ '+': ['termux-clipboard-get'],
\ },
\ 'cache_enabled': 1,
\ }
Now when I cut/copy, tmux buffers share vim's content, PERFECT! (almost...),
I cannot use the + buffer to use the system clipboard though, if I press '+' its just moves my cursor down by one line, if I swap the above order (make termux-clipboard-get/set the * register, instead of +), when I press * it highlights all instances of the word my cursor is on.
From reading, I expected:
By default, nvim use * register, this seems to be true as it successfully registers to tmux buffers with dd/yy and pastes with p (or in tmux with my bind of [PREFIX]+[p]
If I want to cut/copy/paste to my other register + (system clipboard), then I would use +dd/+yy and then paste with +p (or even *dd/*yy/*p) but this isnt working for me.
Problem:
As explained above, + will move my cursor down one line, when changing it to the * register, * highlights the current word and any other occurance of it
Apologies to those with more experience, I'm fresh from emacs (with a very sore pinky finger!:)

In order to yank to or put from a specific register, you have to prepend the name of the register with a ":
Bad
Good
+dd
"+dd
*dd
"*dd
+yy
"+yy
*yy
"*yy

Here's what worked for me in neovim under tmux on macOS:
init.vim (vimscript):
let g:clipboard = {
\ 'name': 'macos+tmux',
\ 'copy': {
\ '+': ['pbcopy'],
\ '*': ['tmux', 'load-buffer', '-'],
\ },
\ 'paste': {
\ '+': ['pbpaste'],
\ '*': ['tmux', 'save-buffer', '-'],
\ },
\ 'cache_enabled': 0,
\ }
In neovim's source code, pbcopy/pbpaste is used without cache_enabled, and the documentation on that setting is confusing to me so I think it is safer to leave it off.
Note that you cannot only override one of the registers with this configuration -- meaning if you only want to change one of the registers' behavior, you still have to replicate the other register's functionality with this g:clipboard configuration. The source can be a helpful reference:
https://github.com/neovim/neovim/blob/22b538139606321bb1083665c510e81adb3d6670/runtime/autoload/provider/clipboard.vim
Also, since this isn't exactly documented, the idea with these configurations is that each array is a set of command line arguments, where the copied/pasted text is expected to be produced on STDIN and STDOUT respectively.

Related

how to get alignment or attention information for translations produced by a torch hub model?

The torch hub provides pretrained models, such as: https://pytorch.org/hub/pytorch_fairseq_translation/
These models can be used in python, or interactively with a CLI.
With the CLI it is possible to get alignments, with the --print-alignment flag. The following code works in a terminal, after installing fairseq (and pytorch)
curl https://dl.fbaipublicfiles.com/fairseq/models/wmt14.v2.en-fr.fconv-py.tar.bz2 | tar xvjf -
MODEL_DIR=wmt14.en-fr.fconv-py
fairseq-interactive \
--path $MODEL_DIR/model.pt $MODEL_DIR \
--beam 5 --source-lang en --target-lang fr \
--tokenizer moses \
--bpe subword_nmt --bpe-codes $MODEL_DIR/bpecodes \
--print-alignment
In python it is possible to specify the keyword args verbose and print_alignment:
import torch
en2fr = torch.hub.load('pytorch/fairseq', 'transformer.wmt14.en-fr', tokenizer='moses', bpe='subword_nmt')
fr = en2fr.translate('Hello world!', beam=5, verbose=True, print_alignment=True)
However, this will only output the alignment as a logging message. And for fairseq 0.9 it seems to be broken and results in an error message (issue).
Is there a way to access alignment information (or possibly even the full attention matrix) from python code?
I've browsed the fairseq codebase and found a hacky way to output alignment information.
Since this requires editing the fairseq sourcecode itself, I don't think it's an acceptable solution. But maybe it helps someone (I'm still very interested in an answer on how to do this properly).
Edit the sample() function and rewrite the return statement.
Here is the whole function (to help you find it better, in the code), but only the last line should be changed:
def sample(self, sentences: List[str], beam: int = 1, verbose: bool = False, **kwargs) -> List[str]:
if isinstance(sentences, str):
return self.sample([sentences], beam=beam, verbose=verbose, **kwargs)[0]
tokenized_sentences = [self.encode(sentence) for sentence in sentences]
batched_hypos = self.generate(tokenized_sentences, beam, verbose, **kwargs)
return list(zip([self.decode(hypos[0]['tokens']) for hypos in batched_hypos], [hypos[0]['alignment'] for hypos in batched_hypos]))

generating method declaration from .m file

I have a class which has all methods public. Today I decided to remove some of the methods that I don't need anymore, so I started to clean-up my .m file.
Now I would like to generate method declarations for my methods from .m to header file. I have started to copy-paste all lines, deleting implementation and adding ; at the end, but we live in XXI century and there might be some tools that may do that for me.
Is there any quick way to do that in AppCode and/or XCode? I heard something about accessorizer, but this tool is paid and I can't test it.
[EDIT]
I have found application called Accessorizer: http://www.kevincallahan.org/software/accessorizer.html
but it's paid and I cannot check if it will solve my problem.
AppCode has many interesting features to ease such things.
You can expose a method by using alt-enter on it:
You can also call a private (non exposed) method, and it will propose you to expose it. (alt-enter on highlighted error)
I often do the opposite, "programming by intuitions" as they call it. First write a call the method that does not exist and it will propose you to create a stub of it (with .h/.m declaration)
For those who do not use AppCode this bash script might help:
#!/bin/bash
if [[ -z "$1" ]]; then
echo "Usage $0 file"
exit 1
fi
while read -r line; do
if [[ "$line" =~ (\+|-)\ ?\( ]]; then
echo "${line% {};"
fi
done < $1

Masking user input & encoding

I wish to create a simple bash alias due to the amount of options & switches this particular set of functions requires. This is the background info and NOT the problem.
To perform the command in question requires a passphrase (often in multiple locations) which I would like to minimize and provide some privacy from other users at the same time.
Here is the alias example...
alias test="read -sp 'Enter passphrase: ' pass; gpg --batch --passphrase $pass --symmetric --cipher-algo aes256 -o file.ext.gpg file.ext"
The alias works fine, prompts the user to enter a passphrase and applies it to the decryption process.
THIS IS THE PROBLEM:
If I encrypt the file and enter a passphrase (without using the read -sp utlity as shown in the above example) the encrypted files password is different than if I use the 'read' binary to mask the input.
If I display the contents of $pass that was captured with read -sp it displays just as I typed it without any additional line endings etc.
Anyone experience this?
Shouldn't you quote $pass? In case it contains spaces etc. Also, you need to escape the $ to make it not expand while setting the alias.
So:
alias test="read -sp 'Enter pp: ' pass; gpg --passphrase \"\$pass\" --batch --symmetric --cipher-algo aes256 -o file.ext.gpg file.ext"
Besides this, you may want to use --passphrase-fd so the passphrase doesn't end up in ps output:
alias test="read -sp 'pp: ' pass; gpg --passphrase-fd 3 --etc-etc 3<<< \$pass"
A shell function will be simpler, as you eliminate a level of quoting, and allows parameters if the function needs to be generalized to other files.
# There is already a standard command called 'test'; use a different name
pass_encrypt () {
in=$1
out=$in.gpg
read -rsp 'Enter passphrase: ' pass
gpg --batch --passphrase-fd 3 --symmetric \
--cipher-algo aes256 -o "$out" "$in" 3<<<$pass
}
(with mvds' suggestion of using --passphrase-fd)

Can xgettext be used to extract specific domain strings only?

(Really surprised this isn't answered anywhere online; couple posts over the past few years with a similar question, but never answered. Let's hope the Stackoverflow crew can come to the rescue)
Situation:
When using gettext to support application localization, one sometimes wishes to specify a 'domain' with dgettext('domain', 'some text string'). However, when running xgettext, all strings wrapped with dgettext(...) are spit out into one file (default: messages.po).
Given the following example:
dgettext('menus', 'login link');
dgettext('menus', 'account link');
dgettext('footer', 'copyright notice');
dgettext('footer', 'contact form');
is there any way to end up with
menus.po
footer.po
using an extractor such as xgettext?
PHP response desired, although I believe this should be applicable across all languages
The only way I've found to do this is to redefine gettext functions...
example:
function _menus ($str) {
return dgettext('menus', $str);
}
function _footer ($_str) {
return dgettext('footer', $str);
}
_menus('login link');
_menus('account link');
_footer('copyright notice');
_footer('contact form');
else, you only have to run following commands:
xgettext [usual options] -k --keyword=_menus:1 -d menus
xgettext [usual options] -k --keyword=_footer:1 -d footer
Bye!
I do not know how to put different contexts in different files, but I did find that xgettext can extract the domain names into msgctxt fields in the po file. For PHP this is not done by default. To enable this, use for example --keyword=dgettext:1c,2 (in poedit, add "dgettext:1c,2") to the keyword list.
See also:
http://developer.gnome.org/glib/2.28/glib-I18N.html
https://www.gnu.org/savannah-checkouts/gnu/gettext/manual/html_node/xgettext-Invocation.html
Achieving this is best done through either code separation or the use of context disambiguation.
If you can separate your menu code from your footer code, then you can truly consider them different domains and extract them accordingly from known locations.
If modular separation is impossible and all the code lives together, then really you should be using context instead of domains. e.g.
translate( 'A string', 'myproject', 'some module' )
Where "myproject" is your domain and "some module" disambiguates the string.
However, reality doesn't always align with best practice, so if you can't refactor your code as Asevere suggests (and that is probably the best answer) then I have a massive hack to offer.
You could exploit the context flag mentioned in Boris's answer - We can repurpose this but only if we're not otherwise going to be using contexts.
I'll repeat that. This hack will only work if your code is not using contexts.
Some PHP holding two domains (including one string used in both) -
<?php // test.php
dgettext( 'abc', 'foo' );
dgettext( 'abc', 'bar' );
dgettext( 'xyz', 'bar' );
We can cheat, and take the domain argument as if we intended it to be the message context (msgctxt field). Extracting from the command line:
xgettext -LPHP --keyword=dgettext:1,2c -o - test.php \
| sed 's/CHARSET/utf-8/' \
> combined.pot
This generates a combined.pot file containing all the strings with our context hack. (note we also fixed the placeholder character set field which would break the next bit)
We can now filter out all messages of a given context into separate files using msggrep. Note we also trash the context field as we're not using it.
msggrep -J -e foo -o - combined.pot | sed '/^msgctxt/d' > foo.pot
msggrep -J -e bar -o - combined.pot | sed '/^msgctxt/d' > bar.pot
Improper, but it works.

Vim script to compile TeX source and launch PDF only if no errors

I am switching to using Vim for for my LaTeX editing environment. I would like to be able to tex the source file from within Vim, and launch an external viewing if the compile was successful.
I know about the Vim-Latex suite, but, if possible, would prefer to avoid using it: it is pretty heavy-weight, hijacks a lot of my keys, and clutters up my vimruntime with a lot of files.
Here is what I have now:
if exists('b:tex_build_mapped')
finish
endif
" use maparg or mapcheck to see if key is free
command! -buffer -nargs=* BuildTex call BuildTex(0, <f-args>)
command! -buffer -nargs=* BuildAndViewTex call BuildTex(1, <f-args>)
noremap <buffer> <silent> <F9> <Esc>:call BuildTex(0)<CR>
noremap <buffer> <silent> <S-F9> <Esc>:call BuildTex(1)<CR>
let b:tex_build_mapped = 1
if exists('g:tex_build_loaded')
finish
endif
let g:tex_build_loaded = 1
function! BuildTex(view_results, ...)
write
if filereadable("Makefile")
" If Makefile is available in current working directory, run 'make' with arguments
echo "(using Makefile)"
let l:cmd = "!make ".join(a:000, ' ')
echo l:cmd
execute l:cmd
if a:view_results && v:shell_error == 0
call ViewTexResults()
endif
else
let b:tex_flavor = 'pdflatex'
compiler tex
make %
if a:view_results && v:shell_error == 0
call ViewTexResults()
endif
endif
endfunction
function! ViewTexResults(...)
if a:0 == 0
let l:target = expand("%:p:r") . ".pdf"
else
let l:target = a:1
endif
if has('mac')
execute "! open -a Preview ".l:target
endif
endfunction
The problem is that v:shell_error is not set, even if there are compile errors. Any suggestions or insight on how to detect whether a compile was successful or not would be greatly appreciated! Thanks!
Between the answers given here, plus some study of other approaches, I think that this has been satisfactorily solved. I am posting the solution here in case anyone else is interested.
Basically, the best solution appears to be to use Rubber, a wrapper around LaTeX, that generally "just works", and provides very clean output/errors. The solution I present below preferentially uses Rubber if it is found on the system and no Makefile is found in the current directory. If a Makefile is found, it uses that instead. If there is no Makefile and Rubber is not installed, it uses pdflatex. In all cases, if the source fails to compile, the (filtered and parsed) errors are sent to the QuickFix buffer and the QuickFix window is automatically opened. If it compiles successfully, a short message is written, and if the user requested it, the PDF will be opened for viewing.
In my own installation, I have lifted the (excellent) "SetLatexEfm()" function from Vim-Latex to parse and filter the tex build output. If this function is not found, however, the function below defaults to setting an error message format that works fine enough for the errors to be identified and highlighted in the QuickFix window, albeit with lots of crud.
function! BuildTex(view_results, ...)
" record position
let save_cursor = getpos(".")
" save work
silent write
" From: http://stackoverflow.com/questions/2679475/vim-script-to-compile-tex-source-and-launch-pdf-only-if-no-errors
" If your shell is bash, you can use the ${PIPESTATUS} array variable to get
" the correct exit code (borrowed from this answer to another question).
silent setlocal shell=bash
silent setlocal shellpipe=2>&1\ \|\ tee\ %s;exit\ \${PIPESTATUS[0]}
let success = 1
if filereadable("Makefile")
" If Makefile is available in current working directory, run 'make' with arguments
echon "compiling using Makefile ..."
let l:makecmd = "make\\ ".join(a:000, '\\ ')
silent execute "setlocal makeprg=" . l:makecmd
try
" This function is defined in the Vim-Latex package,
" and provides excellent parsing and filtering of the error messages
" when running latex outside of the Rubber wrapper.
call s:SetLatexEfm()
catch /E117/
set errorformat=%E!\ LaTeX\ %trror:\ %m,
\%E!\ %m,
\%+WLaTeX\ %.%#Warning:\ %.%#line\ %l%.%#,
\%+W%.%#\ at\ lines\ %l--%*\\d,
\%WLaTeX\ %.%#Warning:\ %m,
\%Cl.%l\ %m,
\%+C\ \ %m.,
\%+C%.%#-%.%#,
\%+C%.%#[]%.%#,
\%+C[]%.%#,
\%+C%.%#%[{}\\]%.%#,
\%+C<%.%#>%.%#,
\%C\ \ %m,
\%-GSee\ the\ LaTeX%m,
\%-GType\ \ H\ <return>%m,
\%-G\ ...%.%#,
\%-G%.%#\ (C)\ %.%#,
\%-G(see\ the\ transcript%.%#),
\%-G\\s%#,
\%+O(%f)%r,
\%+P(%f%r,
\%+P\ %\\=(%f%r,
\%+P%*[^()](%f%r,
\%+P[%\\d%[^()]%#(%f%r,
\%+Q)%r,
\%+Q%*[^()])%r,
\%+Q[%\\d%*[^()])%r
endtry
silent make
else
let l:special_tex_compiler = "rubber"
if executable(l:special_tex_compiler)
echon "compiling with Rubber ..."
silent execute "setlocal makeprg=" . l:special_tex_compiler . "\\ -dfs\\ %"
setlocal errorformat=%f:%l:\ %m
silent make %
else
echon "compiling ..."
let b:tex_flavor = 'pdflatex'
compiler tex
silent make %
endif
endif
" set/report compile status
if v:shell_error
let l:success = 0
" let l:wheight = winheight(bufnr("%")) / 2
" execute "copen ".l:wheight
copen
else
let l:success = 1
cclose
redraw
echon "successfully compiled"
endif
" view results if successful compile
if l:success && a:view_results
call ViewTexResults()
endif
" restore position
call setpos('.', save_cursor)
endfunction
function! ViewTexResults(...)
if a:0 == 0
let l:target = expand("%:p:r") . ".pdf"
else
let l:target = a:1
endif
if has('mac')
silent execute "! open -a Preview ".l:target
" obviously, you will need to write specific commands for other systems
" left as an exercise for the reader ...
endif
endfunction
command! -buffer -nargs=* BuildTex call BuildTex(0, <f-args>)
command! -buffer -nargs=* BuildAndViewTex call BuildTex(1, <f-args>)
noremap <buffer> <silent> <F9> <Esc>:call BuildTex(0)<CR>
noremap <buffer> <silent> <S-F9> <Esc>:call BuildTex(1)<CR>
Update: I have packaged and published this as a Vim file-type plugin script, available at: http://www.vim.org/scripts/script.php?script_id=3230.
Assuming you're falling into the else-theres-no-makefile section, the issue may be with the shellpipe variable.
On my system (Ubuntu), shellpipe=2>&1| tee and the built-in make call doesn't set v:shell_error if it fails.
The return status of | tee might be what v:shell_error is getting set to.
If your shell is bash, you can use the ${PIPESTATUS} array variable to get the correct exit code (borrowed from this answer to another question).
:set shellpipe=2>&1\ \|\ tee\ %s;exit\ \${PIPESTATUS[0]}
Otherwise, you can try:
:set shellpipe=\>
:make %
This sets v:shell_error when it fails but I'm not sure if that will mess with the go-to-error-line-number functionality, if there is any.
To see what the variable is set to:
:set shellpipe?
I know it's not related to vim, but I think that latexmk does the job.
It's a script (written in perl) which compile the latex file and update the pdf. The most useful future is the auto-update one. As soon as you save your file, 'latexmk' compile it, and if your pdf viewer supports it, the view is updated.
latexmk -pdf -pvc
If latexmk runs latex with the '-halt-on-error' option (or in nonstop mode), compilation will cease without pausing for input.

Resources