Vim <CR> mapping not working? - mapping

I just recently got into using vim, and am having great fun adding load of useful plugins. Problem is that at some point during setting up all of my plugins I hadn't noticed that the mapping for the enter key stopped working properly. In insert mode, when I press enter, if there is currently no auto-complete menu, instead of creating a newline it prints this:
pumvisible() ? "\" : "\"
Here is my vimrc:
"{{{Auto Commands
" Improve python indentation and higlighting
autocmd FileType python set complete+=k~/.vim/syntax/python.vim isk+=.,(
" Automatically cd into the directory that the file is in
autocmd BufEnter * execute "chdir ".escape(expand("%:p:h"), ' ')
" Remove any trailing whitespace that is in the file
autocmd BufRead,BufWrite * if ! &bin | silent! %s/\s\+$//ge | endif
" Restore cursor position to where it was before
augroup JumpCursorOnEdit
au!
autocmd BufReadPost *
\ if expand("<afile>:p:h") !=? $TEMP |
\ if line("'\"") > 1 && line("'\"") <= line("$") |
\ let JumpCursorOnEdit_foo = line("'\"") |
\ let b:doopenfold = 1 |
\ if (foldlevel(JumpCursorOnEdit_foo) > foldlevel(JumpCursorOnEdit_foo - 1)) |
\ let JumpCursorOnEdit_foo = JumpCursorOnEdit_foo - 1 |
\ let b:doopenfold = 2 |
\ endif |
\ exe JumpCursorOnEdit_foo |
\ endif |
\ endif
" Need to postpone using "zv" until after reading the modelines.
autocmd BufWinEnter *
\ if exists("b:doopenfold") |
\ exe "normal zv" |
\ if(b:doopenfold > 1) |
\ exe "+".1 |
\ endif |
\ unlet b:doopenfold |
\ endif
augroup END
"}}}
"{{{Misc Settings
" Necesary for lots of cool vim things
set nocompatible
" This shows what you are typing as a command. I love this!
set showcmd
" Folding Stuffs
set foldmethod=marker
" Needed for Syntax Highlighting and stuff
filetype on
filetype plugin on
syntax enable
set grepprg=grep\ -nH\ $*
" Who doesn't like autoindent?
set autoindent
" Spaces are better than a tab character
set expandtab
set smarttab
" Who wants an 8 character tab? Not me!
set shiftwidth=4
set softtabstop=4
" Use english for spellchecking, but don't spellcheck by default
if version >= 700
set spl=en spell
set nospell
endif
" Real men use gcc
"compiler gcc
" Cool tab completion stuff
set wildmenu
set wildmode=list:longest,full
" Enable mouse support in console
set mouse=a
" Got backspace?
set backspace=2
" Line Numbers PWN!
set number
" Ignoring case is a fun trick
set ignorecase
" And so is Artificial Intellegence!
set smartcase
" This is totally awesome - remap jj to escape in insert mode. You'll never type jj anyway, so it's great!
inoremap jj <Esc>
nnoremap JJJJ <Nop>
" Incremental searching is sexy
set incsearch
" Highlight things that we find with the search
set hlsearch
" Since I use linux, I want this
let g:clipbrdDefaultReg = '+'
" When I close a tab, remove the buffer
set nohidden
" Set off the other paren
highlight MatchParen ctermbg=4
" }}}
"{{{Look and Feel
" Favorite Color Scheme
if has("gui_running")
colorscheme desert
" Remove Toolbar
set guioptions-=T
"Terminus is AWESOME
set guifont=Terminus\ 9
set lines=999 columns=999
else
colorscheme desert
endif
"Status line gnarliness
set laststatus=2
set statusline=%F%m%r%h%w\ (%{&ff}){%Y}\ [%l,%v][%p%%]
" }}}
"{{{ Functions
"{{{ Open URL in browser
function! Browser ()
let line = getline (".")
let line = matchstr (line, "http[^ ]*")
exec "!konqueror ".line
endfunction
"}}}
"{{{Theme Rotating
let themeindex=0
function! RotateColorTheme()
let y = -1
while y == -1
let colorstring = "inkpot#ron#blue#elflord#evening#koehler#murphy#pablo#desert#torte#"
let x = match( colorstring, "#", g:themeindex )
let y = match( colorstring, "#", x + 1 )
let g:themeindex = x + 1
if y == -1
let g:themeindex = 0
else
let themestring = strpart(colorstring, x + 1, y - x - 1)
return ":colorscheme ".themestring
endif
endwhile
endfunction
" }}}
"{{{ Paste Toggle
let paste_mode = 0 " 0 = normal, 1 = paste
func! Paste_on_off()
if g:paste_mode == 0
set paste
let g:paste_mode = 1
else
set nopaste
let g:paste_mode = 0
endif
return
endfunc
"}}}
"{{{ Todo List Mode
function! TodoListMode()
e ~/.todo.otl
Calendar
wincmd l
set foldlevel=1
tabnew ~/.notes.txt
tabfirst
" or 'norm! zMzr'
endfunction
"}}}
"}}}
"{{{ Mappings
" Toggle line numbers and fold column for easy copying
nnoremap <silent> <F2> :set nonumber!<CR>:set foldcolumn=0<CR>
" Open the Project Plugin
nnoremap <silent> <Leader>pal :Project .vimproject<CR>
" TODO Mode
nnoremap <silent> <Leader>todo :execute TodoListMode()<CR>
" Open the TagList Plugin <F3>
nnoremap <silent> <F3> :Tlist<CR>
" Open the Fuf Plugin
nnoremap <silent> <F4> :FufFile<CR>
" Open the MRU Plugin
nnoremap <silent> <F5> :MRU<CR>
" Next Tab
nnoremap <silent> <C-Right> :tabnext<CR>
" Previous Tab
nnoremap <silent> <C-Left> :tabprevious<CR>
" New Tab
nnoremap <silent> <C-t> :tabnew<CR>
" Rotate Color Scheme <F8>
nnoremap <silent> <F8> :execute RotateColorTheme()<CR>
" DOS is for fools.
nnoremap <silent> <F9> :%s/$//g<CR>:%s// /g<CR>
" Paste Mode! Dang! <F10>
nnoremap <silent> <F10> :call Paste_on_off()<CR>
set pastetoggle=<F10>
" Execute python file being edited with <Shift> + e:
map <buffer> <S-e> :w<CR>:!/usr/bin/env python % <CR>
" Edit vimrc \ev
nnoremap <silent> <Leader>ev :tabnew<CR>:e ~/.vimrc<CR>
" Edit gvimrc \gv
nnoremap <silent> <Leader>gv :tabnew<CR>:e ~/.gvimrc<CR>
" Up and down are more logical with g..
nnoremap <silent> k gk
nnoremap <silent> j gj
inoremap <silent> <Up> <Esc>gka
inoremap <silent> <Down> <Esc>gja
" Good call Benjie (r for i)
nnoremap <silent> <Home> i <Esc>r
nnoremap <silent> <End> a <Esc>r
" Create Blank Newlines and stay in Normal mode
nnoremap <silent> zj o<Esc>
nnoremap <silent> zk O<Esc>
" Space will toggle folds!
nnoremap <space> za
" Search mappings: These will make it so that going to the next one in a
" search will center on the line it's found in.
map N Nzz
map n nzz
" Testing
set completeopt=longest,menuone,preview
inoremap <expr> <cr> pumvisible() ? "\<c-y>" : "\<c-g>u\<cr>"
inoremap <expr> <c-n> pumvisible() ? "\<lt>c-n>" : "\<lt>c-n>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"
inoremap <expr> <m-;> pumvisible() ? "\<lt>c-n>" : "\<lt>c-x>\<lt>c-o>\<lt>c-n>\<lt>c-p>\<lt>c-r>=pumvisible() ? \"\\<lt>down>\" : \"\"\<lt>cr>"
" Swap ; and : Convenient.
nnoremap ; :
nnoremap : ;
" Fix email paragraphs
nnoremap <leader>par :%s/^>$//<CR>
"ly$O#{{{ "lpjjj_%A#}}}jjzajj
"}}}
"{{{Taglist configuration
let Tlist_Use_Right_Window = 1
let Tlist_Enable_Fold_Column = 0
let Tlist_Exit_OnlyWindow = 1
let Tlist_Use_SingleClick = 1
let Tlist_Inc_Winwidth = 0
"}}}
let g:rct_completion_use_fri = 1
"let g:Tex_DefaultTargetFormat = "pdf"
let g:Tex_ViewRule_pdf = "kpdf"
let g:pydiction_location = "/home/axilus/.vim/after/ftplugin/python_pydiction/complete-dict"
filetype plugin indent on
syntax on
And my loaded scripts:
1: /usr/share/vim/vimrc
2: /usr/share/vim/vim72/debian.vim
3: /usr/share/vim/vim72/syntax/syntax.vim
4: /usr/share/vim/vim72/syntax/synload.vim
5: /usr/share/vim/vim72/syntax/syncolor.vim
6: /usr/share/vim/vim72/filetype.vim
7: /home/axilus/.vimrc
8: /usr/share/vim/vim72/ftplugin.vim
9: /usr/share/vim/vim72/syntax/nosyntax.vim
10: /usr/share/vim/vim72/colors/desert.vim
11: /usr/share/vim/vim72/indent.vim
12: /home/axilus/.vim/plugin/EasyMotion.vim
13: /home/axilus/.vim/plugin/NERD_tree.vim
14: /home/axilus/.vim/plugin/fuf.vim
15: /home/axilus/.vim/autoload/l9.vim
16: /home/axilus/.vim/autoload/fuf.vim
17: /home/axilus/.vim/autoload/fuf/buffer.vim
18: /home/axilus/.vim/autoload/fuf/file.vim
19: /home/axilus/.vim/autoload/fuf/coveragefile.vim
20: /home/axilus/.vim/autoload/fuf/dir.vim
21: /home/axilus/.vim/autoload/fuf/bookmarkfile.vim
22: /home/axilus/.vim/autoload/fuf/bookmarkdir.vim
23: /home/axilus/.vim/autoload/fuf/tag.vim
24: /home/axilus/.vim/autoload/fuf/buffertag.vim
25: /home/axilus/.vim/autoload/fuf/taggedfile.vim
26: /home/axilus/.vim/autoload/fuf/jumplist.vim
27: /home/axilus/.vim/autoload/fuf/changelist.vim
28: /home/axilus/.vim/autoload/fuf/quickfix.vim
29: /home/axilus/.vim/autoload/fuf/line.vim
30: /home/axilus/.vim/autoload/fuf/help.vim
31: /home/axilus/.vim/autoload/fuf/givenfile.vim
32: /home/axilus/.vim/autoload/fuf/givendir.vim
33: /home/axilus/.vim/autoload/fuf/givencmd.vim
34: /home/axilus/.vim/autoload/fuf/callbackfile.vim
35: /home/axilus/.vim/autoload/fuf/callbackitem.vim
36: /home/axilus/.vim/plugin/l9.vim
37: /home/axilus/.vim/plugin/matchit.vim
38: /home/axilus/.vim/plugin/mru.vim
39: /home/axilus/.vim/plugin/pydoc.vim
40: /home/axilus/.vim/plugin/snipMate.vim
41: /home/axilus/.vim/plugin/supertab.vim
42: /home/axilus/.vim/plugin/surround.vim
43: /home/axilus/.vim/plugin/taglist.vim
44: /home/axilus/.vim/plugin/tcomment.vim
45: /usr/share/vim/vim72/plugin/getscriptPlugin.vim
46: /usr/share/vim/vim72/plugin/gzip.vim
47: /usr/share/vim/vim72/plugin/matchparen.vim
48: /usr/share/vim/vim72/plugin/netrwPlugin.vim
49: /usr/share/vim/vim72/plugin/rrhelper.vim
50: /usr/share/vim/vim72/plugin/spellfile.vim
51: /usr/share/vim/vim72/plugin/tarPlugin.vim
52: /usr/share/vim/vim72/plugin/tohtml.vim
53: /usr/share/vim/vim72/plugin/vimballPlugin.vim
54: /usr/share/vim/vim72/plugin/zipPlugin.vim
55: /home/axilus/.vim/after/plugin/snipMate.vim
56: /home/axilus/.vim/nerdtree_plugin/exec_menuitem.vim
57: /home/axilus/.vim/nerdtree_plugin/fs_menu.vim
I'm new to vim, so if there is anything else that is needed please let me know.

Supertab includes a mapping to <CR> that conflicts with the "inoremap <expr> <cr> ..." mapping. Specifically if supertab is loaded after the other it breaks it. If the inoremap mapping comes after supertab is loaded then it works.
You could make your inoremap mappings after supertab by putting them in .vim/after/plugin/mappings.vim or similar.

You might try issuing the command :map <CR>, which will list current mappings for carriage return. If that doesn't help maybe you could try a grep across all the plugin files you have loaded for string that matches map <CR> and/or pumvisible.

What is this mapping supposed to be doing?
inoremap <expr> <cr> pumvisible() ? "\<c-y>" : "\<c-g>u\<cr>"
Seems like that's your problem. Not sure how to fix it, but I'm pretty sure if you take it out and restart, your return key will work again. I don't understand because return accepts the selected completion for me out of the box.

Related

Need msgbox text in a cell

I want below message in a cell:
Dim Msg As String
Msg = "Files moved: " & MovedCount & "(" & NotMovedCount + MovedCount & ")"
If NotMovedCount > 0 Then
Msg = Msg & vbLf & "Files not moved:" & NotMovedCount & "(" _
& NotMovedCount + MovedCount & ")" & vbLf & vbLf _
& "The following files were not moved:" & vbLf _
& Join(dict.keys, vbLf)
End If
MsgBox Msg, IIf(NotMovedCount = 0, vbInformation, vbCritical)
Could you please help me.
I am moving some files from one folder to another. If the files are already available in the target folder, this code gives list in message box. However i need that information in excel cell for example sheet 1, cell AF5.

Lua pattern matching problem with escaped letter

I've already had a rule that \ should be replaced with \\\\
, so the existed code is
string.gsub(s, '\\', '\\\\\\\\')
but there is some data that should not be converted, such as abc\"cba, which will be replaced with abc\\\\"cba.
How can I constraint that only \ followed without " can be replaced, such like
'abc\abc' -> 'abc\\\\abc'
'abc\"abc' -> 'abc\"abc'
I have used patterns like \\[^\"]- and \\[^\"]+- but none of them works.
Thanks
You can use
string.gsub((s .. ' '), '\\([^"])', '\\\\\\\\%1'):sub(1, -2)
See the online demo:
local s = [[abc\abc abc\"abc\]];
s = string.gsub((s .. ' '), '\\([^"])', '\\\\\\\\%1'):sub(1, -2)
print( s );
-- abc\\\\abc abc\"abc\\\\
Notes:
\\([^"]) - matches two chars, a \ and then any one char other than a " char (that is captured into Group 1)
\\\\\\\\%1 - replacement pattern that replaces each match with 4 backslashes and the value captured in Group 1
(s .. ' ') - a space is appended at the end of the input string so that the pattern could consume a char other than a " char
:sub(1, -2) - removes the last "technical" space that was added.

hf-tikz and sphinx are not playing well together

I am trying to add some color to my matrices in sphinx. I was using hf-tikz for it before. However, when I add it to Sphinx, it renders it incorrectly.
The result that I am trying to get is
The result I am getting is
Here is the code that I have.
main.rst:
.. math::
\left(\begin{array}{cc}
\tikzmarkin[style red]{a}a\tikzmarkend{a}
& \tikzmarkin[style green]{b}b\tikzmarkend{b} \\
\tikzmarkin[style blue]{c}c\tikzmarkend{c}
& \tikzmarkin[style orange]{d}d\tikzmarkend{d} \\
\end{array}\right)
\star
\left(\begin{array}{cc}
\tikzmarkin[style red]{w}w\tikzmarkend{w}
& \tikzmarkin[style green]{x}x\tikzmarkend{x} \\
\tikzmarkin[style blue]{y}y\tikzmarkend{y}
& \tikzmarkin[style orange]{z}z\tikzmarkend{z} \\
\end{array}\right)
=
\left(\begin{array}{cc}
\tikzmarkin[hor=style red]{aw}{a\star w}\tikzmarkend{aw}
& \tikzmarkin[hor=style green]{bx}b\star x\tikzmarkend{bx} \\
\tikzmarkin[hor=style blue]{cy}c\star y\tikzmarkend{cy}
& \tikzmarkin[hor=style orange]{dz}d\star z\tikzmarkend{dz} \\
\end{array}\right)
conf.py
extensions = [
'sphinx.ext.imgmath',
]
# Math configurations (https://tex.stackexchange.com/a/69770/51173)
imgmath_image_format = 'svg'
imgmath_use_preview = True
imgmath_latex_preamble = r'''
\usepackage{xcolor}
\usepackage[customcolors]{hf-tikz}
\colorlet{myred}{red!50!purple!30}
\colorlet{mygreen}{green!50!lime!60}
\colorlet{myblue}{blue!50!white!50}
\colorlet{myorange}{orange!80!red!60}
\colorlet{mycyan}{cyan!90!blue!60}
\colorlet{mymagenta}{magenta!90!red!60}
\tikzset{
style red/.style={
set fill color=myred,
set border color=white,
},
style green/.style={
set fill color=mygreen,
set border color=white,
},
style blue/.style={
set fill color=myblue,
set border color=white,
},
style orange/.style={
set fill color=myorange,
set border color=white,
},
style cyan/.style={
set fill color=mycyan,
set border color=white,
},
style magenta/.style={
set fill color=mymagenta,
set border color=white,
},
%
hor/.style={
above left offset={-0.15,0.31},
below right offset={0.15,-0.125},
#1
},
ver/.style={
above left offset={-0.1,0.3},
below right offset={0.15,-0.15},
#1
}
}
'''
Makefile
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
#$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
#$(SPHINXBUILD) -M $# "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
make.bat
#ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
EDIT: Added makefile used to build the rst's
I think I found why this was happening: the problem was in the sphinx.ext.imgmath extension + hf-tikz not working well with the DVI files.
When converting the math equations, sphinx creates a very basic latex document, and compiles it using latexpdf into a DVI file. After that the file is converted into an SVG, and the resulting svg file is copied to the sphinx's _build directory. The problem is that dvisvgm (used by imgmath) cannot convert tikz stuff. Alternative would be using extended DVI, but that doesn't work well either.
The solution is to compile everything into PDF, and convert that pdf into SVG. This is slightly problematic, and the only way I found is to use pdf2svg + pdfcrop. I ended up modifying the imgmath.py into a custom extension. Below are the changes that I put in the imgmath.py. The changes require the use of external applications, so I don't think there is a merit in creating a pull request (at least not with a more scalable solution).
Changes in the imgmath.py:
Create a new method:
def convert_pdf_to_svg(pdfpath, builder):
# type: (str, Builder) -> Tuple[str, int]
"""Convert DVI file to SVG image."""
tempdir = ensure_tempdir(builder)
filename = path.join(tempdir, 'math.svg')
name = 'pdfcrop'
command = [name, pdfpath, pdfpath]
run_external_command(command, name)
name = 'pdf2svg'
command = [name, pdfpath, filename]
run_external_command(command, name)
return filename, None
In the compile_math function, inside the try block, replace the return statement with the following
if builder.config.imgmath_pdf2svg:
return path.join(tempdir, 'math.pdf')
else:
return path.join(tempdir, 'math.dvi')
Inside the render_math method, in the block titles # .dvi -> .png/svg, replace the try block with the following
try:
if image_format == 'png':
imgpath, depth = convert_dvi_to_png(dvipath, self.builder)
elif image_format == 'svg':
if self.builder.config.imgmath_pdf2svg:
imgpath, depth = convert_pdf_to_svg(dvipath, self.builder)
else:
imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
except InvokeError:
self.builder._imgmath_warned_image_translator = True # type: ignore
return None, None
Finally, add a new configuration entry in the very end of the imgmath.py:
app.add_config_value('imgmath_pdf2svg', False, 'html')
After that, you can write in the conf.py to enable the tikz images.
imgmath_image_format = 'svg'
imgmath_latex = 'latexmk'
imgmath_latex_args = ['-pdf']
imgmath_pdf2svg = True # Available only in the custom `imgmath.py`
patch for imgmath extension. Includes some other stuff :)
The patch goes a->b.
--- a/imgmath.py
+++ b/imgmath.py
## -15,7 +15,7 ##
import sys
import tempfile
from hashlib import sha1
-from os import path
+from os import path, symlink
from subprocess import CalledProcessError, PIPE
from typing import Any, Dict, List, Tuple
## -157,6 +157,11 ##
with open(filename, 'w', encoding='utf-8') as f:
f.write(latex)
+ for add_file in builder.config.imgmath_latex_additional_files:
+ filename = path.join(tempdir, path.basename(add_file))
+ if not path.exists(filename):
+ symlink(path.join(builder.confdir, add_file), filename)
+
# build latex command; old versions of latex don't have the
# --output-directory option, so we have to manually chdir to the
# temp dir to run it.
## -165,9 +170,15 ##
command.extend(builder.config.imgmath_latex_args)
command.append('math.tex')
+ output_extension = 'dvi'
+ if builder.config.imgmath_latex == 'xelatex':
+ output_extension = 'xdv'
+ if builder.config.imgmath_pdf2svg:
+ output_extension = 'pdf'
+
try:
subprocess.run(command, stdout=PIPE, stderr=PIPE, cwd=tempdir, check=True)
- return path.join(tempdir, 'math.dvi')
+ return path.join(tempdir, 'math.' + output_extension)
except OSError:
logger.warning(__('LaTeX command %r cannot be run (needed for math '
'display), check the imgmath_latex setting'),
## -177,7 +188,7 ##
raise MathExtError('latex exited with error', exc.stderr, exc.stdout)
-def convert_dvi_to_image(command: List[str], name: str) -> Tuple[bytes, bytes]:
+def run_external_command(command: List[str], name: str) -> Tuple[bytes, bytes]:
"""Convert DVI file to specific image format."""
try:
ret = subprocess.run(command, stdout=PIPE, stderr=PIPE, check=True)
## -203,7 +214,7 ##
command.append('--depth')
command.append(dvipath)
- stdout, stderr = convert_dvi_to_image(command, name)
+ stdout, stderr = run_external_command(command, name)
depth = None
if builder.config.imgmath_use_preview:
## -227,7 +238,7 ##
command.extend(builder.config.imgmath_dvisvgm_args)
command.append(dvipath)
- stdout, stderr = convert_dvi_to_image(command, name)
+ stdout, stderr = run_external_command(command, name)
depth = None
if builder.config.imgmath_use_preview:
## -239,6 +250,21 ##
break
return filename, depth
+
+def convert_pdf_to_svg(pdfpath, builder):
+ # type: (str, Builder) -> Tuple[str, int]
+ """Convert DVI file to SVG image."""
+ tempdir = ensure_tempdir(builder)
+ filename = path.join(tempdir, 'math.svg')
+
+ name = 'pdfcrop'
+ command = [name, pdfpath, pdfpath]
+ run_external_command(command, name)
+
+ name = 'pdf2svg'
+ command = [name, pdfpath, filename]
+ run_external_command(command, name)
+ return filename, None
def render_math(self: HTMLTranslator, math: str) -> Tuple[str, int]:
## -291,7 +317,10 ##
if image_format == 'png':
imgpath, depth = convert_dvi_to_png(dvipath, self.builder)
elif image_format == 'svg':
- imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
+ if self.builder.config.imgmath_pdf2svg:
+ imgpath, depth = convert_pdf_to_svg(dvipath, self.builder)
+ else:
+ imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
except InvokeError:
self.builder._imgmath_warned_image_translator = True # type: ignore
return None, None
## -396,8 +425,10 ##
['-gamma', '1.5', '-D', '110', '-bg', 'Transparent'],
'html')
app.add_config_value('imgmath_dvisvgm_args', ['--no-fonts'], 'html')
+ app.add_config_value('imgmath_pdf2svg', False, 'html')
app.add_config_value('imgmath_latex_args', [], 'html')
app.add_config_value('imgmath_latex_preamble', '', 'html')
+ app.add_config_value('imgmath_latex_additional_files', [], 'html')
app.add_config_value('imgmath_add_tooltips', True, 'html')
app.add_config_value('imgmath_font_size', 12, 'html')
app.connect('build-finished', cleanup_tempdir)

Vim : getline and non ascii character

I use a single function (that a create) to know if the character next to the current cursor position is a space
function Test_caractere_suivant_espace()
"Test si le caractère suivant est une espace"
let position = getcurpos()
let ligne = getline(position[1])
let car_suivant = ligne[position[2]]
if car_suivant == ' '
return 1
else
return 0
endfunction
It work well… but only with Ascii characters, not with not Ascii characters in UTF-8.
Of course, I could try the value of the two first bits of the current character, but is there anyway to have UTF-8 characters in the array returned by getline and not a list of one-byte values?
A pist of solution
DJMcMayhem suggest a solution using
let ligne = split(getline(position[1]), '\zs')
But there is still a problem to determine the next character.
Here is the new version of the function
function Test_caractere_suivant_espace()
"Test si le caractère suivant est une espace"
let position = getcurpos()
let ligne = split(getline(position[1]), '\zs')
let car_suivant = ligne[position[2]]
echom car_suivant
if car_suivant == ' '
return 1
else
return 0
endfunction
In this line
α α α α α α α α α α
If I call the function in the before last α, I get
Error detected while processing function LB_content[2]..Test_caractere_suivant_espace:
line 4:
E684: list index out of range: 25
E15: Invalid expression: ligne[position[2]]
line 5:
E121: Undefined variable: car_suivant
E15: Invalid expression: car_suivant
line 6:
E121: Undefined variable: car_suivant
E15: Invalid expression: car_suivant == ' '
Unfortunately, there's no way to do this that I am aware of. :h getline mentions nothing about encoding options, and from this vim mailing list I found, it seems like this problem has been around for a while with no fix.
However, I did figure out a hacky workaround. Instead of working with strings, you can work with a list of characters instead. Indexing into that will give you whole characters instead of individual bytes. Try this:
let ligne = split(getline(position[1]), '\zs')

How to use some text processing(awk etc..) to put some character in a text file at certain lines

I have a text file which has hex values, one value on one separate line. A file has many such values one below another. I need to do some analysis of the values for which i need to but some kind of delimiter/marker say a '#' in this file before line numbers 32,47,62,77... difference between two line numbers in this patterin is 15 always.
I am trying to do it using awk. I tried few things but didnt work.
What is the command in awk to do it?
Any other solution involving some other language/script/tool is also welcome.
Thank you.
-AD
This is how you can use AWK for it,
awk 'BEGIN{ i=0; } \
{if (FNR<31) {print $0} \
else {i++; if (i%15) {print $0} else {printf "#%s\n",$0}}\
}' inputfile.txt > outputfile.txt
How it works,
BEGIN sets an iterator for counting from your starting line 32
FNR<31 starts counting from the 31st record (the next record needs a #)
input lines are called records and FNR is an AWK variable that counts them
Once we start counting, the i%15 prefixes a # on every 15th line
$0 prints the record (the line) as is
You can type all the text with white spaces skipping the trailing '\' on a single command line.
Or, you can use it as an AWK file,
# File: comment.awk
BEGIN{ i=0; }
$0 ~ {\
if (FNR<31) {print $0} \
else {\
i++; \
if (i%15) {\
print $0
}\
else {\
printf "#%s\n",$0
}\
}\
}
And run it as,
awk -f comment.awk inputfile.txt > outputfile.txt
Hope this will help you to use more AWK.
Python:
f_in = open("file.txt")
f_out = open("file_out.txt","w")
offset = 4 # 0 <= offset < 15 ; first marker after fourth line in this example
for num,line in enumerate(f_in):
if not (num-offset) % 15:
f_out.write("#\n")
f_out.write(line)
Haskell:
offset = 31;
chunk_size = 15;
main = do
{
(h, t) <- fmap (splitAt offset . lines) getContents;
mapM_ putStrLn h;
mapM_ ((putStrLn "#" >>) . mapM_ putStrLn) $
map (take chunk_size) $
takeWhile (not . null) $
iterate (drop chunk_size) t;
}

Resources