code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#!/bin/bash #=============================================================================== # FILE: wrapper.sh # USAGE: ./wrapper.sh scriptname [cmd-line-args] # DESCRIPTION: Wraps the execution of a programm or script. # Use with xterm: xterm -e wrapper.sh scriptname cmd-line-args # This script is used by the Vim plugin bash-support.vim # OPTIONS: --- # REQUIREMENTS: --- # BUGS: --- # NOTES: --- # AUTHOR: Dr.-Ing. Fritz Mehner (fgm), mehner.fritz@fh-swf.de # COMPANY: Fachhochschule Südwestfalen, Iserlohn # CREATED: 23.11.2004 18:04:01 CET # REVISION: $Id: wrapper.sh,v 1.5 2009/06/04 17:14:02 mehner Exp $ #=============================================================================== scriptname="${1}" # name of the script to execute returncode=0 # default return code if [ ${#} -ge 1 ] ; then if [ -x "$scriptname" ] ; then # start an executable script? "${@}" else awk -f "${@}" # start a script which is not executable fi returncode=$? [ $returncode -ne 0 ] && printf "'${@}' returned ${returncode}\n" else printf "\n!! ${0} : no argument(s) !!\n" fi read -p "... press return key ... " dummy exit $returncode
00000svn-vim-cfg
trunk/vimfiles/awk-support/scripts/.svn/text-base/wrapper.sh.svn-base
Shell
gpl3
1,361
%%===================================================================================== %% %% File: awk-hotkeys.tex %% %% Description: awk-support.vim : Key mappings for Awk without GUI. %% %% %% Author: Dr.-Ing. Fritz Mehner %% Email: mehner.fritz@fh-swf.de %% Copyright: Copyright (C) 2012-2013 Dr.-Ing. Fritz Mehner (mehner.fritz@fh-swf.de) %% Version: see \Pluginversion %% Created: 20.12.2012 %% %%===================================================================================== %%====================================================================== %% LaTeX settings [[[1 %%====================================================================== \documentclass[oneside,11pt,landscape,DIV16]{scrartcl} \usepackage[english]{babel} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{lastpage} \usepackage{multicol} \usepackage{fancyhdr} \setlength\parindent{0pt} \newcommand{\Pluginversion}{1.1} \newcommand{\ReleaseDate}{\today} \newcommand{\Rep}{{\scriptsize{[n]}}} %%---------------------------------------------------------------------- %% fancyhdr %%---------------------------------------------------------------------- \pagestyle{fancyplain} \fancyhf{} \fancyfoot[L]{\small \ReleaseDate} \fancyfoot[C]{\small awk-support.vim} \fancyfoot[R]{\small \textbf{Page \thepage{} / \pageref{LastPage}}} \renewcommand{\headrulewidth}{0.0pt} %%---------------------------------------------------------------------- %% luximono : Type1-font %% Makes keyword stand out by using semibold letters. %%---------------------------------------------------------------------- \usepackage[scaled]{luximono} %%---------------------------------------------------------------------- %% hyperref %%---------------------------------------------------------------------- \usepackage[ps2pdf]{hyperref} \hypersetup{pdfauthor={Dr.-Ing. Fritz Mehner, FH Südwestfalen, Iserlohn, Germany}} \hypersetup{pdfkeywords={Vim, Perl}} \hypersetup{pdfsubject={Vim-plug-in, awk-support.vim, hot keys}} \hypersetup{pdftitle={Vim-plug-in, awk-support.vim, hot keys}} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% START OF DOCUMENT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{document}% \begin{multicols}{3} % \begin{center} % %%====================================================================== %% title [[[1 %%====================================================================== \textbf{\textsc{\small{Vim-Plug-in}}}\\ \textbf{\LARGE{awk-support.vim}}\\ \textbf{\textsc{\small{Version \Pluginversion}}}\\ \vspace{5mm}% \textbf{\textsc{\Huge{Hot keys}}}\\ \vspace{5mm}% Key mappings for Vim and gVim.\\ Plug-in: http://vim.sourceforge.net\\ Fritz Mehner (mehner.fritz@fh-swf.de)\\ \vspace{1.0mm} {\normalsize (i)} insert mode, {\normalsize (n)} normal mode, {\normalsize (v)} visual mode\\ \vspace{4.0mm} %%====================================================================== %% table, left part [[[1 %%====================================================================== %%~~~~~ TABULAR : begin ~~~~~~~~~~ \begin{tabular}[]{|p{11mm}|p{60mm}|} %%---------------------------------------------------------------------- %% show plug-in help %%---------------------------------------------------------------------- \hline \multicolumn{2}{|r|}{\textsl{\textbf{H}elp}}\\[1.0ex] \hline \verb'\hm' & display the Awk manual \hfill (n,i)\\ \hline \verb'\hp' & help (plug-in) \hfill (n,i)\\ \hline %%---------------------------------------------------------------------- %% menu comments %%---------------------------------------------------------------------- \hline \multicolumn{2}{|r|}{\textsl{\textbf{C}omments}} \\[1.0ex] \hline \Rep\verb'\cl' & end-of-line comment \hfill (n, i, v)\\ \hline \Rep\verb'\cj' & adjust end-of-line comments \hfill (n, i, v)\\ \hline \verb'\cs' & set end-of-line comment col. \hfill (n) \\ % \hline \Rep\verb'\cc' & code $\leftrightarrow$ comment \hfill (n, i, v)\\ \hline \verb'\cu' & uncomment code block \hfill (n, i, v)\\ % \hline \verb'\cfr' & frame comment \hfill (n, i) \\ \hline \verb'\cfu' & function description \hfill (n, i) \\ \hline \verb'\ch' & file header \hfill (n, i) \\ \hline \verb'\cd' & date \hfill (n, i) \\ \hline \verb'\ct' & date \& time \hfill (n, i) \\ \hline \verb'\ck' & keyword comments \hfill (n, i) \\ \hline \verb'\cma' & plug-in macros \hfill (n, i) \\ \hline \end{tabular}\\ %%~~~~~ TABULAR : end ~~~~~~~~~~ % %%====================================================================== %% table, middle part [[[1 %%====================================================================== % %%~~~~~ TABULAR : begin ~~~~~~~~~~ \begin{tabular}[]{|p{11mm}|p{60mm}|} %%---------------------------------------------------------------------- %% menu statements %%---------------------------------------------------------------------- \hline \multicolumn{2}{|r|}{\textsl{\textbf{S}tatements}} \\[1.0ex] \hline \verb'\sd' & \verb'do { } while' \hfill (n, i, v)\\ \hline \verb'\sf' & \verb'for ( ; ; )' \hfill (n, i)\\ \hline \verb'\sfo' & \verb'for ( ; ; ) { }' \hfill (n, i, v)\\ \hline \verb'\sfi' & \verb'for ( in ) { }' \hfill (n, i, v)\\ \hline \verb'\si' & \verb'if ()' \hfill (n, i)\\ \hline \verb'\sif' & \verb'if () { }' \hfill (n, i, v)\\ \hline \verb'\sie' & \verb'if () else' \hfill (n, i, v)\\ \hline \verb'\sife' & \verb'if ( ) { } else { }' \hfill (n, i, v)\\ \hline \verb'\sw' & \verb'while ()' \hfill (n, i)\\ \hline \verb'\swh' & \verb'while () { }' \hfill (n, i, v)\\ \hline \verb'\ss' & \verb'switch ( ) { }' \hfill (n, i, v)\\ \hline \verb'\sc' & \verb'case : break' \hfill (n, i)\\ \hline \verb'\sb' & \verb'BEGIN { }' \hfill (n, i, v)\\ \hline \verb'\se' & \verb'END { }' \hfill (n, i, v)\\ \hline %%---------------------------------------------------------------------- %% menu idioms %%---------------------------------------------------------------------- \hline \multicolumn{2}{|r|}{\textsl{\textbf{I}dioms}} \\[1.0ex] \hline \verb'\if' & \verb'function' \hfill (n, i, v)\\ \hline \hline %%---------------------------------------------------------------------- %% menu functions %%---------------------------------------------------------------------- \hline \multicolumn{2}{|r|}{\textsl{\textbf{F}unctions}} \\[1.0ex] \hline \verb'\fn ' & numeric functions \hfill (n, i, v)\\ \hline \verb'\fs ' & string functions \hfill (n, i, v)\\ \hline \verb'\fio' & I/O functions \hfill (n, i, v)\\ \hline \verb'\ft ' & time functions \hfill (n, i, v)\\ \hline \verb'\fb ' & bit manipulations functions \hfill (n, i, v)\\ \hline \verb'\fin' & internationalizationfunctions \hfill (n, i, v)\\ \hline \verb'\fa ' & \texttt{isarray()} \hfill (n, i, v)\\ \hline %%---------------------------------------------------------------------- %% snippet menu %%---------------------------------------------------------------------- \hline \multicolumn{2}{|r|}{\textsl{S\textbf{n}ippet}} \\[1.0ex] \hline \verb'\nr' & read code snippet \hfill (n, i) \\ \hline \verb'\nv' & view code snippet \hfill (n, i) \\ \hline \verb'\nw' & write code snippet \hfill (n, i, v)\\ \hline \verb'\ne' & edit code snippet \hfill (n, i) \\ \hline % \end{tabular}\\ %%~~~~~ TABULAR : end ~~~~~~~~~~ % %%====================================================================== %% table, right part [[[1 %%====================================================================== % %%~~~~~ TABULAR : begin ~~~~~~~~~~ \begin{tabular}[]{|p{11mm}|p{62mm}|} %%---------------------------------------------------------------------- %% menu regex menu %%---------------------------------------------------------------------- \hline \multicolumn{2}{|r|}{\textsl{Regular E\textbf{x}pressions}} \\[1.0ex] \hline \verb'xpc' & POSIX classes \hfill (n, i)\\ \hline \verb'xro' & Regex operators \hfill (n, i)\\ \hline \verb'xex' & extended Regex \hfill (n, i)\\ \hline \verb'\xg' & grouping \hfill (n, i, v) \\ \hline \verb'\xa' & alternation \hfill (n, i, v) \\ \hline \verb'\xl' & character list \hfill (n, i, v) \\ \hline \verb'\xw' & word \hfill (n, i) \\ \hline %%---------------------------------------------------------------------- %% menu Special variables %%---------------------------------------------------------------------- \hline \multicolumn{2}{|r|}{\textsl{\textbf{S}pecial Variables}} \\[1.0ex] \hline \verb'\va' & built-in variables, auto-set \hfill (n, i)\\ \hline \verb'\vm' & built-in variables, user-modifiable \hfill (n, i)\\ \hline %%---------------------------------------------------------------------- %% menu run %%---------------------------------------------------------------------- \hline \multicolumn{2}{|r|}{\textsl{\textbf{R}un}} \\[1.0ex] \hline \verb'\rr ' & save and run script \hfill (n, i) \\ \hline \verb'\rs ' & syntax check \hfill (n, i) \\ \hline \verb'\rl ' & lint check \hfill (n, i) \\ \hline \verb'\ra ' & script command line arguments \hfill (n, i) \\ \hline \verb'\raa' & Awk command line arguments \hfill (n, i) \\ \hline \verb'\re ' & make script executable \hfill (n, i) \\ \hline \verb'\rh ' & hardcopy buffer to FILENAME.ps \hfill (n, i) \\ \hline \verb'\rse' & settings and hot keys \hfill (n, i) \\ \hline \verb'\rx ' & xterm size \hfill (n, i) \\ \hline \verb'\ro ' & switch output destination \hfill (n, i) \\ \hline \end{tabular}\\ %%~~~~~ TABULAR : end ~~~~~~~~~~ % \begin{flushleft} \large{\textbf{Ex Commands}}\\[1.0ex] % Set script command line arguments (same as \textbackslash\texttt{ra})\\[1.0ex] \texttt{ :AwkScriptArguments}\\[1.0ex] % Set Awk command line arguments (same as \textbackslash\texttt{raa})\\[1.0ex] \texttt{ :AwkArguments}\\[1.0ex] \end{flushleft} % \end{center}% \end{multicols}% % %%----- TABBING : end ---------- \end{document} % vim: foldmethod=marker foldmarker=[[[,]]]
00000svn-vim-cfg
trunk/vimfiles/awk-support/doc/awk-hotkeys.tex
TeX
gpl3
11,034
"=================================================================================== " FILE: .vimrc " DESCRIPTION: suggestion for a personal configuration file ~/.vimrc " AUTHOR: Dr.-Ing. Fritz Mehner " CREATED: 19.12.2012 "=================================================================================== " "=================================================================================== " GENERAL SETTINGS "=================================================================================== "------------------------------------------------------------------------------- " Use Vim settings, rather then Vi settings. " This must be first, because it changes other options as a side effect. "------------------------------------------------------------------------------- set nocompatible " "------------------------------------------------------------------------------- " Enable file type detection. Use the default filetype settings. " Also load indent files, to automatically do language-dependent indenting. "------------------------------------------------------------------------------- filetype plugin on filetype indent on " "------------------------------------------------------------------------------- " Switch syntax highlighting on. "------------------------------------------------------------------------------- syntax on " " Platform specific items: " - central backup directory (has to be created) " - default dictionary " Uncomment your choice. if has("win16") || has("win32") || has("win64") || \ has("win95") || has("win32unix") " " runtime mswin.vim " set backupdir =$VIM\vimfiles\backupdir " set dictionary=$VIM\vimfiles\wordlists/german.list else " set backupdir =$HOME/.vim.backupdir " set dictionary=$HOME/.vim/wordlists/german.list endif " " Using a backupdir under UNIX/Linux: you may want to include a line similar to " find $HOME/.vim.backupdir -name "*" -type f -mtime +60 -exec rm -f {} \; " in one of your shell startup files (e.g. $HOME/.profile) " "------------------------------------------------------------------------------- " Various settings "------------------------------------------------------------------------------- set autoindent " copy indent from current line set autoread " read open files again when changed outside Vim set autowrite " write a modified buffer on each :next , ... set backspace=indent,eol,start " backspacing over everything in insert mode set backup " keep a backup file set browsedir=current " which directory to use for the file browser set complete+=k " scan the files given with the 'dictionary' option set history=50 " keep 50 lines of command line history set hlsearch " highlight the last used search pattern set incsearch " do incremental searching set listchars=tab:>.,eol:\$ " strings to use in 'list' mode set mouse=a " enable the use of the mouse set nowrap " do not wrap lines set popt=left:8pc,right:3pc " print options set ruler " show the cursor position all the time set shiftwidth=2 " number of spaces to use for each step of indent set showcmd " display incomplete commands set smartindent " smart autoindenting when starting a new line set tabstop=2 " number of spaces that a <Tab> counts for set visualbell " visual bell instead of beeping set wildignore=*.bak,*.o,*.e,*~ " wildmenu: ignore these extensions set wildmenu " command-line completion in an enhanced mode " "=================================================================================== " BUFFERS, WINDOWS "=================================================================================== " "------------------------------------------------------------------------------- " The current directory is the directory of the file in the current window. "------------------------------------------------------------------------------- if has("autocmd") autocmd BufEnter * :lchdir %:p:h endif " "------------------------------------------------------------------------------- " close window (conflicts with the KDE setting for calling the process manager) "------------------------------------------------------------------------------- noremap <C-Esc> :close<CR> inoremap <C-Esc> <C-C>:close<CR> " "------------------------------------------------------------------------------- " Fast switching between buffers " The current buffer will be saved before switching to the next one. " Choose :bprevious or :bnext "------------------------------------------------------------------------------- noremap <silent> <s-tab> :if &modifiable && !&readonly && \ &modified <CR> :write<CR> :endif<CR>:bprevious<CR> inoremap <silent> <s-tab> <C-C>:if &modifiable && !&readonly && \ &modified <CR> :write<CR> :endif<CR>:bprevious<CR> " "------------------------------------------------------------------------------- " Leave the editor with Ctrl-q (KDE): Write all changed buffers and exit Vim "------------------------------------------------------------------------------- nnoremap <C-q> :wqall<CR> " "------------------------------------------------------------------------------- " When editing a file, always jump to the last known cursor position. " Don't do it when the position is invalid or when inside an event handler " (happens when dropping a file on gvim). "------------------------------------------------------------------------------- if has("autocmd") autocmd BufReadPost * \ if line("'\"") > 0 && line("'\"") <= line("$") | \ exe "normal! g`\"" | \ endif endif " has("autocmd") " "------------------------------------------------------------------------------- " some additional hot keys "------------------------------------------------------------------------------- " F2 - write file without confirmation " F3 - call file explorer Ex " F4 - show tag under curser in the preview window (tagfile must exist!) " F5 - open quickfix error window " F6 - close quickfix error window " F7 - display previous error " F8 - display next error "------------------------------------------------------------------------------- " map <silent> <F2> :write<CR> map <silent> <F3> :Explore<CR> nmap <silent> <F4> :exe ":ptag ".expand("<cword>")<CR> map <silent> <F5> :copen<CR> map <silent> <F6> :cclose<CR> map <silent> <F7> :cp<CR> map <silent> <F8> :cn<CR> " imap <silent> <F2> <Esc>:write<CR> imap <silent> <F3> <Esc>:Explore<CR> imap <silent> <F4> <Esc>:exe ":ptag ".expand("<cword>")<CR> imap <silent> <F5> <Esc>:copen<CR> imap <silent> <F6> <Esc>:cclose<CR> imap <silent> <F7> <Esc>:cp<CR> imap <silent> <F8> <Esc>:cn<CR> " "------------------------------------------------------------------------------- " Fast switching between buffers " The current buffer will be saved before switching to the next one. " Choose :bprevious or :bnext "------------------------------------------------------------------------------- " map <silent> <s-tab> <Esc>:if &modifiable && !&readonly && \ &modified <CR> :write<CR> :endif<CR>:bprevious<CR> imap <silent> <s-tab> <Esc>:if &modifiable && !&readonly && \ &modified <CR> :write<CR> :endif<CR>:bprevious<CR> " "------------------------------------------------------------------------------- " Leave the editor with Ctrl-q : Write all changed buffers and exit Vim "------------------------------------------------------------------------------- nmap <C-q> :wqa<CR> " "------------------------------------------------------------------------------- " comma always followed by a space "------------------------------------------------------------------------------- inoremap , ,<Space> " "------------------------------------------------------------------------------- " autocomplete parenthesis, brackets and braces "------------------------------------------------------------------------------- inoremap ( ()<Left> inoremap [ []<Left> inoremap { {}<Left> " vnoremap ( s()<Esc>P<Right>% vnoremap [ s[]<Esc>P<Right>% vnoremap { s{}<Esc>P<Right>% " "------------------------------------------------------------------------------- " autocomplete quotes (visual and select mode) "------------------------------------------------------------------------------- xnoremap ' s''<Esc>P<Right> xnoremap " s""<Esc>P<Right> xnoremap ` s``<Esc>P<Right> " "------------------------------------------------------------------------------- " Change the working directory to the directory containing the current file "------------------------------------------------------------------------------- if has("autocmd") autocmd BufEnter * :lchdir %:p:h endif " has("autocmd") " "=================================================================================== " VARIOUS PLUGIN CONFIGURATIONS "=================================================================================== " "------------------------------------------------------------------------------- " awk-support "------------------------------------------------------------------------------- " " --empty -- " "------------------------------------------------------------------------------- " taglist.vim : toggle the taglist window " taglist.vim : define the title texts for make " taglist.vim : define the title texts for qmake "------------------------------------------------------------------------------- noremap <silent> <F11> <Esc><Esc>:Tlist<CR> inoremap <silent> <F11> <Esc><Esc>:Tlist<CR> let Tlist_GainFocus_On_ToggleOpen = 1 let Tlist_Close_On_Select = 1
00000svn-vim-cfg
trunk/vimfiles/awk-support/rc/customization.vimrc
Vim Script
gpl3
10,061
" Vim syntax file " Language: mm template engine : template library " Maintainer: Wolfgang Mehner <wolfgang-mehner@web.de> " Last Change: 12.08.2013 " Version: 0.9.1-2 if version < 600 syntax clear elseif exists("b:current_syntax") finish endif "------------------------------------------------------------------------------- " Syntax "------------------------------------------------------------------------------- " comment syn match Comment "^§.*$" syn match Comment "\%(==\)\@<=[^=]*$" " templates, lists, ... syn match Structure "^==\s*\%(TEMPLATE:\)\?[a-zA-Z0-9\-+.,_ ]\+==\%(.\+==\)\?" syn match Structure "^==\s*ENDTEMPLATE\s*==" syn match Structure "^==\s*HELP:[a-zA-Z0-9\-+.,_ ]\+==\%(.\+==\)\?" syn match Structure "^==\s*SEP:[a-zA-Z0-9\-+.,_ ]\+==" syn match Structure "^==\s*LIST:\s*[a-zA-Z0-9_]\+\s*==\%(.\+==\)\?" syn match Structure "^==\s*ENDLIST\s*==" " style sections syn match Statement "^==\s*IF\s\+|STYLE|\s\+IS\s\+[a-zA-Z0-9_]\+\s*==" syn match Statement "^==\s*ENDIF\s*==" syn match Statement "^==\s*USE\s\+STYLES\s*:[a-zA-Z0-9_, ]\+==" syn match Statement "^==\s*ENDSTYLES\s*==" " functions: command mode syn match Function "IncludeFile\ze\s*(" syn match Function "SetFormat\ze\s*(" syn match Function "SetMacro\ze\s*(" syn match Function "SetStyle\ze\s*(" syn match Function "SetSyntax\ze\s*(" syn match Function "SetPath\ze\s*(" syn match Function "MenuShortcut\ze\s*(" syn match Function "SetProperty\ze\s*(" syn match Function "SetMap\ze\s*(" syn match Function "SetShortcut\ze\s*(" " functions: standard template syn match Function "|\zsDefaultMacro\ze(" syn match Function "|\zsPrompt\ze(" syn match Function "|\zsPickFile\ze(" syn match Function "|\zsPickList\ze(" syn match Function "|\zsSurroundWith\ze(" syn match Function "|\zsInsert\ze(" syn match Function "|\zsInsertLine\ze(" syn match Comment "|C(.\{-})|" syn match Comment "|Comment(.\{-})|" " functions: picker syn match Function "|\zsPath\ze(" " file syn match Function "|\zsGetPath\ze(" " file syn match Function "|\zsKeepPath\ze(" " file syn match Function "|\zsRemovePath\ze(" " file syn match Function "|\zsList\ze(" " list syn match Function "|\zsGetList\ze(" " list " functions: help syn match Function "|\zsPrompt\ze(" syn match Function "|\zsWord\ze(" syn match Function "|\zsPattern\ze(" syn match Function "|\zsDefault\ze(" syn match Function "|\zsSubstitute\ze(" syn match Function "|\zsLiteralSub\ze(" syn match Function "|\zsSystem\ze(" syn match Function "|\zsVim\ze(" " strings, macros, tags, jump targets syn match String "'\%([^']\|''\)*'" syn match String "\"\%([^\\]\|\\.\)*\"" syn match Tag "|?\?[a-zA-Z][a-zA-Z0-9_:]*|" syn match Tag "<CURSOR>\|{CURSOR}" syn match Tag "<SPLIT>" syn match Tag "<CONTENT>" syn match Search "<\([+-]\)\w*\1>" syn match Search "{\([+-]\)\w*\1}" let b:current_syntax = "template"
00000svn-vim-cfg
trunk/vimfiles/syntax/template.vim
Vim Script
gpl3
2,994
let s:tree_up_dir_line = '.. (up a dir)' "NERDTreeFlags are syntax items that should be invisible, but give clues as to "how things should be highlighted syn match NERDTreeFlag #\~# syn match NERDTreeFlag #\[RO\]# "highlighting for the .. (up dir) line at the top of the tree execute "syn match NERDTreeUp #\\V". s:tree_up_dir_line ."#" "highlighting for the ~/+ symbols for the directory nodes syn match NERDTreeClosable #\~\<# syn match NERDTreeClosable #\~\.# syn match NERDTreeOpenable #+\<# syn match NERDTreeOpenable #+\.#he=e-1 "highlighting for the tree structural parts syn match NERDTreePart #|# syn match NERDTreePart #`# syn match NERDTreePartFile #[|`]-#hs=s+1 contains=NERDTreePart "quickhelp syntax elements syn match NERDTreeHelpKey #" \{1,2\}[^ ]*:#hs=s+2,he=e-1 syn match NERDTreeHelpKey #" \{1,2\}[^ ]*,#hs=s+2,he=e-1 syn match NERDTreeHelpTitle #" .*\~#hs=s+2,he=e-1 contains=NERDTreeFlag syn match NERDTreeToggleOn #".*(on)#hs=e-2,he=e-1 contains=NERDTreeHelpKey syn match NERDTreeToggleOff #".*(off)#hs=e-3,he=e-1 contains=NERDTreeHelpKey syn match NERDTreeHelpCommand #" :.\{-}\>#hs=s+3 syn match NERDTreeHelp #^".*# contains=NERDTreeHelpKey,NERDTreeHelpTitle,NERDTreeFlag,NERDTreeToggleOff,NERDTreeToggleOn,NERDTreeHelpCommand "highlighting for readonly files syn match NERDTreeRO #.*\[RO\]#hs=s+2 contains=NERDTreeFlag,NERDTreeBookmark,NERDTreePart,NERDTreePartFile "highlighting for sym links syn match NERDTreeLink #[^-| `].* -> # contains=NERDTreeBookmark,NERDTreeOpenable,NERDTreeClosable,NERDTreeDirSlash "highlighing for directory nodes and file nodes syn match NERDTreeDirSlash #/# syn match NERDTreeDir #[^-| `].*/# contains=NERDTreeLink,NERDTreeDirSlash,NERDTreeOpenable,NERDTreeClosable syn match NERDTreeExecFile #[|` ].*\*\($\| \)# contains=NERDTreeLink,NERDTreePart,NERDTreeRO,NERDTreePartFile,NERDTreeBookmark syn match NERDTreeFile #|-.*# contains=NERDTreeLink,NERDTreePart,NERDTreeRO,NERDTreePartFile,NERDTreeBookmark,NERDTreeExecFile syn match NERDTreeFile #`-.*# contains=NERDTreeLink,NERDTreePart,NERDTreeRO,NERDTreePartFile,NERDTreeBookmark,NERDTreeExecFile syn match NERDTreeCWD #^[</].*$# "highlighting for bookmarks syn match NERDTreeBookmark # {.*}#hs=s+1 "highlighting for the bookmarks table syn match NERDTreeBookmarksLeader #^># syn match NERDTreeBookmarksHeader #^>-\+Bookmarks-\+$# contains=NERDTreeBookmarksLeader syn match NERDTreeBookmarkName #^>.\{-} #he=e-1 contains=NERDTreeBookmarksLeader syn match NERDTreeBookmark #^>.*$# contains=NERDTreeBookmarksLeader,NERDTreeBookmarkName,NERDTreeBookmarksHeader if exists("g:NERDChristmasTree") && g:NERDChristmasTree hi def link NERDTreePart Special hi def link NERDTreePartFile Type hi def link NERDTreeFile Normal hi def link NERDTreeExecFile Title hi def link NERDTreeDirSlash Identifier hi def link NERDTreeClosable Type else hi def link NERDTreePart Normal hi def link NERDTreePartFile Normal hi def link NERDTreeFile Normal hi def link NERDTreeClosable Title endif hi def link NERDTreeBookmarksHeader statement hi def link NERDTreeBookmarksLeader ignore hi def link NERDTreeBookmarkName Identifier hi def link NERDTreeBookmark normal hi def link NERDTreeHelp String hi def link NERDTreeHelpKey Identifier hi def link NERDTreeHelpCommand Identifier hi def link NERDTreeHelpTitle Macro hi def link NERDTreeToggleOn Question hi def link NERDTreeToggleOff WarningMsg hi def link NERDTreeDir Directory hi def link NERDTreeUp Directory hi def link NERDTreeCWD Statement hi def link NERDTreeLink Macro hi def link NERDTreeOpenable Title hi def link NERDTreeFlag ignore hi def link NERDTreeRO WarningMsg hi def link NERDTreeBookmark Statement hi def link NERDTreeCurrentNode Search
00000svn-vim-cfg
trunk/vimfiles/syntax/nerdtree.vim
Vim Script
gpl3
3,741
" File: MultipleSearch.vim (global plugin) " Last Changed: 14 Aug 2008 " Maintainer: Dan Sharp <dwsharp at hotmail dot com> " Version: 1.3 " License: Vim License " GetLatestVimScripts: 479 1 :AutoInstall: MultipleSearch.vba if exists('loaded_multiplesearch') finish endif let loaded_multiplesearch = 1 " Vim versions prior to 7.0 don't support the autoload mechanism, so go ahead " and load the 'autoload' segment of the code and map the commands using the " non-autoload format. if v:version < 700 runtime autoload/MultipleSearch.vim if !(exists(":SearchBuffers") == 2) command -nargs=* SearchBuffers :silent call MultipleSearch(1, <q-args>) endif if !(exists(":Search") == 2) command -nargs=* Search :silent call MultipleSearch(0, <q-args>) endif " Following Manuel's idea, adapt the former 'Super Star' tip from vim.org to work with " :Search on a visual selection. "vnoremap <silent> <Leader>* y:execute ':Search \V<C-R>=substitute(escape(@@,"/\\"),"\n","\\\\n","ge")<CR>'<CR> vnoremap <silent> <Leader>* y:call MultipleSearch(0,'\V'.substitute(escape(@@,"\\/\"'"),"\n",'\\n','ge'))<CR> else " Only autoload the Search commands, since we shouldn't need to use " :SearchReset and :SearchReinit until after the first :Search. if !(exists(":SearchBuffers") == 2) command -nargs=* SearchBuffers :silent call MultipleSearch#MultipleSearch(1, <q-args>) endif if !(exists(":Search") == 2) command -nargs=* Search :silent call MultipleSearch#MultipleSearch(0, <q-args>) endif " Following Manuel's idea, adapt the former 'Super Star' tip from vim.org to work with " :Search on a visual selection. vnoremap <silent> <Leader>* y:call MultipleSearch#MultipleSearch(0,'\V'.substitute(escape(@@,"\\/\"'"),"\n",'\\n','ge'))<CR> endif " Thanks to Manuel Picaza for the following mapping to :Search the word under " the cursor. nnoremap <silent> <Leader>* :execute ':Search \<' . expand('<cword>') . '\>'<cr>
00000svn-vim-cfg
trunk/vimfiles/plugin/MultipleSearch.vim
Vim Script
gpl3
2,020
"=============================================================================== " " File: awk-support.vim " " Description: awk support " " Write awk scripts by inserting comments, statements, " variables and builtins. " " VIM Version: 7.0+ " Author: Dr. Fritz Mehner (fgm), mehner.fritz@fh-swf.de " Organization: FH Südwestfalen, Iserlohn " Version: see variable g:AwkSupportVersion below " Created: 14.01.2012 10:49 " Revision: 0.1 " License: Copyright (c) 2012-2013, Dr. Fritz Mehner " This program is free software; you can redistribute it and/or " modify it under the terms of the GNU General Public License as " published by the Free Software Foundation, version 2 of the " License. " This program is distributed in the hope that it will be " useful, but WITHOUT ANY WARRANTY; without even the implied " warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR " PURPOSE. " See the GNU General Public License version 2 for more details. "=============================================================================== " if v:version < 700 echohl WarningMsg | echo 'plugin awk-support.vim needs Vim version >= 7'| echohl None finish endif " " Prevent duplicate loading: " if exists("g:AwkSupportVersion") || &cp finish endif " let g:AwkSupportVersion= "1.1" " version number of this script; do not change " "=== FUNCTION ================================================================ " NAME: awk_SetGlobalVariable {{{1 " DESCRIPTION: Define a global variable and assign a default value if nor " already defined " PARAMETERS: name - global variable " default - default value "=============================================================================== function! s:awk_SetGlobalVariable ( name, default ) if !exists('g:'.a:name) exe 'let g:'.a:name." = '".a:default."'" else " check for an empty initialization exe 'let val = g:'.a:name if empty(val) exe 'let g:'.a:name." = '".a:default."'" endif endif endfunction " ---------- end of function s:awk_SetGlobalVariable ---------- " "=== FUNCTION ================================================================ " NAME: GetGlobalSetting {{{1 " DESCRIPTION: take over a global setting " PARAMETERS: varname - variable to set " RETURNS: "=============================================================================== function! s:GetGlobalSetting ( varname ) if exists ( 'g:'.a:varname ) exe 'let s:'.a:varname.' = g:'.a:varname endif endfunction " ---------- end of function s:GetGlobalSetting ---------- " "=== FUNCTION ================================================================ " NAME: ApplyDefaultSetting {{{1 " DESCRIPTION: make a local setting global " PARAMETERS: varname - variable to set " RETURNS: "=============================================================================== function! s:ApplyDefaultSetting ( varname ) if ! exists ( 'g:'.a:varname ) exe 'let g:'.a:varname.' = s:'.a:varname endif endfunction " ---------- end of function s:ApplyDefaultSetting ---------- " "------------------------------------------------------------------------------ " *** PLATFORM SPECIFIC ITEMS *** {{{1 "------------------------------------------------------------------------------ let s:MSWIN = has("win16") || has("win32") || has("win64") || has("win95") let s:UNIX = has("unix") || has("macunix") || has("win32unix") " let s:installation = '*undefined*' let s:Awk_GlobalTemplateFile = '' let s:Awk_GlobalTemplateDir = '' let s:Awk_LocalTemplateFile = '' let s:Awk_LocalTemplateDir = '' let s:Awk_FilenameEscChar = '' let s:Awk_XtermDefaults = '-fa courier -fs 12 -geometry 80x24' if s:MSWIN " ========== MS Windows ====================================================== " " change '\' to '/' to avoid interpretation as escape character if match( substitute( expand("<sfile>"), '\', '/', 'g' ), \ substitute( expand("$HOME"), '\', '/', 'g' ) ) == 0 " " USER INSTALLATION ASSUMED let s:installation = 'local' let s:plugin_dir = substitute( expand('<sfile>:p:h:h'), '\', '/', 'g' ) let s:Awk_LocalTemplateFile = s:plugin_dir.'/awk-support/templates/Templates' let s:Awk_LocalTemplateDir = fnamemodify( s:Awk_LocalTemplateFile, ":p:h" ).'/' else " " SYSTEM WIDE INSTALLATION let s:installation = 'system' let s:plugin_dir = $VIM.'/vimfiles' let s:Awk_GlobalTemplateDir = s:plugin_dir.'/awk-support/templates' let s:Awk_GlobalTemplateFile= s:Awk_GlobalTemplateDir.'/Templates' let s:Awk_LocalTemplateFile = $HOME.'/vimfiles/awk-support/templates/Templates' let s:Awk_LocalTemplateDir = fnamemodify( s:Awk_LocalTemplateFile, ":p:h" ).'/' endif " let s:Awk_FilenameEscChar = '' let s:Awk_Display = '' let s:Awk_ManualReader = 'man.exe' let s:Awk_Awk = 'awk.exe' let s:Awk_OutputGvim = 'xterm' " else " ========== Linux/Unix ====================================================== " if match( expand("<sfile>"), resolve( expand("$HOME") ) ) == 0 " " USER INSTALLATION ASSUMED let s:installation = 'local' let s:plugin_dir = expand('<sfile>:p:h:h') let s:Awk_LocalTemplateFile = s:plugin_dir.'/awk-support/templates/Templates' let s:Awk_LocalTemplateDir = fnamemodify( s:Awk_LocalTemplateFile, ":p:h" ).'/' else " " SYSTEM WIDE INSTALLATION let s:installation = 'system' let s:plugin_dir = $VIM.'/vimfiles' let s:Awk_GlobalTemplateDir = s:plugin_dir.'/awk-support/templates' let s:Awk_GlobalTemplateFile= s:Awk_GlobalTemplateDir.'/Templates' let s:Awk_LocalTemplateFile = $HOME.'/.vim/awk-support/templates/Templates' let s:Awk_LocalTemplateDir = fnamemodify( s:Awk_LocalTemplateFile, ":p:h" ).'/' endif " let s:Awk_Awk = '/usr/bin/awk' let s:Awk_FilenameEscChar = ' \%#[]' let s:Awk_Display = $DISPLAY let s:Awk_ManualReader = '/usr/bin/man' let s:Awk_OutputGvim = 'vim' " endif " let s:Awk_CodeSnippets = s:plugin_dir.'/awk-support/codesnippets/' call s:awk_SetGlobalVariable( 'Awk_CodeSnippets', s:Awk_CodeSnippets ) " " " g:Awk_Dictionary_File must be global " if !exists("g:Awk_Dictionary_File") let g:Awk_Dictionary_File = s:plugin_dir.'/awk-support/wordlists/awk-keywords.list' endif " "---------------------------------------------------------------------- " *** MODUL GLOBAL VARIABLES *** {{{1 "---------------------------------------------------------------------- " let s:Awk_CreateMenusDelayed= 'yes' let s:Awk_MenuVisible = 'no' let s:Awk_GuiSnippetBrowser = 'gui' " gui / commandline let s:Awk_LoadMenus = 'yes' " load the menus? let s:Awk_RootMenu = '&Awk' " name of the root menu " let s:Awk_MapLeader = '' " default: do not overwrite 'maplocalleader' let s:Awk_LineEndCommColDefault = 49 let s:Awk_StartComment = '#' let s:Awk_Printheader = "%<%f%h%m%< %=%{strftime('%x %X')} Page %N" let s:Awk_TemplateJumpTarget = '' let s:Awk_Errorformat = 'awk:\ %f:%l:\ %m' let s:Awk_Wrapper = s:plugin_dir.'/awk-support/scripts/wrapper.sh' let s:Awk_InsertFileHeader = 'yes' " call s:GetGlobalSetting ( 'Awk_InsertFileHeader ') call s:GetGlobalSetting ( 'Awk_GuiSnippetBrowser' ) call s:GetGlobalSetting ( 'Awk_LoadMenus' ) call s:GetGlobalSetting ( 'Awk_RootMenu' ) call s:GetGlobalSetting ( 'Awk_Printheader' ) call s:GetGlobalSetting ( 'Awk_ManualReader' ) call s:GetGlobalSetting ( 'Awk_OutputGvim' ) call s:GetGlobalSetting ( 'Awk_XtermDefaults' ) call s:GetGlobalSetting ( 'Awk_LocalTemplateFile' ) call s:GetGlobalSetting ( 'Awk_GlobalTemplateFile' ) call s:GetGlobalSetting ( 'Awk_CreateMenusDelayed' ) call s:GetGlobalSetting ( 'Awk_LineEndCommColDefault' ) call s:ApplyDefaultSetting ( 'Awk_MapLeader' ) " " set default geometry if not specified " if match( s:Awk_XtermDefaults, "-geometry\\s\\+\\d\\+x\\d\\+" ) < 0 let s:Awk_XtermDefaults = s:Awk_XtermDefaults." -geometry 80x24" endif " let s:Awk_Printheader = escape( s:Awk_Printheader, ' %' ) let s:Awk_saved_global_option = {} let b:Awk_AwkCmdLineArgs = '' "------------------------------------------------------------------------------ " Awk_SaveGlobalOption {{{1 " param 1 : option name " param 2 : characters to be escaped (optional) "------------------------------------------------------------------------------ function! s:Awk_SaveGlobalOption ( option, ... ) exe 'let escaped =&'.a:option if a:0 == 0 let escaped = escape( escaped, ' |"\' ) else let escaped = escape( escaped, ' |"\'.a:1 ) endif let s:Awk_saved_global_option[a:option] = escaped endfunction " ---------- end of function Awk_SaveGlobalOption ---------- " "------------------------------------------------------------------------------ " Awk_RestoreGlobalOption {{{1 "------------------------------------------------------------------------------ function! s:Awk_RestoreGlobalOption ( option ) exe ':set '.a:option.'='.s:Awk_saved_global_option[a:option] endfunction " ---------- end of function Awk_RestoreGlobalOption ---------- " "=== FUNCTION ================================================================ " NAME: Awk_Input {{{1 " DESCRIPTION: Input after a highlighted prompt " PARAMETERS: prompt - prompt string " defaultreply - default reply " ... - completion " RETURNS: reply "=============================================================================== function! Awk_Input ( prompt, defaultreply, ... ) echohl Search " highlight prompt call inputsave() " preserve typeahead if a:0 == 0 || empty(a:1) let retval =input( a:prompt, a:defaultreply ) else let retval =input( a:prompt, a:defaultreply, a:1 ) endif call inputrestore() " restore typeahead echohl None " reset highlighting let retval = substitute( retval, '^\s\+', '', '' ) " remove leading whitespaces let retval = substitute( retval, '\s\+$', '', '' ) " remove trailing whitespaces return retval endfunction " ---------- end of function Awk_Input ---------- " "=== FUNCTION ================================================================ " NAME: Awk_AdjustLineEndComm {{{1 " DESCRIPTION: adjust end-of-line comments " PARAMETERS: - " RETURNS: "=============================================================================== function! Awk_AdjustLineEndComm ( ) range " " patterns to ignore when adjusting line-end comments (maybe incomplete): let s:AlignRegex = [ \ '\([^"]*"[^"]*"\)\+' , \ ] if !exists("b:Awk_LineEndCommentColumn") let b:Awk_LineEndCommentColumn = s:Awk_LineEndCommColDefault endif let save_cursor = getpos('.') let save_expandtab = &expandtab exe ':set expandtab' let linenumber = a:firstline exe ':'.a:firstline while linenumber <= a:lastline let line= getline('.') let idx1 = 1 + match( line, '\s*#.*$', 0 ) let idx2 = 1 + match( line, '#.*$', 0 ) " comment with leading whitespaces left unchanged if match( line, '^\s*#' ) == 0 let idx1 = 0 let idx2 = 0 endif for regex in s:AlignRegex if match( line, regex ) > -1 let start = matchend( line, regex ) let idx1 = 1 + match( line, '\s*#.*$', start ) let idx2 = 1 + match( line, '#.*$', start ) break endif endfor let ln = line('.') call setpos('.', [ 0, ln, idx1, 0 ] ) let vpos1 = virtcol('.') call setpos('.', [ 0, ln, idx2, 0 ] ) let vpos2 = virtcol('.') if ! ( vpos2 == b:Awk_LineEndCommentColumn \ || vpos1 > b:Awk_LineEndCommentColumn \ || idx2 == 0 ) exe ':.,.retab' " insert some spaces if vpos2 < b:Awk_LineEndCommentColumn let diff = b:Awk_LineEndCommentColumn-vpos2 call setpos('.', [ 0, ln, vpos2, 0 ] ) let @" = ' ' exe 'normal '.diff.'P' end " remove some spaces if vpos1 < b:Awk_LineEndCommentColumn && vpos2 > b:Awk_LineEndCommentColumn let diff = vpos2 - b:Awk_LineEndCommentColumn call setpos('.', [ 0, ln, b:Awk_LineEndCommentColumn, 0 ] ) exe 'normal '.diff.'x' end end let linenumber=linenumber+1 normal j endwhile " restore tab expansion settings and cursor position let &expandtab = save_expandtab call setpos('.', save_cursor) endfunction " ---------- end of function Awk_AdjustLineEndComm ---------- " "=== FUNCTION ================================================================ " NAME: Awk_GetLineEndCommCol {{{1 " DESCRIPTION: get end-of-line comment position " PARAMETERS: - " RETURNS: "=============================================================================== function! Awk_GetLineEndCommCol () let actcol = virtcol(".") if actcol+1 == virtcol("$") let b:Awk_LineEndCommentColumn = '' while match( b:Awk_LineEndCommentColumn, '^\s*\d\+\s*$' ) < 0 let b:Awk_LineEndCommentColumn = Awk_Input( 'start line-end comment at virtual column : ', actcol, '' ) endwhile else let b:Awk_LineEndCommentColumn = virtcol(".") endif echomsg "line end comments will start at column ".b:Awk_LineEndCommentColumn endfunction " ---------- end of function Awk_GetLineEndCommCol ---------- " "=== FUNCTION ================================================================ " NAME: Awk_EndOfLineComment {{{1 " DESCRIPTION: single end-of-line comment " PARAMETERS: - " RETURNS: "=============================================================================== function! Awk_EndOfLineComment ( ) range if !exists("b:Awk_LineEndCommentColumn") let b:Awk_LineEndCommentColumn = s:Awk_LineEndCommColDefault endif " ----- trim whitespaces ----- exe a:firstline.','.a:lastline.'s/\s*$//' for line in range( a:lastline, a:firstline, -1 ) silent exe ":".line if getline(line) !~ '^\s*$' let linelength = virtcol( [line, "$"] ) - 1 let diff = 1 if linelength < b:Awk_LineEndCommentColumn let diff = b:Awk_LineEndCommentColumn -1 -linelength endif exe "normal ".diff."A " call mmtemplates#core#InsertTemplate(g:Awk_Templates, 'Comments.end-of-line comment') endif endfor endfunction " ---------- end of function Awk_EndOfLineComment ---------- " "=== FUNCTION ================================================================ " NAME: Awk_CodeComment {{{1 " DESCRIPTION: Code -> Comment " PARAMETERS: - " RETURNS: "=============================================================================== function! Awk_CodeComment() range " add '# ' at the beginning of the lines for line in range( a:firstline, a:lastline ) exe line.'s/^/# /' endfor endfunction " ---------- end of function Awk_CodeComment ---------- " "=== FUNCTION ================================================================ " NAME: Awk_CommentCode {{{1 " DESCRIPTION: Comment -> Code " PARAMETERS: toggle - 0 : uncomment, 1 : toggle comment " RETURNS: "=============================================================================== function! Awk_CommentCode( toggle ) range for i in range( a:firstline, a:lastline ) if getline( i ) =~ '^# ' silent exe i.'s/^# //' elseif getline( i ) =~ '^#' silent exe i.'s/^#//' elseif a:toggle silent exe i.'s/^/# /' endif endfor " endfunction " ---------- end of function Awk_CommentCode ---------- " "=== FUNCTION ================================================================ " NAME: Awk_RereadTemplates {{{1 " DESCRIPTION: Reread the templates. Also set the character which starts " the comments in the template files. " PARAMETERS: - " RETURNS: "=============================================================================== function! g:Awk_RereadTemplates ( displaymsg ) " "------------------------------------------------------------------------------- " SETUP TEMPLATE LIBRARY "------------------------------------------------------------------------------- let g:Awk_Templates = mmtemplates#core#NewLibrary () " " mapleader if empty ( g:Awk_MapLeader ) call mmtemplates#core#Resource ( g:Awk_Templates, 'set', 'property', 'Templates::Mapleader', '\' ) else call mmtemplates#core#Resource ( g:Awk_Templates, 'set', 'property', 'Templates::Mapleader', g:Awk_MapLeader ) endif " " map: choose style call mmtemplates#core#Resource ( g:Awk_Templates, 'set', 'property', 'Templates::EditTemplates::Map', 'ntl' ) call mmtemplates#core#Resource ( g:Awk_Templates, 'set', 'property', 'Templates::RereadTemplates::Map', 'ntr' ) call mmtemplates#core#Resource ( g:Awk_Templates, 'set', 'property', 'Templates::ChooseStyle::Map', 'nts' ) " " syntax: comments call mmtemplates#core#ChangeSyntax ( g:Awk_Templates, 'comment', '§' ) let s:Awk_TemplateJumpTarget = mmtemplates#core#Resource ( g:Awk_Templates, "jumptag" )[0] " let messsage = '' " if s:installation == 'system' "------------------------------------------------------------------------------- " SYSTEM INSTALLATION "------------------------------------------------------------------------------- if filereadable( s:Awk_GlobalTemplateFile ) call mmtemplates#core#ReadTemplates ( g:Awk_Templates, 'load', s:Awk_GlobalTemplateFile ) else echomsg "Global template file '".s:Awk_GlobalTemplateFile."' not readable." return endif let messsage = "Templates read from '".s:Awk_GlobalTemplateFile."'" " "------------------------------------------------------------------------------- " handle local template files "------------------------------------------------------------------------------- if finddir( s:Awk_LocalTemplateDir ) == '' " try to create a local template directory if exists("*mkdir") try call mkdir( s:Awk_LocalTemplateDir, "p" ) catch /.*/ endtry endif endif if isdirectory( s:Awk_LocalTemplateDir ) && !filereadable( s:Awk_LocalTemplateFile ) " write a default local template file let template = [ ] let sample_template_file = fnamemodify( s:Awk_GlobalTemplateDir, ':h' ).'/rc/sample_template_file' if filereadable( sample_template_file ) for line in readfile( sample_template_file ) call add( template, line ) endfor call writefile( template, s:Awk_LocalTemplateFile ) endif endif " if filereadable( s:Awk_LocalTemplateFile ) call mmtemplates#core#ReadTemplates ( g:Awk_Templates, 'load', s:Awk_LocalTemplateFile ) let messsage = messsage." and '".s:Awk_LocalTemplateFile."'" if mmtemplates#core#ExpandText( g:Awk_Templates, '|AUTHOR|' ) == 'YOUR NAME' echomsg "Please set your personal details in file '".s:Awk_LocalTemplateFile."'." endif endif " else "------------------------------------------------------------------------------- " LOCAL INSTALLATION "------------------------------------------------------------------------------- if filereadable( s:Awk_LocalTemplateFile ) call mmtemplates#core#ReadTemplates ( g:Awk_Templates, 'load', s:Awk_LocalTemplateFile ) let messsage = "Templates read from '".s:Awk_LocalTemplateFile."'" else echomsg "Local template file '".s:Awk_LocalTemplateFile."' not readable." return endif " endif if a:displaymsg == 'yes' echomsg messsage.'.' endif endfunction " ---------- end of function Awk_RereadTemplates ---------- " "=== FUNCTION ================================================================ " NAME: InitMenus {{{1 " DESCRIPTION: Initialize menus. " PARAMETERS: - " RETURNS: "=============================================================================== function! s:InitMenus() " " TODO: mapleader configurable " if ! has ( 'menu' ) return endif " " Preparation call mmtemplates#core#CreateMenus ( 'g:Awk_Templates', s:Awk_RootMenu, 'do_reset' ) " " get the mapleader (correctly escaped) let [ esc_mapl, err ] = mmtemplates#core#Resource ( g:Awk_Templates, 'escaped_mapleader' ) " exe 'amenu '.s:Awk_RootMenu.'.Awk <Nop>' exe 'amenu '.s:Awk_RootMenu.'.-Sep00- <Nop>' " "------------------------------------------------------------------------------- " menu headers "------------------------------------------------------------------------------- " call mmtemplates#core#CreateMenus ( 'g:Awk_Templates', s:Awk_RootMenu, 'sub_menu', '&Comments', 'priority', 500 ) " the other, automatically created menus go here; their priority is the standard priority 500 call mmtemplates#core#CreateMenus ( 'g:Awk_Templates', s:Awk_RootMenu, 'sub_menu', 'S&nippets', 'priority', 600 ) call mmtemplates#core#CreateMenus ( 'g:Awk_Templates', s:Awk_RootMenu, 'sub_menu', '&Run' , 'priority', 700 ) call mmtemplates#core#CreateMenus ( 'g:Awk_Templates', s:Awk_RootMenu, 'sub_menu', '&Help' , 'priority', 800 ) " "------------------------------------------------------------------------------- " comments "------------------------------------------------------------------------------- " let head = 'noremenu <silent> '.s:Awk_RootMenu.'.Comments.' let ahead = 'anoremenu <silent> '.s:Awk_RootMenu.'.Comments.' let vhead = 'vnoremenu <silent> '.s:Awk_RootMenu.'.Comments.' let ihead = 'inoremenu <silent> '.s:Awk_RootMenu.'.Comments.' " exe ahead.'end-of-&line\ comment<Tab>'.esc_mapl.'cl :call Awk_EndOfLineComment()<CR>' exe vhead.'end-of-&line\ comment<Tab>'.esc_mapl.'cl :call Awk_EndOfLineComment()<CR>' exe ahead.'ad&just\ end-of-line\ com\.<Tab>'.esc_mapl.'cj :call Awk_AdjustLineEndComm()<CR>' exe ihead.'ad&just\ end-of-line\ com\.<Tab>'.esc_mapl.'cj <Esc>:call Awk_AdjustLineEndComm()<CR>' exe vhead.'ad&just\ end-of-line\ com\.<Tab>'.esc_mapl.'cj :call Awk_AdjustLineEndComm()<CR>' exe head.'&set\ end-of-line\ com\.\ col\.<Tab>'.esc_mapl.'cs <Esc>:call Awk_GetLineEndCommCol()<CR>' " exe ahead.'-Sep01- <Nop>' exe ahead.'&comment<TAB>'.esc_mapl.'cc :call Awk_CodeComment()<CR>' exe vhead.'&comment<TAB>'.esc_mapl.'cc :call Awk_CodeComment()<CR>' exe ahead.'&uncomment<TAB>'.esc_mapl.'cu :call Awk_CommentCode(0)<CR>' exe vhead.'&uncomment<TAB>'.esc_mapl.'cu :call Awk_CommentCode(0)<CR>' exe ahead.'-Sep02- <Nop>' " "------------------------------------------------------------------------------- " generate menus from the templates "------------------------------------------------------------------------------- " call mmtemplates#core#CreateMenus ( 'g:Awk_Templates', s:Awk_RootMenu, 'do_templates' ) " "------------------------------------------------------------------------------- " snippets "------------------------------------------------------------------------------- " if !empty(s:Awk_CodeSnippets) " exe "amenu <silent> ".s:Awk_RootMenu.'.S&nippets.&read\ code\ snippet<Tab>'.esc_mapl.'nr :call Awk_CodeSnippet("read")<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.S&nippets.&read\ code\ snippet<Tab>'.esc_mapl.'nr <C-C>:call Awk_CodeSnippet("read")<CR>' exe "amenu <silent> ".s:Awk_RootMenu.'.S&nippets.&view\ code\ snippet<Tab>'.esc_mapl.'nv :call Awk_CodeSnippet("view")<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.S&nippets.&view\ code\ snippet<Tab>'.esc_mapl.'nv <C-C>:call Awk_CodeSnippet("view")<CR>' exe "amenu <silent> ".s:Awk_RootMenu.'.S&nippets.&write\ code\ snippet<Tab>'.esc_mapl.'nw :call Awk_CodeSnippet("write")<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.S&nippets.&write\ code\ snippet<Tab>'.esc_mapl.'nw <C-C>:call Awk_CodeSnippet("write")<CR>' exe "vmenu <silent> ".s:Awk_RootMenu.'.S&nippets.&write\ code\ snippet<Tab>'.esc_mapl.'nw <C-C>:call Awk_CodeSnippet("writemarked")<CR>' exe "amenu <silent> ".s:Awk_RootMenu.'.S&nippets.&edit\ code\ snippet<Tab>'.esc_mapl.'ne :call Awk_CodeSnippet("edit")<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.S&nippets.&edit\ code\ snippet<Tab>'.esc_mapl.'ne <C-C>:call Awk_CodeSnippet("edit")<CR>' exe "amenu <silent> ".s:Awk_RootMenu.'.S&nippets.-SepSnippets- :' " " :TODO:05.01.2013 11:06:WM: what to do if Awk_CodeSnippet is empty/directory does not exist? " endif " call mmtemplates#core#CreateMenus ( 'g:Awk_Templates', s:Awk_RootMenu, 'do_specials', 'specials_menu', 'S&nippets' ) " "------------------------------------------------------------------------------- " run "------------------------------------------------------------------------------- " exe " menu <silent> ".s:Awk_RootMenu.'.&Run.save\ +\ &run\ script<Tab>'.esc_mapl.'rr\ \ <C-F9> :call Awk_Run("n")<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.save\ +\ &run\ script<Tab>'.esc_mapl.'rr\ \ <C-F9> <C-C>:call Awk_Run("n")<CR>' exe " menu <silent> ".s:Awk_RootMenu.'.&Run.update,\ check\ &syntax<Tab>'.esc_mapl.'rs\ \ <A-F9> :call Awk_SyntaxCheck("syntax")<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.update,\ check\ &syntax<Tab>'.esc_mapl.'rs\ \ <A-F9> <C-C>:call Awk_SyntaxCheck("syntax")<CR>' exe " menu <silent> ".s:Awk_RootMenu.'.&Run.update,\ &lint\ check<Tab>'.esc_mapl.'rl :call Awk_SyntaxCheck("lint")<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.update,\ &lint\ check<Tab>'.esc_mapl.'rl <C-C>:call Awk_SyntaxCheck("lint")<CR>' " exe " menu ".s:Awk_RootMenu.'.&Run.script\ cmd\.\ line\ &arg\.<Tab>'.esc_mapl.'ra\ \ <S-F9> :AwkScriptArguments<Space>' exe "imenu ".s:Awk_RootMenu.'.&Run.script\ cmd\.\ line\ &arg\.<Tab>'.esc_mapl.'ra\ \ <S-F9> <C-C>:AwkScriptArguments<Space>' " exe " menu ".s:Awk_RootMenu.'.&Run.AWK\ cmd\.\ line\ &arg\.<Tab>'.esc_mapl.'raa :AwkArguments<Space>' exe "imenu ".s:Awk_RootMenu.'.&Run.AWK\ cmd\.\ line\ &arg\.<Tab>'.esc_mapl.'raa <C-C>:AwkArguments<Space>' " let ahead = 'amenu <silent> '.s:Awk_RootMenu.'.Run.' let vhead = 'vmenu <silent> '.s:Awk_RootMenu.'.Run.' " if !s:MSWIN exe ahead.'make\ script\ &executable<Tab>'.esc_mapl.'re :call Awk_MakeScriptExecutable()<CR>' endif " exe ahead.'-SEP1- :' if s:MSWIN exe ahead.'&hardcopy\ to\ printer<Tab>'.esc_mapl.'rh <C-C>:call Awk_Hardcopy("n")<CR>' exe vhead.'&hardcopy\ to\ printer<Tab>'.esc_mapl.'rh <C-C>:call Awk_Hardcopy("v")<CR>' else exe ahead.'&hardcopy\ to\ FILENAME\.ps<Tab>'.esc_mapl.'rh <C-C>:call Awk_Hardcopy("n")<CR>' exe vhead.'&hardcopy\ to\ FILENAME\.ps<Tab>'.esc_mapl.'rh <C-C>:call Awk_Hardcopy("v")<CR>' endif " exe ahead.'-SEP2- :' exe ahead.'plugin\ &settings<Tab>'.esc_mapl.'rse :call Awk_Settings()<CR>' " if !s:MSWIN exe " menu <silent> ".s:Awk_RootMenu.'.&Run.x&term\ size<Tab>'.esc_mapl.'rx :call Awk_XtermSize()<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.x&term\ size<Tab>'.esc_mapl.'rx <C-C>:call Awk_XtermSize()<CR>' endif " if s:MSWIN if s:Awk_OutputGvim == "buffer" exe " menu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ BUFFER->term<Tab>'.esc_mapl.'ro :call Awk_Toggle_Gvim_Xterm_MS()<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ BUFFER->term<Tab>'.esc_mapl.'ro <C-C>:call Awk_Toggle_Gvim_Xterm_MS()<CR>' else exe " menu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ TERM->buffer<Tab>'.esc_mapl.'ro :call Awk_Toggle_Gvim_Xterm_MS()<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ TERM->buffer<Tab>'.esc_mapl.'ro <C-C>:call Awk_Toggle_Gvim_Xterm_MS()<CR>' endif else if s:Awk_OutputGvim == "vim" exe " menu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ VIM->buffer->xterm<Tab>'.esc_mapl.'ro :call Awk_Toggle_Gvim_Xterm()<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ VIM->buffer->xterm<Tab>'.esc_mapl.'ro <C-C>:call Awk_Toggle_Gvim_Xterm()<CR>' else if s:Awk_OutputGvim == "buffer" exe " menu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ BUFFER->xterm->vim<Tab>'.esc_mapl.'ro :call Awk_Toggle_Gvim_Xterm()<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ BUFFER->xterm->vim<Tab>'.esc_mapl.'ro <C-C>:call Awk_Toggle_Gvim_Xterm()<CR>' else exe " menu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ XTERM->vim->buffer<Tab>'.esc_mapl.'ro :call Awk_Toggle_Gvim_Xterm()<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ XTERM->vim->buffer<Tab>'.esc_mapl.'ro <C-C>:call Awk_Toggle_Gvim_Xterm()<CR>' endif endif endif " "------------------------------------------------------------------------------- " help "------------------------------------------------------------------------------- " let ahead = 'amenu <silent> '.s:Awk_RootMenu.'.Help.' let ihead = 'imenu <silent> '.s:Awk_RootMenu.'.Help.' " exe ahead.'&AWK\ manual<Tab>'.esc_mapl.'hm :call Awk_help("awk")<CR>' exe ihead.'&AWK\ manual<Tab>'.esc_mapl.'hm <C-C>:call Awk_help("awk")<CR>' exe ahead.'-SEP1- :' exe ahead.'&help\ (Awk-Support)<Tab>'.esc_mapl.'hp :call Awk_HelpAwkSupport()<CR>' exe ihead.'&help\ (Awk-Support)<Tab>'.esc_mapl.'hp <C-C>:call Awk_HelpAwkSupport()<CR>' " endfunction " ---------- end of function s:InitMenus ---------- " "=== FUNCTION ================================================================ " NAME: Awk_JumpForward {{{1 " DESCRIPTION: Jump to the next target, otherwise behind the current string. " PARAMETERS: - " RETURNS: empty string "=============================================================================== function! Awk_JumpForward () let match = search( s:Awk_TemplateJumpTarget, 'c' ) if match > 0 " remove the target call setline( match, substitute( getline('.'), s:Awk_TemplateJumpTarget, '', '' ) ) else " try to jump behind parenthesis or strings call search( "[\]})\"'`]", 'W' ) normal l endif return '' endfunction " ---------- end of function Awk_JumpForward ---------- " "=== FUNCTION ================================================================ " NAME: Awk_CodeSnippet {{{1 " DESCRIPTION: read / write / edit code sni " PARAMETERS: mode - edit, read, write, writemarked, view "=============================================================================== function! Awk_CodeSnippet(mode) if isdirectory(g:Awk_CodeSnippets) " " read snippet file, put content below current line " if a:mode == "read" if has("gui_running") && s:Awk_GuiSnippetBrowser == 'gui' let l:snippetfile=browse(0,"read a code snippet",g:Awk_CodeSnippets,"") else let l:snippetfile=input("read snippet ", g:Awk_CodeSnippets, "file" ) endif if filereadable(l:snippetfile) let linesread= line("$") let l:old_cpoptions = &cpoptions " Prevent the alternate buffer from being set to this files setlocal cpoptions-=a :execute "read ".l:snippetfile let &cpoptions = l:old_cpoptions " restore previous options " let linesread= line("$")-linesread-1 if linesread>=0 && match( l:snippetfile, '\.\(ni\|noindent\)$' ) < 0 silent exe "normal =".linesread."+" endif endif endif " " update current buffer / split window / edit snippet file " if a:mode == "edit" if has("gui_running") && s:Awk_GuiSnippetBrowser == 'gui' let l:snippetfile=browse(0,"edit a code snippet",g:Awk_CodeSnippets,"") else let l:snippetfile=input("edit snippet ", g:Awk_CodeSnippets, "file" ) endif if !empty(l:snippetfile) :execute "update! | split | edit ".l:snippetfile endif endif " " update current buffer / split window / view snippet file " if a:mode == "view" if has("gui_running") && s:Awk_GuiSnippetBrowser == 'gui' let l:snippetfile=browse(0,"view a code snippet",g:Awk_CodeSnippets,"") else let l:snippetfile=input("view snippet ", g:Awk_CodeSnippets, "file" ) endif if !empty(l:snippetfile) :execute "update! | split | view ".l:snippetfile endif endif " " write whole buffer or marked area into snippet file " if a:mode == "write" || a:mode == "writemarked" if has("gui_running") && s:Awk_GuiSnippetBrowser == 'gui' let l:snippetfile=browse(0,"write a code snippet",g:Awk_CodeSnippets,"") else let l:snippetfile=input("write snippet ", g:Awk_CodeSnippets, "file" ) endif if !empty(l:snippetfile) if filereadable(l:snippetfile) if confirm("File ".l:snippetfile." exists ! Overwrite ? ", "&Cancel\n&No\n&Yes") != 3 return endif endif if a:mode == "write" :execute ":write! ".l:snippetfile else :execute ":*write! ".l:snippetfile endif endif endif else redraw! echohl ErrorMsg echo "code snippet directory ".g:Awk_CodeSnippets." does not exist" echohl None endif endfunction " ---------- end of function Awk_CodeSnippet ---------- " "=== FUNCTION ================================================================ " NAME: Awk_Hardcopy {{{1 " DESCRIPTION: Make PostScript document from current buffer " MSWIN : display printer dialog " PARAMETERS: mode - n : print complete buffer, v : print marked area " RETURNS: "=============================================================================== function! Awk_Hardcopy (mode) let outfile = expand("%") if outfile == "" redraw echohl WarningMsg | echo " no file name " | echohl None return endif let outdir = getcwd() if filewritable(outdir) != 2 let outdir = $HOME endif if !s:MSWIN let outdir = outdir.'/' endif let old_printheader=&printheader exe ':set printheader='.s:Awk_Printheader " ----- normal mode ---------------- if a:mode=="n" silent exe 'hardcopy > '.outdir.outfile.'.ps' if !s:MSWIN echo 'file "'.outfile.'" printed to "'.outdir.outfile.'.ps"' endif endif " ----- visual mode ---------------- if a:mode=="v" silent exe "*hardcopy > ".outdir.outfile.".ps" if !s:MSWIN echo 'file "'.outfile.'" (lines '.line("'<").'-'.line("'>").') printed to "'.outdir.outfile.'.ps"' endif endif exe ':set printheader='.escape( old_printheader, ' %' ) endfunction " ---------- end of function Awk_Hardcopy ---------- " "=== FUNCTION ================================================================ " NAME: CreateAdditionalMaps {{{1 " DESCRIPTION: create additional maps " PARAMETERS: - " RETURNS: "=============================================================================== function! s:CreateAdditionalMaps () " " ---------- Awk dictionary ------------------------------------------------- " This will enable keyword completion for Awk " using Vim's dictionary feature |i_CTRL-X_CTRL-K|. " if exists("g:Awk_Dictionary_File") silent! exe 'setlocal dictionary+='.g:Awk_Dictionary_File endif " "------------------------------------------------------------------------------- " USER DEFINED COMMANDS "------------------------------------------------------------------------------- command! -buffer -nargs=* -complete=file AwkScriptArguments call Awk_ScriptCmdLineArguments(<q-args>) command! -buffer -nargs=* -complete=file AwkArguments call Awk_AwkCmdLineArguments(<q-args>) " "------------------------------------------------------------------------------- " settings - local leader "------------------------------------------------------------------------------- if ! empty ( g:Awk_MapLeader ) if exists ( 'g:maplocalleader' ) let ll_save = g:maplocalleader endif let g:maplocalleader = g:Awk_MapLeader endif " "------------------------------------------------------------------------------- " comments "------------------------------------------------------------------------------- nnoremap <buffer> <silent> <LocalLeader>cl :call Awk_EndOfLineComment()<CR> inoremap <buffer> <silent> <LocalLeader>cl <C-C>:call Awk_EndOfLineComment()<CR> vnoremap <buffer> <silent> <LocalLeader>cl :call Awk_EndOfLineComment()<CR> " nnoremap <buffer> <silent> <LocalLeader>cj :call Awk_AdjustLineEndComm()<CR> inoremap <buffer> <silent> <LocalLeader>cj <C-C>:call Awk_AdjustLineEndComm()<CR> vnoremap <buffer> <silent> <LocalLeader>cj :call Awk_AdjustLineEndComm()<CR> " nnoremap <buffer> <silent> <LocalLeader>cs :call Awk_GetLineEndCommCol()<CR> inoremap <buffer> <silent> <LocalLeader>cs <C-C>:call Awk_GetLineEndCommCol()<CR> vnoremap <buffer> <silent> <LocalLeader>cs <C-C>:call Awk_GetLineEndCommCol()<CR> " nnoremap <buffer> <silent> <LocalLeader>cc :call Awk_CodeComment()<CR> inoremap <buffer> <silent> <LocalLeader>cc <C-C>:call Awk_CodeComment()<CR> vnoremap <buffer> <silent> <LocalLeader>cc :call Awk_CodeComment()<CR> " nnoremap <buffer> <silent> <LocalLeader>cu :call Awk_CommentCode(0)<CR> inoremap <buffer> <silent> <LocalLeader>cu <C-C>:call Awk_CommentCode(0)<CR> vnoremap <buffer> <silent> <LocalLeader>cu :call Awk_CommentCode(0)<CR> " "------------------------------------------------------------------------------- " snippets "------------------------------------------------------------------------------- " nnoremap <buffer> <silent> <LocalLeader>nr :call Awk_CodeSnippet("read")<CR> inoremap <buffer> <silent> <LocalLeader>nr <Esc>:call Awk_CodeSnippet("read")<CR> nnoremap <buffer> <silent> <LocalLeader>nw :call Awk_CodeSnippet("write")<CR> inoremap <buffer> <silent> <LocalLeader>nw <Esc>:call Awk_CodeSnippet("write")<CR> vnoremap <buffer> <silent> <LocalLeader>nw <Esc>:call Awk_CodeSnippet("writemarked")<CR> nnoremap <buffer> <silent> <LocalLeader>ne :call Awk_CodeSnippet("edit")<CR> inoremap <buffer> <silent> <LocalLeader>ne <Esc>:call Awk_CodeSnippet("edit")<CR> nnoremap <buffer> <silent> <LocalLeader>nv :call Awk_CodeSnippet("view")<CR> inoremap <buffer> <silent> <LocalLeader>nv <Esc>:call Awk_CodeSnippet("view")<CR> " "------------------------------------------------------------------------------- " run "------------------------------------------------------------------------------- " noremap <buffer> <silent> <LocalLeader>rr :call Awk_Run("n")<CR> inoremap <buffer> <silent> <LocalLeader>rr <Esc>:call Awk_Run("n")<CR> noremap <buffer> <silent> <LocalLeader>rs :call Awk_SyntaxCheck("syntax")<CR> inoremap <buffer> <silent> <LocalLeader>rs <C-C>:call Awk_SyntaxCheck("syntax")<CR> noremap <buffer> <silent> <LocalLeader>rl :call Awk_SyntaxCheck("lint")<CR> inoremap <buffer> <silent> <LocalLeader>rl <C-C>:call Awk_SyntaxCheck("lint")<CR> noremap <buffer> <LocalLeader>ra :AwkScriptArguments<Space> inoremap <buffer> <LocalLeader>ra <Esc>:AwkScriptArguments<Space> noremap <buffer> <LocalLeader>raa :AwkArguments<Space> inoremap <buffer> <LocalLeader>raa <Esc>:AwkArguments<Space> " if s:UNIX noremap <buffer> <silent> <LocalLeader>re :call Awk_MakeScriptExecutable()<CR> inoremap <buffer> <silent> <LocalLeader>re <C-C>:call Awk_MakeScriptExecutable()<CR> endif nnoremap <buffer> <silent> <LocalLeader>rh :call Awk_Hardcopy("n")<CR> vnoremap <buffer> <silent> <LocalLeader>rh <C-C>:call Awk_Hardcopy("v")<CR> " map <buffer> <silent> <C-F9> :call Awk_Run("n")<CR> imap <buffer> <silent> <C-F9> <C-C>:call Awk_Run("n")<CR> " map <buffer> <silent> <A-F9> :call Awk_SyntaxCheck("syntax")<CR> imap <buffer> <silent> <A-F9> <C-C>:call Awk_SyntaxCheck("syntax")<CR> " map <buffer> <S-F9> :AwkScriptArguments<Space> imap <buffer> <S-F9> <C-C>:AwkScriptArguments<Space> if s:MSWIN map <buffer> <silent> <LocalLeader>ro :call Awk_Toggle_Gvim_Xterm_MS()<CR> imap <buffer> <silent> <LocalLeader>ro <Esc>:call Awk_Toggle_Gvim_Xterm_MS()<CR> else map <buffer> <silent> <LocalLeader>ro :call Awk_Toggle_Gvim_Xterm()<CR> imap <buffer> <silent> <LocalLeader>ro <Esc>:call Awk_Toggle_Gvim_Xterm()<CR> endif " "------------------------------------------------------------------------------- " help "------------------------------------------------------------------------------- nnoremap <buffer> <silent> <LocalLeader>rse :call Awk_Settings()<CR> " noremap <buffer> <silent> <LocalLeader>hm :call Awk_help('awk')<CR> inoremap <buffer> <silent> <LocalLeader>hm <Esc>:call Awk_help('awk')<CR> noremap <buffer> <silent> <LocalLeader>hp :call Awk_HelpAwkSupport()<CR> inoremap <buffer> <silent> <LocalLeader>hp <C-C>:call Awk_HelpAwkSupport()<CR> " nmap <buffer> <silent> <C-j> i<C-R>=Awk_JumpForward()<CR> imap <buffer> <silent> <C-j> <C-R>=Awk_JumpForward()<CR> " "------------------------------------------------------------------------------- " settings - reset local leader "------------------------------------------------------------------------------- if ! empty ( g:Awk_MapLeader ) if exists ( 'll_save' ) let g:maplocalleader = ll_save else unlet g:maplocalleader endif endif " endfunction " ---------- end of function s:CreateAdditionalMaps ---------- " "------------------------------------------------------------------------------ " Awk_HelpAwkSupport : help awksupport {{{1 "------------------------------------------------------------------------------ function! Awk_HelpAwkSupport () try :help awksupport catch exe ':helptags '.s:plugin_dir.'/doc' :help awksupport endtry endfunction " ---------- end of function Awk_HelpAwkSupport ---------- " "------------------------------------------------------------------------------ " Awk_help : lookup word under the cursor or ask {{{1 "------------------------------------------------------------------------------ let s:Awk_DocBufferName = "AWK_HELP" let s:Awk_DocHelpBufferNumber = -1 " function! Awk_help( type ) " " jump to an already open AWK manual window or create one " if bufloaded(s:Awk_DocBufferName) != 0 && bufwinnr(s:Awk_DocHelpBufferNumber) != -1 exe bufwinnr(s:Awk_DocHelpBufferNumber) . "wincmd w" " buffer number may have changed, e.g. after a 'save as' if bufnr("%") != s:Awk_DocHelpBufferNumber let s:Awk_DocHelpBufferNumber=bufnr(s:Awk_OutputBufferName) exe ":bn ".s:Awk_DocHelpBufferNumber endif else exe ":new ".s:Awk_DocBufferName let s:Awk_DocHelpBufferNumber=bufnr("%") setlocal buftype=nofile setlocal noswapfile setlocal bufhidden=delete setlocal syntax=OFF endif setlocal modifiable setlocal filetype=man " "------------------------------------------------------------------------------- " open the AWK manual "------------------------------------------------------------------------------- if a:type == 'awk' silent exe ":%!".s:Awk_ManualReader.' 1 awk' if s:MSWIN call s:awk_RemoveSpecialCharacters() endif endif setlocal nomodifiable endfunction " ---------- end of function Awk_help ---------- " "------------------------------------------------------------------------------ " remove <backspace><any character> in CYGWIN man(1) output {{{1 " remove _<any character> in CYGWIN man(1) output {{{1 "------------------------------------------------------------------------------ " function! s:awk_RemoveSpecialCharacters ( ) let patternunderline = '_\%x08' let patternbold = '\%x08.' setlocal modifiable if search(patternunderline) != 0 silent exe ':%s/'.patternunderline.'//g' endif if search(patternbold) != 0 silent exe ':%s/'.patternbold.'//g' endif setlocal nomodifiable silent normal gg endfunction " ---------- end of function s:awk_RemoveSpecialCharacters ---------- " "=== FUNCTION ================================================================ " NAME: Awk_Settings {{{1 " DESCRIPTION: Display plugin settings " PARAMETERS: - " RETURNS: "=============================================================================== function! Awk_Settings () let txt = " awk-Support settings\n\n" let txt = txt.' author : "'.mmtemplates#core#ExpandText( g:Awk_Templates, '|AUTHOR|' )."\"\n" let txt = txt.' authorref : "'.mmtemplates#core#ExpandText( g:Awk_Templates, '|AUTHORREF|' )."\"\n" let txt = txt.' company : "'.mmtemplates#core#ExpandText( g:Awk_Templates, '|COMPANY|' )."\"\n" let txt = txt.' copyright holder : "'.mmtemplates#core#ExpandText( g:Awk_Templates, '|COPYRIGHT|' )."\"\n" let txt = txt.' email : "'.mmtemplates#core#ExpandText( g:Awk_Templates, '|EMAIL|' )."\"\n" let txt = txt.' licence : "'.mmtemplates#core#ExpandText( g:Awk_Templates, '|LICENSE|' )."\"\n" let txt = txt.' organization : "'.mmtemplates#core#ExpandText( g:Awk_Templates, '|ORGANIZATION|')."\"\n" let txt = txt.' project : "'.mmtemplates#core#ExpandText( g:Awk_Templates, '|PROJECT|' )."\"\n" let txt = txt.' AWK executable : '.s:Awk_Awk."\n" if exists( "b:Awk_AwkCmdLineArgs" ) let txt = txt.' AWK cmd. line arguments : '.b:Awk_AwkCmdLineArgs."\n" endif let txt = txt.' plugin installation : "'.s:installation."\"\n" let txt = txt.' code snippet directory : "'.s:Awk_CodeSnippets."\"\n" if s:installation == 'system' let txt = txt.'global template directory : '.s:Awk_GlobalTemplateDir."\n" if filereadable( s:Awk_LocalTemplateFile ) let txt = txt.' local template directory : '.s:Awk_LocalTemplateDir."\n" endif else let txt = txt.' local template directory : '.s:Awk_LocalTemplateDir."\n" endif " ----- dictionaries ------------------------ if !empty(g:Awk_Dictionary_File) let ausgabe= &dictionary let ausgabe= substitute( ausgabe, ",", ",\n + ", "g" ) let txt = txt." dictionary file(s) : ".ausgabe."\n" endif let txt = txt."\n" let txt = txt."__________________________________________________________________________\n" let txt = txt." awk-Support, Version ".g:AwkSupportVersion." / Dr.-Ing. Fritz Mehner / mehner@fh-swf.de\n\n" echo txt endfunction " ---------- end of function Awk_Settings ---------- " "------------------------------------------------------------------------------ " Awk_CreateGuiMenus {{{1 "------------------------------------------------------------------------------ function! Awk_CreateGuiMenus () if s:Awk_MenuVisible == 'no' aunmenu <silent> &Tools.Load\ Awk\ Support amenu <silent> 40.1000 &Tools.-SEP100- : amenu <silent> 40.1010 &Tools.Unload\ Awk\ Support :call Awk_RemoveGuiMenus()<CR> " call g:Awk_RereadTemplates('no') call s:InitMenus () " let s:Awk_MenuVisible = 'yes' endif endfunction " ---------- end of function Awk_CreateGuiMenus ---------- " "------------------------------------------------------------------------------ " Awk_ToolMenu {{{1 "------------------------------------------------------------------------------ function! Awk_ToolMenu () amenu <silent> 40.1000 &Tools.-SEP100- : amenu <silent> 40.1010 &Tools.Load\ Awk\ Support :call Awk_CreateGuiMenus()<CR> endfunction " ---------- end of function Awk_ToolMenu ---------- "------------------------------------------------------------------------------ " Awk_RemoveGuiMenus {{{1 "------------------------------------------------------------------------------ function! Awk_RemoveGuiMenus () if s:Awk_MenuVisible == 'yes' exe "aunmenu <silent> ".s:Awk_RootMenu " aunmenu <silent> &Tools.Unload\ Awk\ Support call Awk_ToolMenu() " let s:Awk_MenuVisible = 'no' endif endfunction " ---------- end of function Awk_RemoveGuiMenus ---------- " "---------------------------------------------------------------------- " Run : toggle output destination (Linux/Unix) {{{1 "---------------------------------------------------------------------- function! Awk_Toggle_Gvim_Xterm () if has("gui_running") let [ esc_mapl, err ] = mmtemplates#core#Resource ( g:Awk_Templates, 'escaped_mapleader' ) if s:Awk_OutputGvim == "vim" exe "aunmenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ VIM->buffer->xterm' exe " menu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ BUFFER->xterm->vim<Tab>'.esc_mapl.' :call Awk_Toggle_Gvim_Xterm()<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ BUFFER->xterm->vim<Tab>'.esc_mapl.' <C-C>:call Awk_Toggle_Gvim_Xterm()<CR>' let s:Awk_OutputGvim = "buffer" else if s:Awk_OutputGvim == "buffer" exe "aunmenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ BUFFER->xterm->vim' exe " menu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ XTERM->vim->buffer<Tab>'.esc_mapl.' :call Awk_Toggle_Gvim_Xterm()<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ XTERM->vim->buffer<Tab>'.esc_mapl.' <C-C>:call Awk_Toggle_Gvim_Xterm()<CR>' let s:Awk_OutputGvim = "xterm" else " ---------- output : xterm -> gvim exe "aunmenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ XTERM->vim->buffer' exe " menu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ VIM->buffer->xterm<Tab>'.esc_mapl.' :call Awk_Toggle_Gvim_Xterm()<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ VIM->buffer->xterm<Tab>'.esc_mapl.' <C-C>:call Awk_Toggle_Gvim_Xterm()<CR>' let s:Awk_OutputGvim = "vim" endif endif else if s:Awk_OutputGvim == "vim" let s:Awk_OutputGvim = "buffer" else let s:Awk_OutputGvim = "vim" endif endif echomsg "output destination is '".s:Awk_OutputGvim."'" endfunction " ---------- end of function Awk_Toggle_Gvim_Xterm ---------- " "---------------------------------------------------------------------- " Run : toggle output destination (Windows) {{{1 "---------------------------------------------------------------------- function! Awk_Toggle_Gvim_Xterm_MS () if has("gui_running") let [ esc_mapl, err ] = mmtemplates#core#Resource ( g:Awk_Templates, 'escaped_mapleader' ) if s:Awk_OutputGvim == "buffer" exe "aunmenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ BUFFER->term' exe " menu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ TERM->buffer<Tab>'.esc_mapl.' :call Awk_Toggle_Gvim_Xterm_MS()<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ TERM->buffer<Tab>'.esc_mapl.' <C-C>:call Awk_Toggle_Gvim_Xterm_MS()<CR>' let s:Awk_OutputGvim = "xterm" else exe "aunmenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ TERM->buffer' exe " menu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ BUFFER->term<Tab>'.esc_mapl.' :call Awk_Toggle_Gvim_Xterm_MS()<CR>' exe "imenu <silent> ".s:Awk_RootMenu.'.&Run.&output:\ BUFFER->term<Tab>'.esc_mapl.' <C-C>:call Awk_Toggle_Gvim_Xterm_MS()<CR>' let s:Awk_OutputGvim = "buffer" endif endif endfunction " ---------- end of function Awk_Toggle_Gvim_Xterm_MS ---------- " "------------------------------------------------------------------------------ " Run : xterm geometry {{{1 "------------------------------------------------------------------------------ function! Awk_XtermSize () let regex = '-geometry\s\+\d\+x\d\+' let geom = matchstr( s:Awk_XtermDefaults, regex ) let geom = matchstr( geom, '\d\+x\d\+' ) let geom = substitute( geom, 'x', ' ', "" ) let answer= Awk_Input(" xterm size (COLUMNS LINES) : ", geom, '' ) while match(answer, '^\s*\d\+\s\+\d\+\s*$' ) < 0 let answer= Awk_Input(" + xterm size (COLUMNS LINES) : ", geom, '' ) endwhile let answer = substitute( answer, '^\s\+', "", "" ) " remove leading whitespaces let answer = substitute( answer, '\s\+$', "", "" ) " remove trailing whitespaces let answer = substitute( answer, '\s\+', "x", "" ) " replace inner whitespaces let s:Awk_XtermDefaults = substitute( s:Awk_XtermDefaults, regex, "-geometry ".answer , "" ) endfunction " ---------- end of function Awk_XtermSize ---------- " "------------------------------------------------------------------------------ " Awk_SaveOption {{{1 " param 1 : option name " param 2 : characters to be escaped (optional) "------------------------------------------------------------------------------ function! Awk_SaveOption ( option, ... ) exe 'let escaped =&'.a:option if a:0 == 0 let escaped = escape( escaped, ' |"\' ) else let escaped = escape( escaped, ' |"\'.a:1 ) endif let s:Awk_saved_option[a:option] = escaped endfunction " ---------- end of function Awk_SaveOption ---------- " let s:Awk_saved_option = {} " "------------------------------------------------------------------------------ " Awk_RestoreOption {{{1 "------------------------------------------------------------------------------ function! Awk_RestoreOption ( option ) exe ':setlocal '.a:option.'='.s:Awk_saved_option[a:option] endfunction " ---------- end of function Awk_RestoreOption ---------- " "------------------------------------------------------------------------------ " Run : Command line arguments {{{1 "------------------------------------------------------------------------------ function! Awk_ScriptCmdLineArguments ( ... ) let b:Awk_ScriptCmdLineArgs = join( a:000 ) endfunction " ---------- end of function Awk_ScriptCmdLineArguments ---------- " "------------------------------------------------------------------------------ " Awk_AwkCmdLineArguments : AWK command line arguments {{{1 "------------------------------------------------------------------------------ function! Awk_AwkCmdLineArguments ( ... ) let b:Awk_AwkCmdLineArgs = join( a:000 ) endfunction " ---------- end of function Awk_AwkCmdLineArguments ---------- " "------------------------------------------------------------------------------ " Run : run {{{1 "------------------------------------------------------------------------------ " let s:Awk_OutputBufferName = "AWK-Output" let s:Awk_OutputBufferNumber = -1 " function! Awk_Run ( mode ) range silent exe ':cclose' " let l:arguments = exists("b:Awk_ScriptCmdLineArgs") ? " ".b:Awk_ScriptCmdLineArgs : "" let l:currentbuffer = bufname("%") let l:fullname = expand("%:p") let l:fullnameesc = fnameescape( l:fullname ) " silent exe ":update" let l:awkCmdLineArgs = exists("b:Awk_AwkCmdLineArgs") ? ' '.b:Awk_AwkCmdLineArgs.' ' : '' if l:arguments =~ '^\s*$' echohl WarningMsg echomsg 'Script call has no file argument.' echohl None endif " "------------------------------------------------------------------------------ " Run : run from the vim command line (Linux only) "------------------------------------------------------------------------------ " if s:Awk_OutputGvim == "vim" " " ----- normal mode ---------- " call Awk_SaveOption( 'makeprg' ) exe ":setlocal makeprg=".s:Awk_Awk exe ':setlocal errorformat='.s:Awk_Errorformat " exe ':make '.l:awkCmdLineArgs." -f '".l:fullname."' ".l:arguments if &term == 'xterm' redraw! endif " call Awk_RestoreOption( 'makeprg' ) exe ":botright cwindow" if l:currentbuffer != bufname("%") let pattern = '^||.*\n\?' setlocal modifiable " remove the regular script output (appears as comment) if search(pattern) != 0 silent exe ':%s/'.pattern.'//' endif " read the buffer back to have it parsed and used as the new error list silent exe ':cgetbuffer' setlocal nomodifiable silent exe ':cc' endif " exe ':setlocal errorformat=' endif " "------------------------------------------------------------------------------ " Run : redirect output to an output buffer "------------------------------------------------------------------------------ if s:Awk_OutputGvim == "buffer" let l:currentbuffernr = bufnr("%") if l:currentbuffer == bufname("%") " if bufloaded(s:Awk_OutputBufferName) != 0 && bufwinnr(s:Awk_OutputBufferNumber)!=-1 exe bufwinnr(s:Awk_OutputBufferNumber) . "wincmd w" " buffer number may have changed, e.g. after a 'save as' if bufnr("%") != s:Awk_OutputBufferNumber let s:Awk_OutputBufferNumber = bufnr(s:Awk_OutputBufferName) exe ":bn ".s:Awk_OutputBufferNumber endif else silent exe ":new ".s:Awk_OutputBufferName let s:Awk_OutputBufferNumber=bufnr("%") setlocal noswapfile setlocal buftype=nofile setlocal syntax=none setlocal bufhidden=delete setlocal tabstop=8 endif " " run script " setlocal modifiable if a:mode=="n" if s:MSWIN silent exe ":%!".s:Awk_Awk.l:awkCmdLineArgs.' -f "'.l:fullname.'" '.l:arguments else silent exe ":%!".s:Awk_Awk.l:awkCmdLineArgs." -f ".l:fullnameesc.l:arguments endif endif " setlocal nomodifiable " " stdout is empty / not empty " if line("$")==1 && col("$")==1 silent exe ":bdelete" else if winheight(winnr()) >= line("$") exe bufwinnr(l:currentbuffernr) . "wincmd w" endif endif " endif endif " "------------------------------------------------------------------------------ " Run : run in a detached xterm "------------------------------------------------------------------------------ if s:Awk_OutputGvim == 'xterm' " if s:MSWIN exe ':!'.s:Awk_Awk.l:awkCmdLineArgs.' -f "'.l:fullname.'" '.l:arguments else silent exe '!xterm -title '.l:fullnameesc.' '.s:Awk_XtermDefaults \ .' -e '.s:Awk_Wrapper.' '.l:awkCmdLineArgs.l:fullnameesc.l:arguments.' &' endif " endif " if !has("gui_running") && v:progname != 'vim' redraw! endif endfunction " ---------- end of function Awk_Run ---------- " "=== FUNCTION ================================================================ " NAME: Awk_SyntaxCheck {{{1 " DESCRIPTION: syntax check " PARAMETERS: - " RETURNS: "=============================================================================== function! Awk_SyntaxCheck ( check ) exe ":cclose" let l:currentbuffer = bufname("%") let l:fullname = expand("%:p") silent exe ":update" " let l:arguments = exists("b:Awk_ScriptCmdLineArgs") ? " ".b:Awk_ScriptCmdLineArgs : "" call s:Awk_SaveGlobalOption('errorformat') call s:Awk_SaveGlobalOption('makeprg') " if a:check == 'syntax' if s:MSWIN && ( l:fullname =~ ' ' ) " let tmpfile = tempname() exe ':setlocal errorformat='.s:Awk_Errorformat silent exe ":make -e 'BEGIN { exit(0) } END { exit(0) }' -f ".l:fullname exe ":cfile ".tmpfile else " " no whitespaces " exe ":setlocal makeprg=".s:Awk_Awk exe ':setlocal errorformat='.s:Awk_Errorformat let l:fullname = fnameescape( l:fullname ) silent exe ":make -e 'BEGIN { exit(0) } END { exit(0) }' -f ".l:fullname endif endif " if a:check == 'lint' if s:MSWIN && ( l:fullname =~ ' ' ) " let tmpfile = tempname() exe ':setlocal errorformat='.s:Awk_Errorformat silent exe ":make --lint -f ".l:fullname.' '.l:arguments exe ":cfile ".tmpfile else " " no whitespaces " exe ":setlocal makeprg=".s:Awk_Awk exe ':setlocal errorformat='.s:Awk_Errorformat let l:fullname = fnameescape( l:fullname ) exe ":make --lint -f ".l:fullname.' '.l:arguments endif endif exe ":botright cwindow" call s:Awk_RestoreGlobalOption('makeprg') call s:Awk_RestoreGlobalOption('errorformat') " " message in case of success " redraw! if l:currentbuffer == bufname("%") echohl Search if a:check == 'lint' echomsg l:currentbuffer." : lint check is OK" else echomsg l:currentbuffer." : Syntax is OK" endif echohl None return 0 else setlocal wrap setlocal linebreak endif endfunction " ---------- end of function Awk_SyntaxCheck ---------- " "=== FUNCTION ================================================================ " NAME: Awk_MakeScriptExecutable {{{1 " DESCRIPTION: make script executable " PARAMETERS: - " RETURNS: "=============================================================================== function! Awk_MakeScriptExecutable () let filename = fnameescape( expand("%:p") ) if &filetype != 'awk' echo '"'.filename.'" not an awk script.' return endif if executable(filename) == 0 silent exe "!chmod u+x ".filename redraw! if v:shell_error echohl WarningMsg echo 'Could not make "'.filename.'" executable !' else echohl Search echo 'Made "'.filename.'" executable.' endif echohl None else echo '"'.filename.'" is already executable.' endif endfunction " ---------- end of function Awk_MakeScriptExecutable ---------- "---------------------------------------------------------------------- " *** SETUP PLUGIN *** {{{1 "---------------------------------------------------------------------- call Awk_ToolMenu() if s:Awk_LoadMenus == 'yes' && s:Awk_CreateMenusDelayed == 'no' call Awk_CreateGuiMenus() endif " if has( 'autocmd' ) autocmd FileType * \ if &filetype == 'awk' | \ if ! exists( 'g:Awk_Templates' ) | \ if s:Awk_LoadMenus == 'yes' | call Awk_CreateGuiMenus () | \ else | call g:Awk_RereadTemplates ('no') | \ endif | \ endif | \ call s:CreateAdditionalMaps () | \ call mmtemplates#core#CreateMaps ( 'g:Awk_Templates', g:Awk_MapLeader, 'do_special_maps' ) | \ endif if s:Awk_InsertFileHeader == 'yes' autocmd BufNewFile *.awk call mmtemplates#core#InsertTemplate(g:Awk_Templates, 'Comments.file description') endif endif " }}}1 " " ===================================================================================== " vim: tabstop=2 shiftwidth=2 foldmethod=marker
00000svn-vim-cfg
trunk/vimfiles/plugin/awk-support.vim
Vim Script
gpl3
62,541
"################################################################################# " " Filename: perl-support.vim " " Description: perl-support.vim implements a Perl-IDE for Vim/gVim. It is " written to considerably speed up writing code in a consistent " style. " This is done by inserting complete statements, comments, " idioms, code snippets, templates, comments and POD " documentation. Reading perldoc is integrated. Syntax " checking, running a script, starting a debugger and a " profiler can be done by a keystroke. " There a many additional hints and options which can improve " speed and comfort when writing Perl. Please read the " documentation. " " Configuration: There are at least some personal details which should be " configured (see the files README.perlsupport and " perlsupport.txt). " " Dependencies: perl pod2man " podchecker pod2text " pod2html perldoc " " optional: " " Devel::FastProf (profiler) " Devel::NYTProf (profiler) " Devel::SmallProf (profiler) " Devel::ptkdb (debugger frontend) " Perl::Critic (stylechecker) " Perl::Tags (generate Ctags style tags) " Perl::Tidy (beautifier) " YAPE::Regex::Explain (regular expression analyzer) " ddd (debugger frontend) " sort(1) (rearrange profiler statistics) " " Author: Dr.-Ing. Fritz Mehner <mehner@fh-swf.de> " " Version: see variable g:Perl_PluginVersion below " Created: 09.07.2001 " License: Copyright (c) 2001-2011, Fritz Mehner " This program is free software; you can redistribute it " and/or modify it under the terms of the GNU General Public " License as published by the Free Software Foundation, " version 2 of the License. " This program is distributed in the hope that it will be " useful, but WITHOUT ANY WARRANTY; without even the implied " warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR " PURPOSE. " See the GNU General Public License version 2 for more details. " Credits: see perlsupport.txt " Revision: $Id: perl-support.vim,v 1.21 2012/05/18 17:17:52 mehner Exp $ "------------------------------------------------------------------------------- " " Prevent duplicate loading: " if exists("g:Perl_PluginVersion") || &compatible finish endif let g:Perl_PluginVersion= "5.1" " "=== FUNCTION ================================================================ " NAME: Perl_SetGlobalVariable {{{1 " DESCRIPTION: Define a global variable and assign a default value if nor " already defined " PARAMETERS: name - global variable " default - default value "=============================================================================== function! s:perl_SetGlobalVariable ( name, default ) if !exists('g:'.a:name) exe 'let g:'.a:name." = '".a:default."'" else " check for an empty initialization exe 'let val = g:'.a:name if empty(val) exe 'let g:'.a:name." = '".a:default."'" endif endif endfunction " ---------- end of function s:perl_SetGlobalVariable ---------- " "=== FUNCTION ================================================================ " NAME: Perl_SetLocalVariable {{{1 " DESCRIPTION: Assign a value to a local variable if a corresponding global " variable exists " PARAMETERS: name - name of a global variable "=============================================================================== function! s:perl_SetLocalVariable ( name ) if exists('g:'.a:name) exe 'let s:'.a:name.' = g:'.a:name endif endfunction " ---------- end of function s:perl_SetLocalVariable ---------- " call s:perl_SetGlobalVariable( "Perl_MenuHeader",'yes' ) call s:perl_SetGlobalVariable( "Perl_OutputGvim",'vim' ) call s:perl_SetGlobalVariable( "Perl_PerlRegexSubstitution",'$~' ) " "------------------------------------------------------------------------------ " " Platform specific items: " - plugin directory " - characters that must be escaped for filenames " let s:MSWIN = has("win16") || has("win32") || has("win64") || has("win95") let s:UNIX = has("unix") || has("macunix") || has("win32unix") " let g:Perl_Installation = '*undefined*' let g:Perl_PluginDir = '' " let s:Perl_GlobalTemplateFile = '' let s:Perl_GlobalTemplateDir = '' let s:Perl_LocalTemplateFile = '' let s:Perl_LocalTemplateDir = '' let g:Perl_FilenameEscChar = '' " if s:MSWIN " ========== MS Windows ====================================================== " " change '\' to '/' to avoid interpretation as escape character if match( substitute( expand("<sfile>"), '\', '/', 'g' ), \ substitute( expand("$HOME"), '\', '/', 'g' ) ) == 0 " USER INSTALLATION ASSUMED let g:Perl_Installation = 'local' let g:Perl_PluginDir = substitute( expand('<sfile>:p:h:h'), '\', '/', 'g' ) let s:Perl_LocalTemplateFile = g:Perl_PluginDir.'/perl-support/templates/Templates' let s:Perl_LocalTemplateDir = fnamemodify( s:Perl_LocalTemplateFile, ":p:h" ).'/' else " SYSTEM WIDE INSTALLATION let g:Perl_Installation = 'system' let g:Perl_PluginDir = $VIM.'/vimfiles' let s:Perl_GlobalTemplateDir = g:Perl_PluginDir.'/perl-support/templates' let s:Perl_GlobalTemplateFile = s:Perl_GlobalTemplateDir.'/Templates' let s:Perl_LocalTemplateFile = $HOME.'/vimfiles/perl-support/templates/Templates' let s:Perl_LocalTemplateDir = fnamemodify( s:Perl_LocalTemplateFile, ":p:h" ).'/' end " let g:Perl_FilenameEscChar = '' " else " ========== Linux/Unix ====================================================== " if match( expand("<sfile>"), resolve( expand("$HOME") ) ) == 0 " USER INSTALLATION ASSUMED let g:Perl_Installation = 'local' let g:Perl_PluginDir = expand("<sfile>:p:h:h") let s:Perl_LocalTemplateFile = g:Perl_PluginDir.'/perl-support/templates/Templates' let s:Perl_LocalTemplateDir = fnamemodify( s:Perl_LocalTemplateFile, ":p:h" ).'/' else " SYSTEM WIDE INSTALLATION let g:Perl_Installation = 'system' let g:Perl_PluginDir = $VIM.'/vimfiles' let s:Perl_GlobalTemplateDir = g:Perl_PluginDir.'/perl-support/templates' let s:Perl_GlobalTemplateFile = s:Perl_GlobalTemplateDir.'/Templates' let s:Perl_LocalTemplateFile = $HOME.'/.vim/perl-support/templates/Templates' let s:Perl_LocalTemplateDir = fnamemodify( s:Perl_LocalTemplateFile, ":p:h" ).'/' endif " let g:Perl_FilenameEscChar = ' \%#[]' " " ============================================================================== endif " " g:Perl_CodeSnippets is used in autoload/perlsupportgui.vim " let s:Perl_CodeSnippets = g:Perl_PluginDir.'/perl-support/codesnippets/' call s:perl_SetGlobalVariable( 'Perl_CodeSnippets', s:Perl_CodeSnippets ) " " call s:perl_SetGlobalVariable( 'Perl_PerlTags', 'off' ) " if !exists("g:Perl_Dictionary_File") let g:Perl_Dictionary_File = g:Perl_PluginDir.'/perl-support/wordlists/perl.list' endif " " " Modul global variables (with default values) which can be overridden. {{{1 " let s:Perl_LoadMenus = 'yes' " display the menus ? let s:Perl_TemplateOverriddenMsg = 'no' let s:Perl_Ctrl_j = 'on' " let s:Perl_FormatDate = '%x' let s:Perl_FormatTime = '%X' let s:Perl_FormatYear = '%Y' let s:Perl_TimestampFormat = '%Y%m%d.%H%M%S' let s:Perl_PerlModuleList = g:Perl_PluginDir.'/perl-support/modules/perl-modules.list' let s:Perl_XtermDefaults = "-fa courier -fs 12 -geometry 80x24" let s:Perl_Debugger = "perl" let s:Perl_ProfilerTimestamp = "no" let s:Perl_LineEndCommColDefault = 49 let s:PerlStartComment = '#' let s:Perl_PodcheckerWarnings = "yes" let s:Perl_PerlcriticOptions = "" let s:Perl_PerlcriticSeverity = 3 let s:Perl_PerlcriticVerbosity = 5 let s:Perl_Printheader = "%<%f%h%m%< %=%{strftime('%x %X')} Page %N" let s:Perl_GuiSnippetBrowser = 'gui' " gui / commandline let s:Perl_GuiTemplateBrowser = 'gui' " gui / explorer / commandline let s:Perl_CreateMenusDelayed = 'yes' " let s:Perl_Wrapper = g:Perl_PluginDir.'/perl-support/scripts/wrapper.sh' let s:Perl_EfmPerl = g:Perl_PluginDir.'/perl-support/scripts/efm_perl.pl' let s:Perl_PerlModuleListGenerator = g:Perl_PluginDir.'/perl-support/scripts/pmdesc3.pl' let s:Perl_PerltidyBackup = "no" " let g:Perl_MapLeader = '\' let s:Perl_RootMenu = '&Perl' " "------------------------------------------------------------------------------ " " Look for global variables (if any), to override the defaults. " call s:perl_SetLocalVariable('Perl_CreateMenusDelayed ') call s:perl_SetLocalVariable('Perl_Ctrl_j ') call s:perl_SetLocalVariable('Perl_Debugger ') call s:perl_SetLocalVariable('Perl_FormatDate ') call s:perl_SetLocalVariable('Perl_FormatTime ') call s:perl_SetLocalVariable('Perl_FormatYear ') call s:perl_SetLocalVariable('Perl_GlobalTemplateFile ') call s:perl_SetLocalVariable('Perl_LocalTemplateFile ') call s:perl_SetLocalVariable('Perl_GuiSnippetBrowser ') call s:perl_SetLocalVariable('Perl_GuiTemplateBrowser ') call s:perl_SetLocalVariable('Perl_LineEndCommColDefault ') call s:perl_SetLocalVariable('Perl_LoadMenus ') call s:perl_SetLocalVariable('Perl_NYTProf_browser ') call s:perl_SetLocalVariable('Perl_NYTProf_html ') call s:perl_SetLocalVariable('Perl_PerlcriticOptions ') call s:perl_SetLocalVariable('Perl_PerlcriticSeverity ') call s:perl_SetLocalVariable('Perl_PerlcriticVerbosity ') call s:perl_SetLocalVariable('Perl_PerlModuleList ') call s:perl_SetLocalVariable('Perl_PerlModuleListGenerator') call s:perl_SetLocalVariable('Perl_PerltidyBackup ') call s:perl_SetLocalVariable('Perl_PodcheckerWarnings ') call s:perl_SetLocalVariable('Perl_Printheader ') call s:perl_SetLocalVariable('Perl_ProfilerTimestamp ') call s:perl_SetLocalVariable('Perl_TemplateOverriddenMsg ') call s:perl_SetLocalVariable('Perl_TimestampFormat ') call s:perl_SetLocalVariable('Perl_XtermDefaults ') if exists('g:Perl_GlobalTemplateFile') && !empty(g:Perl_GlobalTemplateFile) let s:Perl_GlobalTemplateDir = fnamemodify( s:Perl_GlobalTemplateFile, ":h" ) endif " " " set default geometry if not specified " if match( s:Perl_XtermDefaults, "-geometry\\s\\+\\d\\+x\\d\\+" ) < 0 let s:Perl_XtermDefaults = s:Perl_XtermDefaults." -geometry 80x24" endif " " Flags for perldoc " if has("gui_running") let s:Perl_perldoc_flags = "" else " Display docs using plain text converter. let s:Perl_perldoc_flags = "-otext" endif " " escape the printheader " let s:Perl_Printheader = escape( s:Perl_Printheader, ' %' ) let s:Perl_PerlExecutableVersion = '' " "------------------------------------------------------------------------------ " Control variables (not user configurable) "------------------------------------------------------------------------------ " let s:Perl_MenuVisible = 'no' let s:Perl_TemplateJumpTarget = '' let s:MsgInsNotAvail = "insertion not available for a fold" let g:Perl_PerlRegexAnalyser = 'no' let g:Perl_InterfaceInitialized = 'no' let s:Perl_saved_global_option = {} " "=== FUNCTION ================================================================ " NAME: Perl_Input {{{1 " DESCRIPTION: Input after a highlighted prompt " PARAMETERS: prompt - prompt " text - default reply " ... - completion (optional) " RETURNS: "=============================================================================== function! Perl_Input ( prompt, text, ... ) echohl Search " highlight prompt call inputsave() " preserve typeahead if a:0 == 0 || empty(a:1) let retval =input( a:prompt, a:text ) else let retval =input( a:prompt, a:text, a:1 ) endif call inputrestore() " restore typeahead echohl None " reset highlighting let retval = substitute( retval, '^\s\+', "", "" ) " remove leading whitespaces let retval = substitute( retval, '\s\+$', "", "" ) " remove trailing whitespaces return retval endfunction " ---------- end of function Perl_Input ---------- " "------------------------------------------------------------------------------ " Perl_SaveGlobalOption {{{1 " param 1 : option name " param 2 : characters to be escaped (optional) "------------------------------------------------------------------------------ function! s:Perl_SaveGlobalOption ( option, ... ) exe 'let escaped =&'.a:option if a:0 == 0 let escaped = escape( escaped, ' |"\' ) else let escaped = escape( escaped, ' |"\'.a:1 ) endif let s:Perl_saved_global_option[a:option] = escaped endfunction " ---------- end of function Perl_SaveGlobalOption ---------- " "------------------------------------------------------------------------------ " Perl_RestoreGlobalOption {{{1 "------------------------------------------------------------------------------ function! s:Perl_RestoreGlobalOption ( option ) exe ':set '.a:option.'='.s:Perl_saved_global_option[a:option] endfunction " ---------- end of function Perl_RestoreGlobalOption ---------- " "=== FUNCTION ================================================================ " NAME: Perl_GetLineEndCommCol {{{1 " DESCRIPTION: get end-of-line comment position "=============================================================================== function! Perl_GetLineEndCommCol () let actcol = virtcol(".") if actcol+1 == virtcol("$") let b:Perl_LineEndCommentColumn = '' while match( b:Perl_LineEndCommentColumn, '^\s*\d\+\s*$' ) < 0 let b:Perl_LineEndCommentColumn = Perl_Input( 'start line-end comment at virtual column : ', actcol, '' ) endwhile else let b:Perl_LineEndCommentColumn = virtcol(".") endif echomsg "line end comments will start at column ".b:Perl_LineEndCommentColumn endfunction " ---------- end of function Perl_GetLineEndCommCol ---------- " "=== FUNCTION ================================================================ " NAME: Perl_EndOfLineComment {{{1 " DESCRIPTION: apply single end-of-line comment "=============================================================================== function! Perl_EndOfLineComment ( ) range if !exists("b:Perl_LineEndCommentColumn") let b:Perl_LineEndCommentColumn = s:Perl_LineEndCommColDefault endif " ----- trim whitespaces ----- exe a:firstline.','.a:lastline.'s/\s*$//' for line in range( a:lastline, a:firstline, -1 ) let linelength = virtcol( [line, "$"] ) - 1 let diff = 1 if linelength < b:Perl_LineEndCommentColumn let diff = b:Perl_LineEndCommentColumn -1 -linelength endif exe "normal ".diff."A " exe 'normal! A'.s:PerlStartComment.' ' if line > a:firstline normal k endif endfor endfunction " ---------- end of function Perl_EndOfLineComment ---------- " "------------------------------------------------------------------------------ " Perl_AlignLineEndComm: adjust line-end comments "------------------------------------------------------------------------------ " " patterns to ignore when adjusting line-end comments (incomplete): " some heuristics used (only Perl can parse Perl) let s:AlignRegex = [ \ '\$#' , \ '"[^"]\+"' , \ "'[^']\\+'" , \ "`[^`]\+`" , \ '\(m\|qr\)#[^#]\+#' , \ '\(m\|qr\)\?\([\?\/]\)\(.*\)\(\2\)\([imsxg]*\)' , \ '\(m\|qr\)\([[:punct:]]\)\(.*\)\(\2\)\([imsxg]*\)' , \ '\(m\|qr\){\(.*\)}\([imsxg]*\)' , \ '\(m\|qr\)(\(.*\))\([imsxg]*\)' , \ '\(m\|qr\)\[\(.*\)\]\([imsxg]*\)' , \ '\(s\|tr\)#[^#]\+#[^#]\+#' , \ '\(s\|tr\){[^}]\+}{[^}]\+}' , \ ] "=== FUNCTION ================================================================ " NAME: Perl_AlignLineEndComm {{{1 " DESCRIPTION: align end-of-line comments "=============================================================================== function! Perl_AlignLineEndComm ( ) range " if !exists("b:Perl_LineEndCommentColumn") let b:Perl_LineEndCommentColumn = s:Perl_LineEndCommColDefault endif let save_cursor = getpos(".") let save_expandtab = &expandtab exe ":set expandtab" let linenumber = a:firstline exe ":".a:firstline while linenumber <= a:lastline let line= getline(".") " " line is not a pure comment but may contains a comment: " if match( line, '^\s*#' ) < 0 && match( line, '#.*$' ) > 0 " " disregard comments starting in a string " let idx1 = -1 let idx2 = -1 let commentstart= -2 let commentend = 0 while commentstart < idx2 && idx2 < commentend let start = commentend let idx2 = match( line, '#.*$', start ) " loop over the items to ignore for regex in s:AlignRegex if match( line, regex ) > -1 let commentstart = match ( line, regex, start ) let commentend = matchend( line, regex, start ) break endif endfor endwhile " " try to adjust the comment " let idx1 = 1 + match( line, '\s*#.*$', start ) let idx2 = 1 + idx2 call setpos(".", [ 0, linenumber, idx1, 0 ] ) let vpos1 = virtcol(".") call setpos(".", [ 0, linenumber, idx2, 0 ] ) let vpos2 = virtcol(".") if ! ( vpos2 == b:Perl_LineEndCommentColumn \ || vpos1 > b:Perl_LineEndCommentColumn \ || idx2 == 0 ) exe ":.,.retab" " insert some spaces if vpos2 < b:Perl_LineEndCommentColumn let diff = b:Perl_LineEndCommentColumn-vpos2 call setpos(".", [ 0, linenumber, vpos2, 0 ] ) let @" = ' ' exe "normal ".diff."P" endif " remove some spaces if vpos1 < b:Perl_LineEndCommentColumn && vpos2 > b:Perl_LineEndCommentColumn let diff = vpos2 - b:Perl_LineEndCommentColumn call setpos(".", [ 0, linenumber, b:Perl_LineEndCommentColumn, 0 ] ) exe "normal ".diff."x" endif endif endif let linenumber=linenumber+1 normal j endwhile " restore tab expansion settings and cursor position let &expandtab = save_expandtab call setpos('.', save_cursor) endfunction " ---------- end of function Perl_AlignLineEndComm ---------- " "=== FUNCTION ================================================================ " NAME: Perl_MultiLineEndComments {{{1 " DESCRIPTION: apply multiple end-of-line comments "=============================================================================== function! Perl_MultiLineEndComments ( ) " if !exists("b:Perl_LineEndCommentColumn") let b:Perl_LineEndCommentColumn = s:Perl_LineEndCommColDefault endif " let pos0 = line("'<") let pos1 = line("'>") " " ----- trim whitespaces ----- exe pos0.','.pos1.'s/\s*$//' " " ----- find the longest line ----- let maxlength = max( map( range(pos0, pos1), "virtcol([v:val, '$'])" ) ) let maxlength = max( [b:Perl_LineEndCommentColumn, maxlength+1] ) " " ----- fill lines with blanks ----- for linenumber in range( pos0, pos1 ) exe ":".linenumber if getline(linenumber) !~ '^\s*$' let diff = maxlength - virtcol("$") exe "normal ".diff."A " exe 'normal! A'.s:PerlStartComment.' ' endif endfor " " ----- back to the begin of the marked block ----- stopinsert normal '<$ if match( getline("."), '\/\/\s*$' ) < 0 if search( '\/\*', 'bcW', line(".") ) > 1 normal l endif let save_cursor = getpos(".") if getline(".")[save_cursor[2]+1] == ' ' normal l endif else normal $ endif endfunction " ---------- end of function Perl_MultiLineEndComments ---------- " let s:Perl_CmtCounter = 0 let s:Perl_CmtLabel = "BlockCommentNo_" " "=== FUNCTION ================================================================ " NAME: Perl_CommentBlock {{{1 " DESCRIPTION: set block of code within POD == begin / == end " PARAMETERS: mode - curent edit mode "=============================================================================== function! Perl_CommentBlock (mode) " let s:Perl_CmtCounter = 0 let save_line = line(".") let actual_line = 0 " " search for the maximum option number (if any) " normal gg while actual_line < search( s:Perl_CmtLabel."\\d\\+" ) let actual_line = line(".") let actual_opt = matchstr( getline(actual_line), s:Perl_CmtLabel."\\d\\+" ) let actual_opt = strpart( actual_opt, strlen(s:Perl_CmtLabel),strlen(actual_opt)-strlen(s:Perl_CmtLabel)) if s:Perl_CmtCounter < actual_opt let s:Perl_CmtCounter = actual_opt endif endwhile let s:Perl_CmtCounter = s:Perl_CmtCounter+1 silent exe ":".save_line " if a:mode=='a' let zz= "\n=begin BlockComment # ".s:Perl_CmtLabel.s:Perl_CmtCounter let zz= zz."\n\n=end BlockComment # ".s:Perl_CmtLabel.s:Perl_CmtCounter let zz= zz."\n\n=cut\n\n" put =zz endif if a:mode=='v' let zz= "\n=begin BlockComment # ".s:Perl_CmtLabel.s:Perl_CmtCounter."\n\n" :'<put! =zz let zz= "\n=end BlockComment # ".s:Perl_CmtLabel.s:Perl_CmtCounter let zz= zz."\n\n=cut\n\n" :'>put =zz endif endfunction " ---------- end of function Perl_CommentBlock ---------- " "=== FUNCTION ================================================================ " NAME: Perl_UncommentBlock {{{1 " DESCRIPTION: uncomment block of code (remove POD commands) "=============================================================================== function! Perl_UncommentBlock () let frstline = searchpair( '^=begin\s\+BlockComment\s*#\s*'.s:Perl_CmtLabel.'\d\+', \ '', \ '^=end\s\+BlockComment\s\+#\s*'.s:Perl_CmtLabel.'\d\+', \ 'bn' ) if frstline<=0 echohl WarningMsg | echo 'no comment block/tag found or cursor not inside a comment block'| echohl None return endif let lastline = searchpair( '^=begin\s\+BlockComment\s*#\s*'.s:Perl_CmtLabel.'\d\+', \ '', \ '^=end\s\+BlockComment\s\+#\s*'.s:Perl_CmtLabel.'\d\+', \ 'n' ) if lastline<=0 echohl WarningMsg | echo 'no comment block/tag found or cursor not inside a comment block'| echohl None return endif let actualnumber1 = matchstr( getline(frstline), s:Perl_CmtLabel."\\d\\+" ) let actualnumber2 = matchstr( getline(lastline), s:Perl_CmtLabel."\\d\\+" ) if actualnumber1 != actualnumber2 echohl WarningMsg | echo 'lines '.frstline.', '.lastline.': comment tags do not match'| echohl None return endif let line1 = lastline let line2 = lastline " empty line before =end if match( getline(lastline-1), '^\s*$' ) != -1 let line1 = line1-1 endif if lastline+1<line("$") && match( getline(lastline+1), '^\s*$' ) != -1 let line2 = line2+1 endif if lastline+2<line("$") && match( getline(lastline+2), '^=cut' ) != -1 let line2 = line2+1 endif if lastline+3<line("$") && match( getline(lastline+3), '^\s*$' ) != -1 let line2 = line2+1 endif silent exe ':'.line1.','.line2.'d' let line1 = frstline let line2 = frstline if frstline>1 && match( getline(frstline-1), '^\s*$' ) != -1 let line1 = line1-1 endif if match( getline(frstline+1), '^\s*$' ) != -1 let line2 = line2+1 endif silent exe ':'.line1.','.line2.'d' endfunction " ---------- end of function Perl_UncommentBlock ---------- " "=== FUNCTION ================================================================ " NAME: Perl_CommentToggle {{{1 " DESCRIPTION: toggle comment "=============================================================================== function! Perl_CommentToggle () range let comment=1 " for line in range( a:firstline, a:lastline ) if match( getline(line), '^#') == -1 " no comment let comment = 0 break endif endfor if comment == 0 exe a:firstline.','.a:lastline."s/^/#/" else exe a:firstline.','.a:lastline."s/^#//" endif endfunction " ---------- end of function Perl_CommentToggle ---------- " "=== FUNCTION ================================================================ " NAME: Perl_CodeSnippet {{{1 " DESCRIPTION: read / write / edit code sni " PARAMETERS: mode - edit, read, write, writemarked, view "=============================================================================== function! Perl_CodeSnippet(mode) if isdirectory(g:Perl_CodeSnippets) " " read snippet file, put content below current line " if a:mode == "read" if has("gui_running") && s:Perl_GuiSnippetBrowser == 'gui' let l:snippetfile=browse(0,"read a code snippet",g:Perl_CodeSnippets,"") else let l:snippetfile=input("read snippet ", g:Perl_CodeSnippets, "file" ) endif if filereadable(l:snippetfile) let linesread= line("$") let l:old_cpoptions = &cpoptions " Prevent the alternate buffer from being set to this files setlocal cpoptions-=a :execute "read ".l:snippetfile let &cpoptions = l:old_cpoptions " restore previous options " let linesread= line("$")-linesread-1 if linesread>=0 && match( l:snippetfile, '\.\(ni\|noindent\)$' ) < 0 silent exe "normal =".linesread."+" endif endif endif " " update current buffer / split window / edit snippet file " if a:mode == "edit" if has("gui_running") && s:Perl_GuiSnippetBrowser == 'gui' let l:snippetfile=browse(0,"edit a code snippet",g:Perl_CodeSnippets,"") else let l:snippetfile=input("edit snippet ", g:Perl_CodeSnippets, "file" ) endif if !empty(l:snippetfile) :execute "update! | split | edit ".l:snippetfile endif endif " " update current buffer / split window / view snippet file " if a:mode == "view" if has("gui_running") && s:Perl_GuiSnippetBrowser == 'gui' let l:snippetfile=browse(0,"view a code snippet",g:Perl_CodeSnippets,"") else let l:snippetfile=input("view snippet ", g:Perl_CodeSnippets, "file" ) endif if !empty(l:snippetfile) :execute "update! | split | view ".l:snippetfile endif endif " " write whole buffer or marked area into snippet file " if a:mode == "write" || a:mode == "writemarked" if has("gui_running") && s:Perl_GuiSnippetBrowser == 'gui' let l:snippetfile=browse(0,"write a code snippet",g:Perl_CodeSnippets,"") else let l:snippetfile=input("write snippet ", g:Perl_CodeSnippets, "file" ) endif if !empty(l:snippetfile) if filereadable(l:snippetfile) if confirm("File ".l:snippetfile." exists ! Overwrite ? ", "&Cancel\n&No\n&Yes") != 3 return endif endif if a:mode == "write" :execute ":write! ".l:snippetfile else :execute ":*write! ".l:snippetfile endif endif endif else redraw! echohl ErrorMsg echo "code snippet directory ".g:Perl_CodeSnippets." does not exist" echohl None endif endfunction " ---------- end of function Perl_CodeSnippet ---------- " "------------------------------------------------------------------------------ " Perl-Run : Perl_perldoc - lookup word under the cursor or ask "------------------------------------------------------------------------------ " let s:Perl_PerldocBufferName = "PERLDOC" let s:Perl_PerldocHelpBufferNumber = -1 let s:Perl_PerldocModulelistBuffer = -1 let s:Perl_PerldocSearchWord = "" let s:Perl_PerldocTry = "module" " "=== FUNCTION ================================================================ " NAME: Perl_perldoc {{{1 " DESCRIPTION: Perl_perldoc - lookup word under the cursor or ask "=============================================================================== function! Perl_perldoc() if( expand("%:p") == s:Perl_PerlModuleList ) normal 0 let item=expand("<cWORD>") " WORD under the cursor else let cuc = getline(".")[col(".") - 1] " character under the cursor let item = expand("<cword>") " word under the cursor if empty(item) || match( item, cuc ) == -1 let item=Perl_Input("perldoc - module, function or FAQ keyword : ", "", '') endif endif "------------------------------------------------------------------------------ " replace buffer content with Perl documentation "------------------------------------------------------------------------------ if item != "" " " jump to an already open PERLDOC window or create one " if bufloaded(s:Perl_PerldocBufferName) != 0 && bufwinnr(s:Perl_PerldocHelpBufferNumber) != -1 exe bufwinnr(s:Perl_PerldocHelpBufferNumber) . "wincmd w" " buffer number may have changed, e.g. after a 'save as' if bufnr("%") != s:Perl_PerldocHelpBufferNumber let s:Perl_PerldocHelpBufferNumber=bufnr(s:Perl_OutputBufferName) exe ":bn ".s:Perl_PerldocHelpBufferNumber endif else exe ":new ".s:Perl_PerldocBufferName let s:Perl_PerldocHelpBufferNumber=bufnr("%") setlocal buftype=nofile setlocal noswapfile setlocal bufhidden=delete setlocal syntax=OFF endif " " search order: library module --> builtin function --> FAQ keyword " let delete_perldoc_errors = "" if s:UNIX && ( match( $shell, '\ccsh$' ) >= 0 ) " not for csh, tcsh let delete_perldoc_errors = " 2>/dev/null" endif setlocal modifiable " " controll repeated search " if item == s:Perl_PerldocSearchWord " last item : search ring : if s:Perl_PerldocTry == 'module' let next = 'function' endif if s:Perl_PerldocTry == 'function' let next = 'faq' endif if s:Perl_PerldocTry == 'faq' let next = 'module' endif let s:Perl_PerldocTry = next else " new item : let s:Perl_PerldocSearchWord = item let s:Perl_PerldocTry = 'module' endif " " module documentation if s:Perl_PerldocTry == 'module' let command=":%!perldoc ".s:Perl_perldoc_flags." ".item.delete_perldoc_errors silent exe command if v:shell_error != 0 redraw! let s:Perl_PerldocTry = 'function' endif if s:MSWIN call s:perl_RemoveSpecialCharacters() endif endif " " function documentation if s:Perl_PerldocTry == 'function' " -otext has to be ahead of -f and -q silent exe ":%!perldoc ".s:Perl_perldoc_flags." -f ".item.delete_perldoc_errors if v:shell_error != 0 redraw! let s:Perl_PerldocTry = 'faq' endif endif " " FAQ documentation if s:Perl_PerldocTry == 'faq' silent exe ":%!perldoc ".s:Perl_perldoc_flags." -q ".item.delete_perldoc_errors if v:shell_error != 0 redraw! let s:Perl_PerldocTry = 'error' endif endif " " no documentation found if s:Perl_PerldocTry == 'error' redraw! let zz= "No documentation found for perl module, perl function or perl FAQ keyword\n" let zz=zz." '".item."' " silent put! =zz normal 2jdd$ let s:Perl_PerldocTry = 'module' let s:Perl_PerldocSearchWord = "" endif if s:UNIX " remove windows line ends silent! exe ":%s/\r$// | normal gg" endif setlocal nomodifiable redraw! " highlight the headlines :match Search '^\S.*$' " ------------ " " ---------- Add ':' to the keyword characters ------------------------------- " Tokens like 'File::Find' are recognized as one keyword setlocal iskeyword+=: map <buffer> <silent> <S-F1> :call Perl_perldoc()<CR> imap <buffer> <silent> <S-F1> <C-C>:call Perl_perldoc()<CR> endif endfunction " ---------- end of function Perl_perldoc ---------- " "=== FUNCTION ================================================================ " NAME: Perl_RemoveSpecialCharacters {{{1 " DESCRIPTION: remove <backspace><any character> in CYGWIN man(1) output " remove _<any character> in CYGWIN man(1) output "=============================================================================== function! s:perl_RemoveSpecialCharacters ( ) let patternunderline = '_\%x08' let patternbold = '\%x08.' setlocal modifiable if search(patternunderline) != 0 silent exe ':%s/'.patternunderline.'//g' endif if search(patternbold) != 0 silent exe ':%s/'.patternbold.'//g' endif setlocal nomodifiable silent normal gg endfunction " ---------- end of function s:perl_RemoveSpecialCharacters ---------- " "=== FUNCTION ================================================================ " NAME: Perl_perldoc_show_module_list {{{1 " DESCRIPTION: show module list "=============================================================================== function! Perl_perldoc_show_module_list() if !filereadable(s:Perl_PerlModuleList) redraw! echohl WarningMsg | echo 'Have to create '.s:Perl_PerlModuleList.' for the first time:'| echohl None call Perl_perldoc_generate_module_list() endif " " jump to the already open buffer or create one " if bufexists(s:Perl_PerldocModulelistBuffer) && bufwinnr(s:Perl_PerldocModulelistBuffer)!=-1 silent exe bufwinnr(s:Perl_PerldocModulelistBuffer) . "wincmd w" else :split exe ":view ".s:Perl_PerlModuleList let s:Perl_PerldocModulelistBuffer=bufnr("%") setlocal nomodifiable setlocal filetype=perl setlocal syntax=none map <buffer> <silent> <S-F1> :call Perl_perldoc()<CR> imap <buffer> <silent> <S-F1> <C-C>:call Perl_perldoc()<CR> endif normal gg redraw! if has("gui_running") echohl Search | echomsg 'use S-F1 to show a manual' | echohl None else echohl Search | echomsg 'use \hh in normal mode to show a manual' | echohl None endif endfunction " ---------- end of function Perl_perldoc_show_module_list ---------- " "=== FUNCTION ================================================================ " NAME: Perl_perldoc_generate_module_list {{{1 " DESCRIPTION: generate module list "=============================================================================== function! Perl_perldoc_generate_module_list() " save the module list, if any if filereadable( s:Perl_PerlModuleList ) let backupfile = s:Perl_PerlModuleList.'.backup' if rename( s:Perl_PerlModuleList, backupfile ) != 0 echomsg 'Could not rename "'.s:Perl_PerlModuleList.'" to "'.backupfile.'"' endif endif " echohl Search echo " ... generating Perl module list ... " if s:MSWIN silent exe ":!perl \"".s:Perl_PerlModuleListGenerator."\" > \"".s:Perl_PerlModuleList."\"" silent exe ":!sort \"".s:Perl_PerlModuleList."\" /O \"".s:Perl_PerlModuleList."\"" else " direct STDOUT and STDERR to the module list file : silent exe ":!perl ".s:Perl_PerlModuleListGenerator." -s &> ".s:Perl_PerlModuleList endif redraw! echo " DONE " echohl None endfunction " ---------- end of function Perl_perldoc_generate_module_list ---------- " "=== FUNCTION ================================================================ " NAME: Perl_Settings {{{1 " DESCRIPTION: display various plugin settings " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_Settings () let txt = " Perl-Support settings\n\n" let txt = txt.' code snippet directory : "'.g:Perl_CodeSnippets."\"\n" let txt = txt.' author : "'.mmtemplates#core#ExpandText( g:Perl_Templates, '|AUTHOR|' )."\"\n" let txt = txt.' authorref : "'.mmtemplates#core#ExpandText( g:Perl_Templates, '|AUTHORREF|' )."\"\n" let txt = txt.' copyright holder : "'.mmtemplates#core#ExpandText( g:Perl_Templates, '|COPYRIGHT|' )."\"\n" let txt = txt.' email : "'.mmtemplates#core#ExpandText( g:Perl_Templates, '|EMAIL|' )."\"\n" let txt = txt.' organization : "'.mmtemplates#core#ExpandText( g:Perl_Templates, '|ORGANIZATION|' )."\"\n" let txt = txt.' template style : "'.mmtemplates#core#Resource ( g:Perl_Templates, "style" )[0]."\"\n" let txt = txt.' plugin installation : "'.g:Perl_Installation."\"\n" " ----- template files ------------------------ if g:Perl_Installation == 'system' let txt = txt.'global template directory : "'.s:Perl_GlobalTemplateDir."\"\n" if filereadable( s:Perl_LocalTemplateFile ) let txt = txt.' local template directory : '.s:Perl_LocalTemplateDir."\n" endif else let txt = txt.' local template directory : '.s:Perl_LocalTemplateDir."\n" endif " ----- xterm ------------------------ if !s:MSWIN let txt = txt.' xterm defaults : '.s:Perl_XtermDefaults."\n" endif " ----- dictionaries ------------------------ if !empty(g:Perl_Dictionary_File) let ausgabe= &dictionary let ausgabe = substitute( ausgabe, ",", ",\n + ", "g" ) let txt = txt." dictionary file(s) : ".ausgabe."\n" endif let txt = txt." current output dest. : ".g:Perl_OutputGvim."\n" let txt = txt." perlcritic : perlcritic -severity ".s:Perl_PerlcriticSeverity \ .' ['.s:PCseverityName[s:Perl_PerlcriticSeverity].']' \ ." -verbosity ".s:Perl_PerlcriticVerbosity \ ." ".s:Perl_PerlcriticOptions."\n" if !empty(s:Perl_PerlExecutableVersion) let txt = txt." Perl interface version : ".s:Perl_PerlExecutableVersion."\n" endif let txt = txt."\n" let txt = txt." Additional hot keys\n\n" let txt = txt." Shift-F1 : read perldoc (for word under cursor)\n" let txt = txt." F9 : start a debugger (".s:Perl_Debugger.")\n" let txt = txt." Alt-F9 : run syntax check \n" let txt = txt." Ctrl-F9 : run script \n" let txt = txt." Shift-F9 : set command line arguments\n" let txt = txt."_________________________________________________________________________\n" let txt = txt." Perl-Support, Version ".g:Perl_PluginVersion." / Dr.-Ing. Fritz Mehner / mehner@fh-swf.de\n\n" echo txt endfunction " ---------- end of function Perl_Settings ---------- " "=== FUNCTION ================================================================ " NAME: Perl_SyntaxCheck {{{1 " DESCRIPTION: syntax check " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_SyntaxCheck () exe ":cclose" let l:currentbuffer = bufname("%") let l:fullname = expand("%:p") silent exe ":update" " " avoid filtering the Perl output if the file name does not contain blanks: " call s:Perl_SaveGlobalOption('errorformat') call s:Perl_SaveGlobalOption('makeprg') " if s:MSWIN && ( l:fullname =~ ' ' || s:Perl_EfmPerl =~ ' ' ) " " Use tools/efm_perl.pl from the VIM distribution. " This wrapper can handle filenames containing blanks. " Errorformat from tools/efm_perl.pl . " direct call " let tmpfile = tempname() exe ':set errorformat=%f:%l:%m' silent exe ":!\"".s:Perl_EfmPerl."\" -c % > ".tmpfile exe ":cfile ".tmpfile else " " no whitespaces " Errorformat from compiler/perl.vim (VIM distribution). " exe ':set makeprg=perl\ -c' exe ':set errorformat= \%-G%.%#had\ compilation\ errors., \%-G%.%#syntax\ OK, \%m\ at\ %f\ line\ %l., \%+A%.%#\ at\ %f\ line\ %l\\,%.%#, \%+C%.%#' let l:fullname = fnameescape( l:fullname ) silent exe ':make '.l:fullname endif exe ":botright cwindow" call s:Perl_RestoreGlobalOption('makeprg') call s:Perl_RestoreGlobalOption('errorformat') " " message in case of success " redraw! if l:currentbuffer == bufname("%") echohl Search echomsg l:currentbuffer." : Syntax is OK" echohl None return 0 else setlocal wrap setlocal linebreak endif endfunction " ---------- end of function Perl_SyntaxCheck ---------- " "=== FUNCTION ================================================================ " NAME: Perl_Toggle_Gvim_Xterm {{{1 " DESCRIPTION: toggle output destination (vim/buffer/xterm) " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_Toggle_Gvim_Xterm () if g:Perl_OutputGvim == "vim" exe "aunmenu <silent> ".s:Perl_RootMenu.'.&Run.&output:\ VIM->buffer->xterm' exe "amenu <silent> ".s:Perl_RootMenu.'.&Run.&output:\ BUFFER->xterm->vim<Tab>\\ro :call Perl_Toggle_Gvim_Xterm()<CR>' let g:Perl_OutputGvim = "buffer" else if g:Perl_OutputGvim == "buffer" exe "aunmenu <silent> ".s:Perl_RootMenu.'.&Run.&output:\ BUFFER->xterm->vim' if (!s:MSWIN) exe "amenu <silent> ".s:Perl_RootMenu.'.&Run.&output:\ XTERM->vim->buffer<Tab>\\ro :call Perl_Toggle_Gvim_Xterm()<CR>' else exe "amenu <silent> ".s:Perl_RootMenu.'.&Run.&output:\ VIM->buffer->xterm <Tab>\\ro :call Perl_Toggle_Gvim_Xterm()<CR>' endif if (!s:MSWIN) && (!empty($DISPLAY)) let g:Perl_OutputGvim = "xterm" else let g:Perl_OutputGvim = "vim" endif else " ---------- output : xterm -> gvim exe "aunmenu <silent> ".s:Perl_RootMenu.'.&Run.&output:\ XTERM->vim->buffer' exe "amenu <silent> ".s:Perl_RootMenu.'.&Run.&output:\ VIM->buffer->xterm<Tab>\\ro :call Perl_Toggle_Gvim_Xterm()<CR>' let g:Perl_OutputGvim = "vim" endif endif echomsg "output destination is '".g:Perl_OutputGvim."'" endfunction " ---------- end of function Perl_Toggle_Gvim_Xterm ---------- " "=== FUNCTION ================================================================ " NAME: Perl_PerlSwitches {{{1 " DESCRIPTION: read switches to hand down to the Perl interpreter " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_PerlSwitches () let filename = fnameescape( expand("%:p") ) if empty(filename) redraw! echohl WarningMsg | echo " no file name " | echohl None return endif let prompt = 'perl command line switches for "'.filename.'" : ' if exists("b:Perl_Switches") let b:Perl_Switches= Perl_Input( prompt, b:Perl_Switches, '' ) else let b:Perl_Switches= Perl_Input( prompt , "", '' ) endif endfunction " ---------- end of function Perl_PerlSwitches ---------- " let s:Perl_OutputBufferName = "Perl-Output" let s:Perl_OutputBufferNumber = -1 " "=== FUNCTION ================================================================ " NAME: Perl_Run {{{1 " DESCRIPTION: run the current buffer " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_Run () " if &filetype != "perl" echohl WarningMsg | echo expand("%:p").' seems not to be a Perl file' | echohl None return endif let buffername = expand("%") if fnamemodify( s:Perl_PerlModuleList, ":p:t" ) == buffername || s:Perl_PerldocBufferName == buffername return endif " let l:currentbuffernr = bufnr("%") let l:arguments = exists("b:Perl_CmdLineArgs") ? " ".b:Perl_CmdLineArgs : "" let l:switches = exists("b:Perl_Switches") ? b:Perl_Switches.' ' : "" let l:currentbuffer = bufname("%") let l:fullname = expand("%:p") let l:fullname_esc = fnameescape( expand("%:p") ) " silent exe ":update" silent exe ":cclose" " " "------------------------------------------------------------------------------ " run : run from the vim command line "------------------------------------------------------------------------------ if g:Perl_OutputGvim == "vim" " if s:MSWIN exe "!perl ".l:switches.'"'.l:fullname.'" '.l:arguments else exe "!perl ".l:switches.l:fullname_esc.l:arguments endif " endif " "------------------------------------------------------------------------------ " run : redirect output to an output buffer "------------------------------------------------------------------------------ if g:Perl_OutputGvim == "buffer" let l:currentbuffernr = bufnr("%") if l:currentbuffer == bufname("%") " " if bufloaded(s:Perl_OutputBufferName) != 0 && bufwinnr(s:Perl_OutputBufferNumber) != -1 exe bufwinnr(s:Perl_OutputBufferNumber) . "wincmd w" " buffer number may have changed, e.g. after a 'save as' if bufnr("%") != s:Perl_OutputBufferNumber let s:Perl_OutputBufferNumber=bufnr(s:Perl_OutputBufferName) exe ":bn ".s:Perl_OutputBufferNumber endif else silent exe ":new ".s:Perl_OutputBufferName let s:Perl_OutputBufferNumber=bufnr("%") setlocal buftype=nofile setlocal noswapfile setlocal syntax=none setlocal bufhidden=delete setlocal tabstop=8 endif " " run script " setlocal modifiable silent exe ":update" if s:MSWIN exe ":%!perl ".l:switches.'"'.l:fullname.'" '.l:arguments else exe ":%!perl ".l:switches.l:fullname_esc.l:arguments endif setlocal nomodifiable " if winheight(winnr()) >= line("$") exe bufwinnr(l:currentbuffernr) . "wincmd w" endif " endif endif " "------------------------------------------------------------------------------ " run : run in a detached xterm (not available for MS Windows) "------------------------------------------------------------------------------ if g:Perl_OutputGvim == "xterm" " if s:MSWIN " same as "vim" exe "!perl ".l:switches.'"'.l:fullname.'" '.l:arguments else silent exe '!xterm -title '.l:fullname_esc.' '.s:Perl_XtermDefaults.' -e '.s:Perl_Wrapper.' perl '.l:switches.l:fullname_esc.l:arguments :redraw! endif " endif " endfunction " ---------- end of function Perl_Run ---------- " let s:Perl_MakeCmdLineArgs = "" " command line arguments for Run-make; initially empty let s:Perl_Makefile = '' "=== FUNCTION ================================================================ " NAME: Perl_MakeArguments {{{1 " DESCRIPTION: read command line arguments for make(1) " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_MakeArguments () let s:Perl_MakeCmdLineArgs= Perl_Input("make command line arguments : ",s:Perl_MakeCmdLineArgs, 'file' ) endfunction " ---------- end of function Perl_MakeArguments ---------- " "=== FUNCTION ================================================================ " NAME: Perl_MakeClean {{{1 " DESCRIPTION: run 'make clean' " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_MakeClean() " run make clean if s:Perl_Makefile == '' exe ":!make clean" else exe ':lchdir '.fnamemodify( s:Perl_Makefile, ":p:h" ) if s:MSWIN exe ':!make -f "'.s:Perl_Makefile.'" clean' else exe ':!make -f '.s:Perl_Makefile.' clean' endif exe ":lchdir -" endif endfunction " ---------- end of function Perl_MakeClean ---------- " "=== FUNCTION ================================================================ " NAME: Perl_ChooseMakefile {{{1 " DESCRIPTION: choose a makefile " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_ChooseMakefile () let s:Perl_Makefile = '' let mkfile = findfile( "Makefile", ".;" ) " try to find a Makefile if mkfile == '' let mkfile = findfile( "makefile", ".;" ) " try to find a makefile endif if mkfile == '' let mkfile = getcwd() endif let s:Perl_Makefile = Perl_Input ( "choose a Makefile: ", mkfile, "file" ) if s:MSWIN let s:Perl_Makefile = substitute( s:Perl_Makefile, '\\ ', ' ', 'g' ) endif endfunction " ---------- end of function Perl_ChooseMakefile ---------- " "=== FUNCTION ================================================================ " NAME: Perl_Make {{{1 " DESCRIPTION: run make(1) " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_Make() exe ":cclose" " update : write source file if necessary exe ":update" " run make if s:Perl_Makefile == '' if filereadable('Makefile.PL') :!perl Makefile.PL endif exe ":!make ".s:Perl_MakeCmdLineArgs else exe ':lchdir '.fnamemodify( s:Perl_Makefile, ":p:h" ) if !filereadable(s:Perl_Makefile) && filereadable('Makefile.PL') :!perl Makefile.PL endif if s:MSWIN exe ':!make -f "'.s:Perl_Makefile.'" '.s:Perl_MakeCmdLineArgs else exe ':!make -f '.s:Perl_Makefile.' '.s:Perl_MakeCmdLineArgs endif exe ":lchdir -" endif exe ":botright cwindow" " endfunction " ---------- end of function Perl_Make ---------- " " "=== FUNCTION ================================================================ " NAME: Perl_Debugger {{{1 " DESCRIPTION: start debugger " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_Debugger () " silent exe ":update" let l:arguments = exists("b:Perl_CmdLineArgs") ? " ".b:Perl_CmdLineArgs : "" let l:switches = exists("b:Perl_Switches") ? b:Perl_Switches.' ' : "" let filename = expand("%:p") let filename_esc = fnameescape( expand("%:p") ) " if s:MSWIN let l:arguments = substitute( l:arguments, '^\s\+', ' ', '' ) let l:arguments = substitute( l:arguments, '\s\+', "\" \"", 'g') let l:switches = substitute( l:switches, '^\s\+', ' ', '' ) let l:switches = substitute( l:switches, '\s\+', "\" \"", 'g') endif " " debugger is ' perl -d ... ' " if s:Perl_Debugger == "perl" if s:MSWIN exe '!perl -d "'.filename.l:arguments.'"' else if has("gui_running") || &term == "xterm" silent exe "!xterm ".s:Perl_XtermDefaults.' -e perl ' . l:switches . ' -d '.filename_esc.l:arguments.' &' else silent exe '!clear; perl ' . l:switches . ' -d '.filename_esc.l:arguments endif endif endif " if v:windowid != 0 " " grapical debugger is 'ptkdb', uses a PerlTk interface " if s:Perl_Debugger == "ptkdb" if s:MSWIN exe '!perl -d:ptkdb "'.filename.l:arguments.'"' else silent exe '!perl -d:ptkdb '.filename_esc.l:arguments.' &' endif endif " " debugger is 'ddd' (not available for MS Windows); graphical front-end for GDB " if s:Perl_Debugger == "ddd" && !s:MSWIN if !executable("ddd") echohl WarningMsg echo 'ddd does not exist or is not executable!' echohl None return else silent exe '!ddd '.filename_esc.l:arguments.' &' endif endif " endif " redraw! endfunction " ---------- end of function Perl_Debugger ---------- " "=== FUNCTION ================================================================ " NAME: Perl_Arguments {{{1 " DESCRIPTION: read command line arguments for the current buffer " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_Arguments () let filename = fnameescape( expand("%") ) if empty(filename) redraw! echohl WarningMsg | echo " no file name " | echohl None return endif let prompt = 'command line arguments for "'.filename.'" : ' if exists("b:Perl_CmdLineArgs") let b:Perl_CmdLineArgs= Perl_Input( prompt, b:Perl_CmdLineArgs, 'file' ) else let b:Perl_CmdLineArgs= Perl_Input( prompt , "", 'file' ) endif endfunction " ---------- end of function Perl_Arguments ---------- " "=== FUNCTION ================================================================ " NAME: Perl_XtermSize {{{1 " DESCRIPTION: read xterm geometry " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_XtermSize () let regex = '-geometry\s\+\d\+x\d\+' let geom = matchstr( s:Perl_XtermDefaults, regex ) let geom = matchstr( geom, '\d\+x\d\+' ) let geom = substitute( geom, 'x', ' ', "" ) let answer= Perl_Input(" xterm size (COLUMNS LINES) : ", geom ) while match(answer, '^\s*\d\+\s\+\d\+\s*$' ) < 0 let answer= Perl_Input(" + xterm size (COLUMNS LINES) : ", geom ) endwhile let answer = substitute( answer, '\s\+', "x", "" ) " replace inner whitespaces let s:Perl_XtermDefaults = substitute( s:Perl_XtermDefaults, regex, "-geometry ".answer , "" ) endfunction " ---------- end of function Perl_XtermSize ---------- " "=== FUNCTION ================================================================ " NAME: Perl_MakeScriptExecutable {{{1 " DESCRIPTION: make script executable " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_MakeScriptExecutable () let filename = fnameescape( expand("%:p") ) if executable(filename) == 0 " not executable silent exe "!chmod u+x ".filename redraw! if v:shell_error echohl WarningMsg echo 'Could not make "'.filename.'" executable !' else echohl Search echo 'Made "'.filename.'" executable.' endif echohl None else echo '"'.filename.'" is already executable.' endif endfunction " ---------- end of function Perl_MakeScriptExecutable ---------- " "=== FUNCTION ================================================================ " NAME: Perl_PodCheck {{{1 " DESCRIPTION: run POD checker " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_PodCheck () exe ":cclose" let l:currentbuffer = bufname("%") silent exe ":update" " if s:Perl_PodcheckerWarnings == "no" let PodcheckerWarnings = '-nowarnings ' else let PodcheckerWarnings = '-warnings ' endif call s:Perl_SaveGlobalOption('makeprg') set makeprg=podchecker call s:Perl_SaveGlobalOption('errorformat') exe ':set errorformat=***\ %m\ at\ line\ %l\ in\ file\ %f' if s:MSWIN silent exe ':make '.PodcheckerWarnings.'"'.expand("%:p").'"' else silent exe ':make '.PodcheckerWarnings.fnameescape( expand("%:p") ) endif exe ":botright cwindow" call s:Perl_RestoreGlobalOption('makeprg') call s:Perl_RestoreGlobalOption('errorformat') " " message in case of success " redraw! if l:currentbuffer == bufname("%") echohl Search echomsg l:currentbuffer." : POD syntax is OK" echohl None return 0 endif return 1 endfunction " ---------- end of function Perl_PodCheck ---------- " "=== FUNCTION ================================================================ " NAME: Perl_POD {{{1 " DESCRIPTION: convert POD into html / man / text " PARAMETERS: format - target format " RETURNS: "=============================================================================== function! Perl_POD ( format ) let source = expand("%:p") let source_esc = fnameescape( expand("%:p"), ) let target = source.'.'.a:format let target_esc = source_esc.'.'.a:format silent exe ":update" if executable( 'pod2'.a:format ) if s:MSWIN if a:format=='html' silent exe ':!pod2'.a:format.' "--infile='.source.'" "--outfile='.target.'"' else silent exe ':!pod2'.a:format.' "'.source.'" "'.target.'"' endif else if a:format=='html' silent exe ':!pod2'.a:format.' --infile='.source_esc.' --outfile='.target_esc else silent exe ':!pod2'.a:format.' '.source_esc.' '.target_esc endif endif redraw! echo "file '".target."' generated" else redraw! echomsg 'Application "pod2'.a:format.'" does not exist or is not executable.' endif endfunction " ---------- end of function Perl_POD ---------- "=== FUNCTION ================================================================ " NAME: Perl_BrowseTemplateFiles {{{1 " DESCRIPTION: browse the template files " PARAMETERS: type - local / global " RETURNS: "=============================================================================== function! Perl_BrowseTemplateFiles ( type ) let templatefile = eval( 's:Perl_'.a:type.'TemplateFile' ) let templatedir = eval( 's:Perl_'.a:type.'TemplateDir' ) if isdirectory( templatedir ) if has("browse") && s:Perl_GuiTemplateBrowser == 'gui' let l:templatefile = browse(0,"edit a template file", templatedir, "" ) else let l:templatefile = '' if s:Perl_GuiTemplateBrowser == 'explorer' exe ':Explore '.templatedir endif if s:Perl_GuiTemplateBrowser == 'commandline' let l:templatefile = input("edit a template file", templatedir, "file" ) endif endif if !empty(l:templatefile) :execute "update! | split | edit ".l:templatefile endif else echomsg "Template directory '".templatedir."' does not exist." endif endfunction " ---------- end of function Perl_BrowseTemplateFiles ---------- "=== FUNCTION ================================================================ " NAME: Perl_OpenFold {{{1 " DESCRIPTION: Open fold and go to the first or last line of this fold " PARAMETERS: mode - below / start " RETURNS: "=============================================================================== function! Perl_OpenFold ( mode ) if foldclosed(".") >= 0 " we are on a closed fold: get end position, open fold, jump to the " last line of the previously closed fold let foldstart = foldclosed(".") let foldend = foldclosedend(".") normal zv if a:mode == 'below' exe ":".foldend endif if a:mode == 'start' exe ":".foldstart endif endif endfunction " ---------- end of function Perl_OpenFold ---------- "=== FUNCTION ================================================================ " NAME: Perl_HighlightJumpTargets {{{1 " DESCRIPTION: highlight the jump targets " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_HighlightJumpTargets () if s:Perl_Ctrl_j == 'on' exe 'match Search /'.s:Perl_TemplateJumpTarget.'/' endif endfunction " ---------- end of function Perl_HighlightJumpTargets ---------- "=== FUNCTION ================================================================ " NAME: Perl_JumpCtrlJ {{{1 " DESCRIPTION: replaces the template system function for C-j " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_JumpCtrlJ () let match = search( s:Perl_TemplateJumpTarget, 'c' ) if match > 0 " remove the target call setline( match, substitute( getline('.'), s:Perl_TemplateJumpTarget, '', '' ) ) else " try to jump behind parenthesis or strings in the current line if match( getline(".")[col(".") - 1], "[\]})\"'`]" ) != 0 call search( "[\]})\"'`]", '', line(".") ) endif normal l endif return '' endfunction " ---------- end of function Perl_JumpCtrlJ ---------- let s:Perl_perltidy_startscript_executable = 'no' let s:Perl_perltidy_module_executable = 'no' "=== FUNCTION ================================================================ " NAME: Perl_Perltidy {{{1 " DESCRIPTION: run perltidy(1) as a compiler " PARAMETERS: mode - n:normal / v:visual " RETURNS: "=============================================================================== function! Perl_Perltidy (mode) let Sou = expand("%") " name of the file in the current buffer if (&filetype != 'perl') && \ ( a:mode != 'v' || input( "'".Sou."' seems not to be a Perl file. Continue (y/n) : " ) != 'y' ) echomsg "'".Sou."' seems not to be a Perl file." return endif " " check if perltidy start script is executable " if s:Perl_perltidy_startscript_executable == 'no' if !executable("perltidy") echohl WarningMsg echo 'perltidy does not exist or is not executable!' echohl None return else let s:Perl_perltidy_startscript_executable = 'yes' endif endif " " check if perltidy module is executable " WORKAROUND: after upgrading Perl the module will no longer be found " if s:Perl_perltidy_module_executable == 'no' let perltidy_version = system("perltidy -v") if match( perltidy_version, 'copyright\c' ) >= 0 && \ match( perltidy_version, 'Steve\s\+Hancock' ) >= 0 let s:Perl_perltidy_module_executable = 'yes' else echohl WarningMsg echo 'The module Perl::Tidy can not be found! Please reinstall perltidy.' echohl None return endif endif " " ----- normal mode ---------------- if a:mode=="n" if Perl_Input("reformat whole file [y/n/Esc] : ", "y", '' ) != "y" return endif if s:Perl_PerltidyBackup == 'yes' exe ':write! '.Sou.'.bak' endif silent exe ":update" let pos1 = line(".") exe '%!perltidy' exe ':'.pos1 echo 'File "'.Sou.'" reformatted.' endif " ----- visual mode ---------------- if a:mode=="v" let pos1 = line("'<") let pos2 = line("'>") if s:Perl_PerltidyBackup == 'yes' exe pos1.','.pos2.':write! '.Sou.'.bak' endif silent exe pos1.','.pos2.'!perltidy' echo 'File "'.Sou.'" (lines '.pos1.'-'.pos2.') reformatted.' endif " if v:shell_error echohl WarningMsg echomsg 'perltidy reported error code '.v:shell_error.' !' echohl None endif " if filereadable("perltidy.ERR") echohl WarningMsg echo 'Perltidy detected an error when processing file "'.Sou.'". Please see file perltidy.ERR' echohl None endif " endfunction " ---------- end of function Perl_Perltidy ---------- "=== FUNCTION ================================================================ " NAME: Perl_SaveWithTimestamp {{{1 " DESCRIPTION: Save buffer with timestamp " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_SaveWithTimestamp () let file = fnameescape( expand("%") ) " name of the file in the current buffer if empty(file) " do we have a quickfix buffer : syntax errors / profiler report if &filetype == 'qf' let file = getcwd().'/Quickfix-List' else redraw! echohl WarningMsg | echo " no file name " | echohl None return endif endif let file = file.'.'.strftime(s:Perl_TimestampFormat) silent exe ":write ".file echomsg 'file "'.file.'" written' endfunction " ---------- end of function Perl_SaveWithTimestamp ---------- " "=== FUNCTION ================================================================ " NAME: Perl_Hardcopy {{{1 " DESCRIPTION: print PostScript to file " PARAMETERS: mode - n:normal / v:visual " RETURNS: "=============================================================================== function! Perl_Hardcopy (mode) let outfile = expand("%") if empty(outfile) redraw! echohl WarningMsg | echo " no file name " | echohl None return endif let outdir = getcwd() if outdir == substitute( s:Perl_PerlModuleList, '/[^/]\+$', '', '' ) || filewritable(outdir) != 2 let outdir = $HOME endif if !s:MSWIN let outdir = outdir.'/' endif let old_printheader=&printheader exe ':set printheader='.s:Perl_Printheader " ----- normal mode ---------------- if a:mode=="n" silent exe 'hardcopy > '.outdir.outfile.'.ps' if !s:MSWIN echo 'file "'.outfile.'" printed to "'.outdir.outfile.'.ps"' endif endif " ----- visual mode ---------------- if a:mode=="v" silent exe "*hardcopy > ".outdir.outfile.".ps" if !s:MSWIN echo 'file "'.outfile.'" (lines '.line("'<").'-'.line("'>").') printed to "'.outdir.outfile.'.ps"' endif endif exe ':set printheader='.escape( old_printheader, ' %' ) endfunction " ---------- end of function Perl_Hardcopy ---------- " "=== FUNCTION ================================================================ " NAME: Perl_HelpPerlsupport {{{1 " DESCRIPTION: display plugin help " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_HelpPerlsupport () try :help perlsupport catch exe ':helptags '.g:Perl_PluginDir.'/doc' :help perlsupport endtry endfunction " ---------- end of function Perl_HelpPerlsupport ---------- " "------------------------------------------------------------------------------ " run : perlcritic "------------------------------------------------------------------------------ " " All formats consist of 2 parts: " 1. the perlcritic message format " 2. the trailing '%+A%.%#\ at\ %f\ line\ %l%.%#' " Part 1 rebuilds the original perlcritic message. This is done to make " parsing of the messages easier. " Part 2 captures errors from inside perlcritic if any. " Some verbosity levels are treated equal to give quickfix the filename. " " verbosity rebuilt " let s:PCverbosityFormat1 = 1 let s:PCverbosityFormat2 = 2 let s:PCverbosityFormat3 = 3 let s:PCverbosityFormat4 = escape( '"%f:%l:%c:%m. %e (Severity: %s)\n"', '%' ) let s:PCverbosityFormat5 = escape( '"%f:%l:%c:%m. %e (Severity: %s)\n"', '%' ) let s:PCverbosityFormat6 = escape( '"%f:%l:%m, near ' . "'%r'." . ' (Severity: %s)\n"', '%' ) let s:PCverbosityFormat7 = escape( '"%f:%l:%m, near ' . "'%r'." . ' (Severity: %s)\n"', '%' ) let s:PCverbosityFormat8 = escape( '"%f:%l:%c:[%p] %m. (Severity: %s)\n"', '%' ) let s:PCverbosityFormat9 = escape( '"%f:%l:[%p] %m, near ' . "'%r'" . '. (Severity: %s)\n"', '%' ) let s:PCverbosityFormat10 = escape( '"%f:%l:%c:%m.\n %p (Severity: %s)\n%d\n"', '%' ) let s:PCverbosityFormat11 = escape( '"%f:%l:%m, near ' . "'%r'" . '.\n %p (Severity: %s)\n%d\n"', '%' ) " " parses output for different verbosity levels: " let s:PCInnerErrorFormat = ',\%+A%.%#\ at\ %f\ line\ %l%.%#' let s:PCerrorFormat1 = '%f:%l:%c:%m' . s:PCInnerErrorFormat let s:PCerrorFormat2 = '%f:\ (%l:%c)\ %m' . s:PCInnerErrorFormat let s:PCerrorFormat3 = '%m\ at\ %f\ line\ %l'. s:PCInnerErrorFormat let s:PCerrorFormat4 = '%f:%l:%c:%m' . s:PCInnerErrorFormat let s:PCerrorFormat5 = '%f:%l:%c:%m' . s:PCInnerErrorFormat let s:PCerrorFormat6 = '%f:%l:%m' . s:PCInnerErrorFormat let s:PCerrorFormat7 = '%f:%l:%m' . s:PCInnerErrorFormat let s:PCerrorFormat8 = '%f:%l:%m' . s:PCInnerErrorFormat let s:PCerrorFormat9 = '%f:%l:%m' . s:PCInnerErrorFormat let s:PCerrorFormat10 = '%f:%l:%m' . s:PCInnerErrorFormat let s:PCerrorFormat11 = '%f:%l:%m' . s:PCInnerErrorFormat " "=== FUNCTION ================================================================ " NAME: Perl_Perlcritic {{{1 " DESCRIPTION: run perlcritic(1) liek a compiler " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_Perlcritic () let l:currentbuffer = bufname("%") if &filetype != "perl" echohl WarningMsg | echo l:currentbuffer.' seems not to be a Perl file' | echohl None return endif if executable("perlcritic") == 0 " not executable echohl WarningMsg | echo 'perlcritic not installed or not executable' | echohl None return endif let s:Perl_PerlcriticMsg = "" exe ":cclose" silent exe ":update" " " check for a configuration file " let perlCriticRcFile = '' let perlCriticRcFileUsed = 'no' if exists("$PERLCRITIC") let perlCriticRcFile = $PERLCRITIC elseif filereadable( '.perlcriticrc' ) let perlCriticRcFile = '.perlcriticrc' elseif filereadable( $HOME.'/.perlcriticrc' ) let perlCriticRcFile = $HOME.'/.perlcriticrc' endif " " read severity and/or verbosity from the configuration file if specified " if perlCriticRcFile != '' for line in readfile(perlCriticRcFile) " default settings come before the first named block if line =~ '^\s*[' break else let list = matchlist( line, '^\s*severity\s*=\s*\([12345]\)' ) if !empty(list) let s:Perl_PerlcriticSeverity = list[1] let perlCriticRcFileUsed = 'yes' endif let list = matchlist( line, '^\s*severity\s*=\s*\(brutal\|cruel\|harsh\|stern\|gentle\)' ) if !empty(list) let s:Perl_PerlcriticSeverity = index( s:PCseverityName, list[1] ) let perlCriticRcFileUsed = 'yes' endif let list = matchlist( line, '^\s*verbose\s*=\s*\(\d\+\)' ) if !empty(list) && 1<= list[1] && list[1] <= 11 let s:Perl_PerlcriticVerbosity = list[1] let perlCriticRcFileUsed = 'yes' endif endif endfor endif " let perlcriticoptions = \ ' -severity '.s:Perl_PerlcriticSeverity \ .' -verbose '.eval("s:PCverbosityFormat".s:Perl_PerlcriticVerbosity) \ .' '.escape( s:Perl_PerlcriticOptions, g:Perl_FilenameEscChar ) \ .' ' " call s:Perl_SaveGlobalOption('errorformat') exe ':set errorformat='.eval("s:PCerrorFormat".s:Perl_PerlcriticVerbosity) call s:Perl_SaveGlobalOption('makeprg') set makeprg=perlcritic " if s:MSWIN silent exe ':make '.perlcriticoptions.'"'.expand("%:p").'"' else silent exe ':make '.perlcriticoptions.fnameescape( expand("%:p") ) endif " redraw! exe ":botright cwindow" call s:Perl_RestoreGlobalOption('errorformat') call s:Perl_RestoreGlobalOption('makeprg') " " message in case of success " let sev_and_verb = 'severity '.s:Perl_PerlcriticSeverity. \ ' ['.s:PCseverityName[s:Perl_PerlcriticSeverity].']'. \ ', verbosity '.s:Perl_PerlcriticVerbosity " let rcfile = '' if perlCriticRcFileUsed == 'yes' let rcfile = " ( configcfile '".perlCriticRcFile."' )" endif if l:currentbuffer == bufname("%") let s:Perl_PerlcriticMsg = l:currentbuffer.' : NO CRITIQUE, '.sev_and_verb.' '.rcfile else setlocal wrap setlocal linebreak let s:Perl_PerlcriticMsg = 'perlcritic : '.sev_and_verb.rcfile endif redraw! echohl Search | echo s:Perl_PerlcriticMsg | echohl None endfunction " ---------- end of function Perl_Perlcritic ---------- " let s:PCseverityName = [ "DUMMY", "brutal", "cruel", "harsh", "stern", "gentle" ] let s:PCverbosityName = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11' ] "=== FUNCTION ================================================================ " NAME: Perl_PerlcriticSeverityList {{{1 " DESCRIPTION: perlcritic severity : callback function for completion " PARAMETERS: ArgLead - " CmdLine - " CursorPos - " RETURNS: "=============================================================================== function! Perl_PerlcriticSeverityList ( ArgLead, CmdLine, CursorPos ) return filter( copy( s:PCseverityName[1:] ), 'v:val =~ "\\<'.a:ArgLead.'\\w*"' ) endfunction " ---------- end of function Perl_PerlcriticSeverityList ---------- "=== FUNCTION ================================================================ " NAME: Perl_PerlcriticVerbosityList {{{1 " DESCRIPTION: perlcritic verbosity : callback function for completion " PARAMETERS: ArgLead - " CmdLine - " CursorPos - " RETURNS: "=============================================================================== function! Perl_PerlcriticVerbosityList ( ArgLead, CmdLine, CursorPos ) return filter( copy( s:PCverbosityName), 'v:val =~ "\\<'.a:ArgLead.'\\w*"' ) endfunction " ---------- end of function Perl_PerlcriticVerbosityList ---------- "=== FUNCTION ================================================================ " NAME: Perl_GetPerlcriticSeverity {{{1 " DESCRIPTION: perlcritic severity : used in command definition " PARAMETERS: severity - perlcritic severity " RETURNS: "=============================================================================== function! Perl_GetPerlcriticSeverity ( severity ) let s:Perl_PerlcriticSeverity = 3 " the default let sev = a:severity let sev = substitute( sev, '^\s\+', '', '' ) " remove leading whitespaces let sev = substitute( sev, '\s\+$', '', '' ) " remove trailing whitespaces " if sev =~ '^\d$' && 1 <= sev && sev <= 5 " parameter is numeric let s:Perl_PerlcriticSeverity = sev " elseif sev =~ '^\a\+$' " parameter is a word let nr = index( s:PCseverityName, tolower(sev) ) if nr > 0 let s:Perl_PerlcriticSeverity = nr endif else " echomsg "wrong argument '".a:severity."' / severity is set to ".s:Perl_PerlcriticSeverity return endif echomsg "perlcritic severity is set to ".s:Perl_PerlcriticSeverity endfunction " ---------- end of function Perl_GetPerlcriticSeverity ---------- " "=== FUNCTION ================================================================ " NAME: Perl_PerlcriticSeverityInput " DESCRIPTION: read perlcritic severity from the command line " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_PerlcriticSeverityInput () let retval = input( "perlcritic severity (current = '".s:PCseverityName[s:Perl_PerlcriticSeverity]."' / tab exp.): ", '', 'customlist,Perl_PerlcriticSeverityList' ) redraw! call Perl_GetPerlcriticSeverity( retval ) return endfunction " ---------- end of function Perl_PerlcriticSeverityInput ---------- " "=== FUNCTION ================================================================ " NAME: Perl_GetPerlcriticVerbosity {{{1 " DESCRIPTION: perlcritic verbosity : used in command definition " PARAMETERS: verbosity - perlcritic verbosity " RETURNS: "=============================================================================== function! Perl_GetPerlcriticVerbosity ( verbosity ) let s:Perl_PerlcriticVerbosity = 4 let vrb = a:verbosity let vrb = substitute( vrb, '^\s\+', '', '' ) " remove leading whitespaces let vrb = substitute( vrb, '\s\+$', '', '' ) " remove trailing whitespaces if vrb =~ '^\d\{1,2}$' && 1 <= vrb && vrb <= 11 let s:Perl_PerlcriticVerbosity = vrb echomsg "perlcritic verbosity is set to ".s:Perl_PerlcriticVerbosity else echomsg "wrong argument '".a:verbosity."' / perlcritic verbosity is set to ".s:Perl_PerlcriticVerbosity endif endfunction " ---------- end of function Perl_GetPerlcriticVerbosity ---------- " "=== FUNCTION ================================================================ " NAME: Perl_PerlcriticVerbosityInput {{{1 " DESCRIPTION: read perlcritic verbosity from the command line " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_PerlcriticVerbosityInput () let retval = input( "perlcritic verbosity (current = ".s:Perl_PerlcriticVerbosity." / tab exp.): ", '', 'customlist,Perl_PerlcriticVerbosityList' ) redraw! call Perl_GetPerlcriticVerbosity( retval ) return endfunction " ---------- end of function Perl_PerlcriticVerbosityInput ---------- " "=== FUNCTION ================================================================ " NAME: Perl_GetPerlcriticOptions {{{1 " DESCRIPTION: perlcritic options : used in command definition " PARAMETERS: ... - " RETURNS: "=============================================================================== function! Perl_GetPerlcriticOptions ( ... ) let s:Perl_PerlcriticOptions = "" if a:0 > 0 let s:Perl_PerlcriticOptions = a:1 endif endfunction " ---------- end of function Perl_GetPerlcriticOptions ---------- " "=== FUNCTION ================================================================ " NAME: Perl_PerlcriticOptionsInput {{{1 " DESCRIPTION: read perlcritic options from the command line " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_PerlcriticOptionsInput () let retval = input( "perlcritic options (current = '".s:Perl_PerlcriticOptions."'): " ) redraw! call Perl_GetPerlcriticOptions( retval ) return endfunction " ---------- end of function Perl_PerlcriticOptionsInput ---------- " "=== FUNCTION ================================================================ " NAME: Perl_CreateMenusDelayed {{{1 " DESCRIPTION: create GUI menus delayed " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_CreateMenusDelayed () if s:Perl_CreateMenusDelayed == 'yes' && s:Perl_MenuVisible == 'no' call Perl_CreateGuiMenus() endif endfunction " ---------- end of function Perl_CreateMenusDelayed ---------- " "=== FUNCTION ================================================================ " NAME: Perl_CreateGuiMenus {{{1 " DESCRIPTION: create GUI menus immediate " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_CreateGuiMenus () if s:Perl_MenuVisible != 'yes' aunmenu <silent> &Tools.Load\ Perl\ Support amenu <silent> 40.1000 &Tools.-SEP100- : amenu <silent> 40.1160 &Tools.Unload\ Perl\ Support :call Perl_RemoveGuiMenus()<CR> call s:Perl_RereadTemplates('no') call s:Perl_InitMenus () let s:Perl_MenuVisible = 'yes' endif endfunction " ---------- end of function Perl_CreateGuiMenus ---------- "=== FUNCTION ================================================================ " NAME: Perl_RereadTemplates {{{1 " DESCRIPTION: rebuild commands and the menu from the (changed) template file " PARAMETERS: displaymsg - yes / no " RETURNS: "=============================================================================== function! s:Perl_RereadTemplates ( displaymsg ) let g:Perl_Templates = mmtemplates#core#NewLibrary () call mmtemplates#core#ChangeSyntax ( g:Perl_Templates, 'comment', '§', '§' ) let s:Perl_TemplateJumpTarget = mmtemplates#core#Resource ( g:Perl_Templates, "jumptag" )[0] let messsage = '' " if g:Perl_Installation == 'system' "------------------------------------------------------------------------------- " SYSTEM INSTALLATION "------------------------------------------------------------------------------- if filereadable( s:Perl_GlobalTemplateFile ) call mmtemplates#core#ReadTemplates ( g:Perl_Templates, 'load', s:Perl_GlobalTemplateFile ) else echomsg "Global template file '".s:Perl_GlobalTemplateFile."' not readable." return endif let messsage = "Templates read from '".s:Perl_GlobalTemplateFile."'" " "------------------------------------------------------------------------------- " handle local template files "------------------------------------------------------------------------------- if finddir( s:Perl_LocalTemplateDir ) == '' " try to create a local template directory if exists("*mkdir") try call mkdir( s:Perl_LocalTemplateDir, "p" ) catch /.*/ endtry endif endif if isdirectory( s:Perl_LocalTemplateDir ) && !filereadable( s:Perl_LocalTemplateFile ) " write a default local template file let template = [ ] let sample_template_file = fnamemodify( s:Perl_GlobalTemplateDir, ':h' ).'/rc/sample_template_file' if filereadable( sample_template_file ) for line in readfile( sample_template_file ) call add( template, line ) endfor call writefile( template, s:Perl_LocalTemplateFile ) endif endif " if filereadable( s:Perl_LocalTemplateFile ) call mmtemplates#core#ReadTemplates ( g:Perl_Templates, 'load', s:Perl_LocalTemplateFile ) let messsage = messsage." and '".s:Perl_LocalTemplateFile."'" if mmtemplates#core#ExpandText( g:Perl_Templates, '|AUTHOR|' ) == 'YOUR NAME' echomsg "Please set your personal details in file '".s:Perl_LocalTemplateFile."'." endif endif " else "------------------------------------------------------------------------------- " LOCAL INSTALLATION "------------------------------------------------------------------------------- if filereadable( s:Perl_LocalTemplateFile ) call mmtemplates#core#ReadTemplates ( g:Perl_Templates, 'load', s:Perl_LocalTemplateFile ) let messsage = "Templates read from '".s:Perl_LocalTemplateFile."'" else echomsg "Local template file '".s:Perl_LocalTemplateFile."' not readable." return endif " endif if a:displaymsg == 'yes' echomsg messsage.'.' endif endfunction " ---------- end of function s:Perl_RereadTemplates ---------- " "------------------------------------------------------------------------------ " Check the perlcritic default severity and verbosity. "------------------------------------------------------------------------------ silent call Perl_GetPerlcriticSeverity (s:Perl_PerlcriticSeverity) silent call Perl_GetPerlcriticVerbosity(s:Perl_PerlcriticVerbosity) "=== FUNCTION ================================================================ " NAME: Perl_do_tags {{{1 " DESCRIPTION: tag a new file with Perl::Tags " PARAMETERS: filename - " tagfile - name of the tag file " RETURNS: "=============================================================================== function! Perl_do_tags(filename, tagfile) if g:Perl_PerlTags == 'on' perl <<PERL_DO_TAGS my $filename = VIM::Eval('a:filename'); my $tagfile = VIM::Eval('a:tagfile'); if ( -e $filename ) { $naive_tagger->process(files => $filename, refresh=>1 ); } VIM::SetOption("tags+=$tagfile"); # of course, it may not even output, for example, if there's nothing new to process $naive_tagger->output( outfile => $tagfile ); PERL_DO_TAGS endif endfunction " ---------- end of function Perl_do_tags ---------- "=== FUNCTION ================================================================ " NAME: Perl_ModuleListFold {{{1 " DESCRIPTION: compute foldlevel for a module list " debug with "set debug=msg" " PARAMETERS: lnum - " RETURNS: "=============================================================================== function! Perl_ModuleListFold (lnum) let line1 = split( getline(a:lnum-1), '::' ) let line2 = split( getline(a:lnum ), '::' ) let foldlevel = 0 if !empty(line1) while foldlevel < len(line1) && foldlevel < len(line2) && line1[foldlevel] == line2[foldlevel] let foldlevel += 1 endwhile endif return foldlevel endfunction " ---------- end of function Perl_ModuleListFold ---------- " "=== FUNCTION ================================================================ " NAME: Perl_MenuTitle {{{1 " DESCRIPTION: display warning " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_MenuTitle () echohl WarningMsg | echo "This is a menu header." | echohl None endfunction " ---------- end of function Perl_MenuTitle ---------- " "=== FUNCTION ================================================================ " NAME: Perl_InitMenus {{{1 " DESCRIPTION: initialize the hardcoded menu items " PARAMETERS: - " RETURNS: "=============================================================================== function! s:Perl_InitMenus () " " TODO: mapleader configurable " if ! has ( 'menu' ) return endif " " Preparation call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'do_reset' ) " exe 'amenu '.s:Perl_RootMenu.'.Perl <Nop>' exe 'amenu '.s:Perl_RootMenu.'.-Sep00- <Nop>' " "=============================================================================================== "----- Menu : Comments {{{2 "=============================================================================================== call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'sub_menu', '&Comments' ) " let ahead = 'anoremenu <silent> '.s:Perl_RootMenu.'.&Comments.' let vhead = 'vnoremenu <silent> '.s:Perl_RootMenu.'.&Comments.' let ihead = 'inoremenu <silent> '.s:Perl_RootMenu.'.&Comments.' " exe ahead.'end-of-&line\ comment<Tab>\\cl :call Perl_EndOfLineComment()<CR>A' exe ihead.'end-of-&line\ comment<Tab>\\cl <C-C>:call Perl_EndOfLineComment()<CR>A' exe vhead.'end-of-&line\ comment<Tab>\\cl <C-C>:call Perl_MultiLineEndComments()<CR>A' exe ahead.'ad&just\ end-of-line\ com\.<Tab>\\cj :call Perl_AlignLineEndComm()<CR>' exe vhead.'ad&just\ end-of-line\ com\.<Tab>\\cj :call Perl_AlignLineEndComm()<CR>' exe ahead.'&set\ end-of-line\ com\.\ col\.<Tab>\\cs <C-C>:call Perl_GetLineEndCommCol()<CR>' " exe ahead.'-Sep01- <Nop>' exe ahead.'toggle\ &comment<Tab>\\cc :call Perl_CommentToggle()<CR>j' exe ihead.'toggle\ &comment<Tab>\\cc <C-C>:call Perl_CommentToggle()<CR>j' exe vhead.'toggle\ &comment<Tab>\\cc :call Perl_CommentToggle()<CR>j' exe ahead.'comment\ &block<Tab>\\cb :call Perl_CommentBlock("a")<CR>' exe ihead.'comment\ &block<Tab>\\cb <C-C>:call Perl_CommentBlock("a")<CR>' exe vhead.'comment\ &block<Tab>\\cb <C-C>:call Perl_CommentBlock("v")<CR>' exe ahead.'u&ncomment\ block<Tab>\\cub :call Perl_UncommentBlock()<CR>' exe ahead.'-Sep02- <Nop>' " "=============================================================================================== "----- Menu : Statements (title) {{{2 "=============================================================================================== call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'sub_menu', '&Statements' ) " "=============================================================================================== "----- Menu : Idioms (title) {{{2 "=============================================================================================== call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'sub_menu', '&Idioms' ) " "=============================================================================================== "----- Menu : Snippets {{{2 "=============================================================================================== if !empty(s:Perl_CodeSnippets) call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'sub_menu', 'S&nippets' ) exe "amenu <silent> ".s:Perl_RootMenu.'.S&nippets.&read\ code\ snippet<Tab>\\nr :call Perl_CodeSnippet("read")<CR>' exe "imenu <silent> ".s:Perl_RootMenu.'.S&nippets.&read\ code\ snippet<Tab>\\nr <C-C>:call Perl_CodeSnippet("read")<CR>' exe "amenu <silent> ".s:Perl_RootMenu.'.S&nippets.&view\ code\ snippet<Tab>\\nv :call Perl_CodeSnippet("view")<CR>' exe "imenu <silent> ".s:Perl_RootMenu.'.S&nippets.&view\ code\ snippet<Tab>\\nv <C-C>:call Perl_CodeSnippet("view")<CR>' exe "amenu <silent> ".s:Perl_RootMenu.'.S&nippets.&write\ code\ snippet<Tab>\\nw :call Perl_CodeSnippet("write")<CR>' exe "vmenu <silent> ".s:Perl_RootMenu.'.S&nippets.&write\ code\ snippet<Tab>\\nw <C-C>:call Perl_CodeSnippet("writemarked")<CR>' exe "imenu <silent> ".s:Perl_RootMenu.'.S&nippets.&write\ code\ snippet<Tab>\\nw <C-C>:call Perl_CodeSnippet("write")<CR>' exe "amenu <silent> ".s:Perl_RootMenu.'.S&nippets.&edit\ code\ snippet<Tab>\\ne :call Perl_CodeSnippet("edit")<CR>' exe "imenu <silent> ".s:Perl_RootMenu.'.S&nippets.&edit\ code\ snippet<Tab>\\ne <C-C>:call Perl_CodeSnippet("edit")<CR>' exe "amenu <silent> ".s:Perl_RootMenu.'.S&nippets.-SepSnippets- :' " exe "amenu <silent> ".s:Perl_RootMenu.'.S&nippets.edit\ &local\ templates<Tab>\\ntl :call mmtemplates#core#EditTemplateFiles(g:Perl_Templates,-1)<CR>' exe "imenu <silent> ".s:Perl_RootMenu.'.S&nippets.edit\ &local\ templates<Tab>\\ntl <C-C>:call mmtemplates#core#EditTemplateFiles(g:Perl_Templates,-1)<CR>' if g:Perl_Installation == 'system' exe "amenu <silent> ".s:Perl_RootMenu.'.S&nippets.edit\ &local\ templates<Tab>\\ntg :call mmtemplates#core#EditTemplateFiles(g:Perl_Templates,1)<CR>' exe "imenu <silent> ".s:Perl_RootMenu.'.S&nippets.edit\ &local\ templates<Tab>\\ntg <C-C>:call mmtemplates#core#EditTemplateFiles(g:Perl_Templates,1)<CR>' endif " exe "amenu <silent> ".s:Perl_RootMenu.'.S&nippets.reread\ &templates<Tab>\\ntr :call mmtemplates#core#ReadTemplates(g:Perl_Templates,"reload","all")<CR>' exe "imenu <silent> ".s:Perl_RootMenu.'.S&nippets.reread\ &templates<Tab>\\ntr <C-C>:call mmtemplates#core#ReadTemplates(g:Perl_Templates,"reload","all")<CR>' endif " "=============================================================================================== "----- Menu : Regex menu (title) {{{2 "=============================================================================================== call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'sub_menu', '&Regex' ) " "=============================================================================================== "----- Menu : Special Variables menu (title) {{{2 "=============================================================================================== call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'sub_menu', 'Special &Variables' ) " "=============================================================================================== "----- Menu : File-Tests menu {{{2 "=============================================================================================== call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'sub_menu', '&File-Tests' ) " "=============================================================================================== "----- Menu : POD menu (title) {{{2 "=============================================================================================== call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'sub_menu', 'PO&D' ) " "=============================================================================================== "----- Menu : Profiling {{{2 "=============================================================================================== " call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'sub_menu', '&Profiling' ) let ahead = 'amenu <silent> '.s:Perl_RootMenu.'.&Profiling.' exe ahead.'&run\ SmallProf<Tab>\\rps :call perlsupportprofiling#Perl_Smallprof()<CR>' exe ahead.'sort\ SmallProf\ report<Tab>\\rpss :call perlsupportprofiling#Perl_SmallProfSortInput()<CR>' exe ahead.'open\ existing\ SmallProf\ results<Tab>\\rpso :call perlsupportprofiling#Perl_Smallprof_OpenQuickfix()<CR>' exe ahead.'-Sep01- <Nop>' " if !s:MSWIN exe ahead.'&run\ FastProf<Tab>\\rpf :call perlsupportprofiling#Perl_Fastprof()<CR>' exe ahead.'sort\ FastProf\ report<Tab>\\rpfs :call perlsupportprofiling#Perl_FastProfSortInput()<CR>' exe ahead.'open\ existing\ FastProf\ results<Tab>\\rpfo :call perlsupportprofiling#Perl_FastProf_OpenQuickfix()<CR>' exe ahead.'-Sep02- <Nop>' endif " exe ahead.'&run\ NYTProf<Tab>\\rpn :call perlsupportprofiling#Perl_NYTprof()<CR>' exe ahead.'show\ &HTML\ report<Tab>\\rph :call perlsupportprofiling#Perl_NYTprofReadHtml()<CR>' exe ahead.'open\ &CSV\ file<Tab>\\rpno :call perlsupportprofiling#Perl_NYTprofReadCSV("read","line")<CR>' exe ahead.'sort\ NYTProf\ CSV\ report<Tab>\\rpns :call perlsupportprofiling#Perl_SmallProfSortInput()<CR>' " "=============================================================================================== "----- Menu : Run {{{2 "=============================================================================================== " call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'sub_menu', '&Run' ) " " run the script from the local directory " ( the one which is being edited; other versions may exist elsewhere ! ) " let ahead = 'amenu <silent> '.s:Perl_RootMenu.'.&Run.' let vhead = 'vmenu <silent> '.s:Perl_RootMenu.'.&Run.' " exe ahead.'update,\ &run\ script<Tab>\\rr\ \ <C-F9> :call Perl_Run()<CR>' exe ahead.'update,\ check\ &syntax<Tab>\\rs\ \ <A-F9> :call Perl_SyntaxCheck()<CR>' exe ahead.'cmd\.\ line\ &arg\.<Tab>\\ra\ \ <S-F9> :call Perl_Arguments()<CR>' exe ahead.'perl\ s&witches<Tab>\\rw :call Perl_PerlSwitches()<CR>' " " set execution rights for user only ( user may be root ! ) " if !s:MSWIN exe ahead.'make\ script\ &executable<Tab>\\re :call Perl_MakeScriptExecutable()<CR>' endif exe ahead.'-SEP1- :' exe ahead.'run\ &make<Tab>\\rm :call Perl_Make()<CR>' exe ahead.'&choose\ makefile<Tab>\\rcm :call Perl_ChooseMakefile()<CR>' exe ahead.'&make\ clean<Tab>\\rmc :call Perl_MakeClean()<CR>' exe ahead.'cmd\.\ line\ ar&g\.\ for\ make<Tab>\\rma :call Perl_MakeArguments()<CR>' exe ahead.'start\ &debugger<Tab>\\rd\ \ <F9> :call Perl_Debugger()<CR>' exe ahead.'-SEP2- :' exe ahead.'show\ &installed\ Perl\ modules<Tab>\\ri :call Perl_perldoc_show_module_list()<CR>' exe ahead.'&generate\ Perl\ module\ list<Tab>\\rg :call Perl_perldoc_generate_module_list()<CR><CR>' " exe ahead.'-SEP4- :' exe ahead.'run\ perltid&y<Tab>\\ry :call Perl_Perltidy("n")<CR>' exe vhead.'run\ perltid&y<Tab>\\ry <C-C>:call Perl_Perltidy("v")<CR>' " " exe ahead.'-SEP3- :' exe ahead.'run\ perl&critic<Tab>\\rpc :call Perl_Perlcritic()<CR>' " if g:Perl_MenuHeader == "yes" exe ahead.'perlcritic\ severity<Tab>\\rpcs.severity :call Perl_MenuTitle()<CR>' exe ahead.'perlcritic\ severity<Tab>\\rpcs.-Sep5- :' endif let levelnumber = 1 for level in [ "brutal", "cruel", "harsh", "stern", "gentle" ] exe ahead.'perlcritic\ severity<Tab>\\rpcs.&'.level.'<Tab>(='.levelnumber.') :call Perl_GetPerlcriticSeverity("'.level.'")<CR>' let levelnumber = levelnumber+1 endfor " if g:Perl_MenuHeader == "yes" exe ahead.'perlcritic\ &verbosity<Tab>\\rpcv.verbosity :call Perl_MenuTitle()<CR>' exe ahead.'perlcritic\ &verbosity<Tab>\\rpcv.-Sep6- :' endif for level in [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ] exe ahead.'perlcritic\ &verbosity<Tab>\\rpcv.&'.level.' :call Perl_GetPerlcriticVerbosity('.level.')<CR>' endfor exe ahead.'perlcritic\ &options<Tab>\\rpco :call Perl_PerlcriticOptionsInput()<CR>' exe ahead.'-SEP5- :' exe ahead.'save\ buffer\ with\ &timestamp<Tab>\\rt :call Perl_SaveWithTimestamp()<CR>' exe ahead.'&hardcopy\ to\ FILENAME\.ps<Tab>\\rh :call Perl_Hardcopy("n")<CR>' exe ahead.'&hardcopy\ to\ FILENAME\.ps<Tab>\\rh <C-C>:call Perl_Hardcopy("v")<CR>' exe ahead.'-SEP6- :' exe ahead.'settings\ and\ hot\ &keys<Tab>\\rk :call Perl_Settings()<CR>' " if !s:MSWIN exe ahead.'&xterm\ size<Tab>\\rx :call Perl_XtermSize()<CR>' endif if g:Perl_OutputGvim == "vim" exe ahead.'&output:\ VIM->buffer->xterm<Tab>\\ro :call Perl_Toggle_Gvim_Xterm()<CR>' else if g:Perl_OutputGvim == "buffer" exe ahead.'&output:\ BUFFER->xterm->vim<Tab>\\ro :call Perl_Toggle_Gvim_Xterm()<CR>' else exe ahead.'&output:\ XTERM->vim->buffer<Tab>\\ro :call Perl_Toggle_Gvim_Xterm()<CR>' endif endif " "=============================================================================================== "----- Menu : GENERATE MENU ITEMS FROM THE TEMPLATES {{{2 "=============================================================================================== call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'do_templates' ) " "=============================================================================================== "----- Menu : Snippets menu (items) {{{2 "=============================================================================================== if !empty(s:Perl_CodeSnippets) call mmtemplates#core#CreateMenus ( 'g:Perl_Templates', s:Perl_RootMenu, 'do_styles', \ 'specials_menu', 'Snippets' ) endif " "=============================================================================================== "----- Menu : Regex menu (items) {{{2 "=============================================================================================== let ahead = 'anoremenu <silent> '.s:Perl_RootMenu.'.Rege&x.' let vhead = 'vnoremenu <silent> '.s:Perl_RootMenu.'.Rege&x.' let ihead = 'inoremenu <silent> '.s:Perl_RootMenu.'.Rege&x.' " exe " noremenu ".s:Perl_RootMenu.'.Rege&x.-SEP7- :' exe "amenu <silent> ".s:Perl_RootMenu.'.Rege&x.pick\ up\ &regex<Tab>\\xr :call perlsupportregex#Perl_RegexPick( "regexp", "n" )<CR>j' exe "amenu <silent> ".s:Perl_RootMenu.'.Rege&x.pick\ up\ s&tring<Tab>\\xs :call perlsupportregex#Perl_RegexPick( "string", "n" )<CR>j' exe "amenu <silent> ".s:Perl_RootMenu.'.Rege&x.pick\ up\ &flag(s)<Tab>\\xf :call perlsupportregex#Perl_RegexPickFlag( "n" )<CR>' exe "vmenu <silent> ".s:Perl_RootMenu.'.Rege&x.pick\ up\ &regex<Tab>\\xr <C-C>:call perlsupportregex#Perl_RegexPick( "regexp", "v" )<CR>'."'>j" exe "vmenu <silent> ".s:Perl_RootMenu.'.Rege&x.pick\ up\ s&tring<Tab>\\xs <C-C>:call perlsupportregex#Perl_RegexPick( "string", "v" )<CR>'."'>j" exe "vmenu <silent> ".s:Perl_RootMenu.'.Rege&x.pick\ up\ &flag(s)<Tab>\\xf <C-C>:call perlsupportregex#Perl_RegexPickFlag( "v" )<CR>'."'>j" " Menu exe "amenu <silent> ".s:Perl_RootMenu.'.Rege&x.&match<Tab>\\xm :call perlsupportregex#Perl_RegexVisualize( )<CR>' exe "amenu <silent> ".s:Perl_RootMenu.'.Rege&x.matc&h\ several\ targets<Tab>\\xmm :call perlsupportregex#Perl_RegexMatchSeveral( )<CR>' exe "amenu <silent> ".s:Perl_RootMenu.'.Rege&x.&explain\ regex<Tab>\\xe :call perlsupportregex#Perl_RegexExplain( "n" )<CR>' exe "vmenu <silent> ".s:Perl_RootMenu.'.Rege&x.&explain\ regex<Tab>\\xe <C-C>:call perlsupportregex#Perl_RegexExplain( "v" )<CR>' " "=============================================================================================== "----- Menu : POD menu (items) {{{2 "=============================================================================================== exe "amenu ".s:Perl_RootMenu.'.&POD.-SEP4- :' exe "amenu <silent> ".s:Perl_RootMenu.'.&POD.run\ &podchecker<Tab>\\pod :call Perl_PodCheck()<CR>' exe "amenu <silent> ".s:Perl_RootMenu.'.&POD.POD\ ->\ &html<Tab>\\podh :call Perl_POD("html")<CR>' exe "amenu <silent> ".s:Perl_RootMenu.'.&POD.POD\ ->\ &man<Tab>\\podm :call Perl_POD("man")<CR>' exe "amenu <silent> ".s:Perl_RootMenu.'.&POD.POD\ ->\ &text<Tab>\\podt :call Perl_POD("text")<CR>' " return endfunction " ---------- end of function s:Perl_InitMenus ---------- "=== FUNCTION ================================================================ " NAME: Perl_ShowMenus {{{1 " DESCRIPTION: display the Perl menu " PARAMETERS: - " RETURNS: "=============================================================================== function! s:Perl_ShowMenus () call s:Perl_RereadTemplates ('no') if s:Perl_LoadMenus == 'yes' call s:Perl_InitMenus () let s:Perl_MenuVisible = 'yes' call s:Perl_ToolMenuUnloadItem() endif endfunction " ---------- end of function s:Perl_ShowMenus ---------- "=== FUNCTION ================================================================ " NAME: Perl_ToolMenu {{{1 " DESCRIPTION: generate the tool menu item " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_ToolMenu () amenu <silent> 40.1000 &Tools.-SEP100- : amenu <silent> 40.1160 &Tools.Load\ Perl\ Support :call Perl_CreateGuiMenus()<CR> endfunction " ---------- end of function Perl_ToolMenu ---------- "=== FUNCTION ================================================================ " NAME: Perl_RemoveGuiMenus {{{1 " DESCRIPTION: remove the Perl menu " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_RemoveGuiMenus () if s:Perl_MenuVisible == 'yes' exe "aunmenu <silent> ".s:Perl_RootMenu " aunmenu <silent> &Tools.Unload\ Perl\ Support call Perl_ToolMenu() " let s:Perl_MenuVisible = 'no' endif endfunction " ---------- end of function Perl_RemoveGuiMenus ---------- " "=== FUNCTION ================================================================ " NAME: Perl_GetRegexSubstitution {{{1 " DESCRIPTION: get regex control character replacements (2 characters) " PARAMETERS: - "=============================================================================== function! Perl_GetRegexSubstitution () let retval = input( "regex control character replacements (current = '".g:Perl_PerlRegexSubstitution."'): " ) if strlen( retval ) == 2 let g:Perl_PerlRegexSubstitution = retval endif endfunction " ---------- end of function Perl_GetRegexSubstitution ---------- " "=== FUNCTION ================================================================ " NAME: Perl_InitializePerlInterface {{{1 " DESCRIPTION: initialize the Perl interface " PARAMETERS: - " RETURNS: "=============================================================================== function! Perl_InitializePerlInterface( ) if g:Perl_InterfaceInitialized == 'no' if has('perl') perl <<INITIALIZE_PERL_INTERFACE # use utf8; # Perl pragma to enable/disable UTF-8 in source # # --------------------------------------------------------------- # find out the version of the Perl interface # --------------------------------------------------------------- VIM::DoCommand("let s:Perl_PerlExecutableVersion = \"$^V\""); VIM::DoCommand("let g:Perl_InterfaceInitialized = 'yes'"); # INITIALIZE_PERL_INTERFACE endif endif endfunction " ---------- end of function Perl_InitializePerlInterface ---------- " "=== FUNCTION ================================================================ " NAME: CreateAdditionalMaps {{{1 " DESCRIPTION: create additional maps " PARAMETERS: - " RETURNS: "=============================================================================== function! s:CreateAdditionalMaps () " ---------- tabulator / shiftwidth ------------------------------------------ " Set tabulator and shift width to 4 conforming to the Perl Style Guide. " Uncomment the next two lines to force these settings for all files with " filetype 'perl' . " setlocal tabstop=4 setlocal shiftwidth=4 if exists('g:Perl_Perltidy') && g:Perl_Perltidy == 'on' && executable("perltidy") setlocal equalprg='perltidy' endif " " ---------- Add ':' to the keyword characters ------------------------------- " Tokens like 'File::Find' are recognized as one keyword setlocal iskeyword+=: " " ---------- Do we have a mapleader other than '\' ? ------------ " if exists("g:Perl_MapLeader") let maplocalleader = g:Perl_MapLeader endif " " ---------- Perl dictionary ------------------------------------------------- " This will enable keyword completion for Perl " using Vim's dictionary feature |i_CTRL-X_CTRL-K|. " if exists("g:Perl_Dictionary_File") let save=&dictionary silent! exe 'setlocal dictionary='.g:Perl_Dictionary_File silent! exe 'setlocal dictionary+='.save endif " "------------------------------------------------------------------------------- " USER DEFINED COMMANDS "------------------------------------------------------------------------------- " ---------- commands : perlcritic ------------------------------------- command! -nargs=? CriticOptions call Perl_GetPerlcriticOptions (<f-args>) command! -nargs=1 -complete=customlist,Perl_PerlcriticSeverityList CriticSeverity call Perl_GetPerlcriticSeverity (<f-args>) command! -nargs=1 -complete=customlist,Perl_PerlcriticVerbosityList CriticVerbosity call Perl_GetPerlcriticVerbosity(<f-args>) " " ---------- commands : perlcritic ------------------------------------- command! -nargs=1 RegexSubstitutions call perlsupportregex#Perl_PerlRegexSubstitutions(<f-args>) " " ---------- commands : profiling ------------------------------------- command! -nargs=1 -complete=customlist,perlsupportprofiling#Perl_SmallProfSortList SmallProfSort \ call perlsupportprofiling#Perl_SmallProfSortQuickfix ( <f-args> ) " if !s:MSWIN command! -nargs=1 -complete=customlist,perlsupportprofiling#Perl_FastProfSortList FastProfSort \ call perlsupportprofiling#Perl_FastProfSortQuickfix ( <f-args> ) endif " command! -nargs=1 -complete=customlist,perlsupportprofiling#Perl_NYTProfSortList NYTProfSort \ call perlsupportprofiling#Perl_NYTProfSortQuickfix ( <f-args> ) " command! -nargs=0 NYTProfCSV call perlsupportprofiling#Perl_NYTprofReadCSV () " command! -nargs=0 NYTProfHTML call perlsupportprofiling#Perl_NYTprofReadHtml () " " ---------- Key mappings : function keys ------------------------------------ " " Ctrl-F9 run script " Alt-F9 run syntax check " Shift-F9 set command line arguments " Shift-F1 read Perl documentation " Vim (non-GUI) : shifted keys are mapped to their unshifted key !!! " if has("gui_running") " map <buffer> <silent> <A-F9> :call Perl_SyntaxCheck()<CR> imap <buffer> <silent> <A-F9> <C-C>:call Perl_SyntaxCheck()<CR> " map <buffer> <silent> <C-F9> :call Perl_Run()<CR> imap <buffer> <silent> <C-F9> <C-C>:call Perl_Run()<CR> " map <buffer> <silent> <S-F9> :call Perl_Arguments()<CR> imap <buffer> <silent> <S-F9> <C-C>:call Perl_Arguments()<CR> " map <buffer> <silent> <S-F1> :call Perl_perldoc()<CR> imap <buffer> <silent> <S-F1> <C-C>:call Perl_perldoc()<CR> endif " " ---------- plugin help ----------------------------------------------------- " map <buffer> <silent> <LocalLeader>h :call Perl_perldoc()<CR> map <buffer> <silent> <LocalLeader>hp :call Perl_HelpPerlsupport()<CR> " imap <buffer> <silent> <LocalLeader>h <C-C>:call Perl_perldoc()<CR> imap <buffer> <silent> <LocalLeader>hp <C-C>:call Perl_HelpPerlsupport()<CR> " " ---------------------------------------------------------------------------- " Comments " ---------------------------------------------------------------------------- " nnoremap <buffer> <silent> <LocalLeader>cl :call Perl_EndOfLineComment()<CR>A inoremap <buffer> <silent> <LocalLeader>cl <C-C>:call Perl_EndOfLineComment()<CR> vnoremap <buffer> <silent> <LocalLeader>cl <C-C>:call Perl_MultiLineEndComments()<CR>A " nnoremap <buffer> <silent> <LocalLeader>cj :call Perl_AlignLineEndComm()<CR> inoremap <buffer> <silent> <LocalLeader>cj <C-C>:call Perl_AlignLineEndComm()<CR> vnoremap <buffer> <silent> <LocalLeader>cj :call Perl_AlignLineEndComm()<CR> nnoremap <buffer> <silent> <LocalLeader>cs :call Perl_GetLineEndCommCol()<CR> nnoremap <buffer> <silent> <LocalLeader>cc :call Perl_CommentToggle()<CR>j vnoremap <buffer> <silent> <LocalLeader>cc :call Perl_CommentToggle()<CR>j nnoremap <buffer> <silent> <LocalLeader>cb :call Perl_CommentBlock("a")<CR> inoremap <buffer> <silent> <LocalLeader>cb <C-C>:call Perl_CommentBlock("a")<CR> vnoremap <buffer> <silent> <LocalLeader>cb <C-C>:call Perl_CommentBlock("v")<CR> nnoremap <buffer> <silent> <LocalLeader>cub :call Perl_UncommentBlock()<CR> " " ---------------------------------------------------------------------------- " Snippets & Templates " ---------------------------------------------------------------------------- " nnoremap <buffer> <silent> <LocalLeader>nr :call Perl_CodeSnippet("read")<CR> nnoremap <buffer> <silent> <LocalLeader>nw :call Perl_CodeSnippet("write")<CR> vnoremap <buffer> <silent> <LocalLeader>nw <Esc>:call Perl_CodeSnippet("wv")<CR> nnoremap <buffer> <silent> <LocalLeader>ne :call Perl_CodeSnippet("edit")<CR> nnoremap <buffer> <silent> <LocalLeader>nv :call Perl_CodeSnippet("view")<CR> " inoremap <buffer> <silent> <LocalLeader>nr <Esc>:call Perl_CodeSnippet("read")<CR> inoremap <buffer> <silent> <LocalLeader>nw <Esc>:call Perl_CodeSnippet("write")<CR> inoremap <buffer> <silent> <LocalLeader>ne <Esc>:call Perl_CodeSnippet("edit")<CR> inoremap <buffer> <silent> <LocalLeader>nv <Esc>:call Perl_CodeSnippet("view")<CR> " nnoremap <buffer> <silent> <LocalLeader>ntl :call mmtemplates#core#EditTemplateFiles(g:Perl_Templates,-1)<CR> inoremap <buffer> <silent> <LocalLeader>ntl <C-C>:call mmtemplates#core#EditTemplateFiles(g:Perl_Templates,-1)<CR> if g:Perl_Installation == 'system' nnoremap <buffer> <silent> <LocalLeader>ntg :call mmtemplates#core#EditTemplateFiles(g:Perl_Templates,1)<CR> inoremap <buffer> <silent> <LocalLeader>ntg <C-C>:call mmtemplates#core#EditTemplateFiles(g:Perl_Templates,1)<CR> endif nnoremap <buffer> <silent> <LocalLeader>ntr :call mmtemplates#core#ReadTemplates(g:Perl_Templates,"reload","all")<CR> inoremap <buffer> <silent> <LocalLeader>ntr <C-C>:call mmtemplates#core#ReadTemplates(g:Perl_Templates,"reload","all")<CR> nnoremap <buffer> <silent> <LocalLeader>nts :call mmtemplates#core#ChooseStyle(g:Perl_Templates,"!pick")<CR> inoremap <buffer> <silent> <LocalLeader>nts <C-C>:call mmtemplates#core#ChooseStyle(g:Perl_Templates,"!pick")<CR> " " " ---------------------------------------------------------------------------- " Regex " ---------------------------------------------------------------------------- " nnoremap <buffer> <silent> <LocalLeader>xr :call perlsupportregex#Perl_RegexPick( "regexp", "n" )<CR>j nnoremap <buffer> <silent> <LocalLeader>xs :call perlsupportregex#Perl_RegexPick( "string", "n" )<CR>j nnoremap <buffer> <silent> <LocalLeader>xf :call perlsupportregex#Perl_RegexPickFlag( "n" )<CR> vnoremap <buffer> <silent> <LocalLeader>xr <C-C>:call perlsupportregex#Perl_RegexPick( "regexp", "v" )<CR>'>j vnoremap <buffer> <silent> <LocalLeader>xs <C-C>:call perlsupportregex#Perl_RegexPick( "string", "v" )<CR>'>j vnoremap <buffer> <silent> <LocalLeader>xf <C-C>:call perlsupportregex#Perl_RegexPickFlag( "v" )<CR>'>j nnoremap <buffer> <silent> <LocalLeader>xm :call perlsupportregex#Perl_RegexVisualize( )<CR> nnoremap <buffer> <silent> <LocalLeader>xmm :call perlsupportregex#Perl_RegexMatchSeveral( )<CR> nnoremap <buffer> <silent> <LocalLeader>xe :call perlsupportregex#Perl_RegexExplain( "n" )<CR> vnoremap <buffer> <silent> <LocalLeader>xe <C-C>:call perlsupportregex#Perl_RegexExplain( "v" )<CR> " " " ---------------------------------------------------------------------------- " POD " ---------------------------------------------------------------------------- " nnoremap <buffer> <silent> <LocalLeader>pod :call Perl_PodCheck()<CR> nnoremap <buffer> <silent> <LocalLeader>podh :call Perl_POD('html')<CR> nnoremap <buffer> <silent> <LocalLeader>podm :call Perl_POD('man')<CR> nnoremap <buffer> <silent> <LocalLeader>podt :call Perl_POD('text')<CR> " inoremap <buffer> <silent> <LocalLeader>pod <Esc>:call Perl_PodCheck()<CR> inoremap <buffer> <silent> <LocalLeader>podh <Esc>:call Perl_POD('html')<CR> inoremap <buffer> <silent> <LocalLeader>podm <Esc>:call Perl_POD('man')<CR> inoremap <buffer> <silent> <LocalLeader>podt <Esc>:call Perl_POD('text')<CR> " " ---------------------------------------------------------------------------- " Profiling " ---------------------------------------------------------------------------- " nnoremap <buffer> <silent> <LocalLeader>rps :call perlsupportprofiling#Perl_Smallprof()<CR> inoremap <buffer> <silent> <LocalLeader>rps <C-C>:call perlsupportprofiling#Perl_Smallprof()<CR> nnoremap <buffer> <silent> <LocalLeader>rpss :call perlsupportprofiling#Perl_SmallProfSortInput()<CR> inoremap <buffer> <silent> <LocalLeader>rpss <C-C>:call perlsupportprofiling#Perl_SmallProfSortInput()<CR> nnoremap <buffer> <silent> <LocalLeader>rpf :call perlsupportprofiling#Perl_Fastprof()<CR> inoremap <buffer> <silent> <LocalLeader>rpf <C-C>:call perlsupportprofiling#Perl_Fastprof()<CR> nnoremap <buffer> <silent> <LocalLeader>rpfs :call perlsupportprofiling#Perl_FastProfSortInput()<CR> inoremap <buffer> <silent> <LocalLeader>rpfs <C-C>:call perlsupportprofiling#Perl_FastProfSortInput()<CR> nnoremap <buffer> <silent> <LocalLeader>rpn :call perlsupportprofiling#Perl_NYTprof()<CR> nnoremap <buffer> <silent> <LocalLeader>rpnc :call perlsupportprofiling#Perl_NYTprofReadCSV("read","line")<CR> nnoremap <buffer> <silent> <LocalLeader>rpns :call perlsupportprofiling#Perl_NYTProfSortInput()<CR> nnoremap <buffer> <silent> <LocalLeader>rpnh :call perlsupportprofiling#Perl_NYTprofReadHtml()<CR> " inoremap <buffer> <silent> <LocalLeader>rpn <C-C>:call perlsupportprofiling#Perl_NYTprof()<CR> inoremap <buffer> <silent> <LocalLeader>rpnc <C-C>:call perlsupportprofiling#Perl_NYTprofReadCSV("read","line")<CR> inoremap <buffer> <silent> <LocalLeader>rpns <C-C>:call perlsupportprofiling#Perl_NYTProfSortInput()<CR> inoremap <buffer> <silent> <LocalLeader>rpnh <C-C>:call perlsupportprofiling#Perl_NYTprofReadHtml()<CR> " " ---------------------------------------------------------------------------- " Run " ---------------------------------------------------------------------------- " noremap <buffer> <silent> <LocalLeader>rr :call Perl_Run()<CR> noremap <buffer> <silent> <LocalLeader>rs :call Perl_SyntaxCheck()<CR> noremap <buffer> <silent> <LocalLeader>ra :call Perl_Arguments()<CR> noremap <buffer> <silent> <LocalLeader>rw :call Perl_PerlSwitches()<CR> noremap <buffer> <silent> <LocalLeader>rm :call Perl_Make()<CR> noremap <buffer> <silent> <LocalLeader>rcm :call Perl_ChooseMakefile()<CR> noremap <buffer> <silent> <LocalLeader>rmc :call Perl_MakeClean()<CR> noremap <buffer> <silent> <LocalLeader>rma :call Perl_MakeArguments()<CR> inoremap <buffer> <silent> <LocalLeader>rr <C-C>:call Perl_Run()<CR> inoremap <buffer> <silent> <LocalLeader>rs <C-C>:call Perl_SyntaxCheck()<CR> inoremap <buffer> <silent> <LocalLeader>ra <C-C>:call Perl_Arguments()<CR> inoremap <buffer> <silent> <LocalLeader>rw <C-C>:call Perl_PerlSwitches()<CR> inoremap <buffer> <silent> <LocalLeader>rm <C-C>:call Perl_Make()<CR> inoremap <buffer> <silent> <LocalLeader>rcm <C-C>:call Perl_ChooseMakefile()<CR> inoremap <buffer> <silent> <LocalLeader>rmc <C-C>:call Perl_MakeClean()<CR> inoremap <buffer> <silent> <LocalLeader>rma <C-C>:call Perl_MakeArguments()<CR> " noremap <buffer> <silent> <LocalLeader>rd :call Perl_Debugger()<CR> noremap <buffer> <silent> <F9> :call Perl_Debugger()<CR> inoremap <buffer> <silent> <F9> <C-C>:call Perl_Debugger()<CR> " if s:UNIX noremap <buffer> <silent> <LocalLeader>re :call Perl_MakeScriptExecutable()<CR> inoremap <buffer> <silent> <LocalLeader>re <C-C>:call Perl_MakeScriptExecutable()<CR> endif " map <buffer> <silent> <LocalLeader>ri :call Perl_perldoc_show_module_list()<CR> map <buffer> <silent> <LocalLeader>rg :call Perl_perldoc_generate_module_list()<CR> " map <buffer> <silent> <LocalLeader>ry :call Perl_Perltidy("n")<CR> vmap <buffer> <silent> <LocalLeader>ry <C-C>:call Perl_Perltidy("v")<CR> " map <buffer> <silent> <LocalLeader>rpc :call Perl_Perlcritic()<CR> map <buffer> <silent> <LocalLeader>rt :call Perl_SaveWithTimestamp()<CR> map <buffer> <silent> <LocalLeader>rh :call Perl_Hardcopy("n")<CR> vmap <buffer> <silent> <LocalLeader>rh <C-C>:call Perl_Hardcopy("v")<CR> " map <buffer> <silent> <LocalLeader>rk :call Perl_Settings()<CR> " imap <buffer> <silent> <LocalLeader>ri <C-C>:call Perl_perldoc_show_module_list()<CR> imap <buffer> <silent> <LocalLeader>rg <C-C>:call Perl_perldoc_generate_module_list()<CR> imap <buffer> <silent> <LocalLeader>ry <C-C>:call Perl_Perltidy("n")<CR> imap <buffer> <silent> <LocalLeader>rpc <C-C>:call Perl_Perlcritic()<CR> imap <buffer> <silent> <LocalLeader>rt <C-C>:call Perl_SaveWithTimestamp()<CR> imap <buffer> <silent> <LocalLeader>rh <C-C>:call Perl_Hardcopy("n")<CR> imap <buffer> <silent> <LocalLeader>rk <C-C>:call Perl_Settings()<CR> " if has("gui_running") && s:UNIX map <buffer> <silent> <LocalLeader>rx :call Perl_XtermSize()<CR> imap <buffer> <silent> <LocalLeader>rx <C-C>:call Perl_XtermSize()<CR> endif " map <buffer> <silent> <LocalLeader>ro :call Perl_Toggle_Gvim_Xterm()<CR> imap <buffer> <silent> <LocalLeader>ro <C-C>:call Perl_Toggle_Gvim_Xterm()<CR> " map <buffer> <silent> <LocalLeader>rpcs :call Perl_PerlcriticSeverityInput()<CR> map <buffer> <silent> <LocalLeader>rpcv :call Perl_PerlcriticVerbosityInput()<CR> map <buffer> <silent> <LocalLeader>rpco :call Perl_PerlcriticOptionsInput()<CR> " " ---------------------------------------------------------------------------- " if !exists("g:Perl_Ctrl_j") || ( exists("g:Perl_Ctrl_j") && g:Perl_Ctrl_j != 'off' ) nmap <buffer> <silent> <C-j> i<C-R>=Perl_JumpCtrlJ()<CR> imap <buffer> <silent> <C-j> <C-R>=Perl_JumpCtrlJ()<CR> endif " " ---------------------------------------------------------------------------- " Generate (possibly exuberant) Ctags style tags for Perl sourcecode. " Controlled by g:Perl_PerlTags, disabled by default. " ---------------------------------------------------------------------------- if has('perl') && exists("g:Perl_PerlTags") && g:Perl_PerlTags == 'on' if ! exists("s:defined_functions") function s:init_tags() perl <<EOF use if defined $ENV{PERL_LOCAL_INSTALLATION}, lib => $ENV{PERL_LOCAL_INSTALLATION}; eval { require Perl::Tags }; if ( $@ ) { # Perl::Tags not loadable VIM::DoCommand("let g:Perl_PerlTags = 'off'" ); } else { $naive_tagger = Perl::Tags::Naive->new( max_level=>2 ); } EOF endfunction " let vim do the tempfile cleanup and protection let s:tagfile = tempname() call s:init_tags() " only the first time let s:defined_functions = 1 endif call Perl_do_tags( expand('%'), s:tagfile ) augroup perltags au! autocmd BufRead,BufWritePost *.pm,*.pl call Perl_do_tags(expand('%'), s:tagfile) augroup END endif " endfunction " ---------- end of function s:CreateAdditionalMaps ---------- "=============================================================================== "=============================================================================== " call Perl_ToolMenu() if s:Perl_LoadMenus == 'yes' && s:Perl_CreateMenusDelayed == 'no' call Perl_CreateGuiMenus() endif "------------------------------------------------------------------------------ " Automated header insertion "------------------------------------------------------------------------------ if has("autocmd") " autocmd BufNewFile,BufRead *.pl,*.pm,*.t,*.pod \ if ( &filetype == 'perl' || &filetype == 'pod') | \ call Perl_CreateMenusDelayed() | \ call mmtemplates#core#CreateMaps ( 'g:Perl_Templates', g:Perl_MapLeader ) | \ endif | " autocmd BufRead * \ if ( &filetype == 'perl' || &filetype == 'pod') | \ call Perl_CreateMenusDelayed() | \ call mmtemplates#core#CreateMaps ( 'g:Perl_Templates', g:Perl_MapLeader ) | \ endif " autocmd BufNewFile,BufRead *.pod setlocal syntax=perl autocmd BufNewFile,BufRead *.t setlocal filetype=perl " autocmd BufNewFile *.pl call mmtemplates#core#InsertTemplate(g:Perl_Templates, 'Comments.file description pl') autocmd BufNewFile *.pm call mmtemplates#core#InsertTemplate(g:Perl_Templates, 'Comments.file description pm') autocmd BufNewFile *.t call mmtemplates#core#InsertTemplate(g:Perl_Templates, 'Comments.file description t') autocmd BufNew *.pl,*.pm,*.t,*.pod call Perl_InitializePerlInterface() autocmd BufRead *.pl,*.pm,*.t,*.pod call Perl_HighlightJumpTargets() " " Wrap error descriptions in the quickfix window. autocmd BufReadPost quickfix setlocal wrap | setlocal linebreak " exe 'autocmd BufNewFile,BufReadPost '.s:Perl_PerlModuleList.' setlocal foldmethod=expr | setlocal foldexpr=Perl_ModuleListFold(v:lnum)' " autocmd BufNewFile,BufRead * if &filetype =~ '^\(perl\|pod\)$' | \ call s:CreateAdditionalMaps() | endif endif " " vim: tabstop=2 shiftwidth=2 foldmethod=marker
00000svn-vim-cfg
trunk/vimfiles/plugin/perl-support.vim
Vim Script
gpl3
124,005
" sqlplus.vim " author: Jamis Buck (jgb3@email.byu.edu) " version: 1.2.3 " " This file contains routines that may be used to execute SQL queries and describe " tables from within VIM. It depends on SQL*Plus. You must have $ORACLE_HOME " $ORACLE_SID set in your environment, although you can explicitly set the " database name to use with the :DB <db-name> command. " " In command mode: " <F8>: execute the SELECT query under your cursor. The query must begin with " the "select" keyword and end with a ";" " <Leader><F8>: prompt for an SQL command/query to execute. " <F9>: treat the identifier under the cursor as a table name, and do a 'describe' " on it. " <F10>: prompt for a table to describe. " <F11>: set the current SQL*Plus username and password " <Leader>sb: open an empty buffer in a new window to enter SQL commands in " <Leader>ss: execute the (one-line) query on the current line " <Leader>se: execute the query under the cursor (as <F8>) " <Leader>st: describe the table under the cursor (as <F9>) " <Leader>sc: open the user's common SQL buffer (g:sqlplus_common_buffer) in a " new window. " " :Select <...> -- execute the given Select query. " :Update <...> -- execute the given Update command. " :Delete <...> -- execute the given Delete command " :DB <db-name> -- set the database name to <db-name> " :SQL <...> -- open a blank SQL buffer in a new window, or if a filename is " specified, open the given file in a new window. " " In visual mode: " <F8>: execute the selected query " " If queries contain bind variables, you will be prompted to give a value for " each one. if the value is a string, you must explicitly put quotes around it. " If the query contains an INTO clause, it is removed before executing. " " You will be prompted for your user-name and password the first time you access " one of these functions during a session. After that, your user-id and password " will be remembered until the session ends. " " The results of the query/command are displayed in a separate window. " " You can specify the values of the following global variables in your .vimrc " file, to alter the behavior of this plugin: " " g:sqlplus_userid -- the user-id to log in to the database as. If this " is specified, g:sqlplus_passwd must be given as well, which is the " password to use. Default: "" " g:sqlplus_path -- the path the the SQL*Plus executable, including any " command line options. Default: $ORACLE_HOME . "/bin/sqlplus -s" " g:sqlplus_common_commands -- any SQL*Plus commands that should be " executed every time SQL*Plus is invoked. " Default: "set pagesize 10000\nset wrap off\nset linesize 9999\n" " g:sqlplus_common_buffer -- the name of a file that will contain " common SQL queries and expressions, that may be opened via the " <Leader>sc command. " g:sqlplus_db -- the name of the database to connect to. This variable " may also be modified via the :DB command. " " ------------------------------------------------------------------------------ " Thanks to: " Matt Kunze (kunzem@optimiz.com) for getting this script to work under " Windows " ------------------------------------------------------------------------------ " Global variables (may be set in ~/.vimrc) {{{1 if !exists( "g:sqlplus_userid" ) let g:sqlplus_userid = "" let g:sqlplus_passwd = "" endif if !exists( "g:sqlplus_path" ) let g:sqlplus_path = $ORACLE_HOME . "/bin/sqlplus -s " endif if !exists( "g:sqlplus_common_commands" ) let g:sqlplus_common_commands = "set pagesize 10000\nset wrap off\nset linesize 9999\n" endif if !exists( "g:sqlplus_common_buffer" ) let g:sqlplus_common_buffer = "~/.vim_sql" endif if !exists( "g:sqlplus_db" ) let g:sqlplus_db = $ORACLE_SID endif "}}} function! AE_getSQLPlusUIDandPasswd( force ) "{{{1 if g:sqlplus_userid == "" || a:force != 0 if g:sqlplus_userid == "" if has("win32") let l:userid = '' else let l:userid = substitute( system( "whoami" ), "\n", "", "g" ) endif else let l:userid = g:sqlplus_userid endif let g:sqlplus_userid = input( "Please enter your SQL*Plus user-id: ", l:userid ) let g:sqlplus_passwd = inputsecret( "Please enter your SQL*Plus password: " ) let g:sqlplus_db = input( "Please enter your database name: ", g:sqlplus_db ) endif endfunction "}}} function! AE_configureOutputWindow() "{{{1 set ts=8 buftype=nofile nowrap sidescroll=5 listchars+=precedes:<,extends:> normal $G while getline(".") == "" normal dd endwhile normal 1G let l:newheight = line("$") if l:newheight < winheight(0) exe "resize " . l:newheight endif endfunction "}}} function! AE_configureSqlBuffer() "{{{1 set syn=sql endfunction "}}} function! AE_describeTable( tableName ) "{{{1 let l:cmd = "prompt DESCRIBING TABLE '" . a:tableName . "'\ndesc " . a:tableName call AE_execQuery( l:cmd ) endfunction "}}} function! AE_describeTableUnderCursor() "{{{1 normal viw"zy call AE_describeTable( @z ) endfunction "}}} function! AE_describeTablePrompt() "{{{1 let l:tablename = input( "Please enter the name of the table to describe: " ) call AE_describeTable( l:tablename ) endfunction "}}} function! AE_execQuery( sql_query ) "{{{1 call AE_getSQLPlusUIDandPasswd( 0 ) new let l:tmpfile = tempname() . ".sql" let l:oldo = @o let @o="i" . g:sqlplus_common_commands . a:sql_query let l:pos = match( @o, ";$" ) if l:pos < 0 let @o=@o . ";" endif let @o=@o . "\n" normal @o let @o=l:oldo exe "silent write " . l:tmpfile close new let l:cmd = g:sqlplus_path . g:sqlplus_userid . "/" . g:sqlplus_passwd . "@" . g:sqlplus_db let l:cmd = l:cmd . " @" . l:tmpfile exe "1,$!" . l:cmd call AE_configureOutputWindow() call delete( l:tmpfile ) endfunction "}}} function! AE_promptQuery() "{{{1 let l:sqlquery = input( "SQL Query: " ) call AE_execQuery( l:sqlquery ) endfunction "}}} function! AE_resetPassword() "{{{1 let g:sqlplus_userid = "" let g:sqlplus_passwd = "" endfunction "}}} function! AE_execLiteralQuery( sql_query ) "{{{1 let l:query = substitute( a:sql_query, '\c\<INTO\>.*\<FROM\>', 'FROM', 'g' ) let l:idx = stridx( l:query, "\n" ) while l:idx >= 0 let l:query = strpart( l:query, 0, l:idx ) . " " . strpart( l:query, l:idx+1 ) let l:idx = stridx( l:query, "\n" ) endwhile let l:var = matchstr( l:query, ':\h\w*' ) while l:var > "" let l:var_val = input( "Enter value for " . strpart( l:var, 1 ) . ": " ) let l:query = substitute( l:query, l:var . '\>', l:var_val, 'g' ) let l:var = matchstr( l:query, ':\h\w*' ) endwhile call AE_execQuery( l:query ) endfunction "}}} function! AE_execQueryUnderCursor() "{{{1 exe "silent norm! ?\\c[^.]*\\<\\(select\\|update\\|delete\\)\\>\nv/;\nh\"zy" noh call AE_execLiteralQuery( @z ) endfunction "}}} function! AE_execWholeScript() "{{{1 "exe "silent norm! :%y z" exe "%y z" call AE_getSQLPlusUIDandPasswd( 0 ) new let l:tmpfile = tempname() . ".sql" let @z="i" . @z . "\n" normal @z exe "silent write " . l:tmpfile close new let l:cmd = g:sqlplus_path . g:sqlplus_userid . "/" . g:sqlplus_passwd . "@" . g:sqlplus_db let l:cmd = l:cmd . " @" . l:tmpfile exe "1,$!" . l:cmd call AE_configureOutputWindow() call delete( l:tmpfile ) endfunction "}}} function! AE_openSqlBuffer( fname ) "{{{1 exe "new " . a:fname call AE_configureSqlBuffer() endfunction "}}} function! AE_openEmptySqlBuffer() "{{{1 call AE_openSqlBuffer( "" ) endfunction "}}} " command-mode mappings {{{1 "" 05-09-2013 ## GVIM74 Mapping key crash when Load Awk/Perl support - change 's*' to 'sq*'## "" map <Leader>sb :call AE_openEmptySqlBuffer()<CR> "" map <Leader>ss "zyy:call AE_execLiteralQuery( @z )<CR> "" map <Leader>se :call AE_execQueryUnderCursor()<CR> "" map <Leader>st :call AE_describeTableUnderCursor()<CR> "" exe "map <Leader>sc :call AE_openSqlBuffer( \"" . g:sqlplus_common_buffer . "\" )<CR>" "" 05-09-2013 ## GVIM74 Mapping key crash when Load Awk/Perl support - change 's*' to '*s*'## map <Leader>bsb :call AE_openEmptySqlBuffer()<CR> map <Leader>sss "zyy:call AE_execLiteralQuery( @z )<CR> map <Leader>ese :call AE_execQueryUnderCursor()<CR> map <Leader>tst :call AE_describeTableUnderCursor()<CR> exe "map <Leader>csc :call AE_openSqlBuffer( \"" . g:sqlplus_common_buffer . "\" )<CR>" map <C-F7> :call AE_execWholeScript()<CR> map <C-F8> :call AE_execQueryUnderCursor()<CR> map <Leader><C-F8> :call AE_promptQuery()<CR> map <C-F9> :call AE_describeTableUnderCursor()<CR> map <C-F10> :call AE_describeTablePrompt()<CR> map <C-F11> :call AE_getSQLPlusUIDandPasswd(1)<CR> "}}} " visual mode mappings {{{1 vmap <F8> "zy:call AE_execLiteralQuery( @z )<CR> "}}} " commands {{{1 command! -nargs=+ Select :call AE_execQuery( "select <a>" ) command! -nargs=+ Update :call AE_execQuery( "update <a>" ) command! -nargs=+ Delete :call AE_execQuery( "delete <a>" ) command! -nargs=1 DB :let g:sqlplus_db="<args>" command! -nargs=? SQL :call AE_openSqlBuffer( "<args>" ) :menu Oracle.Execute\ whole\ script<Tab>^F7 :call AE_execWholeScript()<CR> :menu Oracle.Execute\ query\ under\ cursor<Tab>^F8 :call AE_execQueryUnderCursor()<CR> :menu Oracle.Prompt\ for\ query<Tab>\\^F8 :call AE_promptQuery()<CR> :menu Oracle.Describe\ table\ under\ cursor<Tab>^F09 :call AE_describeTableUnderCursor()<CR> :menu Oracle.Prompt\ for\ table\ to\ describe<Tab>^F10 :call AE_describeTablePrompt()<CR> :menu Oracle.Change\ connect\ information<Tab>^F11 :call AE_getSQLPlusUIDandPasswd(1)<CR> "}}}
00000svn-vim-cfg
trunk/vimfiles/plugin/sqlplus.vim
Vim Script
gpl3
9,693
" ============================================================================ " File: NERD_tree.vim " Description: vim global plugin that provides a nice tree explorer " Maintainer: Martin Grenfell <martin.grenfell at gmail dot com> " Last Change: 28 December, 2011 " License: This program is free software. It comes without any warranty, " to the extent permitted by applicable law. You can redistribute " it and/or modify it under the terms of the Do What The Fuck You " Want To Public License, Version 2, as published by Sam Hocevar. " See http://sam.zoy.org/wtfpl/COPYING for more details. " " ============================================================================ let s:NERD_tree_version = '4.2.0' " SECTION: Script init stuff {{{1 "============================================================ if exists("loaded_nerd_tree") finish endif if v:version < 700 echoerr "NERDTree: this plugin requires vim >= 7. DOWNLOAD IT! You'll thank me later!" finish endif let loaded_nerd_tree = 1 "for line continuation - i.e dont want C in &cpo let s:old_cpo = &cpo set cpo&vim let s:running_windows = has("win16") || has("win32") || has("win64") "Function: s:initVariable() function {{{2 "This function is used to initialise a given variable to a given value. The "variable is only initialised if it does not exist prior " "Args: "var: the name of the var to be initialised "value: the value to initialise var to " "Returns: "1 if the var is set, 0 otherwise function! s:initVariable(var, value) if !exists(a:var) exec 'let ' . a:var . ' = ' . "'" . substitute(a:value, "'", "''", "g") . "'" return 1 endif return 0 endfunction "SECTION: Init variable calls and other random constants {{{2 call s:initVariable("g:NERDChristmasTree", 1) call s:initVariable("g:NERDTreeAutoCenter", 1) call s:initVariable("g:NERDTreeAutoCenterThreshold", 3) call s:initVariable("g:NERDTreeCaseSensitiveSort", 0) call s:initVariable("g:NERDTreeChDirMode", 0) call s:initVariable("g:NERDTreeMinimalUI", 0) if !exists("g:NERDTreeIgnore") let g:NERDTreeIgnore = ['\~$'] endif call s:initVariable("g:NERDTreeBookmarksFile", expand('$HOME') . '/.NERDTreeBookmarks') call s:initVariable("g:NERDTreeHighlightCursorline", 1) call s:initVariable("g:NERDTreeHijackNetrw", 1) call s:initVariable("g:NERDTreeMouseMode", 1) call s:initVariable("g:NERDTreeNotificationThreshold", 100) call s:initVariable("g:NERDTreeQuitOnOpen", 0) call s:initVariable("g:NERDTreeShowBookmarks", 0) call s:initVariable("g:NERDTreeShowFiles", 1) call s:initVariable("g:NERDTreeShowHidden", 0) call s:initVariable("g:NERDTreeShowLineNumbers", 0) call s:initVariable("g:NERDTreeSortDirs", 1) call s:initVariable("g:NERDTreeDirArrows", !s:running_windows) if !exists("g:NERDTreeSortOrder") let g:NERDTreeSortOrder = ['\/$', '*', '\.swp$', '\.bak$', '\~$'] else "if there isnt a * in the sort sequence then add one if count(g:NERDTreeSortOrder, '*') < 1 call add(g:NERDTreeSortOrder, '*') endif endif "we need to use this number many times for sorting... so we calculate it only "once here let s:NERDTreeSortStarIndex = index(g:NERDTreeSortOrder, '*') if !exists('g:NERDTreeStatusline') "the exists() crap here is a hack to stop vim spazzing out when "loading a session that was created with an open nerd tree. It spazzes "because it doesnt store b:NERDTreeRoot (its a b: var, and its a hash) let g:NERDTreeStatusline = "%{exists('b:NERDTreeRoot')?b:NERDTreeRoot.path.str():''}" endif call s:initVariable("g:NERDTreeWinPos", "left") call s:initVariable("g:NERDTreeWinSize", 31) "init the shell commands that will be used to copy nodes, and remove dir trees " "Note: the space after the command is important if s:running_windows call s:initVariable("g:NERDTreeRemoveDirCmd", 'rmdir /s /q ') else call s:initVariable("g:NERDTreeRemoveDirCmd", 'rm -rf ') call s:initVariable("g:NERDTreeCopyCmd", 'cp -r ') endif "SECTION: Init variable calls for key mappings {{{2 call s:initVariable("g:NERDTreeMapActivateNode", "o") call s:initVariable("g:NERDTreeMapChangeRoot", "C") call s:initVariable("g:NERDTreeMapChdir", "cd") call s:initVariable("g:NERDTreeMapCloseChildren", "X") call s:initVariable("g:NERDTreeMapCloseDir", "x") call s:initVariable("g:NERDTreeMapDeleteBookmark", "D") call s:initVariable("g:NERDTreeMapMenu", "m") call s:initVariable("g:NERDTreeMapHelp", "?") call s:initVariable("g:NERDTreeMapJumpFirstChild", "K") call s:initVariable("g:NERDTreeMapJumpLastChild", "J") call s:initVariable("g:NERDTreeMapJumpNextSibling", "<C-j>") call s:initVariable("g:NERDTreeMapJumpParent", "p") call s:initVariable("g:NERDTreeMapJumpPrevSibling", "<C-k>") call s:initVariable("g:NERDTreeMapJumpRoot", "P") call s:initVariable("g:NERDTreeMapOpenExpl", "e") call s:initVariable("g:NERDTreeMapOpenInTab", "t") call s:initVariable("g:NERDTreeMapOpenInTabSilent", "T") call s:initVariable("g:NERDTreeMapOpenRecursively", "O") call s:initVariable("g:NERDTreeMapOpenSplit", "i") call s:initVariable("g:NERDTreeMapOpenVSplit", "s") call s:initVariable("g:NERDTreeMapPreview", "g" . NERDTreeMapActivateNode) call s:initVariable("g:NERDTreeMapPreviewSplit", "g" . NERDTreeMapOpenSplit) call s:initVariable("g:NERDTreeMapPreviewVSplit", "g" . NERDTreeMapOpenVSplit) call s:initVariable("g:NERDTreeMapQuit", "q") call s:initVariable("g:NERDTreeMapRefresh", "r") call s:initVariable("g:NERDTreeMapRefreshRoot", "R") call s:initVariable("g:NERDTreeMapToggleBookmarks", "B") call s:initVariable("g:NERDTreeMapToggleFiles", "F") call s:initVariable("g:NERDTreeMapToggleFilters", "f") call s:initVariable("g:NERDTreeMapToggleHidden", "I") call s:initVariable("g:NERDTreeMapToggleZoom", "A") call s:initVariable("g:NERDTreeMapUpdir", "u") call s:initVariable("g:NERDTreeMapUpdirKeepOpen", "U") "SECTION: Script level variable declaration{{{2 if s:running_windows let s:escape_chars = " `\|\"#%&,?()\*^<>" else let s:escape_chars = " \\`\|\"#%&,?()\*^<>[]" endif let s:NERDTreeBufName = 'NERD_tree_' let s:tree_wid = 2 let s:tree_markup_reg = '^[ `|]*[\-+~▾▸ ]\+' let s:tree_up_dir_line = '.. (up a dir)' "the number to add to the nerd tree buffer name to make the buf name unique let s:next_buffer_number = 1 " SECTION: Commands {{{1 "============================================================ "init the command that users start the nerd tree with command! -n=? -complete=dir -bar NERDTree :call s:initNerdTree('<args>') command! -n=? -complete=dir -bar NERDTreeToggle :call s:toggle('<args>') command! -n=0 -bar NERDTreeClose :call s:closeTreeIfOpen() command! -n=1 -complete=customlist,s:completeBookmarks -bar NERDTreeFromBookmark call s:initNerdTree('<args>') command! -n=0 -bar NERDTreeMirror call s:initNerdTreeMirror() command! -n=0 -bar NERDTreeFind call s:findAndRevealPath() " SECTION: Auto commands {{{1 "============================================================ augroup NERDTree "Save the cursor position whenever we close the nerd tree exec "autocmd BufWinLeave ". s:NERDTreeBufName ."* call <SID>saveScreenState()" "disallow insert mode in the NERDTree exec "autocmd BufEnter ". s:NERDTreeBufName ."* stopinsert" "cache bookmarks when vim loads autocmd VimEnter * call s:Bookmark.CacheBookmarks(0) "load all nerdtree plugins after vim starts autocmd VimEnter * runtime! nerdtree_plugin/**/*.vim augroup END if g:NERDTreeHijackNetrw augroup NERDTreeHijackNetrw autocmd VimEnter * silent! autocmd! FileExplorer au BufEnter,VimEnter * call s:checkForBrowse(expand("<amatch>")) augroup END endif "SECTION: Classes {{{1 "============================================================ "CLASS: Bookmark {{{2 "============================================================ let s:Bookmark = {} " FUNCTION: Bookmark.activate() {{{3 function! s:Bookmark.activate() if self.path.isDirectory call self.toRoot() else if self.validate() let n = s:TreeFileNode.New(self.path) call n.open() call s:closeTreeIfQuitOnOpen() endif endif endfunction " FUNCTION: Bookmark.AddBookmark(name, path) {{{3 " Class method to add a new bookmark to the list, if a previous bookmark exists " with the same name, just update the path for that bookmark function! s:Bookmark.AddBookmark(name, path) for i in s:Bookmark.Bookmarks() if i.name ==# a:name let i.path = a:path return endif endfor call add(s:Bookmark.Bookmarks(), s:Bookmark.New(a:name, a:path)) call s:Bookmark.Sort() endfunction " Function: Bookmark.Bookmarks() {{{3 " Class method to get all bookmarks. Lazily initializes the bookmarks global " variable function! s:Bookmark.Bookmarks() if !exists("g:NERDTreeBookmarks") let g:NERDTreeBookmarks = [] endif return g:NERDTreeBookmarks endfunction " Function: Bookmark.BookmarkExistsFor(name) {{{3 " class method that returns 1 if a bookmark with the given name is found, 0 " otherwise function! s:Bookmark.BookmarkExistsFor(name) try call s:Bookmark.BookmarkFor(a:name) return 1 catch /^NERDTree.BookmarkNotFoundError/ return 0 endtry endfunction " Function: Bookmark.BookmarkFor(name) {{{3 " Class method to get the bookmark that has the given name. {} is return if no " bookmark is found function! s:Bookmark.BookmarkFor(name) for i in s:Bookmark.Bookmarks() if i.name ==# a:name return i endif endfor throw "NERDTree.BookmarkNotFoundError: no bookmark found for name: \"". a:name .'"' endfunction " Function: Bookmark.BookmarkNames() {{{3 " Class method to return an array of all bookmark names function! s:Bookmark.BookmarkNames() let names = [] for i in s:Bookmark.Bookmarks() call add(names, i.name) endfor return names endfunction " FUNCTION: Bookmark.CacheBookmarks(silent) {{{3 " Class method to read all bookmarks from the bookmarks file intialize " bookmark objects for each one. " " Args: " silent - dont echo an error msg if invalid bookmarks are found function! s:Bookmark.CacheBookmarks(silent) if filereadable(g:NERDTreeBookmarksFile) let g:NERDTreeBookmarks = [] let g:NERDTreeInvalidBookmarks = [] let bookmarkStrings = readfile(g:NERDTreeBookmarksFile) let invalidBookmarksFound = 0 for i in bookmarkStrings "ignore blank lines if i != '' let name = substitute(i, '^\(.\{-}\) .*$', '\1', '') let path = substitute(i, '^.\{-} \(.*\)$', '\1', '') try let bookmark = s:Bookmark.New(name, s:Path.New(path)) call add(g:NERDTreeBookmarks, bookmark) catch /^NERDTree.InvalidArgumentsError/ call add(g:NERDTreeInvalidBookmarks, i) let invalidBookmarksFound += 1 endtry endif endfor if invalidBookmarksFound call s:Bookmark.Write() if !a:silent call s:echo(invalidBookmarksFound . " invalid bookmarks were read. See :help NERDTreeInvalidBookmarks for info.") endif endif call s:Bookmark.Sort() endif endfunction " FUNCTION: Bookmark.compareTo(otherbookmark) {{{3 " Compare these two bookmarks for sorting purposes function! s:Bookmark.compareTo(otherbookmark) return a:otherbookmark.name < self.name endfunction " FUNCTION: Bookmark.ClearAll() {{{3 " Class method to delete all bookmarks. function! s:Bookmark.ClearAll() for i in s:Bookmark.Bookmarks() call i.delete() endfor call s:Bookmark.Write() endfunction " FUNCTION: Bookmark.delete() {{{3 " Delete this bookmark. If the node for this bookmark is under the current " root, then recache bookmarks for its Path object function! s:Bookmark.delete() let node = {} try let node = self.getNode(1) catch /^NERDTree.BookmarkedNodeNotFoundError/ endtry call remove(s:Bookmark.Bookmarks(), index(s:Bookmark.Bookmarks(), self)) if !empty(node) call node.path.cacheDisplayString() endif call s:Bookmark.Write() endfunction " FUNCTION: Bookmark.getNode(searchFromAbsoluteRoot) {{{3 " Gets the treenode for this bookmark " " Args: " searchFromAbsoluteRoot: specifies whether we should search from the current " tree root, or the highest cached node function! s:Bookmark.getNode(searchFromAbsoluteRoot) let searchRoot = a:searchFromAbsoluteRoot ? s:TreeDirNode.AbsoluteTreeRoot() : b:NERDTreeRoot let targetNode = searchRoot.findNode(self.path) if empty(targetNode) throw "NERDTree.BookmarkedNodeNotFoundError: no node was found for bookmark: " . self.name endif return targetNode endfunction " FUNCTION: Bookmark.GetNodeForName(name, searchFromAbsoluteRoot) {{{3 " Class method that finds the bookmark with the given name and returns the " treenode for it. function! s:Bookmark.GetNodeForName(name, searchFromAbsoluteRoot) let bookmark = s:Bookmark.BookmarkFor(a:name) return bookmark.getNode(a:searchFromAbsoluteRoot) endfunction " FUNCTION: Bookmark.GetSelected() {{{3 " returns the Bookmark the cursor is over, or {} function! s:Bookmark.GetSelected() let line = getline(".") let name = substitute(line, '^>\(.\{-}\) .\+$', '\1', '') if name != line try return s:Bookmark.BookmarkFor(name) catch /^NERDTree.BookmarkNotFoundError/ return {} endtry endif return {} endfunction " Function: Bookmark.InvalidBookmarks() {{{3 " Class method to get all invalid bookmark strings read from the bookmarks " file function! s:Bookmark.InvalidBookmarks() if !exists("g:NERDTreeInvalidBookmarks") let g:NERDTreeInvalidBookmarks = [] endif return g:NERDTreeInvalidBookmarks endfunction " FUNCTION: Bookmark.mustExist() {{{3 function! s:Bookmark.mustExist() if !self.path.exists() call s:Bookmark.CacheBookmarks(1) throw "NERDTree.BookmarkPointsToInvalidLocationError: the bookmark \"". \ self.name ."\" points to a non existing location: \"". self.path.str() endif endfunction " FUNCTION: Bookmark.New(name, path) {{{3 " Create a new bookmark object with the given name and path object function! s:Bookmark.New(name, path) if a:name =~# ' ' throw "NERDTree.IllegalBookmarkNameError: illegal name:" . a:name endif let newBookmark = copy(self) let newBookmark.name = a:name let newBookmark.path = a:path return newBookmark endfunction " FUNCTION: Bookmark.openInNewTab(options) {{{3 " Create a new bookmark object with the given name and path object function! s:Bookmark.openInNewTab(options) let currentTab = tabpagenr() if self.path.isDirectory tabnew call s:initNerdTree(self.name) else exec "tabedit " . self.path.str({'format': 'Edit'}) endif if has_key(a:options, 'stayInCurrentTab') exec "tabnext " . currentTab endif endfunction " Function: Bookmark.setPath(path) {{{3 " makes this bookmark point to the given path function! s:Bookmark.setPath(path) let self.path = a:path endfunction " Function: Bookmark.Sort() {{{3 " Class method that sorts all bookmarks function! s:Bookmark.Sort() let CompareFunc = function("s:compareBookmarks") call sort(s:Bookmark.Bookmarks(), CompareFunc) endfunction " Function: Bookmark.str() {{{3 " Get the string that should be rendered in the view for this bookmark function! s:Bookmark.str() let pathStrMaxLen = winwidth(s:getTreeWinNum()) - 4 - len(self.name) if &nu let pathStrMaxLen = pathStrMaxLen - &numberwidth endif let pathStr = self.path.str({'format': 'UI'}) if len(pathStr) > pathStrMaxLen let pathStr = '<' . strpart(pathStr, len(pathStr) - pathStrMaxLen) endif return '>' . self.name . ' ' . pathStr endfunction " FUNCTION: Bookmark.toRoot() {{{3 " Make the node for this bookmark the new tree root function! s:Bookmark.toRoot() if self.validate() try let targetNode = self.getNode(1) catch /^NERDTree.BookmarkedNodeNotFoundError/ let targetNode = s:TreeFileNode.New(s:Bookmark.BookmarkFor(self.name).path) endtry call targetNode.makeRoot() call s:renderView() call targetNode.putCursorHere(0, 0) endif endfunction " FUNCTION: Bookmark.ToRoot(name) {{{3 " Make the node for this bookmark the new tree root function! s:Bookmark.ToRoot(name) let bookmark = s:Bookmark.BookmarkFor(a:name) call bookmark.toRoot() endfunction "FUNCTION: Bookmark.validate() {{{3 function! s:Bookmark.validate() if self.path.exists() return 1 else call s:Bookmark.CacheBookmarks(1) call s:renderView() call s:echo(self.name . "now points to an invalid location. See :help NERDTreeInvalidBookmarks for info.") return 0 endif endfunction " Function: Bookmark.Write() {{{3 " Class method to write all bookmarks to the bookmarks file function! s:Bookmark.Write() let bookmarkStrings = [] for i in s:Bookmark.Bookmarks() call add(bookmarkStrings, i.name . ' ' . i.path.str()) endfor "add a blank line before the invalid ones call add(bookmarkStrings, "") for j in s:Bookmark.InvalidBookmarks() call add(bookmarkStrings, j) endfor call writefile(bookmarkStrings, g:NERDTreeBookmarksFile) endfunction "CLASS: KeyMap {{{2 "============================================================ let s:KeyMap = {} "FUNCTION: KeyMap.All() {{{3 function! s:KeyMap.All() if !exists("s:keyMaps") let s:keyMaps = [] endif return s:keyMaps endfunction "FUNCTION: KeyMap.BindAll() {{{3 function! s:KeyMap.BindAll() for i in s:KeyMap.All() call i.bind() endfor endfunction "FUNCTION: KeyMap.bind() {{{3 function! s:KeyMap.bind() exec "nnoremap <silent> <buffer> ". self.key ." :call ". self.callback ."()<cr>" endfunction "FUNCTION: KeyMap.Create(options) {{{3 function! s:KeyMap.Create(options) let newKeyMap = copy(self) let newKeyMap.key = a:options['key'] let newKeyMap.quickhelpText = a:options['quickhelpText'] let newKeyMap.callback = a:options['callback'] call add(s:KeyMap.All(), newKeyMap) endfunction "CLASS: MenuController {{{2 "============================================================ let s:MenuController = {} "FUNCTION: MenuController.New(menuItems) {{{3 "create a new menu controller that operates on the given menu items function! s:MenuController.New(menuItems) let newMenuController = copy(self) if a:menuItems[0].isSeparator() let newMenuController.menuItems = a:menuItems[1:-1] else let newMenuController.menuItems = a:menuItems endif return newMenuController endfunction "FUNCTION: MenuController.showMenu() {{{3 "start the main loop of the menu and get the user to choose/execute a menu "item function! s:MenuController.showMenu() call self._saveOptions() try let self.selection = 0 let done = 0 while !done redraw! call self._echoPrompt() let key = nr2char(getchar()) let done = self._handleKeypress(key) endwhile finally call self._restoreOptions() endtry if self.selection != -1 let m = self._current() call m.execute() endif endfunction "FUNCTION: MenuController._echoPrompt() {{{3 function! s:MenuController._echoPrompt() echo "NERDTree Menu. Use j/k/enter and the shortcuts indicated" echo "==========================================================" for i in range(0, len(self.menuItems)-1) if self.selection == i echo "> " . self.menuItems[i].text else echo " " . self.menuItems[i].text endif endfor endfunction "FUNCTION: MenuController._current(key) {{{3 "get the MenuItem that is currently selected function! s:MenuController._current() return self.menuItems[self.selection] endfunction "FUNCTION: MenuController._handleKeypress(key) {{{3 "change the selection (if appropriate) and return 1 if the user has made "their choice, 0 otherwise function! s:MenuController._handleKeypress(key) if a:key == 'j' call self._cursorDown() elseif a:key == 'k' call self._cursorUp() elseif a:key == nr2char(27) "escape let self.selection = -1 return 1 elseif a:key == "\r" || a:key == "\n" "enter and ctrl-j return 1 else let index = self._nextIndexFor(a:key) if index != -1 let self.selection = index if len(self._allIndexesFor(a:key)) == 1 return 1 endif endif endif return 0 endfunction "FUNCTION: MenuController._allIndexesFor(shortcut) {{{3 "get indexes to all menu items with the given shortcut function! s:MenuController._allIndexesFor(shortcut) let toReturn = [] for i in range(0, len(self.menuItems)-1) if self.menuItems[i].shortcut == a:shortcut call add(toReturn, i) endif endfor return toReturn endfunction "FUNCTION: MenuController._nextIndexFor(shortcut) {{{3 "get the index to the next menu item with the given shortcut, starts from the "current cursor location and wraps around to the top again if need be function! s:MenuController._nextIndexFor(shortcut) for i in range(self.selection+1, len(self.menuItems)-1) if self.menuItems[i].shortcut == a:shortcut return i endif endfor for i in range(0, self.selection) if self.menuItems[i].shortcut == a:shortcut return i endif endfor return -1 endfunction "FUNCTION: MenuController._setCmdheight() {{{3 "sets &cmdheight to whatever is needed to display the menu function! s:MenuController._setCmdheight() let &cmdheight = len(self.menuItems) + 3 endfunction "FUNCTION: MenuController._saveOptions() {{{3 "set any vim options that are required to make the menu work (saving their old "values) function! s:MenuController._saveOptions() let self._oldLazyredraw = &lazyredraw let self._oldCmdheight = &cmdheight set nolazyredraw call self._setCmdheight() endfunction "FUNCTION: MenuController._restoreOptions() {{{3 "restore the options we saved in _saveOptions() function! s:MenuController._restoreOptions() let &cmdheight = self._oldCmdheight let &lazyredraw = self._oldLazyredraw endfunction "FUNCTION: MenuController._cursorDown() {{{3 "move the cursor to the next menu item, skipping separators function! s:MenuController._cursorDown() let done = 0 while !done if self.selection < len(self.menuItems)-1 let self.selection += 1 else let self.selection = 0 endif if !self._current().isSeparator() let done = 1 endif endwhile endfunction "FUNCTION: MenuController._cursorUp() {{{3 "move the cursor to the previous menu item, skipping separators function! s:MenuController._cursorUp() let done = 0 while !done if self.selection > 0 let self.selection -= 1 else let self.selection = len(self.menuItems)-1 endif if !self._current().isSeparator() let done = 1 endif endwhile endfunction "CLASS: MenuItem {{{2 "============================================================ let s:MenuItem = {} "FUNCTION: MenuItem.All() {{{3 "get all top level menu items function! s:MenuItem.All() if !exists("s:menuItems") let s:menuItems = [] endif return s:menuItems endfunction "FUNCTION: MenuItem.AllEnabled() {{{3 "get all top level menu items that are currently enabled function! s:MenuItem.AllEnabled() let toReturn = [] for i in s:MenuItem.All() if i.enabled() call add(toReturn, i) endif endfor return toReturn endfunction "FUNCTION: MenuItem.Create(options) {{{3 "make a new menu item and add it to the global list function! s:MenuItem.Create(options) let newMenuItem = copy(self) let newMenuItem.text = a:options['text'] let newMenuItem.shortcut = a:options['shortcut'] let newMenuItem.children = [] let newMenuItem.isActiveCallback = -1 if has_key(a:options, 'isActiveCallback') let newMenuItem.isActiveCallback = a:options['isActiveCallback'] endif let newMenuItem.callback = -1 if has_key(a:options, 'callback') let newMenuItem.callback = a:options['callback'] endif if has_key(a:options, 'parent') call add(a:options['parent'].children, newMenuItem) else call add(s:MenuItem.All(), newMenuItem) endif return newMenuItem endfunction "FUNCTION: MenuItem.CreateSeparator(options) {{{3 "make a new separator menu item and add it to the global list function! s:MenuItem.CreateSeparator(options) let standard_options = { 'text': '--------------------', \ 'shortcut': -1, \ 'callback': -1 } let options = extend(a:options, standard_options, "force") return s:MenuItem.Create(options) endfunction "FUNCTION: MenuItem.CreateSubmenu(options) {{{3 "make a new submenu and add it to global list function! s:MenuItem.CreateSubmenu(options) let standard_options = { 'callback': -1 } let options = extend(a:options, standard_options, "force") return s:MenuItem.Create(options) endfunction "FUNCTION: MenuItem.enabled() {{{3 "return 1 if this menu item should be displayed " "delegates off to the isActiveCallback, and defaults to 1 if no callback was "specified function! s:MenuItem.enabled() if self.isActiveCallback != -1 return {self.isActiveCallback}() endif return 1 endfunction "FUNCTION: MenuItem.execute() {{{3 "perform the action behind this menu item, if this menuitem has children then "display a new menu for them, otherwise deletegate off to the menuitem's "callback function! s:MenuItem.execute() if len(self.children) let mc = s:MenuController.New(self.children) call mc.showMenu() else if self.callback != -1 call {self.callback}() endif endif endfunction "FUNCTION: MenuItem.isSeparator() {{{3 "return 1 if this menuitem is a separator function! s:MenuItem.isSeparator() return self.callback == -1 && self.children == [] endfunction "FUNCTION: MenuItem.isSubmenu() {{{3 "return 1 if this menuitem is a submenu function! s:MenuItem.isSubmenu() return self.callback == -1 && !empty(self.children) endfunction "CLASS: TreeFileNode {{{2 "This class is the parent of the TreeDirNode class and constitures the "'Component' part of the composite design pattern between the treenode "classes. "============================================================ let s:TreeFileNode = {} "FUNCTION: TreeFileNode.activate(forceKeepWinOpen) {{{3 function! s:TreeFileNode.activate(forceKeepWinOpen) call self.open() if !a:forceKeepWinOpen call s:closeTreeIfQuitOnOpen() end endfunction "FUNCTION: TreeFileNode.bookmark(name) {{{3 "bookmark this node with a:name function! s:TreeFileNode.bookmark(name) "if a bookmark exists with the same name and the node is cached then save "it so we can update its display string let oldMarkedNode = {} try let oldMarkedNode = s:Bookmark.GetNodeForName(a:name, 1) catch /^NERDTree.BookmarkNotFoundError/ catch /^NERDTree.BookmarkedNodeNotFoundError/ endtry call s:Bookmark.AddBookmark(a:name, self.path) call self.path.cacheDisplayString() call s:Bookmark.Write() if !empty(oldMarkedNode) call oldMarkedNode.path.cacheDisplayString() endif endfunction "FUNCTION: TreeFileNode.cacheParent() {{{3 "initializes self.parent if it isnt already function! s:TreeFileNode.cacheParent() if empty(self.parent) let parentPath = self.path.getParent() if parentPath.equals(self.path) throw "NERDTree.CannotCacheParentError: already at root" endif let self.parent = s:TreeFileNode.New(parentPath) endif endfunction "FUNCTION: TreeFileNode.compareNodes {{{3 "This is supposed to be a class level method but i cant figure out how to "get func refs to work from a dict.. " "A class level method that compares two nodes " "Args: "n1, n2: the 2 nodes to compare function! s:compareNodes(n1, n2) return a:n1.path.compareTo(a:n2.path) endfunction "FUNCTION: TreeFileNode.clearBoomarks() {{{3 function! s:TreeFileNode.clearBoomarks() for i in s:Bookmark.Bookmarks() if i.path.equals(self.path) call i.delete() end endfor call self.path.cacheDisplayString() endfunction "FUNCTION: TreeFileNode.copy(dest) {{{3 function! s:TreeFileNode.copy(dest) call self.path.copy(a:dest) let newPath = s:Path.New(a:dest) let parent = b:NERDTreeRoot.findNode(newPath.getParent()) if !empty(parent) call parent.refresh() return parent.findNode(newPath) else return {} endif endfunction "FUNCTION: TreeFileNode.delete {{{3 "Removes this node from the tree and calls the Delete method for its path obj function! s:TreeFileNode.delete() call self.path.delete() call self.parent.removeChild(self) endfunction "FUNCTION: TreeFileNode.displayString() {{{3 " "Returns a string that specifies how the node should be represented as a "string " "Return: "a string that can be used in the view to represent this node function! s:TreeFileNode.displayString() return self.path.displayString() endfunction "FUNCTION: TreeFileNode.equals(treenode) {{{3 " "Compares this treenode to the input treenode and returns 1 if they are the "same node. " "Use this method instead of == because sometimes when the treenodes contain "many children, vim seg faults when doing == " "Args: "treenode: the other treenode to compare to function! s:TreeFileNode.equals(treenode) return self.path.str() ==# a:treenode.path.str() endfunction "FUNCTION: TreeFileNode.findNode(path) {{{3 "Returns self if this node.path.Equals the given path. "Returns {} if not equal. " "Args: "path: the path object to compare against function! s:TreeFileNode.findNode(path) if a:path.equals(self.path) return self endif return {} endfunction "FUNCTION: TreeFileNode.findOpenDirSiblingWithVisibleChildren(direction) {{{3 " "Finds the next sibling for this node in the indicated direction. This sibling "must be a directory and may/may not have children as specified. " "Args: "direction: 0 if you want to find the previous sibling, 1 for the next sibling " "Return: "a treenode object or {} if no appropriate sibling could be found function! s:TreeFileNode.findOpenDirSiblingWithVisibleChildren(direction) "if we have no parent then we can have no siblings if self.parent != {} let nextSibling = self.findSibling(a:direction) while nextSibling != {} if nextSibling.path.isDirectory && nextSibling.hasVisibleChildren() && nextSibling.isOpen return nextSibling endif let nextSibling = nextSibling.findSibling(a:direction) endwhile endif return {} endfunction "FUNCTION: TreeFileNode.findSibling(direction) {{{3 " "Finds the next sibling for this node in the indicated direction " "Args: "direction: 0 if you want to find the previous sibling, 1 for the next sibling " "Return: "a treenode object or {} if no sibling could be found function! s:TreeFileNode.findSibling(direction) "if we have no parent then we can have no siblings if self.parent != {} "get the index of this node in its parents children let siblingIndx = self.parent.getChildIndex(self.path) if siblingIndx != -1 "move a long to the next potential sibling node let siblingIndx = a:direction ==# 1 ? siblingIndx+1 : siblingIndx-1 "keep moving along to the next sibling till we find one that is valid let numSiblings = self.parent.getChildCount() while siblingIndx >= 0 && siblingIndx < numSiblings "if the next node is not an ignored node (i.e. wont show up in the "view) then return it if self.parent.children[siblingIndx].path.ignore() ==# 0 return self.parent.children[siblingIndx] endif "go to next node let siblingIndx = a:direction ==# 1 ? siblingIndx+1 : siblingIndx-1 endwhile endif endif return {} endfunction "FUNCTION: TreeFileNode.getLineNum(){{{3 "returns the line number this node is rendered on, or -1 if it isnt rendered function! s:TreeFileNode.getLineNum() "if the node is the root then return the root line no. if self.isRoot() return s:TreeFileNode.GetRootLineNum() endif let totalLines = line("$") "the path components we have matched so far let pathcomponents = [substitute(b:NERDTreeRoot.path.str({'format': 'UI'}), '/ *$', '', '')] "the index of the component we are searching for let curPathComponent = 1 let fullpath = self.path.str({'format': 'UI'}) let lnum = s:TreeFileNode.GetRootLineNum() while lnum > 0 let lnum = lnum + 1 "have we reached the bottom of the tree? if lnum ==# totalLines+1 return -1 endif let curLine = getline(lnum) let indent = s:indentLevelFor(curLine) if indent ==# curPathComponent let curLine = s:stripMarkupFromLine(curLine, 1) let curPath = join(pathcomponents, '/') . '/' . curLine if stridx(fullpath, curPath, 0) ==# 0 if fullpath ==# curPath || strpart(fullpath, len(curPath)-1,1) ==# '/' let curLine = substitute(curLine, '/ *$', '', '') call add(pathcomponents, curLine) let curPathComponent = curPathComponent + 1 if fullpath ==# curPath return lnum endif endif endif endif endwhile return -1 endfunction "FUNCTION: TreeFileNode.GetRootForTab(){{{3 "get the root node for this tab function! s:TreeFileNode.GetRootForTab() if s:treeExistsForTab() return getbufvar(t:NERDTreeBufName, 'NERDTreeRoot') end return {} endfunction "FUNCTION: TreeFileNode.GetRootLineNum(){{{3 "gets the line number of the root node function! s:TreeFileNode.GetRootLineNum() let rootLine = 1 while getline(rootLine) !~# '^\(/\|<\)' let rootLine = rootLine + 1 endwhile return rootLine endfunction "FUNCTION: TreeFileNode.GetSelected() {{{3 "gets the treenode that the cursor is currently over function! s:TreeFileNode.GetSelected() try let path = s:getPath(line(".")) if path ==# {} return {} endif return b:NERDTreeRoot.findNode(path) catch /NERDTree/ return {} endtry endfunction "FUNCTION: TreeFileNode.isVisible() {{{3 "returns 1 if this node should be visible according to the tree filters and "hidden file filters (and their on/off status) function! s:TreeFileNode.isVisible() return !self.path.ignore() endfunction "FUNCTION: TreeFileNode.isRoot() {{{3 "returns 1 if this node is b:NERDTreeRoot function! s:TreeFileNode.isRoot() if !s:treeExistsForBuf() throw "NERDTree.NoTreeError: No tree exists for the current buffer" endif return self.equals(b:NERDTreeRoot) endfunction "FUNCTION: TreeFileNode.makeRoot() {{{3 "Make this node the root of the tree function! s:TreeFileNode.makeRoot() if self.path.isDirectory let b:NERDTreeRoot = self else call self.cacheParent() let b:NERDTreeRoot = self.parent endif call b:NERDTreeRoot.open() "change dir to the dir of the new root if instructed to if g:NERDTreeChDirMode ==# 2 exec "cd " . b:NERDTreeRoot.path.str({'format': 'Edit'}) endif endfunction "FUNCTION: TreeFileNode.New(path) {{{3 "Returns a new TreeNode object with the given path and parent " "Args: "path: a path object representing the full filesystem path to the file/dir that the node represents function! s:TreeFileNode.New(path) if a:path.isDirectory return s:TreeDirNode.New(a:path) else let newTreeNode = copy(self) let newTreeNode.path = a:path let newTreeNode.parent = {} return newTreeNode endif endfunction "FUNCTION: TreeFileNode.open() {{{3 "Open the file represented by the given node in the current window, splitting "the window if needed " "ARGS: "treenode: file node to open function! s:TreeFileNode.open() if b:NERDTreeType ==# "secondary" exec 'edit ' . self.path.str({'format': 'Edit'}) return endif "if the file is already open in this tab then just stick the cursor in it let winnr = bufwinnr('^' . self.path.str() . '$') if winnr != -1 call s:exec(winnr . "wincmd w") else if !s:isWindowUsable(winnr("#")) && s:firstUsableWindow() ==# -1 call self.openSplit() else try if !s:isWindowUsable(winnr("#")) call s:exec(s:firstUsableWindow() . "wincmd w") else call s:exec('wincmd p') endif exec ("edit " . self.path.str({'format': 'Edit'})) catch /^Vim\%((\a\+)\)\=:E37/ call s:putCursorInTreeWin() throw "NERDTree.FileAlreadyOpenAndModifiedError: ". self.path.str() ." is already open and modified." catch /^Vim\%((\a\+)\)\=:/ echo v:exception endtry endif endif endfunction "FUNCTION: TreeFileNode.openSplit() {{{3 "Open this node in a new window function! s:TreeFileNode.openSplit() if b:NERDTreeType ==# "secondary" exec "split " . self.path.str({'format': 'Edit'}) return endif " Save the user's settings for splitbelow and splitright let savesplitbelow=&splitbelow let savesplitright=&splitright " 'there' will be set to a command to move from the split window " back to the explorer window " " 'back' will be set to a command to move from the explorer window " back to the newly split window " " 'right' and 'below' will be set to the settings needed for " splitbelow and splitright IF the explorer is the only window. " let there= g:NERDTreeWinPos ==# "left" ? "wincmd h" : "wincmd l" let back = g:NERDTreeWinPos ==# "left" ? "wincmd l" : "wincmd h" let right= g:NERDTreeWinPos ==# "left" let below=0 " Attempt to go to adjacent window call s:exec(back) let onlyOneWin = (winnr("$") ==# 1) " If no adjacent window, set splitright and splitbelow appropriately if onlyOneWin let &splitright=right let &splitbelow=below else " found adjacent window - invert split direction let &splitright=!right let &splitbelow=!below endif let splitMode = onlyOneWin ? "vertical" : "" " Open the new window try exec(splitMode." sp " . self.path.str({'format': 'Edit'})) catch /^Vim\%((\a\+)\)\=:E37/ call s:putCursorInTreeWin() throw "NERDTree.FileAlreadyOpenAndModifiedError: ". self.path.str() ." is already open and modified." catch /^Vim\%((\a\+)\)\=:/ "do nothing endtry "resize the tree window if no other window was open before if onlyOneWin let size = exists("b:NERDTreeOldWindowSize") ? b:NERDTreeOldWindowSize : g:NERDTreeWinSize call s:exec(there) exec("silent ". splitMode ." resize ". size) call s:exec('wincmd p') endif " Restore splitmode settings let &splitbelow=savesplitbelow let &splitright=savesplitright endfunction "FUNCTION: TreeFileNode.openVSplit() {{{3 "Open this node in a new vertical window function! s:TreeFileNode.openVSplit() if b:NERDTreeType ==# "secondary" exec "vnew " . self.path.str({'format': 'Edit'}) return endif let winwidth = winwidth(".") if winnr("$")==#1 let winwidth = g:NERDTreeWinSize endif call s:exec("wincmd p") exec "vnew " . self.path.str({'format': 'Edit'}) "resize the nerd tree back to the original size call s:putCursorInTreeWin() exec("silent vertical resize ". winwidth) call s:exec('wincmd p') endfunction "FUNCTION: TreeFileNode.openInNewTab(options) {{{3 function! s:TreeFileNode.openInNewTab(options) let currentTab = tabpagenr() if !has_key(a:options, 'keepTreeOpen') call s:closeTreeIfQuitOnOpen() endif exec "tabedit " . self.path.str({'format': 'Edit'}) if has_key(a:options, 'stayInCurrentTab') && a:options['stayInCurrentTab'] exec "tabnext " . currentTab endif endfunction "FUNCTION: TreeFileNode.putCursorHere(isJump, recurseUpward){{{3 "Places the cursor on the line number this node is rendered on " "Args: "isJump: 1 if this cursor movement should be counted as a jump by vim "recurseUpward: try to put the cursor on the parent if the this node isnt "visible function! s:TreeFileNode.putCursorHere(isJump, recurseUpward) let ln = self.getLineNum() if ln != -1 if a:isJump mark ' endif call cursor(ln, col(".")) else if a:recurseUpward let node = self while node != {} && node.getLineNum() ==# -1 let node = node.parent call node.open() endwhile call s:renderView() call node.putCursorHere(a:isJump, 0) endif endif endfunction "FUNCTION: TreeFileNode.refresh() {{{3 function! s:TreeFileNode.refresh() call self.path.refresh() endfunction "FUNCTION: TreeFileNode.rename() {{{3 "Calls the rename method for this nodes path obj function! s:TreeFileNode.rename(newName) let newName = substitute(a:newName, '\(\\\|\/\)$', '', '') call self.path.rename(newName) call self.parent.removeChild(self) let parentPath = self.path.getParent() let newParent = b:NERDTreeRoot.findNode(parentPath) if newParent != {} call newParent.createChild(self.path, 1) call newParent.refresh() endif endfunction "FUNCTION: TreeFileNode.renderToString {{{3 "returns a string representation for this tree to be rendered in the view function! s:TreeFileNode.renderToString() return self._renderToString(0, 0, [], self.getChildCount() ==# 1) endfunction "Args: "depth: the current depth in the tree for this call "drawText: 1 if we should actually draw the line for this node (if 0 then the "child nodes are rendered only) "vertMap: a binary array that indicates whether a vertical bar should be draw "for each depth in the tree "isLastChild:true if this curNode is the last child of its parent function! s:TreeFileNode._renderToString(depth, drawText, vertMap, isLastChild) let output = "" if a:drawText ==# 1 let treeParts = '' "get all the leading spaces and vertical tree parts for this line if a:depth > 1 for j in a:vertMap[0:-2] if g:NERDTreeDirArrows let treeParts = treeParts . ' ' else if j ==# 1 let treeParts = treeParts . '| ' else let treeParts = treeParts . ' ' endif endif endfor endif "get the last vertical tree part for this line which will be different "if this node is the last child of its parent if !g:NERDTreeDirArrows if a:isLastChild let treeParts = treeParts . '`' else let treeParts = treeParts . '|' endif endif "smack the appropriate dir/file symbol on the line before the file/dir "name itself if self.path.isDirectory if self.isOpen if g:NERDTreeDirArrows let treeParts = treeParts . '▾ ' else let treeParts = treeParts . '~' endif else if g:NERDTreeDirArrows let treeParts = treeParts . '▸ ' else let treeParts = treeParts . '+' endif endif else if g:NERDTreeDirArrows let treeParts = treeParts . ' ' else let treeParts = treeParts . '-' endif endif let line = treeParts . self.displayString() let output = output . line . "\n" endif "if the node is an open dir, draw its children if self.path.isDirectory ==# 1 && self.isOpen ==# 1 let childNodesToDraw = self.getVisibleChildren() if len(childNodesToDraw) > 0 "draw all the nodes children except the last let lastIndx = len(childNodesToDraw)-1 if lastIndx > 0 for i in childNodesToDraw[0:lastIndx-1] let output = output . i._renderToString(a:depth + 1, 1, add(copy(a:vertMap), 1), 0) endfor endif "draw the last child, indicating that it IS the last let output = output . childNodesToDraw[lastIndx]._renderToString(a:depth + 1, 1, add(copy(a:vertMap), 0), 1) endif endif return output endfunction "CLASS: TreeDirNode {{{2 "This class is a child of the TreeFileNode class and constitutes the "'Composite' part of the composite design pattern between the treenode "classes. "============================================================ let s:TreeDirNode = copy(s:TreeFileNode) "FUNCTION: TreeDirNode.AbsoluteTreeRoot(){{{3 "class method that returns the highest cached ancestor of the current root function! s:TreeDirNode.AbsoluteTreeRoot() let currentNode = b:NERDTreeRoot while currentNode.parent != {} let currentNode = currentNode.parent endwhile return currentNode endfunction "FUNCTION: TreeDirNode.activate(forceKeepWinOpen) {{{3 unlet s:TreeDirNode.activate function! s:TreeDirNode.activate(forceKeepWinOpen) call self.toggleOpen() call s:renderView() call self.putCursorHere(0, 0) endfunction "FUNCTION: TreeDirNode.addChild(treenode, inOrder) {{{3 "Adds the given treenode to the list of children for this node " "Args: "-treenode: the node to add "-inOrder: 1 if the new node should be inserted in sorted order function! s:TreeDirNode.addChild(treenode, inOrder) call add(self.children, a:treenode) let a:treenode.parent = self if a:inOrder call self.sortChildren() endif endfunction "FUNCTION: TreeDirNode.close() {{{3 "Closes this directory function! s:TreeDirNode.close() let self.isOpen = 0 endfunction "FUNCTION: TreeDirNode.closeChildren() {{{3 "Closes all the child dir nodes of this node function! s:TreeDirNode.closeChildren() for i in self.children if i.path.isDirectory call i.close() call i.closeChildren() endif endfor endfunction "FUNCTION: TreeDirNode.createChild(path, inOrder) {{{3 "Instantiates a new child node for this node with the given path. The new "nodes parent is set to this node. " "Args: "path: a Path object that this node will represent/contain "inOrder: 1 if the new node should be inserted in sorted order " "Returns: "the newly created node function! s:TreeDirNode.createChild(path, inOrder) let newTreeNode = s:TreeFileNode.New(a:path) call self.addChild(newTreeNode, a:inOrder) return newTreeNode endfunction "FUNCTION: TreeDirNode.findNode(path) {{{3 "Will find one of the children (recursively) that has the given path " "Args: "path: a path object unlet s:TreeDirNode.findNode function! s:TreeDirNode.findNode(path) if a:path.equals(self.path) return self endif if stridx(a:path.str(), self.path.str(), 0) ==# -1 return {} endif if self.path.isDirectory for i in self.children let retVal = i.findNode(a:path) if retVal != {} return retVal endif endfor endif return {} endfunction "FUNCTION: TreeDirNode.getChildCount() {{{3 "Returns the number of children this node has function! s:TreeDirNode.getChildCount() return len(self.children) endfunction "FUNCTION: TreeDirNode.getChild(path) {{{3 "Returns child node of this node that has the given path or {} if no such node "exists. " "This function doesnt not recurse into child dir nodes " "Args: "path: a path object function! s:TreeDirNode.getChild(path) if stridx(a:path.str(), self.path.str(), 0) ==# -1 return {} endif let index = self.getChildIndex(a:path) if index ==# -1 return {} else return self.children[index] endif endfunction "FUNCTION: TreeDirNode.getChildByIndex(indx, visible) {{{3 "returns the child at the given index "Args: "indx: the index to get the child from "visible: 1 if only the visible children array should be used, 0 if all the "children should be searched. function! s:TreeDirNode.getChildByIndex(indx, visible) let array_to_search = a:visible? self.getVisibleChildren() : self.children if a:indx > len(array_to_search) throw "NERDTree.InvalidArgumentsError: Index is out of bounds." endif return array_to_search[a:indx] endfunction "FUNCTION: TreeDirNode.getChildIndex(path) {{{3 "Returns the index of the child node of this node that has the given path or "-1 if no such node exists. " "This function doesnt not recurse into child dir nodes " "Args: "path: a path object function! s:TreeDirNode.getChildIndex(path) if stridx(a:path.str(), self.path.str(), 0) ==# -1 return -1 endif "do a binary search for the child let a = 0 let z = self.getChildCount() while a < z let mid = (a+z)/2 let diff = a:path.compareTo(self.children[mid].path) if diff ==# -1 let z = mid elseif diff ==# 1 let a = mid+1 else return mid endif endwhile return -1 endfunction "FUNCTION: TreeDirNode.GetSelected() {{{3 "Returns the current node if it is a dir node, or else returns the current "nodes parent unlet s:TreeDirNode.GetSelected function! s:TreeDirNode.GetSelected() let currentDir = s:TreeFileNode.GetSelected() if currentDir != {} && !currentDir.isRoot() if currentDir.path.isDirectory ==# 0 let currentDir = currentDir.parent endif endif return currentDir endfunction "FUNCTION: TreeDirNode.getVisibleChildCount() {{{3 "Returns the number of visible children this node has function! s:TreeDirNode.getVisibleChildCount() return len(self.getVisibleChildren()) endfunction "FUNCTION: TreeDirNode.getVisibleChildren() {{{3 "Returns a list of children to display for this node, in the correct order " "Return: "an array of treenodes function! s:TreeDirNode.getVisibleChildren() let toReturn = [] for i in self.children if i.path.ignore() ==# 0 call add(toReturn, i) endif endfor return toReturn endfunction "FUNCTION: TreeDirNode.hasVisibleChildren() {{{3 "returns 1 if this node has any childre, 0 otherwise.. function! s:TreeDirNode.hasVisibleChildren() return self.getVisibleChildCount() != 0 endfunction "FUNCTION: TreeDirNode._initChildren() {{{3 "Removes all childen from this node and re-reads them " "Args: "silent: 1 if the function should not echo any "please wait" messages for "large directories " "Return: the number of child nodes read function! s:TreeDirNode._initChildren(silent) "remove all the current child nodes let self.children = [] "get an array of all the files in the nodes dir let dir = self.path let globDir = dir.str({'format': 'Glob'}) let filesStr = globpath(globDir, '*') . "\n" . globpath(globDir, '.*') let files = split(filesStr, "\n") if !a:silent && len(files) > g:NERDTreeNotificationThreshold call s:echo("Please wait, caching a large dir ...") endif let invalidFilesFound = 0 for i in files "filter out the .. and . directories "Note: we must match .. AND ../ cos sometimes the globpath returns "../ for path with strange chars (eg $) if i !~# '\/\.\.\/\?$' && i !~# '\/\.\/\?$' "put the next file in a new node and attach it try let path = s:Path.New(i) call self.createChild(path, 0) catch /^NERDTree.\(InvalidArguments\|InvalidFiletype\)Error/ let invalidFilesFound += 1 endtry endif endfor call self.sortChildren() if !a:silent && len(files) > g:NERDTreeNotificationThreshold call s:echo("Please wait, caching a large dir ... DONE (". self.getChildCount() ." nodes cached).") endif if invalidFilesFound call s:echoWarning(invalidFilesFound . " file(s) could not be loaded into the NERD tree") endif return self.getChildCount() endfunction "FUNCTION: TreeDirNode.New(path) {{{3 "Returns a new TreeNode object with the given path and parent " "Args: "path: a path object representing the full filesystem path to the file/dir that the node represents unlet s:TreeDirNode.New function! s:TreeDirNode.New(path) if a:path.isDirectory != 1 throw "NERDTree.InvalidArgumentsError: A TreeDirNode object must be instantiated with a directory Path object." endif let newTreeNode = copy(self) let newTreeNode.path = a:path let newTreeNode.isOpen = 0 let newTreeNode.children = [] let newTreeNode.parent = {} return newTreeNode endfunction "FUNCTION: TreeDirNode.open() {{{3 "Reads in all this nodes children " "Return: the number of child nodes read unlet s:TreeDirNode.open function! s:TreeDirNode.open() let self.isOpen = 1 if self.children ==# [] return self._initChildren(0) else return 0 endif endfunction " FUNCTION: TreeDirNode.openExplorer() {{{3 " opens an explorer window for this node in the previous window (could be a " nerd tree or a netrw) function! s:TreeDirNode.openExplorer() let oldwin = winnr() call s:exec('wincmd p') if oldwin ==# winnr() || (&modified && s:bufInWindows(winbufnr(winnr())) < 2) call s:exec('wincmd p') call self.openSplit() else exec ("silent edit " . self.path.str({'format': 'Edit'})) endif endfunction "FUNCTION: TreeDirNode.openInNewTab(options) {{{3 unlet s:TreeDirNode.openInNewTab function! s:TreeDirNode.openInNewTab(options) let currentTab = tabpagenr() if !has_key(a:options, 'keepTreeOpen') || !a:options['keepTreeOpen'] call s:closeTreeIfQuitOnOpen() endif tabnew call s:initNerdTree(self.path.str()) if has_key(a:options, 'stayInCurrentTab') && a:options['stayInCurrentTab'] exec "tabnext " . currentTab endif endfunction "FUNCTION: TreeDirNode.openRecursively() {{{3 "Opens this treenode and all of its children whose paths arent 'ignored' "because of the file filters. " "This method is actually a wrapper for the OpenRecursively2 method which does "the work. function! s:TreeDirNode.openRecursively() call self._openRecursively2(1) endfunction "FUNCTION: TreeDirNode._openRecursively2() {{{3 "Opens this all children of this treenode recursively if either: " *they arent filtered by file filters " *a:forceOpen is 1 " "Args: "forceOpen: 1 if this node should be opened regardless of file filters function! s:TreeDirNode._openRecursively2(forceOpen) if self.path.ignore() ==# 0 || a:forceOpen let self.isOpen = 1 if self.children ==# [] call self._initChildren(1) endif for i in self.children if i.path.isDirectory ==# 1 call i._openRecursively2(0) endif endfor endif endfunction "FUNCTION: TreeDirNode.refresh() {{{3 unlet s:TreeDirNode.refresh function! s:TreeDirNode.refresh() call self.path.refresh() "if this node was ever opened, refresh its children if self.isOpen || !empty(self.children) "go thru all the files/dirs under this node let newChildNodes = [] let invalidFilesFound = 0 let dir = self.path let globDir = dir.str({'format': 'Glob'}) let filesStr = globpath(globDir, '*') . "\n" . globpath(globDir, '.*') let files = split(filesStr, "\n") for i in files "filter out the .. and . directories "Note: we must match .. AND ../ cos sometimes the globpath returns "../ for path with strange chars (eg $) if i !~# '\/\.\.\/\?$' && i !~# '\/\.\/\?$' try "create a new path and see if it exists in this nodes children let path = s:Path.New(i) let newNode = self.getChild(path) if newNode != {} call newNode.refresh() call add(newChildNodes, newNode) "the node doesnt exist so create it else let newNode = s:TreeFileNode.New(path) let newNode.parent = self call add(newChildNodes, newNode) endif catch /^NERDTree.InvalidArgumentsError/ let invalidFilesFound = 1 endtry endif endfor "swap this nodes children out for the children we just read/refreshed let self.children = newChildNodes call self.sortChildren() if invalidFilesFound call s:echoWarning("some files could not be loaded into the NERD tree") endif endif endfunction "FUNCTION: TreeDirNode.reveal(path) {{{3 "reveal the given path, i.e. cache and open all treenodes needed to display it "in the UI function! s:TreeDirNode.reveal(path) if !a:path.isUnder(self.path) throw "NERDTree.InvalidArgumentsError: " . a:path.str() . " should be under " . self.path.str() endif call self.open() if self.path.equals(a:path.getParent()) let n = self.findNode(a:path) call s:renderView() call n.putCursorHere(1,0) return endif let p = a:path while !p.getParent().equals(self.path) let p = p.getParent() endwhile let n = self.findNode(p) call n.reveal(a:path) endfunction "FUNCTION: TreeDirNode.removeChild(treenode) {{{3 " "Removes the given treenode from this nodes set of children " "Args: "treenode: the node to remove " "Throws a NERDTree.ChildNotFoundError if the given treenode is not found function! s:TreeDirNode.removeChild(treenode) for i in range(0, self.getChildCount()-1) if self.children[i].equals(a:treenode) call remove(self.children, i) return endif endfor throw "NERDTree.ChildNotFoundError: child node was not found" endfunction "FUNCTION: TreeDirNode.sortChildren() {{{3 " "Sorts the children of this node according to alphabetical order and the "directory priority. " function! s:TreeDirNode.sortChildren() let CompareFunc = function("s:compareNodes") call sort(self.children, CompareFunc) endfunction "FUNCTION: TreeDirNode.toggleOpen() {{{3 "Opens this directory if it is closed and vice versa function! s:TreeDirNode.toggleOpen() if self.isOpen ==# 1 call self.close() else call self.open() endif endfunction "FUNCTION: TreeDirNode.transplantChild(newNode) {{{3 "Replaces the child of this with the given node (where the child node's full "path matches a:newNode's fullpath). The search for the matching node is "non-recursive " "Arg: "newNode: the node to graft into the tree function! s:TreeDirNode.transplantChild(newNode) for i in range(0, self.getChildCount()-1) if self.children[i].equals(a:newNode) let self.children[i] = a:newNode let a:newNode.parent = self break endif endfor endfunction "============================================================ "CLASS: Path {{{2 "============================================================ let s:Path = {} "FUNCTION: Path.AbsolutePathFor(str) {{{3 function! s:Path.AbsolutePathFor(str) let prependCWD = 0 if s:running_windows let prependCWD = a:str !~# '^.:\(\\\|\/\)' else let prependCWD = a:str !~# '^/' endif let toReturn = a:str if prependCWD let toReturn = getcwd() . s:Path.Slash() . a:str endif return toReturn endfunction "FUNCTION: Path.bookmarkNames() {{{3 function! s:Path.bookmarkNames() if !exists("self._bookmarkNames") call self.cacheDisplayString() endif return self._bookmarkNames endfunction "FUNCTION: Path.cacheDisplayString() {{{3 function! s:Path.cacheDisplayString() let self.cachedDisplayString = self.getLastPathComponent(1) if self.isExecutable let self.cachedDisplayString = self.cachedDisplayString . '*' endif let self._bookmarkNames = [] for i in s:Bookmark.Bookmarks() if i.path.equals(self) call add(self._bookmarkNames, i.name) endif endfor if !empty(self._bookmarkNames) let self.cachedDisplayString .= ' {' . join(self._bookmarkNames) . '}' endif if self.isSymLink let self.cachedDisplayString .= ' -> ' . self.symLinkDest endif if self.isReadOnly let self.cachedDisplayString .= ' [RO]' endif endfunction "FUNCTION: Path.changeToDir() {{{3 function! s:Path.changeToDir() let dir = self.str({'format': 'Cd'}) if self.isDirectory ==# 0 let dir = self.getParent().str({'format': 'Cd'}) endif try execute "cd " . dir call s:echo("CWD is now: " . getcwd()) catch throw "NERDTree.PathChangeError: cannot change CWD to " . dir endtry endfunction "FUNCTION: Path.compareTo() {{{3 " "Compares this Path to the given path and returns 0 if they are equal, -1 if "this Path is "less than" the given path, or 1 if it is "greater". " "Args: "path: the path object to compare this to " "Return: "1, -1 or 0 function! s:Path.compareTo(path) let thisPath = self.getLastPathComponent(1) let thatPath = a:path.getLastPathComponent(1) "if the paths are the same then clearly we return 0 if thisPath ==# thatPath return 0 endif let thisSS = self.getSortOrderIndex() let thatSS = a:path.getSortOrderIndex() "compare the sort sequences, if they are different then the return "value is easy if thisSS < thatSS return -1 elseif thisSS > thatSS return 1 else "if the sort sequences are the same then compare the paths "alphabetically let pathCompare = g:NERDTreeCaseSensitiveSort ? thisPath <# thatPath : thisPath <? thatPath if pathCompare return -1 else return 1 endif endif endfunction "FUNCTION: Path.Create(fullpath) {{{3 " "Factory method. " "Creates a path object with the given path. The path is also created on the "filesystem. If the path already exists, a NERDTree.Path.Exists exception is "thrown. If any other errors occur, a NERDTree.Path exception is thrown. " "Args: "fullpath: the full filesystem path to the file/dir to create function! s:Path.Create(fullpath) "bail if the a:fullpath already exists if isdirectory(a:fullpath) || filereadable(a:fullpath) throw "NERDTree.CreatePathError: Directory Exists: '" . a:fullpath . "'" endif try "if it ends with a slash, assume its a dir create it if a:fullpath =~# '\(\\\|\/\)$' "whack the trailing slash off the end if it exists let fullpath = substitute(a:fullpath, '\(\\\|\/\)$', '', '') call mkdir(fullpath, 'p') "assume its a file and create else call writefile([], a:fullpath) endif catch throw "NERDTree.CreatePathError: Could not create path: '" . a:fullpath . "'" endtry return s:Path.New(a:fullpath) endfunction "FUNCTION: Path.copy(dest) {{{3 " "Copies the file/dir represented by this Path to the given location " "Args: "dest: the location to copy this dir/file to function! s:Path.copy(dest) if !s:Path.CopyingSupported() throw "NERDTree.CopyingNotSupportedError: Copying is not supported on this OS" endif let dest = s:Path.WinToUnixPath(a:dest) let cmd = g:NERDTreeCopyCmd . " " . escape(self.str(), s:escape_chars) . " " . escape(dest, s:escape_chars) let success = system(cmd) if success != 0 throw "NERDTree.CopyError: Could not copy ''". self.str() ."'' to: '" . a:dest . "'" endif endfunction "FUNCTION: Path.CopyingSupported() {{{3 " "returns 1 if copying is supported for this OS function! s:Path.CopyingSupported() return exists('g:NERDTreeCopyCmd') endfunction "FUNCTION: Path.copyingWillOverwrite(dest) {{{3 " "returns 1 if copy this path to the given location will cause files to "overwritten " "Args: "dest: the location this path will be copied to function! s:Path.copyingWillOverwrite(dest) if filereadable(a:dest) return 1 endif if isdirectory(a:dest) let path = s:Path.JoinPathStrings(a:dest, self.getLastPathComponent(0)) if filereadable(path) return 1 endif endif endfunction "FUNCTION: Path.delete() {{{3 " "Deletes the file represented by this path. "Deletion of directories is not supported " "Throws NERDTree.Path.Deletion exceptions function! s:Path.delete() if self.isDirectory let cmd = g:NERDTreeRemoveDirCmd . self.str({'escape': 1}) let success = system(cmd) if v:shell_error != 0 throw "NERDTree.PathDeletionError: Could not delete directory: '" . self.str() . "'" endif else let success = delete(self.str()) if success != 0 throw "NERDTree.PathDeletionError: Could not delete file: '" . self.str() . "'" endif endif "delete all bookmarks for this path for i in self.bookmarkNames() let bookmark = s:Bookmark.BookmarkFor(i) call bookmark.delete() endfor endfunction "FUNCTION: Path.displayString() {{{3 " "Returns a string that specifies how the path should be represented as a "string function! s:Path.displayString() if self.cachedDisplayString ==# "" call self.cacheDisplayString() endif return self.cachedDisplayString endfunction "FUNCTION: Path.extractDriveLetter(fullpath) {{{3 " "If running windows, cache the drive letter for this path function! s:Path.extractDriveLetter(fullpath) if s:running_windows let self.drive = substitute(a:fullpath, '\(^[a-zA-Z]:\).*', '\1', '') else let self.drive = '' endif endfunction "FUNCTION: Path.exists() {{{3 "return 1 if this path points to a location that is readable or is a directory function! s:Path.exists() let p = self.str() return filereadable(p) || isdirectory(p) endfunction "FUNCTION: Path.getDir() {{{3 " "Returns this path if it is a directory, else this paths parent. " "Return: "a Path object function! s:Path.getDir() if self.isDirectory return self else return self.getParent() endif endfunction "FUNCTION: Path.getParent() {{{3 " "Returns a new path object for this paths parent " "Return: "a new Path object function! s:Path.getParent() if s:running_windows let path = self.drive . '\' . join(self.pathSegments[0:-2], '\') else let path = '/'. join(self.pathSegments[0:-2], '/') endif return s:Path.New(path) endfunction "FUNCTION: Path.getLastPathComponent(dirSlash) {{{3 " "Gets the last part of this path. " "Args: "dirSlash: if 1 then a trailing slash will be added to the returned value for "directory nodes. function! s:Path.getLastPathComponent(dirSlash) if empty(self.pathSegments) return '' endif let toReturn = self.pathSegments[-1] if a:dirSlash && self.isDirectory let toReturn = toReturn . '/' endif return toReturn endfunction "FUNCTION: Path.getSortOrderIndex() {{{3 "returns the index of the pattern in g:NERDTreeSortOrder that this path matches function! s:Path.getSortOrderIndex() let i = 0 while i < len(g:NERDTreeSortOrder) if self.getLastPathComponent(1) =~# g:NERDTreeSortOrder[i] return i endif let i = i + 1 endwhile return s:NERDTreeSortStarIndex endfunction "FUNCTION: Path.ignore() {{{3 "returns true if this path should be ignored function! s:Path.ignore() let lastPathComponent = self.getLastPathComponent(0) "filter out the user specified paths to ignore if b:NERDTreeIgnoreEnabled for i in g:NERDTreeIgnore if lastPathComponent =~# i return 1 endif endfor endif "dont show hidden files unless instructed to if b:NERDTreeShowHidden ==# 0 && lastPathComponent =~# '^\.' return 1 endif if b:NERDTreeShowFiles ==# 0 && self.isDirectory ==# 0 return 1 endif return 0 endfunction "FUNCTION: Path.isUnder(path) {{{3 "return 1 if this path is somewhere under the given path in the filesystem. " "a:path should be a dir function! s:Path.isUnder(path) if a:path.isDirectory == 0 return 0 endif let this = self.str() let that = a:path.str() return stridx(this, that . s:Path.Slash()) == 0 endfunction "FUNCTION: Path.JoinPathStrings(...) {{{3 function! s:Path.JoinPathStrings(...) let components = [] for i in a:000 let components = extend(components, split(i, '/')) endfor return '/' . join(components, '/') endfunction "FUNCTION: Path.equals() {{{3 " "Determines whether 2 path objects are "equal". "They are equal if the paths they represent are the same " "Args: "path: the other path obj to compare this with function! s:Path.equals(path) return self.str() ==# a:path.str() endfunction "FUNCTION: Path.New() {{{3 "The Constructor for the Path object function! s:Path.New(path) let newPath = copy(self) call newPath.readInfoFromDisk(s:Path.AbsolutePathFor(a:path)) let newPath.cachedDisplayString = "" return newPath endfunction "FUNCTION: Path.Slash() {{{3 "return the slash to use for the current OS function! s:Path.Slash() return s:running_windows ? '\' : '/' endfunction "FUNCTION: Path.readInfoFromDisk(fullpath) {{{3 " " "Throws NERDTree.Path.InvalidArguments exception. function! s:Path.readInfoFromDisk(fullpath) call self.extractDriveLetter(a:fullpath) let fullpath = s:Path.WinToUnixPath(a:fullpath) if getftype(fullpath) ==# "fifo" throw "NERDTree.InvalidFiletypeError: Cant handle FIFO files: " . a:fullpath endif let self.pathSegments = split(fullpath, '/') let self.isReadOnly = 0 if isdirectory(a:fullpath) let self.isDirectory = 1 elseif filereadable(a:fullpath) let self.isDirectory = 0 let self.isReadOnly = filewritable(a:fullpath) ==# 0 else throw "NERDTree.InvalidArgumentsError: Invalid path = " . a:fullpath endif let self.isExecutable = 0 if !self.isDirectory let self.isExecutable = getfperm(a:fullpath) =~# 'x' endif "grab the last part of the path (minus the trailing slash) let lastPathComponent = self.getLastPathComponent(0) "get the path to the new node with the parent dir fully resolved let hardPath = resolve(self.strTrunk()) . '/' . lastPathComponent "if the last part of the path is a symlink then flag it as such let self.isSymLink = (resolve(hardPath) != hardPath) if self.isSymLink let self.symLinkDest = resolve(fullpath) "if the link is a dir then slap a / on the end of its dest if isdirectory(self.symLinkDest) "we always wanna treat MS windows shortcuts as files for "simplicity if hardPath !~# '\.lnk$' let self.symLinkDest = self.symLinkDest . '/' endif endif endif endfunction "FUNCTION: Path.refresh() {{{3 function! s:Path.refresh() call self.readInfoFromDisk(self.str()) call self.cacheDisplayString() endfunction "FUNCTION: Path.rename() {{{3 " "Renames this node on the filesystem function! s:Path.rename(newPath) if a:newPath ==# '' throw "NERDTree.InvalidArgumentsError: Invalid newPath for renaming = ". a:newPath endif let success = rename(self.str(), a:newPath) if success != 0 throw "NERDTree.PathRenameError: Could not rename: '" . self.str() . "'" . 'to:' . a:newPath endif call self.readInfoFromDisk(a:newPath) for i in self.bookmarkNames() let b = s:Bookmark.BookmarkFor(i) call b.setPath(copy(self)) endfor call s:Bookmark.Write() endfunction "FUNCTION: Path.str() {{{3 " "Returns a string representation of this Path " "Takes an optional dictionary param to specify how the output should be "formatted. " "The dict may have the following keys: " 'format' " 'escape' " 'truncateTo' " "The 'format' key may have a value of: " 'Cd' - a string to be used with the :cd command " 'Edit' - a string to be used with :e :sp :new :tabedit etc " 'UI' - a string used in the NERD tree UI " "The 'escape' key, if specified will cause the output to be escaped with "shellescape() " "The 'truncateTo' key causes the resulting string to be truncated to the value "'truncateTo' maps to. A '<' char will be prepended. function! s:Path.str(...) let options = a:0 ? a:1 : {} let toReturn = "" if has_key(options, 'format') let format = options['format'] if has_key(self, '_strFor' . format) exec 'let toReturn = self._strFor' . format . '()' else raise 'NERDTree.UnknownFormatError: unknown format "'. format .'"' endif else let toReturn = self._str() endif if has_key(options, 'escape') && options['escape'] let toReturn = shellescape(toReturn) endif if has_key(options, 'truncateTo') let limit = options['truncateTo'] if len(toReturn) > limit let toReturn = "<" . strpart(toReturn, len(toReturn) - limit + 1) endif endif return toReturn endfunction "FUNCTION: Path._strForUI() {{{3 function! s:Path._strForUI() let toReturn = '/' . join(self.pathSegments, '/') if self.isDirectory && toReturn != '/' let toReturn = toReturn . '/' endif return toReturn endfunction "FUNCTION: Path._strForCd() {{{3 " " returns a string that can be used with :cd function! s:Path._strForCd() return escape(self.str(), s:escape_chars) endfunction "FUNCTION: Path._strForEdit() {{{3 " "Return: the string for this path that is suitable to be used with the :edit "command function! s:Path._strForEdit() let p = self.str({'format': 'UI'}) let cwd = getcwd() if s:running_windows let p = tolower(self.str()) let cwd = tolower(getcwd()) endif let p = escape(p, s:escape_chars) let cwd = cwd . s:Path.Slash() "return a relative path if we can if stridx(p, cwd) ==# 0 let p = strpart(p, strlen(cwd)) endif if p ==# '' let p = '.' endif return p endfunction "FUNCTION: Path._strForGlob() {{{3 function! s:Path._strForGlob() let lead = s:Path.Slash() "if we are running windows then slap a drive letter on the front if s:running_windows let lead = self.drive . '\' endif let toReturn = lead . join(self.pathSegments, s:Path.Slash()) if !s:running_windows let toReturn = escape(toReturn, s:escape_chars) endif return toReturn endfunction "FUNCTION: Path._str() {{{3 " "Gets the string path for this path object that is appropriate for the OS. "EG, in windows c:\foo\bar " in *nix /foo/bar function! s:Path._str() let lead = s:Path.Slash() "if we are running windows then slap a drive letter on the front if s:running_windows let lead = self.drive . '\' endif return lead . join(self.pathSegments, s:Path.Slash()) endfunction "FUNCTION: Path.strTrunk() {{{3 "Gets the path without the last segment on the end. function! s:Path.strTrunk() return self.drive . '/' . join(self.pathSegments[0:-2], '/') endfunction "FUNCTION: Path.WinToUnixPath(pathstr){{{3 "Takes in a windows path and returns the unix equiv " "A class level method " "Args: "pathstr: the windows path to convert function! s:Path.WinToUnixPath(pathstr) if !s:running_windows return a:pathstr endif let toReturn = a:pathstr "remove the x:\ of the front let toReturn = substitute(toReturn, '^.*:\(\\\|/\)\?', '/', "") "convert all \ chars to / let toReturn = substitute(toReturn, '\', '/', "g") return toReturn endfunction " SECTION: General Functions {{{1 "============================================================ "FUNCTION: s:bufInWindows(bnum){{{2 "[[STOLEN FROM VTREEEXPLORER.VIM]] "Determine the number of windows open to this buffer number. "Care of Yegappan Lakshman. Thanks! " "Args: "bnum: the subject buffers buffer number function! s:bufInWindows(bnum) let cnt = 0 let winnum = 1 while 1 let bufnum = winbufnr(winnum) if bufnum < 0 break endif if bufnum ==# a:bnum let cnt = cnt + 1 endif let winnum = winnum + 1 endwhile return cnt endfunction " >>> "FUNCTION: s:checkForBrowse(dir) {{{2 "inits a secondary nerd tree in the current buffer if appropriate function! s:checkForBrowse(dir) if a:dir != '' && isdirectory(a:dir) call s:initNerdTreeInPlace(a:dir) endif endfunction "FUNCTION: s:compareBookmarks(first, second) {{{2 "Compares two bookmarks function! s:compareBookmarks(first, second) return a:first.compareTo(a:second) endfunction " FUNCTION: s:completeBookmarks(A,L,P) {{{2 " completion function for the bookmark commands function! s:completeBookmarks(A,L,P) return filter(s:Bookmark.BookmarkNames(), 'v:val =~# "^' . a:A . '"') endfunction " FUNCTION: s:exec(cmd) {{{2 " same as :exec cmd but eventignore=all is set for the duration function! s:exec(cmd) let old_ei = &ei set ei=all exec a:cmd let &ei = old_ei endfunction " FUNCTION: s:findAndRevealPath() {{{2 function! s:findAndRevealPath() try let p = s:Path.New(expand("%:p")) catch /^NERDTree.InvalidArgumentsError/ call s:echo("no file for the current buffer") return endtry if !s:treeExistsForTab() try let cwd = s:Path.New(getcwd()) catch /^NERDTree.InvalidArgumentsError/ call s:echo("current directory does not exist.") let cwd = p.getParent() endtry if p.isUnder(cwd) call s:initNerdTree(cwd.str()) else call s:initNerdTree(p.getParent().str()) endif else if !p.isUnder(s:TreeFileNode.GetRootForTab().path) call s:initNerdTree(p.getParent().str()) else if !s:isTreeOpen() call s:toggle("") endif endif endif call s:putCursorInTreeWin() call b:NERDTreeRoot.reveal(p) endfunction "FUNCTION: s:initNerdTree(name) {{{2 "Initialise the nerd tree for this tab. The tree will start in either the "given directory, or the directory associated with the given bookmark " "Args: "name: the name of a bookmark or a directory function! s:initNerdTree(name) let path = {} if s:Bookmark.BookmarkExistsFor(a:name) let path = s:Bookmark.BookmarkFor(a:name).path else let dir = a:name ==# '' ? getcwd() : a:name "hack to get an absolute path if a relative path is given if dir =~# '^\.' let dir = getcwd() . s:Path.Slash() . dir endif let dir = resolve(dir) try let path = s:Path.New(dir) catch /^NERDTree.InvalidArgumentsError/ call s:echo("No bookmark or directory found for: " . a:name) return endtry endif if !path.isDirectory let path = path.getParent() endif "if instructed to, then change the vim CWD to the dir the NERDTree is "inited in if g:NERDTreeChDirMode != 0 call path.changeToDir() endif if s:treeExistsForTab() if s:isTreeOpen() call s:closeTree() endif unlet t:NERDTreeBufName endif let newRoot = s:TreeDirNode.New(path) call newRoot.open() call s:createTreeWin() let b:treeShowHelp = 0 let b:NERDTreeIgnoreEnabled = 1 let b:NERDTreeShowFiles = g:NERDTreeShowFiles let b:NERDTreeShowHidden = g:NERDTreeShowHidden let b:NERDTreeShowBookmarks = g:NERDTreeShowBookmarks let b:NERDTreeRoot = newRoot let b:NERDTreeType = "primary" call s:renderView() call b:NERDTreeRoot.putCursorHere(0, 0) endfunction "FUNCTION: s:initNerdTreeInPlace(dir) {{{2 function! s:initNerdTreeInPlace(dir) try let path = s:Path.New(a:dir) catch /^NERDTree.InvalidArgumentsError/ call s:echo("Invalid directory name:" . a:name) return endtry "we want the directory buffer to disappear when we do the :edit below setlocal bufhidden=wipe let previousBuf = expand("#") "we need a unique name for each secondary tree buffer to ensure they are "all independent exec "silent edit " . s:nextBufferName() let b:NERDTreePreviousBuf = bufnr(previousBuf) let b:NERDTreeRoot = s:TreeDirNode.New(path) call b:NERDTreeRoot.open() call s:setCommonBufOptions() let b:NERDTreeType = "secondary" call s:renderView() endfunction " FUNCTION: s:initNerdTreeMirror() {{{2 function! s:initNerdTreeMirror() "get the names off all the nerd tree buffers let treeBufNames = [] for i in range(1, tabpagenr("$")) let nextName = s:tabpagevar(i, 'NERDTreeBufName') if nextName != -1 && (!exists("t:NERDTreeBufName") || nextName != t:NERDTreeBufName) call add(treeBufNames, nextName) endif endfor let treeBufNames = s:unique(treeBufNames) "map the option names (that the user will be prompted with) to the nerd "tree buffer names let options = {} let i = 0 while i < len(treeBufNames) let bufName = treeBufNames[i] let treeRoot = getbufvar(bufName, "NERDTreeRoot") let options[i+1 . '. ' . treeRoot.path.str() . ' (buf name: ' . bufName . ')'] = bufName let i = i + 1 endwhile "work out which tree to mirror, if there is more than 1 then ask the user let bufferName = '' if len(keys(options)) > 1 let choices = ["Choose a tree to mirror"] let choices = extend(choices, sort(keys(options))) let choice = inputlist(choices) if choice < 1 || choice > len(options) || choice ==# '' return endif let bufferName = options[sort(keys(options))[choice-1]] elseif len(keys(options)) ==# 1 let bufferName = values(options)[0] else call s:echo("No trees to mirror") return endif if s:treeExistsForTab() && s:isTreeOpen() call s:closeTree() endif let t:NERDTreeBufName = bufferName call s:createTreeWin() exec 'buffer ' . bufferName if !&hidden call s:renderView() endif endfunction " FUNCTION: s:nextBufferName() {{{2 " returns the buffer name for the next nerd tree function! s:nextBufferName() let name = s:NERDTreeBufName . s:next_buffer_number let s:next_buffer_number += 1 return name endfunction " FUNCTION: s:tabpagevar(tabnr, var) {{{2 function! s:tabpagevar(tabnr, var) let currentTab = tabpagenr() let old_ei = &ei set ei=all exec "tabnext " . a:tabnr let v = -1 if exists('t:' . a:var) exec 'let v = t:' . a:var endif exec "tabnext " . currentTab let &ei = old_ei return v endfunction " Function: s:treeExistsForBuffer() {{{2 " Returns 1 if a nerd tree root exists in the current buffer function! s:treeExistsForBuf() return exists("b:NERDTreeRoot") endfunction " Function: s:treeExistsForTab() {{{2 " Returns 1 if a nerd tree root exists in the current tab function! s:treeExistsForTab() return exists("t:NERDTreeBufName") endfunction " Function: s:unique(list) {{{2 " returns a:list without duplicates function! s:unique(list) let uniqlist = [] for elem in a:list if index(uniqlist, elem) ==# -1 let uniqlist += [elem] endif endfor return uniqlist endfunction " SECTION: Public API {{{1 "============================================================ let g:NERDTreePath = s:Path let g:NERDTreeDirNode = s:TreeDirNode let g:NERDTreeFileNode = s:TreeFileNode let g:NERDTreeBookmark = s:Bookmark function! NERDTreeAddMenuItem(options) call s:MenuItem.Create(a:options) endfunction function! NERDTreeAddMenuSeparator(...) let opts = a:0 ? a:1 : {} call s:MenuItem.CreateSeparator(opts) endfunction function! NERDTreeAddSubmenu(options) return s:MenuItem.Create(a:options) endfunction function! NERDTreeAddKeyMap(options) call s:KeyMap.Create(a:options) endfunction function! NERDTreeRender() call s:renderView() endfunction " SECTION: View Functions {{{1 "============================================================ "FUNCTION: s:centerView() {{{2 "centers the nerd tree window around the cursor (provided the nerd tree "options permit) function! s:centerView() if g:NERDTreeAutoCenter let current_line = winline() let lines_to_top = current_line let lines_to_bottom = winheight(s:getTreeWinNum()) - current_line if lines_to_top < g:NERDTreeAutoCenterThreshold || lines_to_bottom < g:NERDTreeAutoCenterThreshold normal! zz endif endif endfunction "FUNCTION: s:closeTree() {{{2 "Closes the primary NERD tree window for this tab function! s:closeTree() if !s:isTreeOpen() throw "NERDTree.NoTreeFoundError: no NERDTree is open" endif if winnr("$") != 1 if winnr() == s:getTreeWinNum() wincmd p let bufnr = bufnr("") wincmd p else let bufnr = bufnr("") endif call s:exec(s:getTreeWinNum() . " wincmd w") close call s:exec(bufwinnr(bufnr) . " wincmd w") else close endif endfunction "FUNCTION: s:closeTreeIfOpen() {{{2 "Closes the NERD tree window if it is open function! s:closeTreeIfOpen() if s:isTreeOpen() call s:closeTree() endif endfunction "FUNCTION: s:closeTreeIfQuitOnOpen() {{{2 "Closes the NERD tree window if the close on open option is set function! s:closeTreeIfQuitOnOpen() if g:NERDTreeQuitOnOpen && s:isTreeOpen() call s:closeTree() endif endfunction "FUNCTION: s:createTreeWin() {{{2 "Inits the NERD tree window. ie. opens it, sizes it, sets all the local "options etc function! s:createTreeWin() "create the nerd tree window let splitLocation = g:NERDTreeWinPos ==# "left" ? "topleft " : "botright " let splitSize = g:NERDTreeWinSize if !exists('t:NERDTreeBufName') let t:NERDTreeBufName = s:nextBufferName() silent! exec splitLocation . 'vertical ' . splitSize . ' new' silent! exec "edit " . t:NERDTreeBufName else silent! exec splitLocation . 'vertical ' . splitSize . ' split' silent! exec "buffer " . t:NERDTreeBufName endif setlocal winfixwidth call s:setCommonBufOptions() endfunction "FUNCTION: s:dumpHelp {{{2 "prints out the quick help function! s:dumpHelp() let old_h = @h if b:treeShowHelp ==# 1 let @h= "\" NERD tree (" . s:NERD_tree_version . ") quickhelp~\n" let @h=@h."\" ============================\n" let @h=@h."\" File node mappings~\n" let @h=@h."\" ". (g:NERDTreeMouseMode ==# 3 ? "single" : "double") ."-click,\n" let @h=@h."\" <CR>,\n" if b:NERDTreeType ==# "primary" let @h=@h."\" ". g:NERDTreeMapActivateNode .": open in prev window\n" else let @h=@h."\" ". g:NERDTreeMapActivateNode .": open in current window\n" endif if b:NERDTreeType ==# "primary" let @h=@h."\" ". g:NERDTreeMapPreview .": preview\n" endif let @h=@h."\" ". g:NERDTreeMapOpenInTab.": open in new tab\n" let @h=@h."\" ". g:NERDTreeMapOpenInTabSilent .": open in new tab silently\n" let @h=@h."\" middle-click,\n" let @h=@h."\" ". g:NERDTreeMapOpenSplit .": open split\n" let @h=@h."\" ". g:NERDTreeMapPreviewSplit .": preview split\n" let @h=@h."\" ". g:NERDTreeMapOpenVSplit .": open vsplit\n" let @h=@h."\" ". g:NERDTreeMapPreviewVSplit .": preview vsplit\n" let @h=@h."\"\n\" ----------------------------\n" let @h=@h."\" Directory node mappings~\n" let @h=@h."\" ". (g:NERDTreeMouseMode ==# 1 ? "double" : "single") ."-click,\n" let @h=@h."\" ". g:NERDTreeMapActivateNode .": open & close node\n" let @h=@h."\" ". g:NERDTreeMapOpenRecursively .": recursively open node\n" let @h=@h."\" ". g:NERDTreeMapCloseDir .": close parent of node\n" let @h=@h."\" ". g:NERDTreeMapCloseChildren .": close all child nodes of\n" let @h=@h."\" current node recursively\n" let @h=@h."\" middle-click,\n" let @h=@h."\" ". g:NERDTreeMapOpenExpl.": explore selected dir\n" let @h=@h."\"\n\" ----------------------------\n" let @h=@h."\" Bookmark table mappings~\n" let @h=@h."\" double-click,\n" let @h=@h."\" ". g:NERDTreeMapActivateNode .": open bookmark\n" let @h=@h."\" ". g:NERDTreeMapOpenInTab.": open in new tab\n" let @h=@h."\" ". g:NERDTreeMapOpenInTabSilent .": open in new tab silently\n" let @h=@h."\" ". g:NERDTreeMapDeleteBookmark .": delete bookmark\n" let @h=@h."\"\n\" ----------------------------\n" let @h=@h."\" Tree navigation mappings~\n" let @h=@h."\" ". g:NERDTreeMapJumpRoot .": go to root\n" let @h=@h."\" ". g:NERDTreeMapJumpParent .": go to parent\n" let @h=@h."\" ". g:NERDTreeMapJumpFirstChild .": go to first child\n" let @h=@h."\" ". g:NERDTreeMapJumpLastChild .": go to last child\n" let @h=@h."\" ". g:NERDTreeMapJumpNextSibling .": go to next sibling\n" let @h=@h."\" ". g:NERDTreeMapJumpPrevSibling .": go to prev sibling\n" let @h=@h."\"\n\" ----------------------------\n" let @h=@h."\" Filesystem mappings~\n" let @h=@h."\" ". g:NERDTreeMapChangeRoot .": change tree root to the\n" let @h=@h."\" selected dir\n" let @h=@h."\" ". g:NERDTreeMapUpdir .": move tree root up a dir\n" let @h=@h."\" ". g:NERDTreeMapUpdirKeepOpen .": move tree root up a dir\n" let @h=@h."\" but leave old root open\n" let @h=@h."\" ". g:NERDTreeMapRefresh .": refresh cursor dir\n" let @h=@h."\" ". g:NERDTreeMapRefreshRoot .": refresh current root\n" let @h=@h."\" ". g:NERDTreeMapMenu .": Show menu\n" let @h=@h."\" ". g:NERDTreeMapChdir .":change the CWD to the\n" let @h=@h."\" selected dir\n" let @h=@h."\"\n\" ----------------------------\n" let @h=@h."\" Tree filtering mappings~\n" let @h=@h."\" ". g:NERDTreeMapToggleHidden .": hidden files (" . (b:NERDTreeShowHidden ? "on" : "off") . ")\n" let @h=@h."\" ". g:NERDTreeMapToggleFilters .": file filters (" . (b:NERDTreeIgnoreEnabled ? "on" : "off") . ")\n" let @h=@h."\" ". g:NERDTreeMapToggleFiles .": files (" . (b:NERDTreeShowFiles ? "on" : "off") . ")\n" let @h=@h."\" ". g:NERDTreeMapToggleBookmarks .": bookmarks (" . (b:NERDTreeShowBookmarks ? "on" : "off") . ")\n" "add quickhelp entries for each custom key map if len(s:KeyMap.All()) let @h=@h."\"\n\" ----------------------------\n" let @h=@h."\" Custom mappings~\n" for i in s:KeyMap.All() let @h=@h."\" ". i.key .": ". i.quickhelpText ."\n" endfor endif let @h=@h."\"\n\" ----------------------------\n" let @h=@h."\" Other mappings~\n" let @h=@h."\" ". g:NERDTreeMapQuit .": Close the NERDTree window\n" let @h=@h."\" ". g:NERDTreeMapToggleZoom .": Zoom (maximize-minimize)\n" let @h=@h."\" the NERDTree window\n" let @h=@h."\" ". g:NERDTreeMapHelp .": toggle help\n" let @h=@h."\"\n\" ----------------------------\n" let @h=@h."\" Bookmark commands~\n" let @h=@h."\" :Bookmark <name>\n" let @h=@h."\" :BookmarkToRoot <name>\n" let @h=@h."\" :RevealBookmark <name>\n" let @h=@h."\" :OpenBookmark <name>\n" let @h=@h."\" :ClearBookmarks [<names>]\n" let @h=@h."\" :ClearAllBookmarks\n" silent! put h elseif g:NERDTreeMinimalUI == 0 let @h="\" Press ". g:NERDTreeMapHelp ." for help\n" silent! put h endif let @h = old_h endfunction "FUNCTION: s:echo {{{2 "A wrapper for :echo. Appends 'NERDTree:' on the front of all messages " "Args: "msg: the message to echo function! s:echo(msg) redraw echomsg "NERDTree: " . a:msg endfunction "FUNCTION: s:echoWarning {{{2 "Wrapper for s:echo, sets the message type to warningmsg for this message "Args: "msg: the message to echo function! s:echoWarning(msg) echohl warningmsg call s:echo(a:msg) echohl normal endfunction "FUNCTION: s:echoError {{{2 "Wrapper for s:echo, sets the message type to errormsg for this message "Args: "msg: the message to echo function! s:echoError(msg) echohl errormsg call s:echo(a:msg) echohl normal endfunction "FUNCTION: s:firstUsableWindow(){{{2 "find the window number of the first normal window function! s:firstUsableWindow() let i = 1 while i <= winnr("$") let bnum = winbufnr(i) if bnum != -1 && getbufvar(bnum, '&buftype') ==# '' \ && !getwinvar(i, '&previewwindow') \ && (!getbufvar(bnum, '&modified') || &hidden) return i endif let i += 1 endwhile return -1 endfunction "FUNCTION: s:getPath(ln) {{{2 "Gets the full path to the node that is rendered on the given line number " "Args: "ln: the line number to get the path for " "Return: "A path if a node was selected, {} if nothing is selected. "If the 'up a dir' line was selected then the path to the parent of the "current root is returned function! s:getPath(ln) let line = getline(a:ln) let rootLine = s:TreeFileNode.GetRootLineNum() "check to see if we have the root node if a:ln == rootLine return b:NERDTreeRoot.path endif if !g:NERDTreeDirArrows " in case called from outside the tree if line !~# '^ *[|`▸▾ ]' || line =~# '^$' return {} endif endif if line ==# s:tree_up_dir_line return b:NERDTreeRoot.path.getParent() endif let indent = s:indentLevelFor(line) "remove the tree parts and the leading space let curFile = s:stripMarkupFromLine(line, 0) let wasdir = 0 if curFile =~# '/$' let wasdir = 1 let curFile = substitute(curFile, '/\?$', '/', "") endif let dir = "" let lnum = a:ln while lnum > 0 let lnum = lnum - 1 let curLine = getline(lnum) let curLineStripped = s:stripMarkupFromLine(curLine, 1) "have we reached the top of the tree? if lnum == rootLine let dir = b:NERDTreeRoot.path.str({'format': 'UI'}) . dir break endif if curLineStripped =~# '/$' let lpindent = s:indentLevelFor(curLine) if lpindent < indent let indent = indent - 1 let dir = substitute (curLineStripped,'^\\', "", "") . dir continue endif endif endwhile let curFile = b:NERDTreeRoot.path.drive . dir . curFile let toReturn = s:Path.New(curFile) return toReturn endfunction "FUNCTION: s:getTreeWinNum() {{{2 "gets the nerd tree window number for this tab function! s:getTreeWinNum() if exists("t:NERDTreeBufName") return bufwinnr(t:NERDTreeBufName) else return -1 endif endfunction "FUNCTION: s:indentLevelFor(line) {{{2 function! s:indentLevelFor(line) let level = match(a:line, '[^ \-+~▸▾`|]') / s:tree_wid " check if line includes arrows if match(a:line, '[▸▾]') > -1 " decrement level as arrow uses 3 ascii chars let level = level - 1 endif return level endfunction "FUNCTION: s:isTreeOpen() {{{2 function! s:isTreeOpen() return s:getTreeWinNum() != -1 endfunction "FUNCTION: s:isWindowUsable(winnumber) {{{2 "Returns 0 if opening a file from the tree in the given window requires it to "be split, 1 otherwise " "Args: "winnumber: the number of the window in question function! s:isWindowUsable(winnumber) "gotta split if theres only one window (i.e. the NERD tree) if winnr("$") ==# 1 return 0 endif let oldwinnr = winnr() call s:exec(a:winnumber . "wincmd p") let specialWindow = getbufvar("%", '&buftype') != '' || getwinvar('%', '&previewwindow') let modified = &modified call s:exec(oldwinnr . "wincmd p") "if its a special window e.g. quickfix or another explorer plugin then we "have to split if specialWindow return 0 endif if &hidden return 1 endif return !modified || s:bufInWindows(winbufnr(a:winnumber)) >= 2 endfunction " FUNCTION: s:jumpToChild(direction) {{{2 " Args: " direction: 0 if going to first child, 1 if going to last function! s:jumpToChild(direction) let currentNode = s:TreeFileNode.GetSelected() if currentNode ==# {} || currentNode.isRoot() call s:echo("cannot jump to " . (a:direction ? "last" : "first") . " child") return end let dirNode = currentNode.parent let childNodes = dirNode.getVisibleChildren() let targetNode = childNodes[0] if a:direction let targetNode = childNodes[len(childNodes) - 1] endif if targetNode.equals(currentNode) let siblingDir = currentNode.parent.findOpenDirSiblingWithVisibleChildren(a:direction) if siblingDir != {} let indx = a:direction ? siblingDir.getVisibleChildCount()-1 : 0 let targetNode = siblingDir.getChildByIndex(indx, 1) endif endif call targetNode.putCursorHere(1, 0) call s:centerView() endfunction "FUNCTION: s:promptToDelBuffer(bufnum, msg){{{2 "prints out the given msg and, if the user responds by pushing 'y' then the "buffer with the given bufnum is deleted " "Args: "bufnum: the buffer that may be deleted "msg: a message that will be echoed to the user asking them if they wish to " del the buffer function! s:promptToDelBuffer(bufnum, msg) echo a:msg if nr2char(getchar()) ==# 'y' exec "silent bdelete! " . a:bufnum endif endfunction "FUNCTION: s:putCursorOnBookmarkTable(){{{2 "Places the cursor at the top of the bookmarks table function! s:putCursorOnBookmarkTable() if !b:NERDTreeShowBookmarks throw "NERDTree.IllegalOperationError: cant find bookmark table, bookmarks arent active" endif if g:NERDTreeMinimalUI return cursor(1, 2) endif let rootNodeLine = s:TreeFileNode.GetRootLineNum() let line = 1 while getline(line) !~# '^>-\+Bookmarks-\+$' let line = line + 1 if line >= rootNodeLine throw "NERDTree.BookmarkTableNotFoundError: didnt find the bookmarks table" endif endwhile call cursor(line, 2) endfunction "FUNCTION: s:putCursorInTreeWin(){{{2 "Places the cursor in the nerd tree window function! s:putCursorInTreeWin() if !s:isTreeOpen() throw "NERDTree.InvalidOperationError: cant put cursor in NERD tree window, no window exists" endif call s:exec(s:getTreeWinNum() . "wincmd w") endfunction "FUNCTION: s:renderBookmarks {{{2 function! s:renderBookmarks() if g:NERDTreeMinimalUI == 0 call setline(line(".")+1, ">----------Bookmarks----------") call cursor(line(".")+1, col(".")) endif for i in s:Bookmark.Bookmarks() call setline(line(".")+1, i.str()) call cursor(line(".")+1, col(".")) endfor call setline(line(".")+1, '') call cursor(line(".")+1, col(".")) endfunction "FUNCTION: s:renderView {{{2 "The entry function for rendering the tree function! s:renderView() setlocal modifiable "remember the top line of the buffer and the current line so we can "restore the view exactly how it was let curLine = line(".") let curCol = col(".") let topLine = line("w0") "delete all lines in the buffer (being careful not to clobber a register) silent 1,$delete _ call s:dumpHelp() "delete the blank line before the help and add one after it if g:NERDTreeMinimalUI == 0 call setline(line(".")+1, "") call cursor(line(".")+1, col(".")) endif if b:NERDTreeShowBookmarks call s:renderBookmarks() endif "add the 'up a dir' line if !g:NERDTreeMinimalUI call setline(line(".")+1, s:tree_up_dir_line) call cursor(line(".")+1, col(".")) endif "draw the header line let header = b:NERDTreeRoot.path.str({'format': 'UI', 'truncateTo': winwidth(0)}) call setline(line(".")+1, header) call cursor(line(".")+1, col(".")) "draw the tree let old_o = @o let @o = b:NERDTreeRoot.renderToString() silent put o let @o = old_o "delete the blank line at the top of the buffer silent 1,1delete _ "restore the view let old_scrolloff=&scrolloff let &scrolloff=0 call cursor(topLine, 1) normal! zt call cursor(curLine, curCol) let &scrolloff = old_scrolloff setlocal nomodifiable endfunction "FUNCTION: s:renderViewSavingPosition {{{2 "Renders the tree and ensures the cursor stays on the current node or the "current nodes parent if it is no longer available upon re-rendering function! s:renderViewSavingPosition() let currentNode = s:TreeFileNode.GetSelected() "go up the tree till we find a node that will be visible or till we run "out of nodes while currentNode != {} && !currentNode.isVisible() && !currentNode.isRoot() let currentNode = currentNode.parent endwhile call s:renderView() if currentNode != {} call currentNode.putCursorHere(0, 0) endif endfunction "FUNCTION: s:restoreScreenState() {{{2 " "Sets the screen state back to what it was when s:saveScreenState was last "called. " "Assumes the cursor is in the NERDTree window function! s:restoreScreenState() if !exists("b:NERDTreeOldTopLine") || !exists("b:NERDTreeOldPos") || !exists("b:NERDTreeOldWindowSize") return endif exec("silent vertical resize ".b:NERDTreeOldWindowSize) let old_scrolloff=&scrolloff let &scrolloff=0 call cursor(b:NERDTreeOldTopLine, 0) normal! zt call setpos(".", b:NERDTreeOldPos) let &scrolloff=old_scrolloff endfunction "FUNCTION: s:saveScreenState() {{{2 "Saves the current cursor position in the current buffer and the window "scroll position function! s:saveScreenState() let win = winnr() try call s:putCursorInTreeWin() let b:NERDTreeOldPos = getpos(".") let b:NERDTreeOldTopLine = line("w0") let b:NERDTreeOldWindowSize = winwidth("") call s:exec(win . "wincmd w") catch /^NERDTree.InvalidOperationError/ endtry endfunction "FUNCTION: s:setCommonBufOptions() {{{2 function! s:setCommonBufOptions() "throwaway buffer options setlocal noswapfile setlocal buftype=nofile setlocal bufhidden=hide setlocal nowrap setlocal foldcolumn=0 setlocal nobuflisted setlocal nospell if g:NERDTreeShowLineNumbers setlocal nu else setlocal nonu if v:version >= 703 setlocal nornu endif endif iabc <buffer> if g:NERDTreeHighlightCursorline setlocal cursorline endif call s:setupStatusline() let b:treeShowHelp = 0 let b:NERDTreeIgnoreEnabled = 1 let b:NERDTreeShowFiles = g:NERDTreeShowFiles let b:NERDTreeShowHidden = g:NERDTreeShowHidden let b:NERDTreeShowBookmarks = g:NERDTreeShowBookmarks setfiletype nerdtree call s:bindMappings() endfunction "FUNCTION: s:setupStatusline() {{{2 function! s:setupStatusline() if g:NERDTreeStatusline != -1 let &l:statusline = g:NERDTreeStatusline endif endfunction "FUNCTION: s:stripMarkupFromLine(line, removeLeadingSpaces){{{2 "returns the given line with all the tree parts stripped off " "Args: "line: the subject line "removeLeadingSpaces: 1 if leading spaces are to be removed (leading spaces = "any spaces before the actual text of the node) function! s:stripMarkupFromLine(line, removeLeadingSpaces) let line = a:line "remove the tree parts and the leading space let line = substitute (line, s:tree_markup_reg,"","") "strip off any read only flag let line = substitute (line, ' \[RO\]', "","") "strip off any bookmark flags let line = substitute (line, ' {[^}]*}', "","") "strip off any executable flags let line = substitute (line, '*\ze\($\| \)', "","") let wasdir = 0 if line =~# '/$' let wasdir = 1 endif let line = substitute (line,' -> .*',"","") " remove link to if wasdir ==# 1 let line = substitute (line, '/\?$', '/', "") endif if a:removeLeadingSpaces let line = substitute (line, '^ *', '', '') endif return line endfunction "FUNCTION: s:toggle(dir) {{{2 "Toggles the NERD tree. I.e the NERD tree is open, it is closed, if it is "closed it is restored or initialized (if it doesnt exist) " "Args: "dir: the full path for the root node (is only used if the NERD tree is being "initialized. function! s:toggle(dir) if s:treeExistsForTab() if !s:isTreeOpen() call s:createTreeWin() if !&hidden call s:renderView() endif call s:restoreScreenState() else call s:closeTree() endif else call s:initNerdTree(a:dir) endif endfunction "SECTION: Interface bindings {{{1 "============================================================ "FUNCTION: s:activateNode(forceKeepWindowOpen) {{{2 "If the current node is a file, open it in the previous window (or a new one "if the previous is modified). If it is a directory then it is opened. " "args: "forceKeepWindowOpen - dont close the window even if NERDTreeQuitOnOpen is set function! s:activateNode(forceKeepWindowOpen) if getline(".") ==# s:tree_up_dir_line return s:upDir(0) endif let treenode = s:TreeFileNode.GetSelected() if treenode != {} call treenode.activate(a:forceKeepWindowOpen) else let bookmark = s:Bookmark.GetSelected() if !empty(bookmark) call bookmark.activate() endif endif endfunction "FUNCTION: s:bindMappings() {{{2 function! s:bindMappings() " set up mappings and commands for this buffer nnoremap <silent> <buffer> <middlerelease> :call <SID>handleMiddleMouse()<cr> nnoremap <silent> <buffer> <leftrelease> <leftrelease>:call <SID>checkForActivate()<cr> nnoremap <silent> <buffer> <2-leftmouse> :call <SID>activateNode(0)<cr> exec "nnoremap <silent> <buffer> ". g:NERDTreeMapActivateNode . " :call <SID>activateNode(0)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapOpenSplit ." :call <SID>openEntrySplit(0,0)<cr>" exec "nnoremap <silent> <buffer> <cr> :call <SID>activateNode(0)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapPreview ." :call <SID>previewNode(0)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapPreviewSplit ." :call <SID>previewNode(1)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapOpenVSplit ." :call <SID>openEntrySplit(1,0)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapPreviewVSplit ." :call <SID>previewNode(2)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapOpenRecursively ." :call <SID>openNodeRecursively()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapUpdirKeepOpen ." :call <SID>upDir(1)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapUpdir ." :call <SID>upDir(0)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapChangeRoot ." :call <SID>chRoot()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapChdir ." :call <SID>chCwd()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapQuit ." :call <SID>closeTreeWindow()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapRefreshRoot ." :call <SID>refreshRoot()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapRefresh ." :call <SID>refreshCurrent()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapHelp ." :call <SID>displayHelp()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapToggleZoom ." :call <SID>toggleZoom()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapToggleHidden ." :call <SID>toggleShowHidden()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapToggleFilters ." :call <SID>toggleIgnoreFilter()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapToggleFiles ." :call <SID>toggleShowFiles()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapToggleBookmarks ." :call <SID>toggleShowBookmarks()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapCloseDir ." :call <SID>closeCurrentDir()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapCloseChildren ." :call <SID>closeChildren()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapMenu ." :call <SID>showMenu()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapJumpParent ." :call <SID>jumpToParent()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapJumpNextSibling ." :call <SID>jumpToSibling(1)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapJumpPrevSibling ." :call <SID>jumpToSibling(0)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapJumpFirstChild ." :call <SID>jumpToFirstChild()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapJumpLastChild ." :call <SID>jumpToLastChild()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapJumpRoot ." :call <SID>jumpToRoot()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapOpenInTab ." :call <SID>openInNewTab(0)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapOpenInTabSilent ." :call <SID>openInNewTab(1)<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapOpenExpl ." :call <SID>openExplorer()<cr>" exec "nnoremap <silent> <buffer> ". g:NERDTreeMapDeleteBookmark ." :call <SID>deleteBookmark()<cr>" "bind all the user custom maps call s:KeyMap.BindAll() command! -buffer -nargs=? Bookmark :call <SID>bookmarkNode('<args>') command! -buffer -complete=customlist,s:completeBookmarks -nargs=1 RevealBookmark :call <SID>revealBookmark('<args>') command! -buffer -complete=customlist,s:completeBookmarks -nargs=1 OpenBookmark :call <SID>openBookmark('<args>') command! -buffer -complete=customlist,s:completeBookmarks -nargs=* ClearBookmarks call <SID>clearBookmarks('<args>') command! -buffer -complete=customlist,s:completeBookmarks -nargs=+ BookmarkToRoot call s:Bookmark.ToRoot('<args>') command! -buffer -nargs=0 ClearAllBookmarks call s:Bookmark.ClearAll() <bar> call <SID>renderView() command! -buffer -nargs=0 ReadBookmarks call s:Bookmark.CacheBookmarks(0) <bar> call <SID>renderView() command! -buffer -nargs=0 WriteBookmarks call s:Bookmark.Write() endfunction " FUNCTION: s:bookmarkNode(name) {{{2 " Associate the current node with the given name function! s:bookmarkNode(...) let currentNode = s:TreeFileNode.GetSelected() if currentNode != {} let name = a:1 if empty(name) let name = currentNode.path.getLastPathComponent(0) endif try call currentNode.bookmark(name) call s:renderView() catch /^NERDTree.IllegalBookmarkNameError/ call s:echo("bookmark names must not contain spaces") endtry else call s:echo("select a node first") endif endfunction "FUNCTION: s:checkForActivate() {{{2 "Checks if the click should open the current node, if so then activate() is "called (directories are automatically opened if the symbol beside them is "clicked) function! s:checkForActivate() let currentNode = s:TreeFileNode.GetSelected() if currentNode != {} let startToCur = strpart(getline(line(".")), 0, col(".")) if currentNode.path.isDirectory if startToCur =~# s:tree_markup_reg . '$' && startToCur =~# '[+~▾▸]$' call s:activateNode(0) return endif endif if (g:NERDTreeMouseMode ==# 2 && currentNode.path.isDirectory) || g:NERDTreeMouseMode ==# 3 let char = strpart(startToCur, strlen(startToCur)-1, 1) if char !~# s:tree_markup_reg call s:activateNode(0) return endif endif endif endfunction " FUNCTION: s:chCwd() {{{2 function! s:chCwd() let treenode = s:TreeFileNode.GetSelected() if treenode ==# {} call s:echo("Select a node first") return endif try call treenode.path.changeToDir() catch /^NERDTree.PathChangeError/ call s:echoWarning("could not change cwd") endtry endfunction " FUNCTION: s:chRoot() {{{2 " changes the current root to the selected one function! s:chRoot() let treenode = s:TreeFileNode.GetSelected() if treenode ==# {} call s:echo("Select a node first") return endif call treenode.makeRoot() call s:renderView() call b:NERDTreeRoot.putCursorHere(0, 0) endfunction " FUNCTION: s:clearBookmarks(bookmarks) {{{2 function! s:clearBookmarks(bookmarks) if a:bookmarks ==# '' let currentNode = s:TreeFileNode.GetSelected() if currentNode != {} call currentNode.clearBoomarks() endif else for name in split(a:bookmarks, ' ') let bookmark = s:Bookmark.BookmarkFor(name) call bookmark.delete() endfor endif call s:renderView() endfunction " FUNCTION: s:closeChildren() {{{2 " closes all childnodes of the current node function! s:closeChildren() let currentNode = s:TreeDirNode.GetSelected() if currentNode ==# {} call s:echo("Select a node first") return endif call currentNode.closeChildren() call s:renderView() call currentNode.putCursorHere(0, 0) endfunction " FUNCTION: s:closeCurrentDir() {{{2 " closes the parent dir of the current node function! s:closeCurrentDir() let treenode = s:TreeFileNode.GetSelected() if treenode ==# {} call s:echo("Select a node first") return endif let parent = treenode.parent if parent ==# {} || parent.isRoot() call s:echo("cannot close tree root") else call treenode.parent.close() call s:renderView() call treenode.parent.putCursorHere(0, 0) endif endfunction " FUNCTION: s:closeTreeWindow() {{{2 " close the tree window function! s:closeTreeWindow() if b:NERDTreeType ==# "secondary" && b:NERDTreePreviousBuf != -1 exec "buffer " . b:NERDTreePreviousBuf else if winnr("$") > 1 call s:closeTree() else call s:echo("Cannot close last window") endif endif endfunction " FUNCTION: s:deleteBookmark() {{{2 " if the cursor is on a bookmark, prompt to delete function! s:deleteBookmark() let bookmark = s:Bookmark.GetSelected() if bookmark ==# {} call s:echo("Put the cursor on a bookmark") return endif echo "Are you sure you wish to delete the bookmark:\n\"" . bookmark.name . "\" (yN):" if nr2char(getchar()) ==# 'y' try call bookmark.delete() call s:renderView() redraw catch /^NERDTree/ call s:echoWarning("Could not remove bookmark") endtry else call s:echo("delete aborted" ) endif endfunction " FUNCTION: s:displayHelp() {{{2 " toggles the help display function! s:displayHelp() let b:treeShowHelp = b:treeShowHelp ? 0 : 1 call s:renderView() call s:centerView() endfunction " FUNCTION: s:handleMiddleMouse() {{{2 function! s:handleMiddleMouse() let curNode = s:TreeFileNode.GetSelected() if curNode ==# {} call s:echo("Put the cursor on a node first" ) return endif if curNode.path.isDirectory call s:openExplorer() else call s:openEntrySplit(0,0) endif endfunction " FUNCTION: s:jumpToFirstChild() {{{2 " wrapper for the jump to child method function! s:jumpToFirstChild() call s:jumpToChild(0) endfunction " FUNCTION: s:jumpToLastChild() {{{2 " wrapper for the jump to child method function! s:jumpToLastChild() call s:jumpToChild(1) endfunction " FUNCTION: s:jumpToParent() {{{2 " moves the cursor to the parent of the current node function! s:jumpToParent() let currentNode = s:TreeFileNode.GetSelected() if !empty(currentNode) if !empty(currentNode.parent) call currentNode.parent.putCursorHere(1, 0) call s:centerView() else call s:echo("cannot jump to parent") endif else call s:echo("put the cursor on a node first") endif endfunction " FUNCTION: s:jumpToRoot() {{{2 " moves the cursor to the root node function! s:jumpToRoot() call b:NERDTreeRoot.putCursorHere(1, 0) call s:centerView() endfunction " FUNCTION: s:jumpToSibling() {{{2 " moves the cursor to the sibling of the current node in the given direction " " Args: " forward: 1 if the cursor should move to the next sibling, 0 if it should " move back to the previous sibling function! s:jumpToSibling(forward) let currentNode = s:TreeFileNode.GetSelected() if !empty(currentNode) let sibling = currentNode.findSibling(a:forward) if !empty(sibling) call sibling.putCursorHere(1, 0) call s:centerView() endif else call s:echo("put the cursor on a node first") endif endfunction " FUNCTION: s:openBookmark(name) {{{2 " put the cursor on the given bookmark and, if its a file, open it function! s:openBookmark(name) try let targetNode = s:Bookmark.GetNodeForName(a:name, 0) call targetNode.putCursorHere(0, 1) redraw! catch /^NERDTree.BookmarkedNodeNotFoundError/ call s:echo("note - target node is not cached") let bookmark = s:Bookmark.BookmarkFor(a:name) let targetNode = s:TreeFileNode.New(bookmark.path) endtry if targetNode.path.isDirectory call targetNode.openExplorer() else call targetNode.open() endif endfunction " FUNCTION: s:openEntrySplit(vertical, forceKeepWindowOpen) {{{2 "Opens the currently selected file from the explorer in a "new window " "args: "forceKeepWindowOpen - dont close the window even if NERDTreeQuitOnOpen is set function! s:openEntrySplit(vertical, forceKeepWindowOpen) let treenode = s:TreeFileNode.GetSelected() if treenode != {} if a:vertical call treenode.openVSplit() else call treenode.openSplit() endif if !a:forceKeepWindowOpen call s:closeTreeIfQuitOnOpen() endif else call s:echo("select a node first") endif endfunction " FUNCTION: s:openExplorer() {{{2 function! s:openExplorer() let treenode = s:TreeDirNode.GetSelected() if treenode != {} call treenode.openExplorer() else call s:echo("select a node first") endif endfunction " FUNCTION: s:openInNewTab(stayCurrentTab) {{{2 " Opens the selected node or bookmark in a new tab " Args: " stayCurrentTab: if 1 then vim will stay in the current tab, if 0 then vim " will go to the tab where the new file is opened function! s:openInNewTab(stayCurrentTab) let target = s:TreeFileNode.GetSelected() if target == {} let target = s:Bookmark.GetSelected() endif if target != {} call target.openInNewTab({'stayInCurrentTab': a:stayCurrentTab}) endif endfunction " FUNCTION: s:openNodeRecursively() {{{2 function! s:openNodeRecursively() let treenode = s:TreeFileNode.GetSelected() if treenode ==# {} || treenode.path.isDirectory ==# 0 call s:echo("Select a directory node first" ) else call s:echo("Recursively opening node. Please wait...") call treenode.openRecursively() call s:renderView() redraw call s:echo("Recursively opening node. Please wait... DONE") endif endfunction "FUNCTION: s:previewNode() {{{2 "Args: " openNewWin: if 0, use the previous window, if 1 open in new split, if 2 " open in a vsplit function! s:previewNode(openNewWin) let currentBuf = bufnr("") if a:openNewWin > 0 call s:openEntrySplit(a:openNewWin ==# 2,1) else call s:activateNode(1) end call s:exec(bufwinnr(currentBuf) . "wincmd w") endfunction " FUNCTION: s:revealBookmark(name) {{{2 " put the cursor on the node associate with the given name function! s:revealBookmark(name) try let targetNode = s:Bookmark.GetNodeForName(a:name, 0) call targetNode.putCursorHere(0, 1) catch /^NERDTree.BookmarkNotFoundError/ call s:echo("Bookmark isnt cached under the current root") endtry endfunction " FUNCTION: s:refreshRoot() {{{2 " Reloads the current root. All nodes below this will be lost and the root dir " will be reloaded. function! s:refreshRoot() call s:echo("Refreshing the root node. This could take a while...") call b:NERDTreeRoot.refresh() call s:renderView() redraw call s:echo("Refreshing the root node. This could take a while... DONE") endfunction " FUNCTION: s:refreshCurrent() {{{2 " refreshes the root for the current node function! s:refreshCurrent() let treenode = s:TreeDirNode.GetSelected() if treenode ==# {} call s:echo("Refresh failed. Select a node first") return endif call s:echo("Refreshing node. This could take a while...") call treenode.refresh() call s:renderView() redraw call s:echo("Refreshing node. This could take a while... DONE") endfunction " FUNCTION: s:showMenu() {{{2 function! s:showMenu() let curNode = s:TreeFileNode.GetSelected() if curNode ==# {} call s:echo("Put the cursor on a node first" ) return endif let mc = s:MenuController.New(s:MenuItem.AllEnabled()) call mc.showMenu() endfunction " FUNCTION: s:toggleIgnoreFilter() {{{2 " toggles the use of the NERDTreeIgnore option function! s:toggleIgnoreFilter() let b:NERDTreeIgnoreEnabled = !b:NERDTreeIgnoreEnabled call s:renderViewSavingPosition() call s:centerView() endfunction " FUNCTION: s:toggleShowBookmarks() {{{2 " toggles the display of bookmarks function! s:toggleShowBookmarks() let b:NERDTreeShowBookmarks = !b:NERDTreeShowBookmarks if b:NERDTreeShowBookmarks call s:renderView() call s:putCursorOnBookmarkTable() else call s:renderViewSavingPosition() endif call s:centerView() endfunction " FUNCTION: s:toggleShowFiles() {{{2 " toggles the display of hidden files function! s:toggleShowFiles() let b:NERDTreeShowFiles = !b:NERDTreeShowFiles call s:renderViewSavingPosition() call s:centerView() endfunction " FUNCTION: s:toggleShowHidden() {{{2 " toggles the display of hidden files function! s:toggleShowHidden() let b:NERDTreeShowHidden = !b:NERDTreeShowHidden call s:renderViewSavingPosition() call s:centerView() endfunction " FUNCTION: s:toggleZoom() {{2 " zoom (maximize/minimize) the NERDTree window function! s:toggleZoom() if exists("b:NERDTreeZoomed") && b:NERDTreeZoomed let size = exists("b:NERDTreeOldWindowSize") ? b:NERDTreeOldWindowSize : g:NERDTreeWinSize exec "silent vertical resize ". size let b:NERDTreeZoomed = 0 else exec "vertical resize" let b:NERDTreeZoomed = 1 endif endfunction "FUNCTION: s:upDir(keepState) {{{2 "moves the tree up a level " "Args: "keepState: 1 if the current root should be left open when the tree is "re-rendered function! s:upDir(keepState) let cwd = b:NERDTreeRoot.path.str({'format': 'UI'}) if cwd ==# "/" || cwd =~# '^[^/]..$' call s:echo("already at top dir") else if !a:keepState call b:NERDTreeRoot.close() endif let oldRoot = b:NERDTreeRoot if empty(b:NERDTreeRoot.parent) let path = b:NERDTreeRoot.path.getParent() let newRoot = s:TreeDirNode.New(path) call newRoot.open() call newRoot.transplantChild(b:NERDTreeRoot) let b:NERDTreeRoot = newRoot else let b:NERDTreeRoot = b:NERDTreeRoot.parent endif if g:NERDTreeChDirMode ==# 2 call b:NERDTreeRoot.path.changeToDir() endif call s:renderView() call oldRoot.putCursorHere(0, 0) endif endfunction "reset &cpo back to users setting let &cpo = s:old_cpo " vim: set sw=4 sts=4 et fdm=marker:
00000svn-vim-cfg
trunk/vimfiles/plugin/NERD_tree.vim
Vim Script
gpl3
126,233
" Script Name: mark.vim " Description: Highlight several words in different colors simultaneously. " " Copyright: (C) 2005-2008 Yuheng Xie " (C) 2008-2013 Ingo Karkat " The VIM LICENSE applies to this script; see ':help copyright'. " " Maintainer: Ingo Karkat <ingo@karkat.de> " Orig Author: Yuheng Xie <elephant@linux.net.cn> " Contributors:Luc Hermitte, Ingo Karkat " " Dependencies: " - Requires Vim 7.1 with "matchadd()", or Vim 7.2 or higher. " - mark.vim autoload script " - mark/palettes.vim autoload script for additional palettes " " Version: 2.8.0 " Changes: " 31-May-2013, Ingo Karkat " - Define default mappings for keys 1-9 on the numerical keypad to jump to a " particular group (backwards with <C-kN>). Their definition is controlled by " the new g:mwDirectGroupJumpMappingNum variable. " - ENH: Allow to store an arbitrary number of marks via named slots that can " optionally be passed to :MarkLoad / :MarkSave. If the slot is all-uppercase, " the marks will also be persisted across Vim invocations. " " 31-Jan-2013, Ingo Karkat " - Also allow a [count] for <Leader>r to select (or query for) a mark group, as " with <Leader>m. " - CHG: Also set the current mark to the used mark group when a mark was set " via <Leader>r and :Mark so that it is easier to determine whether the " entered pattern actually matches anywhere. Thanks to Xiaopan Zhang for " notifying me about this problem. " - Add <Plug>MarkSearchGroupNext / <Plug>MarkSearchGroupPrev to enable " searching for particular mark groups. Thanks to Xiaopan Zhang for the " suggestion. " " 13-Sep-2012, Ingo Karkat " - Enable alternative * / # mappings that do not remember the last search type " through new <Plug>MarkSearchOrCurNext, <Plug>MarkSearchOrCurPrev, " <Plug>MarkSearchOrAnyNext, <Plug>MarkSearchOrAnyPrev mappings. " " 04-Jul-2012, Ingo Karkat " - Introduce g:mwPalettes instead of hard-coding them in " s:DefaultHighlightings(), which got s:DefineHighlightings() extracted and " the rest renamed to s:GetPalette(). " - Allow overriding of existing mark highlighting via a:isOverride argument to " s:DefineHighlightings(). " - Add "maximum" palette contributed by rockybalboa4 and move it and the " "extended" palette to a separate mark/palettes.vim autoload script. " - ENH: Implement :MarkPalette command to switch mark highlighting on-the-fly " during runtime. " " 24-Jun-2012, Ingo Karkat " - Don't define the default <Leader>m and <Leader>r mappings in select mode, " just visual mode. Thanks to rockybalboa4 for pointing this out. " " 27-Mar-2012, Ingo Karkat " - ENH: Allow choosing of palette and limiting of default mark highlight groups " via g:mwDefaultHighlightingPalette and g:mwDefaultHighlightingNum. " - ENH: Offer an extended color palette in addition to the original 6-color one. " " 23-Mar-2012, Ingo Karkat " - ENH: Add :Marks command that prints all mark highlight groups and their " search patterns, plus information about the current search mark, next mark " group, and whether marks are disabled. " - FIX: When the cursor is positioned on the current mark, [N]<Leader>n / " <Plug>MarkClear with [N] appended the pattern for the current mark (again " and again) instead of clearing it. Must not pass current mark pattern when " [N] is given. " " 22-Mar-2012, Ingo Karkat " - ENH: Allow [count] for <Leader>m and :Mark to add / subtract match to / from " highlight group [count], and use [count]<Leader>n to clear only highlight " group [count]. This was also requested by Philipp Marek. " " 02-Mar-2012, Philipp Marek " - BUG: Version check mistakenly excluded Vim 7.1 versions that do have the " matchadd() function. " " 06-May-2011, Ingo Karkat " - By default, enable g:mwAutoSaveMarks, so that marks are always persisted, " but disable g:mwAutoLoadMarks, so that persisted marks have to be explicitly " loaded, if that is desired. I often wondered why I got unexpected mark " highlightings in a new Vim session until I realized that I had used marks in " a previous session and forgot to clear them. " " 21-Apr-2011, Ingo Karkat " - Expose toggling of mark display (keeping the mark patterns) via new " <Plug>MarkToggle mapping. Offer :MarkClear command as a replacement for the " old argumentless :Mark command, which now just disables, but not clears all " marks. " - Implement lazy-loading of disabled persistent marks via g:mwDoDeferredLoad " flag passing to autoload/mark.vim. " " 19-Apr-2011, Ingo Karkat " - ENH: Add explicit mark persistence via :MarkLoad and :MarkSave commands and " automatic persistence via the g:mwAutoLoadMarks and g:mwAutoSaveMarks " configuration flags. " " 15-Apr-2011, Ingo Karkat " - Avoid losing the mark highlightings on :syn on or :colorscheme commands. " Thanks to Zhou YiChao for alerting me to this issue and suggesting a fix. " " 17-Nov-2009, Ingo Karkat " - Replaced the (overly) generic mark#GetVisualSelectionEscaped() with " mark#GetVisualSelectionAsRegexp() and " mark#GetVisualSelectionAsLiteralPattern(). " " 04-Jul-2009, Ingo Karkat " - A [count] before any mapping either caused "No range allowed" error or just " repeated the :call [count] times, resulting in the current search pattern " echoed [count] times and a hit-enter prompt. Now suppressing [count] via " <C-u> and handling it inside the implementation. " - Now passing isBackward (0/1) instead of optional 'b' flag into functions. " Also passing empty regexp to mark#MarkRegex() to avoid any optional " arguments. " " 02-Jul-2009, Ingo Karkat " - Split off functions into autoload script. " - Removed g:force_reload_mark. " - Initialization of global variables and autocommands is now done lazily on " the first use, not during loading of the plugin. This reduces Vim startup " time and footprint as long as the functionality isn't yet used. " " 6-Jun-2009, Ingo Karkat " 1. Somehow s:WrapMessage() needs a redraw before the :echo to avoid that a " later Vim redraw clears the wrap message. This happened when there's no " statusline and thus :echo'ing into the ruler. " 2. Removed line-continuations and ':set cpo=...'. Upper-cased <SID> and <CR>. " 3. Added default highlighting for the special search type. " " 2-Jun-2009, Ingo Karkat " 1. Replaced highlighting via :syntax with matchadd() / matchdelete(). This " requires Vim 7.2 / 7.1 with patches. This method is faster, there are no " more clashes with syntax highlighting (:match always has preference), and " the background highlighting does not disappear under 'cursorline'. " 2. Factored :windo application out into s:MarkScope(). " 3. Using winrestcmd() to fix effects of :windo: By entering a window, its " height is potentially increased from 0 to 1. " 4. Handling multiple tabs by calling s:UpdateScope() on the TabEnter event. " " 1-Jun-2009, Ingo Karkat " 1. Now using Vim List for g:mwWord and thus requiring Vim 7. g:mwCycle is now " zero-based, but the syntax groups "MarkWordx" are still one-based. " 2. Added missing setter for re-inclusion guard. " 3. Factored :syntax operations out of s:DoMark() and s:UpdateMark() so that " they can all be done in a single :windo. " 4. Normal mode <Plug>MarkSet now has the same semantics as its visual mode " cousin: If the cursor is on an existing mark, the mark is removed. " Beforehand, one could only remove a visually selected mark via again " selecting it. Now, one simply can invoke the mapping when on such a mark. " 5. Highlighting can now actually be overridden in the vimrc (anywhere " _before_ sourcing this script) by using ':hi def'. " " 31-May-2009, Ingo Karkat " 1. Refactored s:Search() to optionally take advantage of SearchSpecial.vim " autoload functionality for echoing of search pattern, wrap and error " messages. " 2. Now prepending search type ("any-mark", "same-mark", "new-mark") for " better identification. " 3. Retired the algorithm in s:PrevWord in favor of simply using <cword>, " which makes mark.vim work like the * command. At the end of a line, " non-keyword characters may now be marked; the previous algorithm prefered " any preceding word. " 4. BF: If 'iskeyword' contains characters that have a special meaning in a " regex (e.g. [.*]), these are now escaped properly. " " 01-Sep-2008, Ingo Karkat: bugfixes and enhancements " 1. Added <Plug>MarkAllClear (without a default mapping), which clears all " marks, even when the cursor is on a mark. " 2. Added <Plug>... mappings for hard-coded \*, \#, \/, \?, * and #, to allow " re-mapping and disabling. Beforehand, there were some <Plug>... mappings " and hard-coded ones; now, everything can be customized. " 3. Bugfix: Using :autocmd without <bang> to avoid removing _all_ autocmds for " the BufWinEnter event. (Using a custom :augroup would be even better.) " 4. Bugfix: Explicitly defining s:current_mark_position; some execution paths " left it undefined, causing errors. " 5. Refactoring: Instead of calling s:InitMarkVariables() at the beginning of " several functions, just calling it once when sourcing the script. " 6. Refactoring: Moved multiple 'let lastwinnr = winnr()' to a single one at the " top of DoMark(). " 7. ENH: Make the match according to the 'ignorecase' setting, like the star " command. " 8. The jumps to the next/prev occurrence now print 'search hit BOTTOM, " continuing at TOP" and "Pattern not found:..." messages, like the * and " n/N Vim search commands. " 9. Jumps now open folds if the occurrence is inside a closed fold, just like n/N " do. " " 10th Mar 2006, Yuheng Xie: jump to ANY mark " (*) added \* \# \/ \? for the ability of jumping to ANY mark, even when the " cursor is not currently over any mark " " 20th Sep 2005, Yuheng Xie: minor modifications " (*) merged MarkRegexVisual into MarkRegex " (*) added GetVisualSelectionEscaped for multi-lines visual selection and " visual selection contains ^, $, etc. " (*) changed the name ThisMark to CurrentMark " (*) added SearchCurrentMark and re-used raw map (instead of Vim function) to " implement * and # " " 14th Sep 2005, Luc Hermitte: modifications done on v1.1.4 " (*) anti-reinclusion guards. They do not guard colors definitions in case " this script must be reloaded after .gvimrc " (*) Protection against disabled |line-continuation|s. " (*) Script-local functions " (*) Default keybindings " (*) \r for visual mode " (*) uses <Leader> instead of "\" " (*) do not mess with global variable g:w " (*) regex simplified -> double quotes changed into simple quotes. " (*) strpart(str, idx, 1) -> str[idx] " (*) command :Mark " -> e.g. :Mark Mark.\{-}\ze( " Avoid installing twice or when in unsupported Vim version. if exists('g:loaded_mark') || (v:version == 701 && ! exists('*matchadd')) || (v:version < 701) finish endif let g:loaded_mark = 1 let s:save_cpo = &cpo set cpo&vim "- configuration -------------------------------------------------------------- if ! exists('g:mwHistAdd') let g:mwHistAdd = '/@' endif if ! exists('g:mwAutoLoadMarks') let g:mwAutoLoadMarks = 0 endif if ! exists('g:mwAutoSaveMarks') let g:mwAutoSaveMarks = 1 endif if ! exists('g:mwDefaultHighlightingNum') let g:mwDefaultHighlightingNum = -1 endif if ! exists('g:mwDefaultHighlightingPalette') let g:mwDefaultHighlightingPalette = 'original' endif if ! exists('g:mwPalettes') let g:mwPalettes = { \ 'original': [ \ { 'ctermbg':'Cyan', 'ctermfg':'Black', 'guibg':'#8CCBEA', 'guifg':'Black' }, \ { 'ctermbg':'Green', 'ctermfg':'Black', 'guibg':'#A4E57E', 'guifg':'Black' }, \ { 'ctermbg':'Yellow', 'ctermfg':'Black', 'guibg':'#FFDB72', 'guifg':'Black' }, \ { 'ctermbg':'Red', 'ctermfg':'Black', 'guibg':'#FF7272', 'guifg':'Black' }, \ { 'ctermbg':'Magenta', 'ctermfg':'Black', 'guibg':'#FFB3FF', 'guifg':'Black' }, \ { 'ctermbg':'Blue', 'ctermfg':'Black', 'guibg':'#9999FF', 'guifg':'Black' }, \ { 'ctermbg':'Darkcyan', 'ctermfg':'Black', 'guibg':'#008080', 'guifg':'Black' }, \ { 'ctermbg':'Darkgreen', 'ctermfg':'Black', 'guibg':'#008000', 'guifg':'Black' }, \ { 'ctermbg':'Darkgray', 'ctermfg':'Black', 'guibg':'#A9A9A9', 'guifg':'Black' }, \ { 'ctermbg':'Lightred', 'ctermfg':'Black', 'guibg':'#FFA0A0', 'guifg':'Black' }, \ { 'ctermbg':'Lightblue', 'ctermfg':'Black', 'guibg':'#ADD8E6', 'guifg':'Black' }, \ { 'ctermbg':'Lightgreen', 'ctermfg':'Black', 'guibg':'#90EE90', 'guifg':'Black' }, \ { 'ctermbg':'Brown', 'ctermfg':'Black', 'guibg':'#804040', 'guifg':'Black' }, \ { 'ctermbg':'Grey', 'ctermfg':'Black', 'guibg':'#C0C0C0', 'guifg':'Black' }, \], \ 'extended': function('mark#palettes#Extended'), \ 'maximum': function('mark#palettes#Maximum') \} endif if ! exists('g:mwDirectGroupJumpMappingNum') let g:mwDirectGroupJumpMappingNum = 9 endif "- default highlightings ------------------------------------------------------ function! s:GetPalette() let l:palette = [] if type(g:mwDefaultHighlightingPalette) == type([]) " There are custom color definitions, not a named built-in palette. return g:mwDefaultHighlightingPalette endif if ! has_key(g:mwPalettes, g:mwDefaultHighlightingPalette) if ! empty(g:mwDefaultHighlightingPalette) let v:warningmsg = 'Mark: Unknown value for g:mwDefaultHighlightingPalette: ' . g:mwDefaultHighlightingPalette echohl WarningMsg echomsg v:warningmsg echohl None endif return [] endif if type(g:mwPalettes[g:mwDefaultHighlightingPalette]) == type([]) return g:mwPalettes[g:mwDefaultHighlightingPalette] elseif type(g:mwPalettes[g:mwDefaultHighlightingPalette]) == type(function('tr')) return call(g:mwPalettes[g:mwDefaultHighlightingPalette], []) else let v:errmsg = printf('Mark: Invalid value type for g:mwPalettes[%s]', g:mwDefaultHighlightingPalette) echohl ErrorMsg echomsg v:errmsg echohl None return [] endif endfunction function! s:DefineHighlightings( palette, isOverride ) let l:command = (a:isOverride ? 'highlight' : 'highlight def') let l:highlightingNum = (g:mwDefaultHighlightingNum == -1 ? len(a:palette) : g:mwDefaultHighlightingNum) for i in range(1, l:highlightingNum) execute l:command 'MarkWord' . i join(map(items(a:palette[i - 1]), 'join(v:val, "=")')) endfor return l:highlightingNum endfunction call s:DefineHighlightings(s:GetPalette(), 0) autocmd ColorScheme * call <SID>DefineHighlightings(<SID>GetPalette(), 0) " Default highlighting for the special search type. " You can override this by defining / linking the 'SearchSpecialSearchType' " highlight group before this script is sourced. highlight def link SearchSpecialSearchType MoreMsg "- mappings ------------------------------------------------------------------- nnoremap <silent> <Plug>MarkSet :<C-u>if !mark#MarkCurrentWord(v:count)<Bar>execute "normal! \<lt>C-\>\<lt>C-n>\<lt>Esc>"<Bar>endif<CR> vnoremap <silent> <Plug>MarkSet :<C-u>if !mark#DoMark(v:count, mark#GetVisualSelectionAsLiteralPattern())[0]<Bar>execute "normal! \<lt>C-\>\<lt>C-n>\<lt>Esc>"<Bar>endif<CR> nnoremap <silent> <Plug>MarkRegex :<C-u>if !mark#MarkRegex(v:count, '')<Bar>execute "normal! \<lt>C-\>\<lt>C-n>\<lt>Esc>"<Bar>endif<CR> vnoremap <silent> <Plug>MarkRegex :<C-u>if !mark#MarkRegex(v:count, mark#GetVisualSelectionAsRegexp())<Bar>execute "normal! \<lt>C-\>\<lt>C-n>\<lt>Esc>"<Bar>endif<CR> nnoremap <silent> <Plug>MarkClear :<C-u>if !mark#DoMark(v:count, (v:count ? '' : mark#CurrentMark()[0]))[0]<Bar>execute "normal! \<lt>C-\>\<lt>C-n>\<lt>Esc>"<Bar>endif<CR> nnoremap <silent> <Plug>MarkAllClear :<C-u>call mark#ClearAll()<CR> nnoremap <silent> <Plug>MarkToggle :<C-u>call mark#Toggle()<CR> nnoremap <silent> <Plug>MarkSearchCurrentNext :<C-u>call mark#SearchCurrentMark(0)<CR> nnoremap <silent> <Plug>MarkSearchCurrentPrev :<C-u>call mark#SearchCurrentMark(1)<CR> nnoremap <silent> <Plug>MarkSearchAnyNext :<C-u>call mark#SearchAnyMark(0)<CR> nnoremap <silent> <Plug>MarkSearchAnyPrev :<C-u>call mark#SearchAnyMark(1)<CR> " When typed, [*#nN] open the fold at the search result, but inside a mapping or " :normal this must be done explicitly via 'zv'. nnoremap <silent> <Plug>MarkSearchNext :<C-u>if !mark#SearchNext(0)<Bar>execute 'normal! *zv'<Bar>endif<CR> nnoremap <silent> <Plug>MarkSearchPrev :<C-u>if !mark#SearchNext(1)<Bar>execute 'normal! #zv'<Bar>endif<CR> nnoremap <silent> <Plug>MarkSearchOrCurNext :<C-u>if !mark#SearchNext(0,'mark#SearchCurrentMark')<Bar>execute 'normal! *zv'<Bar>endif<CR> nnoremap <silent> <Plug>MarkSearchOrCurPrev :<C-u>if !mark#SearchNext(1,'mark#SearchCurrentMark')<Bar>execute 'normal! #zv'<Bar>endif<CR> nnoremap <silent> <Plug>MarkSearchOrAnyNext :<C-u>if !mark#SearchNext(0,'mark#SearchAnyMark')<Bar>execute 'normal! *zv'<Bar>endif<CR> nnoremap <silent> <Plug>MarkSearchOrAnyPrev :<C-u>if !mark#SearchNext(1,'mark#SearchAnyMark')<Bar>execute 'normal! #zv'<Bar>endif<CR> nnoremap <silent> <Plug>MarkSearchGroupNext :<C-u>call mark#SearchGroupMark(v:count, 1, 0, 1)<CR> nnoremap <silent> <Plug>MarkSearchGroupPrev :<C-u>call mark#SearchGroupMark(v:count, 1, 1, 1)<CR> if !hasmapto('<Plug>MarkSet', 'n') nmap <unique> <Leader>m <Plug>MarkSet endif if !hasmapto('<Plug>MarkSet', 'x') xmap <unique> <Leader>m <Plug>MarkSet endif if !hasmapto('<Plug>MarkRegex', 'n') nmap <unique> <Leader>r <Plug>MarkRegex endif if !hasmapto('<Plug>MarkRegex', 'x') xmap <unique> <Leader>r <Plug>MarkRegex endif if !hasmapto('<Plug>MarkClear', 'n') nmap <unique> <Leader>n <Plug>MarkClear endif " No default mapping for <Plug>MarkAllClear. " No default mapping for <Plug>MarkToggle. if !hasmapto('<Plug>MarkSearchCurrentNext', 'n') nmap <unique> <Leader>* <Plug>MarkSearchCurrentNext endif if !hasmapto('<Plug>MarkSearchCurrentPrev', 'n') nmap <unique> <Leader># <Plug>MarkSearchCurrentPrev endif if !hasmapto('<Plug>MarkSearchAnyNext', 'n') nmap <unique> <Leader>/ <Plug>MarkSearchAnyNext endif if !hasmapto('<Plug>MarkSearchAnyPrev', 'n') nmap <unique> <Leader>? <Plug>MarkSearchAnyPrev endif if !hasmapto('<Plug>MarkSearchNext', 'n') nmap <unique> * <Plug>MarkSearchNext endif if !hasmapto('<Plug>MarkSearchPrev', 'n') nmap <unique> # <Plug>MarkSearchPrev endif " No default mapping for <Plug>MarkSearchOrCurNext " No default mapping for <Plug>MarkSearchOrCurPrev " No default mapping for <Plug>MarkSearchOrAnyNext " No default mapping for <Plug>MarkSearchOrAnyPrev " No default mapping for <Plug>MarkSearchGroupNext " No default mapping for <Plug>MarkSearchGroupPrev function! s:MakeDirectGroupMappings() for l:cnt in range(1, g:mwDirectGroupJumpMappingNum) for [l:isBackward, l:direction, l:keyModifier] in [[0, 'Next', ''], [1, 'Prev', 'C-']] let l:plugMappingName = printf('<Plug>MarkSearchGroup%d%s', l:cnt, l:direction) execute printf('nnoremap <silent> %s :<C-u>call mark#SearchGroupMark(%d, v:count1, %d, 1)<CR>', l:plugMappingName, l:cnt, l:isBackward) if ! hasmapto(l:plugMappingName, 'n') execute printf('nmap <%sk%d> %s', l:keyModifier, l:cnt, l:plugMappingName) endif endfor endfor endfunction call s:MakeDirectGroupMappings() delfunction s:MakeDirectGroupMappings "- commands ------------------------------------------------------------------- command! -count -nargs=? Mark if !mark#DoMarkAndSetCurrent(<count>, <f-args>)[0] | echoerr printf('Only %d mark highlight groups', mark#GetGroupNum()) | endif command! -bar MarkClear call mark#ClearAll() command! -bar Marks call mark#List() command! -bar -nargs=? -complete=customlist,mark#MarksVariablesComplete MarkLoad call mark#LoadCommand(1, <f-args>) command! -bar -nargs=? -complete=customlist,mark#MarksVariablesComplete MarkSave call mark#SaveCommand(<f-args>) function! s:SetPalette( paletteName ) if type(g:mwDefaultHighlightingPalette) == type([]) " Convert the directly defined list to a palette named "default". let g:mwPalettes['default'] = g:mwDefaultHighlightingPalette unlet! g:mwDefaultHighlightingPalette " Avoid E706. endif let g:mwDefaultHighlightingPalette = a:paletteName let l:palette = s:GetPalette() if empty(l:palette) return endif call mark#ReInit(s:DefineHighlightings(l:palette, 1)) call mark#UpdateScope() endfunction function! s:MarkPaletteComplete( ArgLead, CmdLine, CursorPos ) return sort(filter(keys(g:mwPalettes), 'v:val =~ ''\V\^'' . escape(a:ArgLead, "\\")')) endfunction command! -bar -nargs=1 -complete=customlist,<SID>MarkPaletteComplete MarkPalette call <SID>SetPalette(<q-args>) "- marks persistence ---------------------------------------------------------- if g:mwAutoLoadMarks " As the viminfo is only processed after sourcing of the runtime files, the " persistent global variables are not yet available here. Defer this until Vim " startup has completed. function! s:AutoLoadMarks() if g:mwAutoLoadMarks && exists('g:MARK_MARKS') && g:MARK_MARKS !=# '[]' if ! exists('g:MARK_ENABLED') || g:MARK_ENABLED " There are persistent marks and they haven't been disabled; we need to " show them right now. call mark#LoadCommand(0) else " Though there are persistent marks, they have been disabled. We avoid " sourcing the autoload script and its invasive autocmds right now; " maybe the marks are never turned on. We just inform the autoload " script that it should do this once it is sourced on-demand by a " mark mapping or command. let g:mwDoDeferredLoad = 1 endif endif endfunction augroup MarkInitialization autocmd! " Note: Avoid triggering the autoload unless there actually are persistent " marks. For that, we need to check that g:MARK_MARKS doesn't contain the " empty list representation, and also :execute the :call. autocmd VimEnter * call <SID>AutoLoadMarks() augroup END endif let &cpo = s:save_cpo unlet s:save_cpo " vim: ts=4 sts=0 sw=4 noet
00000svn-vim-cfg
trunk/vimfiles/plugin/mark.vim
Vim Script
gpl3
21,967
"=============================================================================== " " File: perlsupportprofiling.vim " " Description: Plugin perl-support: " Profiler support " " VIM Version: 7.0+ " Author: Dr. Fritz Mehner (mn), mehner@fh-swf.de " Company: FH Südwestfalen, Iserlohn " Version: 1.0 " Created: 22.02.2009 " Revision: $Id: perlsupportprofiling.vim,v 1.2 2012/02/19 21:24:53 mehner Exp $ " License: Copyright 2009-2011 Dr. Fritz Mehner "=============================================================================== " " Exit quickly when: " - this plugin was already loaded " - when 'compatible' is set " if exists("g:loaded_perlsupportprofiling") || &compatible finish endif let g:loaded_perlsupportregex = "v1.0" " let s:MSWIN = has("win16") || has("win32") || has("win64") || has("win95") let s:UNIX = has("unix") || has("macunix") || has("win32unix") " "------------------------------------------------------------------------------ " run : SmallProf, data structures {{{1 "------------------------------------------------------------------------------ let s:Perl_CWD = '' let s:Perl_SmallProfOutput = 'smallprof.out' let s:Perl_SmallProfErrorFormat = '%f:%l:%m' let s:Perl_SmallProfSortQuickfixField = { \ 'file-name' : 1 , \ 'line-number' : 2 , \ 'line-count' : 3 , \ 'time' : 4 , \ 'ctime' : 5 , \ } let s:Perl_SmallProfSortQuickfixHL = { \ 'file-name' : '/^[^|]\+/' , \ 'line-number' : '/|\d\+|/' , \ 'line-count' : '/ \@<=\d\+:\@=/' , \ 'time' : '/:\@<=\d\+\(:\d\+:\)\@=/' , \ 'ctime' : '/:\@<=\d\+\(: \)\@=/' , \ } "------------------------------------------------------------------------------ " run : SmallProf, generate statistics {{{1 " Also called in the filetype plugin perl.vim "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_Smallprof () let Sou = escape( expand("%:p"), g:Perl_FilenameEscChar ) " name of the file in the current buffer if &filetype != "perl" echohl WarningMsg | echo Sou.' seems not to be a Perl file' | echohl None return endif silent exe ":update" " let l:arguments = exists("b:Perl_CmdLineArgs") ? " ".b:Perl_CmdLineArgs : "" " let s:Perl_CWD = getcwd() echohl Search | echon ' ... profiling ... ' | echohl None " if s:MSWIN if filereadable( '.smallprof' ) let profilercmd = 'perl -d:SmallProf "'.Sou.l:arguments.'"' else echon "you need a config file '.smallprof' / please see the plugin help" return endif else " g : grep format / z : drop zeros (lines which were never called) let profilercmd = 'SMALLPROF_CONFIG=gz perl -d:SmallProf '.Sou.l:arguments endif let errortext = system(profilercmd) " if v:shell_error redraw echon errortext return endif " redraw! echon ' profiling done ' " call perlsupportprofiling#Perl_Smallprof_OpenQuickfix () endfunction " ---------- end of function Perl_Smallprof ---------- " "------------------------------------------------------------------------------ " run : SmallProf, open existing statistics file {{{1 "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_Smallprof_OpenQuickfix () if filereadable( s:Perl_SmallProfOutput ) exe ':setlocal errorformat='.s:Perl_SmallProfErrorFormat exe ':cfile '.s:Perl_SmallProfOutput exe ':copen' exe ':match Visual '.s:Perl_SmallProfSortQuickfixHL['time'] exe ':setlocal nowrap' else echon "No profiling statistics file '".s:Perl_SmallProfOutput."' found." endif endfunction " ---------- end of function Perl_Smallprof_OpenQuickfix ---------- " "------------------------------------------------------------------------------ " run : SmallProf, sort report {{{1 " Rearrange the profiler report. "------------------------------------------------------------------------------ let s:Perl_SmallProfSortSkipRegex = { \ 'file-name' : '' , \ 'line-number' : ' n /^[^:]\+:/' , \ 'line-count' : '! n /^[^:]\+:\d\+:/' , \ 'time' : '! n /^[^:]\+:\d\+:\d\+:/' , \ 'ctime' : '! n /^[^:]\+:\d\+:\d\+:\d\+:/' , \ } function! perlsupportprofiling#Perl_SmallProfSortQuickfix ( mode ) " if &filetype == 'qf' " if ! has_key( s:Perl_SmallProfSortQuickfixField, a:mode ) echomsg 'Allowed sort keys : ['.join( keys(s:Perl_SmallProfSortQuickfixField), '|' ).'].' return endif " let filename = escape( s:Perl_CWD.'/'.s:Perl_SmallProfOutput, g:Perl_FilenameEscChar ) exe ':edit '.filename exe ':2,$sort'.s:Perl_SmallProfSortSkipRegex[a:mode] let currentbuffer = bufnr("%") :exit exe ':bdelete '.currentbuffer exe ':setlocal errorformat='.s:Perl_SmallProfErrorFormat exe ':cfile '.filename :copen exe ':match Visual '.s:Perl_SmallProfSortQuickfixHL[a:mode] :setlocal nowrap " else echomsg 'the current buffer is not a QuickFix List (error list)' endif " endfunction " ---------- end of function Perl_SmallProfSortQuickfix ---------- " function! perlsupportprofiling#Perl_SmallProfSortInput ( ) let retval = input( "SmallProf report sort criterion (tab exp.): ", '', 'customlist,perlsupportprofiling#Perl_SmallProfSortList' ) redraw! call perlsupportprofiling#Perl_SmallProfSortQuickfix( retval ) return endfunction " ---------- end of function Perl_SmallProfSortInput ---------- " function! perlsupportprofiling#Perl_FastProfSortInput ( ) let retval = input( "FastProf report sort criterion (tab exp.): ", '', 'customlist,perlsupportprofiling#Perl_FastProfSortList' ) redraw! call perlsupportprofiling#Perl_FastProfSortQuickfix( retval ) return endfunction " ---------- end of function Perl_FastProfSortInput ---------- " function! perlsupportprofiling#Perl_NYTProfSortInput ( ) let retval = input( "NYTProf report sort criterion (tab exp.): ", '', 'customlist,perlsupportprofiling#Perl_NYTProfSortList' ) redraw! call perlsupportprofiling#Perl_NYTProfSortQuickfix( retval ) return endfunction " ---------- end of function Perl_NYTProfSortInput ---------- " "------------------------------------------------------------------------------ " run : Profiler; ex command tab expansion {{{1 "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_ProfSortList ( ArgLead, List ) " show all types if a:ArgLead == '' return a:List endif " show types beginning with a:ArgLead let expansions = [] for item in a:List if match( item, '\<'.a:ArgLead.'\w*' ) == 0 call add( expansions, item ) endif endfor return expansions endfunction " ---------- end of function Perl_ProfSortList ---------- "------------------------------------------------------------------------------ " run : SmallProf, ex command tab expansion {{{1 "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_SmallProfSortList ( ArgLead, CmdLine, CursorPos ) return perlsupportprofiling#Perl_ProfSortList( a:ArgLead, keys(s:Perl_SmallProfSortQuickfixField) ) endfunction " ---------- end of function Perl_SmallProfSortList ---------- "------------------------------------------------------------------------------ " run : FastProf, data structures {{{1 "------------------------------------------------------------------------------ let s:Perl_FastProfOutput = 'fastprof.out' let s:Perl_Fprofpp = '' let s:Perl_FastProfErrorFormat = '%f:%l\ %m' let s:Perl_FastProfSortQuickfixField = { \ 'file-name' : 1 , \ 'line-number' : 2 , \ 'time' : 2 , \ 'line-count' : 3 , \ } let s:Perl_FastProfSortQuickfixHL = { \ 'file-name' : '/^[^|]\+/' , \ 'line-number' : '/|\d\+|/' , \ 'time' : '/\(| \)\@<=\d\+\.\d\+/' , \ 'line-count' : '/ \@<=\d\+:\@=/' , \ } "------------------------------------------------------------------------------ " run : FastProf, generate statistics {{{1 " Also called in the filetype plugin perl.vim "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_Fastprof () let Sou = escape( expand("%:p"), g:Perl_FilenameEscChar ) " name of the file in the current buffer if &filetype != "perl" echohl WarningMsg | echo Sou.' seems not to be a Perl file' | echohl None return endif silent exe ":update" " let l:arguments = exists("b:Perl_CmdLineArgs") ? " ".b:Perl_CmdLineArgs : "" " let s:Perl_CWD = getcwd() echohl Search | echon ' ... profiling ... ' | echohl None " let profilercmd = 'perl -d:FastProf '.Sou.l:arguments let errortext = system(profilercmd) " if v:shell_error redraw echon errortext return endif " call perlsupportprofiling#Perl_FastProf_OpenQuickfix () " redraw! echon ' profiling done ' endfunction " ---------- end of function Perl_Fastprof ---------- " "------------------------------------------------------------------------------ " run : FastProf, open existing statistics file {{{1 "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_FastProf_OpenQuickfix () " if filereadable( s:Perl_FastProfOutput ) if s:Perl_Fprofpp == '' let s:Perl_Fprofpp = tempname() endif let profilercmd = 'fprofpp > '.s:Perl_Fprofpp let errortext = system( profilercmd ) " if v:shell_error redraw echon errortext return endif " exe ':setlocal errorformat='.s:Perl_FastProfErrorFormat exe ':cfile '.s:Perl_Fprofpp exe ':copen' exe ':match Visual '.s:Perl_FastProfSortQuickfixHL['time'] exe ':setlocal nowrap' else echon "No profiling statistics file '".s:Perl_FastProfOutput."' found." endif endfunction " ---------- end of function Perl_FastProf_OpenQuickfix ---------- "------------------------------------------------------------------------------ " run : FastProf, sort report {{{1 " Rearrange the profiler report. "------------------------------------------------------------------------------ let s:Perl_FastProfSortSkipRegex = { \ 'file-name' : '' , \ 'line-number' : ' n /^[^:]\+:/' , \ 'time' : ' n /^[^:]\+:/d\+ ' , \ 'line-count' : '! n /^[^:]\+:\d\+ \d\+\.\d\+ /' , \ } function! perlsupportprofiling#Perl_FastProfSortQuickfix ( mode ) " if &filetype == 'qf' " if ! has_key( s:Perl_FastProfSortQuickfixField, a:mode ) echomsg 'Allowed sort keys : ['.join( keys(s:Perl_FastProfSortQuickfixField), '|' ).'].' return endif " if a:mode == 'time' " generate new data to avoid sorting let profilercmd = 'fprofpp -r > '.s:Perl_Fprofpp let errortext = system( profilercmd ) " if v:shell_error redraw echon errortext return endif else exe ':edit '.s:Perl_Fprofpp exe ':3,$sort'.s:Perl_FastProfSortSkipRegex[a:mode] let currentbuffer = bufnr("%") :exit exe ':bdelete '.currentbuffer endif " exe ':setlocal errorformat='.s:Perl_FastProfErrorFormat exe ':cfile '.s:Perl_Fprofpp :copen exe ':match Visual '.s:Perl_FastProfSortQuickfixHL[a:mode] :setlocal nowrap " else echomsg 'the current buffer is not a QuickFix List (error list)' endif " endfunction " ---------- end of function Perl_FastProfSortQuickfix ---------- " "------------------------------------------------------------------------------ " run : FastProf, ex command tab expansion {{{1 "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_FastProfSortList ( ArgLead, CmdLine, CursorPos ) return perlsupportprofiling#Perl_ProfSortList( a:ArgLead, keys(s:Perl_FastProfSortQuickfixField) ) endfunction " ---------- end of function Perl_FastProfSortList ---------- "------------------------------------------------------------------------------ " run : NYTProf, data structures {{{1 "------------------------------------------------------------------------------ let s:Perl_NYTProf_html = 'no' if exists( 'g:Perl_NYTProf_html' ) let s:Perl_NYTProf_html = g:Perl_NYTProf_html endif let s:Perl_NYTProf_browser = 'konqueror' if exists( 'g:Perl_NYTProf_browser' ) let s:Perl_NYTProf_browser = g:Perl_NYTProf_browser endif let s:Perl_csv2err = g:Perl_PluginDir.'/perl-support/scripts/csv2err.pl' let s:Perl_NYTProfErrorFormat = '%f:%l:%m' let g:Perl_NYTProfCSVfile = '' let s:Perl_NYTProfSortQuickfixHL = { \ 'file' : '/^[^|]\+/' , \ 'line' : '/|\d\+|/' , \ 'time' : '/\(| \)\@<=\d\+\.\d\+:\@=/' , \ 'calls' : '/:\@<=\d\+:\@=/' , \ 'time_per_call' : '/:\@<=\d\+\.\d\+\(: \)\@=/' , \ } "------------------------------------------------------------------------------ " run : NYTProf, generate statistics {{{1 " Also called in the filetype plugin perl.vim "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_NYTprof () let Sou = escape( expand("%:p"), g:Perl_FilenameEscChar ) " name of the file in the current buffer if &filetype != "perl" echohl WarningMsg | echo Sou.' seems not to be a Perl file' | echohl None return endif silent exe ":update" " let l:arguments = exists("b:Perl_CmdLineArgs") ? " ".b:Perl_CmdLineArgs : "" " echohl Search | echon ' ... profiling ... ' | echohl None " if s:MSWIN let profilercmd = 'perl -d:NYTProf "'.Sou.l:arguments.'"' else let profilercmd = 'perl -d:NYTProf '.Sou.l:arguments endif let errortext = system(profilercmd) " if v:shell_error redraw echon errortext return endif " if s:Perl_NYTProf_html == 'yes' let errortext = system( 'nytprofhtml' ) if v:shell_error redraw echon errortext return endif endif " let errortext = system( 'nytprofcsv' ) " if v:shell_error redraw echon errortext return endif " redraw! if s:Perl_NYTProf_html == 'yes' echon ' profiling done -- read a CSV file or load the HTML files' else echon ' profiling done -- read a CSV file' endif " endfunction " ---------- end of function Perl_NYTprof ---------- "------------------------------------------------------------------------------ " run : NYTProf, generate statistics {{{1 " Also called in the filetype plugin perl.vim " mode : read, sort " criterion : file, line, time, calls, time_per_call "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_NYTprofReadCSV ( mode, criterion ) if a:mode == 'sort' && &filetype != 'qf' echomsg 'the current buffer is not a QuickFix List (error list)' return endif if a:mode == 'read' || g:Perl_NYTProfCSVfile == '' if has("gui_running") let g:Perl_NYTProfCSVfile = browse( 0, 'read a Devel::NYTProf CSV-file', 'nytprof', '*.csv' ) else let g:Perl_NYTProfCSVfile = input( 'read a Devel::NYTProf CSV-file : ', '', "file" ) end let g:Perl_NYTProfCSVfile = substitute( g:Perl_NYTProfCSVfile, '^\s\+', '', '' ) let g:Perl_NYTProfCSVfile = substitute( g:Perl_NYTProfCSVfile, '\s\+$', '', '' ) " " return if command canceled if g:Perl_NYTProfCSVfile =~ '^$' return endif " " return if not a CSV file if g:Perl_NYTProfCSVfile !~ '\.csv$' echohl WarningMsg | echo g:Perl_NYTProfCSVfile.' seems not to be a CSV file' | echohl None return endif " full path, remove filename and last directory: let currentworkingdirectory = fnamemodify( g:Perl_NYTProfCSVfile, ":p:h:h" ) let g:Perl_NYTProfCSVfile = currentworkingdirectory.'/'.g:Perl_NYTProfCSVfile endif " let sourcefilename = substitute( g:Perl_NYTProfCSVfile, '-\(pl\|pm\)\(-\(\d\+\)\)\?-\(block\|line\|sub\)\.csv$', '.\1', '' ) let sourcefilename = substitute( sourcefilename, '\/nytprof', '', '' ) if !filereadable( sourcefilename ) let sourcefilename_save = sourcefilename let sourcefilename = findfile( fnamemodify( sourcefilename, ":t") ) if sourcefilename == '' echomsg "Could not find file '".sourcefilename_save."'" return endif endif " let makeprg_saved = &makeprg exe ':setlocal errorformat='.s:Perl_NYTProfErrorFormat " exe ":setlocal makeprg=perl" if s:MSWIN silent exe ':make "'.s:Perl_csv2err.'" -s '.a:criterion \ .' -i "'.g:Perl_NYTProfCSVfile.'"' \ .' -n "'.sourcefilename.'"' else silent exe ':make '.s:Perl_csv2err.' -s '.a:criterion \ .' -i '.escape( g:Perl_NYTProfCSVfile, g:Perl_FilenameEscChar ) \ .' -n '.escape( sourcefilename, g:Perl_FilenameEscChar ) endif " exe ":setlocal makeprg=".makeprg_saved exe ":botright cwindow" copen setlocal modifiable exe ':match Visual '.s:Perl_NYTProfSortQuickfixHL[a:criterion] exe ':setlocal nowrap' setlocal nomodifiable endfunction " ---------- end of function Perl_NYTprofReadCSV ---------- "------------------------------------------------------------------------------ " run : NYTProf, generate statistics {{{1 " Also called in the filetype plugin perl.vim " mode : read, sort " criterion : file, line, time, calls, time_per_call "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_NYTProfSortQuickfix ( criterion ) call perlsupportprofiling#Perl_NYTprofReadCSV( 'sort', a:criterion ) endfunction " ---------- end of function Perl_NYTProfSortQuickfix ---------- " "------------------------------------------------------------------------------ " run : NYTProf, generate statistics {{{1 " Also called in the filetype plugin perl.vim "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_NYTprofReadHtml () if !has("gui_running") echomsg "Function not available: no GUI running." return end if executable( s:Perl_NYTProf_browser ) != 1 echomsg 'Browser '.s:Perl_NYTProf_browser.' does not exist or is not executable.' return endif if s:MSWIN echomsg "** not yet implemented **" else let index = 'nytprof/index.html' if !filereadable( index ) let index = getcwd() endif let errortext = system( s:Perl_NYTProf_browser.' '.index.' &' ) " if v:shell_error redraw echon errortext return endif endif endfunction " ---------- end of function Perl_NYTprofReadHtml ---------- " "------------------------------------------------------------------------------ " run : NYTProf, ex command tab expansion {{{1 "------------------------------------------------------------------------------ function! perlsupportprofiling#Perl_NYTProfSortList ( ArgLead, CmdLine, CursorPos ) return perlsupportprofiling#Perl_ProfSortList( a:ArgLead, keys(s:Perl_NYTProfSortQuickfixHL) ) endfunction " ---------- end of function Perl_NYTProfSortList ---------- " vim: tabstop=2 shiftwidth=2 foldmethod=marker
00000svn-vim-cfg
trunk/vimfiles/autoload/perlsupportprofiling.vim
Vim Script
gpl3
19,030
" mark/palettes.vim: Additional palettes for mark highlighting. " " DEPENDENCIES: " " Copyright: (C) 2012 Ingo Karkat " The VIM LICENSE applies to this script; see ':help copyright'. " " Maintainer: Ingo Karkat <ingo@karkat.de> " Contributors: rockybalboa4 " " Version: 2.7.0 " Changes: " 04-Jul-2012, Ingo Karkat " - Add "maximum" palette contributed by rockybalboa4 and move it and the " "extended" palette to a separate mark/palettes.vim autoload script. function! mark#palettes#Extended() return [ \ { 'ctermbg':'Blue', 'ctermfg':'Black', 'guibg':'#A1B7FF', 'guifg':'#001E80' }, \ { 'ctermbg':'Magenta', 'ctermfg':'Black', 'guibg':'#FFA1C6', 'guifg':'#80005D' }, \ { 'ctermbg':'Green', 'ctermfg':'Black', 'guibg':'#ACFFA1', 'guifg':'#0F8000' }, \ { 'ctermbg':'Yellow', 'ctermfg':'Black', 'guibg':'#FFE8A1', 'guifg':'#806000' }, \ { 'ctermbg':'DarkCyan', 'ctermfg':'Black', 'guibg':'#D2A1FF', 'guifg':'#420080' }, \ { 'ctermbg':'Cyan', 'ctermfg':'Black', 'guibg':'#A1FEFF', 'guifg':'#007F80' }, \ { 'ctermbg':'DarkBlue', 'ctermfg':'Black', 'guibg':'#A1DBFF', 'guifg':'#004E80' }, \ { 'ctermbg':'DarkMagenta','ctermfg':'Black', 'guibg':'#A29CCF', 'guifg':'#120080' }, \ { 'ctermbg':'DarkRed', 'ctermfg':'Black', 'guibg':'#F5A1FF', 'guifg':'#720080' }, \ { 'ctermbg':'Brown', 'ctermfg':'Black', 'guibg':'#FFC4A1', 'guifg':'#803000' }, \ { 'ctermbg':'DarkGreen', 'ctermfg':'Black', 'guibg':'#D0FFA1', 'guifg':'#3F8000' }, \ { 'ctermbg':'Red', 'ctermfg':'Black', 'guibg':'#F3FFA1', 'guifg':'#6F8000' }, \ { 'ctermbg':'White', 'ctermfg':'Gray', 'guibg':'#E3E3D2', 'guifg':'#999999' }, \ { 'ctermbg':'LightGray', 'ctermfg':'White', 'guibg':'#D3D3C3', 'guifg':'#666666' }, \ { 'ctermbg':'Gray', 'ctermfg':'Black', 'guibg':'#A3A396', 'guifg':'#222222' }, \ { 'ctermbg':'Black', 'ctermfg':'White', 'guibg':'#53534C', 'guifg':'#DDDDDD' }, \ { 'ctermbg':'Black', 'ctermfg':'Gray', 'guibg':'#131311', 'guifg':'#AAAAAA' }, \ { 'ctermbg':'Blue', 'ctermfg':'White', 'guibg':'#0000FF', 'guifg':'#F0F0FF' }, \ { 'ctermbg':'DarkRed', 'ctermfg':'White', 'guibg':'#FF0000', 'guifg':'#FFFFFF' }, \] endfunction function! mark#palettes#Maximum() let l:palette = [ \ { 'ctermbg':'Cyan', 'ctermfg':'Black', 'guibg':'#8CCBEA', 'guifg':'Black' }, \ { 'ctermbg':'Green', 'ctermfg':'Black', 'guibg':'#A4E57E', 'guifg':'Black' }, \ { 'ctermbg':'Yellow', 'ctermfg':'Black', 'guibg':'#FFDB72', 'guifg':'Black' }, \ { 'ctermbg':'Red', 'ctermfg':'Black', 'guibg':'#FF7272', 'guifg':'Black' }, \ { 'ctermbg':'Magenta', 'ctermfg':'Black', 'guibg':'#FFB3FF', 'guifg':'Black' }, \ { 'ctermbg':'Blue', 'ctermfg':'Black', 'guibg':'#9999FF', 'guifg':'Black' }, \] if has('gui_running') || &t_Co >= 88 let l:palette += [ \ { 'ctermfg':'White', 'ctermbg':'17', 'guifg':'White', 'guibg':'#00005f' }, \ { 'ctermfg':'White', 'ctermbg':'22', 'guifg':'White', 'guibg':'#005f00' }, \ { 'ctermfg':'White', 'ctermbg':'23', 'guifg':'White', 'guibg':'#005f5f' }, \ { 'ctermfg':'White', 'ctermbg':'27', 'guifg':'White', 'guibg':'#005fff' }, \ { 'ctermfg':'White', 'ctermbg':'29', 'guifg':'White', 'guibg':'#00875f' }, \ { 'ctermfg':'White', 'ctermbg':'34', 'guifg':'White', 'guibg':'#00af00' }, \ { 'ctermfg':'Black', 'ctermbg':'37', 'guifg':'Black', 'guibg':'#00afaf' }, \ { 'ctermfg':'Black', 'ctermbg':'43', 'guifg':'Black', 'guibg':'#00d7af' }, \ { 'ctermfg':'Black', 'ctermbg':'47', 'guifg':'Black', 'guibg':'#00ff5f' }, \ { 'ctermfg':'White', 'ctermbg':'52', 'guifg':'White', 'guibg':'#5f0000' }, \ { 'ctermfg':'White', 'ctermbg':'53', 'guifg':'White', 'guibg':'#5f005f' }, \ { 'ctermfg':'White', 'ctermbg':'58', 'guifg':'White', 'guibg':'#5f5f00' }, \ { 'ctermfg':'White', 'ctermbg':'60', 'guifg':'White', 'guibg':'#5f5f87' }, \ { 'ctermfg':'White', 'ctermbg':'64', 'guifg':'White', 'guibg':'#5f8700' }, \ { 'ctermfg':'White', 'ctermbg':'65', 'guifg':'White', 'guibg':'#5f875f' }, \ { 'ctermfg':'Black', 'ctermbg':'66', 'guifg':'Black', 'guibg':'#5f8787' }, \ { 'ctermfg':'Black', 'ctermbg':'72', 'guifg':'Black', 'guibg':'#5faf87' }, \ { 'ctermfg':'Black', 'ctermbg':'74', 'guifg':'Black', 'guibg':'#5fafd7' }, \ { 'ctermfg':'Black', 'ctermbg':'78', 'guifg':'Black', 'guibg':'#5fd787' }, \ { 'ctermfg':'Black', 'ctermbg':'79', 'guifg':'Black', 'guibg':'#5fd7af' }, \ { 'ctermfg':'Black', 'ctermbg':'85', 'guifg':'Black', 'guibg':'#5fffaf' }, \] endif if has('gui_running') || &t_Co >= 256 let l:palette += [ \ { 'ctermfg':'White', 'ctermbg':'90', 'guifg':'White', 'guibg':'#870087' }, \ { 'ctermfg':'White', 'ctermbg':'95', 'guifg':'White', 'guibg':'#875f5f' }, \ { 'ctermfg':'White', 'ctermbg':'96', 'guifg':'White', 'guibg':'#875f87' }, \ { 'ctermfg':'Black', 'ctermbg':'101', 'guifg':'Black', 'guibg':'#87875f' }, \ { 'ctermfg':'Black', 'ctermbg':'107', 'guifg':'Black', 'guibg':'#87af5f' }, \ { 'ctermfg':'Black', 'ctermbg':'114', 'guifg':'Black', 'guibg':'#87d787' }, \ { 'ctermfg':'Black', 'ctermbg':'117', 'guifg':'Black', 'guibg':'#87d7ff' }, \ { 'ctermfg':'Black', 'ctermbg':'118', 'guifg':'Black', 'guibg':'#87ff00' }, \ { 'ctermfg':'Black', 'ctermbg':'122', 'guifg':'Black', 'guibg':'#87ffd7' }, \ { 'ctermfg':'White', 'ctermbg':'130', 'guifg':'White', 'guibg':'#af5f00' }, \ { 'ctermfg':'White', 'ctermbg':'131', 'guifg':'White', 'guibg':'#af5f5f' }, \ { 'ctermfg':'Black', 'ctermbg':'133', 'guifg':'Black', 'guibg':'#af5faf' }, \ { 'ctermfg':'Black', 'ctermbg':'138', 'guifg':'Black', 'guibg':'#af8787' }, \ { 'ctermfg':'Black', 'ctermbg':'142', 'guifg':'Black', 'guibg':'#afaf00' }, \ { 'ctermfg':'Black', 'ctermbg':'152', 'guifg':'Black', 'guibg':'#afd7d7' }, \ { 'ctermfg':'White', 'ctermbg':'160', 'guifg':'White', 'guibg':'#d70000' }, \ { 'ctermfg':'Black', 'ctermbg':'166', 'guifg':'Black', 'guibg':'#d75f00' }, \ { 'ctermfg':'Black', 'ctermbg':'169', 'guifg':'Black', 'guibg':'#d75faf' }, \ { 'ctermfg':'Black', 'ctermbg':'174', 'guifg':'Black', 'guibg':'#d78787' }, \ { 'ctermfg':'Black', 'ctermbg':'175', 'guifg':'Black', 'guibg':'#d787af' }, \ { 'ctermfg':'Black', 'ctermbg':'186', 'guifg':'Black', 'guibg':'#d7d787' }, \ { 'ctermfg':'Black', 'ctermbg':'190', 'guifg':'Black', 'guibg':'#d7ff00' }, \ { 'ctermfg':'White', 'ctermbg':'198', 'guifg':'White', 'guibg':'#ff0087' }, \ { 'ctermfg':'Black', 'ctermbg':'202', 'guifg':'Black', 'guibg':'#ff5f00' }, \ { 'ctermfg':'Black', 'ctermbg':'204', 'guifg':'Black', 'guibg':'#ff5f87' }, \ { 'ctermfg':'Black', 'ctermbg':'209', 'guifg':'Black', 'guibg':'#ff875f' }, \ { 'ctermfg':'Black', 'ctermbg':'212', 'guifg':'Black', 'guibg':'#ff87d7' }, \ { 'ctermfg':'Black', 'ctermbg':'215', 'guifg':'Black', 'guibg':'#ffaf5f' }, \ { 'ctermfg':'Black', 'ctermbg':'220', 'guifg':'Black', 'guibg':'#ffd700' }, \ { 'ctermfg':'Black', 'ctermbg':'224', 'guifg':'Black', 'guibg':'#ffd7d7' }, \ { 'ctermfg':'Black', 'ctermbg':'228', 'guifg':'Black', 'guibg':'#ffff87' }, \] endif if has('gui_running') let l:palette += [ \ { 'guifg':'Black', 'guibg':'#b3dcff' }, \ { 'guifg':'Black', 'guibg':'#99cbd6' }, \ { 'guifg':'Black', 'guibg':'#7afff0' }, \ { 'guifg':'Black', 'guibg':'#a6ffd2' }, \ { 'guifg':'Black', 'guibg':'#a2de9e' }, \ { 'guifg':'Black', 'guibg':'#bcff80' }, \ { 'guifg':'Black', 'guibg':'#e7ff8c' }, \ { 'guifg':'Black', 'guibg':'#f2e19d' }, \ { 'guifg':'Black', 'guibg':'#ffcc73' }, \ { 'guifg':'Black', 'guibg':'#f7af83' }, \ { 'guifg':'Black', 'guibg':'#fcb9b1' }, \ { 'guifg':'Black', 'guibg':'#ff8092' }, \ { 'guifg':'Black', 'guibg':'#ff73bb' }, \ { 'guifg':'Black', 'guibg':'#fc97ef' }, \ { 'guifg':'Black', 'guibg':'#c8a3d9' }, \ { 'guifg':'Black', 'guibg':'#ac98eb' }, \ { 'guifg':'Black', 'guibg':'#6a6feb' }, \ { 'guifg':'Black', 'guibg':'#8caeff' }, \ { 'guifg':'Black', 'guibg':'#70b9fa' }, \] endif return l:palette endfunction " vim: ts=4 sts=0 sw=4 noet
00000svn-vim-cfg
trunk/vimfiles/autoload/mark/palettes.vim
Vim Script
gpl3
9,577
" File: MultipleSearch.vim (global plugin) " Last Changed: 13 Aug 2008 " Maintainer: Dan Sharp <dwsharp at hotmail dot com> " Version: 1.3 " License: Vim License "----------------------------------------------------------------------------- " MultipleSearch allows you to have the results of multiple searches displayed " on the screen at the same time. Each search highlights its results in a " different color, and all searches are displayed at once. After the maximum " number of colors is used, the script starts over with the first color. " " The command syntax is: " :Search <pattern1> " which will highlight all occurrences of <pattern1> in the current buffer. A " subsequent :Search <pattern2> will highlight all occurrences of <pattern2> " in the current buffer, retaining the highlighting of <pattern1> as well. " <pattern1> and <pattern2> are any search pattern like you would use in a " normal /<pattern> search. " " The :Search command honors Vim's 'ignorecase' and 'smartcase' settings for " its own search. You can use the \c and \C flags in the search pattern to " force case matching no matter the setting of 'ignorecase' and 'smartcase'. " " The :SearchBuffers command works just like :Search, but the search occurs in " all currently listed buffers (i.e., those that appear in the output of :ls). " The match in all buffers will have the same color. This is different than " :bufdo Search <pattern> because in that case, each buffer will highlight the " match in a different color. " " To clear the highlighting, issue the command :SearchReset (for the current " buffer) or :SearchBuffersReset (for all buffers). " " You can specify the maximum number of different colors to use by setting the " g:MultipleSearchMaxColors variable in your .vimrc. The default setting is " four, but the script should handle as much as your terminal / GUI can " display. The g:MultipleSearchColorSequence variable lets you list the " colors you want displayed, and in what order. To make the text more " readable, you can set the g:MultipleSearchTextColorSequence variable to a " list of colors for the text, each position corresponding to the color in the " same position in g:MultipleSearchColorSequence. " If you change one of the preference variables, you can issue the command " :SearchReinit " to update the script with your new selections. " Supporters: " Thanks to Peter Valach for suggestions and testing! " Thanks to Jeff Mei for the suggestion and testing of the :SearchBuffers " command. " Thanks to Amber Hassan for fixing a problem with a search pattern containing " quote characters! " Thanks to Manuel Picaza for the mapping to :Search the word under the " cursor. " ---------------------------------------------------------------------------- " This script uses continuation lines, so make sure it runs using " Vim-default 'cpoptions'. let s:save_cpo = &cpo set cpo&vim " FUNCTIONS " -------------------------------------------------- " ----- " Strntok: Utility function to implement C-like strntok() by Michael Geddes " and Benji Fisher at http://groups.yahoo.com/group/vimdev/message/26788 " ----- function! s:Strntok( s, tok, n) return matchstr( a:s.a:tok[0], '\v(\zs([^'.a:tok.']*)\ze['.a:tok.']){'.a:n.'}') endfun " ----- " MultipleSearchInit: Initialize the higlight groups. This function will add " highlighting groups if g:MultipSearchMaxColors has increased since the " plugin was first loaded. " ----- function! s:MultipleSearchInit() " Specify a maximum number of colors to use. if exists('g:MultipleSearchMaxColors') let s:MaxColors = g:MultipleSearchMaxColors else let s:MaxColors = 4 endif " Define the sequence of colors to use for searches. if exists('g:MultipleSearchColorSequence') let s:ColorSequence = g:MultipleSearchColorSequence else let s:ColorSequence = "red,yellow,blue,green,magenta,cyan,gray,brown" endif " Define the text color for searches, so that it can still be read against the " colored background. if exists('g:MultipleSearchTextColorSequence') let s:TextColorSequence = g:MultipleSearchTextColorSequence else let s:TextColorSequence = "white,black,white,black,white,black,black,white" endif " Start off with the first color let s:colorToUse = 0 let s:colorsInUse = 0 " Sanity check: make sure MaxColors is not larger than the number of " colors in ColorSequence or the corresponding TextColorSequence. let s:MaxColors = s:Min(s:MaxColors, s:ItemCount(s:ColorSequence . ','), \ s:ItemCount(s:TextColorSequence . ',')) let loopCount = 0 while loopCount < s:MaxColors " Define the colors to use let bgColor = s:Strntok(s:ColorSequence, ',', loopCount + 1) let fgColor = s:Strntok(s:TextColorSequence, ',', loopCount + 1) execute 'highlight MultipleSearch' . loopCount \ . ' ctermbg=' . bgColor . ' guibg=' . bgColor \ . ' ctermfg=' . fgColor . ' guifg=' . fgColor let loopCount = loopCount + 1 endwhile endfunction " ----- " ItemCount: Returns the number of items in the given string. " ----- function! s:ItemCount(string) let itemCount = 0 let newstring = a:string let pos = stridx(newstring, ',') while pos > -1 let itemCount = itemCount + 1 let newstring = strpart(newstring, pos + 1) let pos = stridx(newstring, ',') endwhile return itemCount endfunction " ----- " Min: Returns the minimum of the given parameters. " ----- function! s:Min(...) let min = a:1 let index = 2 while index <= a:0 execute "if min > a:" . index . " | let min = a:" . index . " | endif" let index = index + 1 endwhile return min endfunction " ----- " GetNextSequenceNumber: Determine the next Search color to use. " ----- function! s:GetNextSequenceNumber() let sequenceNumber = s:colorToUse % s:MaxColors let s:colorToUse = s:colorToUse + 1 if s:colorToUse >= s:MaxColors let s:colorToUse = 0 endif return sequenceNumber endfunction " ----- " DoSearch: The main searching function that highlights all matches in the " current buffer. " ----- function! s:DoSearch(useSearch, forwhat) " Clear the previous highlighting for this color execute 'silent syntax clear ' . a:useSearch " Should it be a case-sensitive match or case-insensitive? if &ignorecase == 1 " If 'smartcase' is on and our search pattern has an upper-case " character, do a case sensitive match. if &smartcase == 1 " match() respects 'ignorecase', so turn it off for now set noignorecase if match(a:forwhat, '\u') > -1 syntax case match else syntax case ignore endif " Be sure to turn 'ignorecase' back on! set ignorecase else syntax case ignore endif else syntax case match endif " Highlight the new search execute 'syntax match ' . a:useSearch . ' "' . a:forwhat . '" containedin=ALL' let @/ = a:forwhat endfunction " ----- " MultipleSearch: Highlight the given pattern in the next available color. " Vim versions prior to 7.0 don't support the autoload mechanism, so define " the main function without the autoload prefix. " ----- if v:version < 700 function! MultipleSearch(allBuffers, forwhat) call s:MultipleSearchCommon(a:allBuffers, a:forwhat) endfunction else function! MultipleSearch#MultipleSearch(allBuffers, forwhat) call s:MultipleSearchCommon(a:allBuffers, a:forwhat) endfunction endif " ----- " MultipleSearchCommon: Highlight the given pattern in the next available color. " ----- function! s:MultipleSearchCommon(allBuffers, forwhat) let patt = a:forwhat if( l:patt =~ "[^\\\\]'" ) " if single quote not escaped let l:patt = escape(l:patt,"'") " escape single quotes with a \ char endif if( l:patt =~ '[^\\]"' ) " if double quote not escaped let l:patt = escape(l:patt, '"') " escape double quotes with a \ char endif "let patt = escape(a:forwhat,"'") " escape single quotes with a \ char "let l:patt = escape(l:patt, '"') " escape double quotes with a \ char " Determine which search color to use. let s:curr_sequence = s:GetNextSequenceNumber() let s:patterns{s:curr_sequence} = l:patt let s:searchSequence = s:curr_sequence if s:colorsInUse < s:MaxColors let s:colorsInUse += 1 endif let useSearch = "MultipleSearch" . s:curr_sequence if a:allBuffers " If a:allBuffers is on, we want to show the match in all currently " listed buffers. let counter = 1 let bufCount = bufnr("$") let current = bufnr("%") let lz_save = &lazyredraw " Loop through all the buffers and perform the search in each one. while counter <= bufCount if buflisted(counter) exec "buffer " . counter call s:DoSearch(useSearch, l:patt) endif let counter = counter + 1 endwhile exec "buffer " . current let &lazyredraw = lz_save else " Otherwise, just search in the current buffer. call s:DoSearch(useSearch, l:patt) endif endfunction " --- " DoReset: Clear the highlighting " --- function! s:DoReset() let seq = 0 while seq < s:MaxColors execute 'syntax clear MultipleSearch' . seq let seq = seq + 1 endwhile endfunction " ----- " MultipleSearchReset: Clear all the current search selections. " ----- function! s:MultipleSearchReset(allBuffers) let s:colorToUse = 0 let s:colorsInUse = 0 if a:allBuffers == 1 " If a:allBuffers is on, we want to clear the match in all " currently listed buffers. let current = bufnr("%") bufdo call s:DoReset() execute "buffer " . current else " Otherwise, just clear the current buffer. call s:DoReset() endif endfunction " ----- " SearchNext: Switch to the next search item to cycle through with n and N " ----- function! s:SearchNext(direction) if a:direction == 0 let s:searchSequence += 1 if s:searchSequence >= s:colorsInUse let s:searchSequence = 0 endif else let s:searchSequence -= 1 if s:searchSequence < 0 let s:searchSequence = s:colorsInUse - 1 endif endif let @/ = s:patterns{s:searchSequence} call search(s:patterns{s:searchSequence}) endfunction " Initialize the script the first time through. call <SID>MultipleSearchInit() let &cpo = s:save_cpo " COMMANDS " ------------------------------------------------ " Clear the current search selections and start over with the first color in " the sequence. if !(exists(":SearchReset") == 2) command -nargs=0 SearchReset :silent call <SID>MultipleSearchReset(0) endif " Clear the current search selections and start over with the first color in " the sequence. if !(exists(":SearchBuffersReset") == 2) command -nargs=0 SearchBuffersReset :silent call <SID>MultipleSearchReset(1) endif " Reinitialize the script after changing one of the global preferences. if !(exists(":SearchReinit") == 2) command -nargs=0 SearchReinit :silent call <SID>MultipleSearchInit() endif " Set the current search pattern to the next one in the list nnoremap <silent> <Leader>n :call <SID>SearchNext(0)<CR> " " Set the current search pattern to the previous one in the list nnoremap <silent> <Leader>N :call <SID>SearchNext(1)<CR>
00000svn-vim-cfg
trunk/vimfiles/autoload/MultipleSearch.vim
Vim Script
gpl3
11,510
"=============================================================================== " " File: mmtemplates#core.vim " " Description: Template engine: Core. " " Maps & Menus - Template Engine " " VIM Version: 7.0+ " Author: Wolfgang Mehner, wolfgang-mehner@web.de " Organization: " Version: see variable g:Templates_Version below " Created: 30.08.2011 " Revision: 11.02.2013 " License: Copyright (c) 2012-2013, Wolfgang Mehner " This program is free software; you can redistribute it and/or " modify it under the terms of the GNU General Public License as " published by the Free Software Foundation, version 2 of the " License. " This program is distributed in the hope that it will be " useful, but WITHOUT ANY WARRANTY; without even the implied " warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR " PURPOSE. " See the GNU General Public License version 2 for more details. "=============================================================================== " "------------------------------------------------------------------------------- " === Basic Checks === {{{1 "------------------------------------------------------------------------------- " " need at least 7.0 if v:version < 700 echohl WarningMsg echo 'The plugin templates.vim needs Vim version >= 7.' echohl None finish endif " " prevent duplicate loading " need compatible if &cp || ( exists('g:Templates_Version') && ! exists('g:Templates_DevelopmentOverwrite') ) finish endif let g:Templates_Version= '0.9.1-2' " version number of this script; do not change " if ! exists ( 'g:Templates_MapInUseWarn' ) let g:Templates_MapInUseWarn = 1 endif " "---------------------------------------------------------------------- " === Modul Setup === {{{1 "---------------------------------------------------------------------- " let s:DebugGlobalOverwrite = 0 let s:DebugLevel = s:DebugGlobalOverwrite " let s:StateStackStyleTop = -2 let s:StateStackFile = -1 " let s:StateStackLength = 2 " let s:Flagactions = { \ ':i' : '', \ ':l' : ' (-> lowercase)', \ ':u' : ' (-> uppercase)', \ ':c' : ' (-> capitalize)', \ ':L' : ' (-> legalize name)', \ } " let s:StandardPriority = 500 " "---------------------------------------------------------------------- " s:StandardMacros : The standard macros. {{{2 "---------------------------------------------------------------------- " let s:StandardMacros = { \ 'BASENAME' : '', \ 'DATE' : '%x', \ 'FILENAME' : '', \ 'PATH' : '', \ 'SUFFIX' : '', \ 'TIME' : '%X', \ 'YEAR' : '%Y', \ } " "---------------------------------------------------------------------- " s:StandardProperties : The standard properties. {{{2 "---------------------------------------------------------------------- " let s:StandardProperties = { \ 'Templates::EditTemplates::Map' : 're', \ 'Templates::RereadTemplates::Map' : 'rr', \ 'Templates::ChooseStyle::Map' : 'rs', \ \ 'Templates::EditTemplates::Shortcut' : 'e', \ 'Templates::RereadTemplates::Shortcut' : 'r', \ 'Templates::ChooseStyle::Shortcut' : 's', \ \ 'Templates::Mapleader' : '\', \ } " "---------------------------------------------------------------------- " s:TypeNames : Name of types as characters. {{{2 "---------------------------------------------------------------------- " let s:TypeNames = [ ' ', ' ', ' ', ' ', ' ', ' ' ] " let s:TypeNames[ type(0) ] = 'i' " integer let s:TypeNames[ type("") ] = 's' " string let s:TypeNames[ type([]) ] = 'l' " list let s:TypeNames[ type({}) ] = 'd' " dict "let s:TypeNames[ type(0.0) ] = 'n' " number " TODO: why does float not work in some cases? " not important right now. " "---------------------------------------------------------------------- " === Syntax: Regular Expressions === {{{1 "---------------------------------------------------------------------- " let s:RegexSettings = { \ 'MacroName' : '[a-zA-Z_][a-zA-Z0-9_]*', \ 'MacroList' : '\%([a-zA-Z_]\|[a-zA-Z_][a-zA-Z0-9_ \t,]*[a-zA-Z0-9_]\)', \ 'TemplateName' : '[a-zA-Z_][a-zA-Z0-9_+\-\., ]*[a-zA-Z0-9_+\-\.,]', \ 'TextOpt' : '[a-zA-Z_][a-zA-Z0-9_+\-: \t,]*[a-zA-Z0-9_+\-]', \ 'Mapping' : '[a-zA-Z0-9+\-]\+', \ \ 'CommentStart' : '\$', \ 'BlockDelimiter' : '==', \ \ 'CommentHint' : '$', \ 'CommandHint' : '[A-Z]', \ 'DelimHint' : '=', \ 'MacroHint' : '|', \ \ 'MacroStart' : '|', \ 'MacroEnd' : '|', \ 'EditTagStart' : '<', \ 'EditTagEnd' : '>', \ 'JumpTag1Start' : '{', \ 'JumpTag1End' : '}', \ 'JumpTag2Start' : '<', \ 'JumpTag2End' : '>', \ } " "---------------------------------------------------------------------- " s:UpdateFileReadRegex : Update the regular expressions. {{{2 "---------------------------------------------------------------------- " function! s:UpdateFileReadRegex ( regex, settings ) " let quote = '\(["'']\?\)' " " Basics let a:regex.MacroName = a:settings.MacroName let a:regex.MacroNameC = '\('.a:settings.MacroName.'\)' let a:regex.TemplateNameC = '\('.a:settings.TemplateName.'\)' let a:regex.Mapping = a:settings.Mapping let a:regex.AbsolutePath = '^[\~/]' " TODO: Is that right and/or complete? " " Syntax Categories let a:regex.EmptyLine = '^\s*$' let a:regex.CommentLine = '^'.a:settings.CommentStart let a:regex.FunctionCall = '^\s*'.a:regex.MacroNameC.'\s*(\(.*\))\s*$' let a:regex.MacroAssign = '^\s*'.a:settings.MacroStart.a:regex.MacroNameC.a:settings.MacroEnd \ .'\s*=\s*'.quote.'\(.\{-}\)'.'\2'.'\s*$' " deprecated " " Blocks let delim = a:settings.BlockDelimiter let a:regex.Styles1Start = '^'.delim.'\s*IF\s\+|STYLE|\s\+IS\s\+'.a:regex.MacroNameC.'\s*'.delim let a:regex.Styles1End = '^'.delim.'\s*ENDIF\s*'.delim let a:regex.Styles2Start = '^'.delim.'\s*USE\s\+STYLES\s*:' \ .'\s*\('.a:settings.MacroList.'\)'.'\s*'.delim let a:regex.Styles2End = '^'.delim.'\s*ENDSTYLES\s*'.delim " " Texts let a:regex.TemplateStart = '^'.delim.'\s*\%(TEMPLATE:\)\?\s*'.a:regex.TemplateNameC.'\s*'.delim \ .'\s*\%(\('.a:settings.TextOpt.'\)\s*'.delim.'\)\?' let a:regex.TemplateEnd = '^'.delim.'\s*ENDTEMPLATE\s*'.delim " let a:regex.HelpStart = '^'.delim.'\s*HELP:\s*'.a:regex.TemplateNameC.'\s*'.delim \ .'\s*\%(\('.a:settings.TextOpt.'\)\s*'.delim.'\)\?' "let a:regex.HelpEnd = '^'.delim.'\s*ENDHELP\s*'.delim " let a:regex.MenuSep = '^'.delim.'\s*SEP:\s*'.a:regex.TemplateNameC.'\s*'.delim " let a:regex.ListStart = '^'.delim.'\s*LIST:\s*'.a:regex.MacroNameC.'\s*'.delim \ .'\s*\%(\('.a:settings.TextOpt.'\)\s*'.delim.'\)\?' let a:regex.ListEnd = '^'.delim.'\s*ENDLIST\s*'.delim " " Special Hints let a:regex.CommentHint = a:settings.CommentHint let a:regex.CommandHint = a:settings.CommandHint let a:regex.DelimHint = a:settings.DelimHint let a:regex.MacroHint = a:settings.MacroHint " endfunction " ---------- end of function s:UpdateFileReadRegex ---------- " "---------------------------------------------------------------------- " s:UpdateTemplateRegex : Update the regular expressions. {{{2 "---------------------------------------------------------------------- " function! s:UpdateTemplateRegex ( regex, settings ) " let quote = '["'']' " " Function Arguments let a:regex.RemoveQuote = '^\s*'.quote.'\zs.*\ze'.quote.'\s*$' " " Basics let a:regex.MacroStart = a:settings.MacroStart let a:regex.MacroEnd = a:settings.MacroEnd let a:regex.MacroName = a:settings.MacroName let a:regex.MacroNameC = '\('.a:settings.MacroName.'\)' let a:regex.MacroMatch = '^'.a:settings.MacroStart.a:settings.MacroName.a:settings.MacroEnd.'$' " " Syntax Categories let a:regex.FunctionLine = '^'.a:settings.MacroStart.'\('.a:regex.MacroNameC.'(\(.*\))\)'.a:settings.MacroEnd.'\s*\n' let a:regex.FunctionChecked = '^'.a:regex.MacroNameC.'(\(.*\))$' let a:regex.FunctionList = '^LIST(\(.\{-}\))$' let a:regex.FunctionComment = a:settings.MacroStart.'\(C\|Comment\)'.'(\(.\{-}\))'.a:settings.MacroEnd let a:regex.FunctionInsert = a:settings.MacroStart.'\(Insert\|InsertLine\)'.'(\(.\{-}\))'.a:settings.MacroEnd let a:regex.MacroRequest = a:settings.MacroStart.'?'.a:regex.MacroNameC.'\%(:\(\a\)\)\?'.a:settings.MacroEnd let a:regex.MacroInsert = a:settings.MacroStart.''.a:regex.MacroNameC.'\%(:\(\a\)\)\?'.a:settings.MacroEnd let a:regex.MacroNoCapture = a:settings.MacroStart.a:settings.MacroName.'\%(:\a\)\?'.a:settings.MacroEnd let a:regex.ListItem = a:settings.MacroStart.''.a:regex.MacroNameC.':ENTRY_*'.a:settings.MacroEnd " let a:regex.TextBlockFunctions = '^\%(C\|Comment\|Insert\|InsertLine\)$' " " Jump Tags let a:regex.JumpTagBoth = '<-\w*->\|{-\w*-}\|<+\w*+>\|{+\w*+}' let a:regex.JumpTagType2 = '<-\w*->\|{-\w*-}' " endfunction " ---------- end of function s:UpdateTemplateRegex ---------- " }}}2 " "---------------------------------------------------------------------- " === Script: Auxiliary Functions === {{{1 "---------------------------------------------------------------------- " "---------------------------------------------------------------------- " s:ParameterTypes : Get the types of the arguments. {{{2 " " Returns a string with one character per argument, denoting the type. " Uses the codebook 's:TypeNames'. " " Examples: " - s:ParameterTypes ( 1, "string", [] ) -> "isl" " - s:ParameterTypes ( 1, 'string', {} ) -> "isd" " - s:ParameterTypes ( 1, 1.0 ) -> "in" "---------------------------------------------------------------------- " function! s:ParameterTypes ( ... ) return join( map( copy( a:000 ), 's:TypeNames[ type ( v:val ) ]' ), '' ) endfunction " ---------- end of function s:ParameterTypes ---------- " "---------------------------------------------------------------------- " s:FunctionCheck : Check the syntax, name and parameter types. {{{2 " " Throw a 'Template:Check:*' exception whenever: " - The syntax of the call "name( params )" is wrong. " - The function name 'name' is not a key in 'namespace'. " - The parameter string (as produced by s:ParameterTypes) does not match " the regular expression found in "namespace[name]". "---------------------------------------------------------------------- " function! s:FunctionCheck ( name, param, namespace ) " " check the syntax and get the parameter string try exe 'let param_s = s:ParameterTypes( '.a:param.' )' catch /^Vim(let):E\d\+:/ throw 'Template:Check:function call "'.a:name.'('.a:param.')": '.matchstr ( v:exception, '^Vim(let):E\d\+:\zs.*' ) endtry " " check the function and the parameters if ! has_key ( a:namespace, a:name ) throw 'Template:Check:unknown function: "'.a:name.'"' elseif param_s !~ '^'.a:namespace[ a:name ].'$' throw 'Template:Check:wrong parameter types: "'.a:name.'"' endif " endfunction " ---------- end of function s:FunctionCheck ---------- " "---------------------------------------------------------------------- " s:LiteralReplacement : Substitute without using regular expressions. {{{2 "---------------------------------------------------------------------- " function! s:LiteralReplacement ( text, remove, insert, flag ) return substitute( a:text, \ '\V'.escape( a:remove, '\' ), \ escape( a:insert, '\&~' ), a:flag ) " \ '\='.string( a:insert ), a:flag ) endfunction " ---------- end of function s:LiteralReplacement ---------- " "---------------------------------------------------------------------- " s:ConcatNormalizedFilename : Concatenate and normalize a filename. {{{2 "---------------------------------------------------------------------- " function! s:ConcatNormalizedFilename ( ... ) if a:0 == 1 let filename = ( a:1 ) elseif a:0 == 2 let filename = ( a:1 ).'/'.( a:2 ) endif return fnamemodify( filename, ':p' ) endfunction " ---------- end of function s:ConcatNormalizedFilename ---------- " "---------------------------------------------------------------------- " s:GetNormalizedPath : Split and normalize a path. {{{2 "---------------------------------------------------------------------- " function! s:GetNormalizedPath ( filename ) return fnamemodify( a:filename, ':p:h' ) endfunction " ---------- end of function s:GetNormalizedPath ---------- " ""---------------------------------------------------------------------- " s:UserInput : Input after a highlighted prompt. {{{2 " " 3. argument : optional completion " 4. argument : optional list, if the 3. argument is 'customlist' " " Throws an exception 'Template:UserInputAborted' if the obtained input is empty, " so use it like this: " try " let style = s:UserInput( 'prompt', '', ... ) " catch /Template:UserInputAborted/ " return " endtry "---------------------------------------------------------------------- " function! s:UserInput ( prompt, text, ... ) " echohl Search " highlight prompt call inputsave() " preserve typeahead if a:0 == 0 || a:1 == '' let retval = input( a:prompt, a:text ) elseif a:1 == 'customlist' let s:UserInputList = a:2 let retval = input( a:prompt, a:text, 'customlist,mmtemplates#core#UserInputEx' ) let s:UserInputList = [] else let retval = input( a:prompt, a:text, a:1 ) endif call inputrestore() " restore typeahead echohl None " reset highlighting " if empty( retval ) throw 'Template:UserInputAborted' endif " let retval = substitute( retval, '^\s\+', "", "" ) " remove leading whitespaces let retval = substitute( retval, '\s\+$', "", "" ) " remove trailing whitespaces " return retval " endfunction " ---------- end of function s:UserInput ---------- " "---------------------------------------------------------------------- " mmtemplates#core#UserInputEx : ex-command for s:UserInput. {{{3 "---------------------------------------------------------------------- " function! mmtemplates#core#UserInputEx ( ArgLead, CmdLine, CursorPos ) return filter( copy( s:UserInputList ), 'v:val =~ "\\V\\<'.escape(a:ArgLead,'\').'\\w\\*"' ) endfunction " ---------- end of function mmtemplates#core#UserInputEx ---------- " }}}3 " let s:UserInputList = [] " "---------------------------------------------------------------------- " s:ErrorMsg : Print an error message. {{{2 "---------------------------------------------------------------------- " function! s:ErrorMsg ( ... ) echohl WarningMsg for line in a:000 echomsg line endfor echohl None endfunction " ---------- end of function s:ErrorMsg ---------- " "---------------------------------------------------------------------- " s:DebugMsg : Print debug information. {{{2 "---------------------------------------------------------------------- " function! s:DebugMsg ( msg, ... ) if s:DebugLevel if a:0 == 0 || ( a:1 <= s:DebugLevel ) echo a:msg endif endif endfunction " ---------- end of function s:DebugMsg ---------- " "---------------------------------------------------------------------- " s:OpenFold : Open fold and go to the first or last line of this fold. {{{2 "---------------------------------------------------------------------- " function! s:OpenFold ( mode ) if foldclosed(".") < 0 return endif " we are on a closed fold: " get end position, open fold, " jump to the last line of the previously closed fold let foldstart = foldclosed(".") let foldend = foldclosedend(".") normal zv if a:mode == 'below' exe ":".foldend elseif a:mode == 'start' exe ":".foldstart endif endfunction " ---------- end of function s:OpenFold ---------- " "---------------------------------------------------------------------- " mmtemplates#core#NewLibrary : Create a new template library. {{{1 "---------------------------------------------------------------------- " function! mmtemplates#core#NewLibrary ( ... ) " " ================================================== " options " ================================================== " let i = 1 while i <= a:0 " if a:[i] == 'debug' && i+1 <= a:0 && ! s:DebugGlobalOverwrite let s:DebugLevel = a:[i+1] let i += 2 else if type ( a:[i] ) == type ( '' ) | call s:ErrorMsg ( 'Unknown option: "'.a:[i].'"' ) else | call s:ErrorMsg ( 'Unknown option at position '.i.'.' ) | endif let i += 1 endif " endwhile " " ================================================== " data " ================================================== " " library let library = { \ 'macros' : {}, \ 'properties' : {}, \ 'resources' : {}, \ 'templates' : {}, \ \ 'menu_order' : [], \ \ 'styles' : [ 'default' ], \ 'current_style' : 'default', \ \ 'menu_shortcuts' : {}, \ 'menu_existing' : { 'base' : 0 }, \ \ 'regex_settings' : ( copy ( s:RegexSettings ) ), \ 'regex_file' : {}, \ 'regex_template' : {}, \ \ 'library_files' : [], \ } " entry used by maps: 'map_commands' " call extend ( library.macros, s:StandardMacros, 'keep' ) call extend ( library.properties, s:StandardProperties, 'keep' ) " call s:UpdateFileReadRegex ( library.regex_file, library.regex_settings ) call s:UpdateTemplateRegex ( library.regex_template, library.regex_settings ) " " ================================================== " wrap up " ================================================== " let s:DebugLevel = s:DebugGlobalOverwrite " reset debug " return library " return the new library " endfunction " ---------- end of function mmtemplates#core#NewLibrary ---------- " "---------------------------------------------------------------------- " === Read Templates: Auxiliary Functions === {{{1 "---------------------------------------------------------------------- " "---------------------------------------------------------------------- " s:TemplateTypeNames : Readable type names for templates. {{{2 "---------------------------------------------------------------------- " let s:TemplateTypeNames = { \ 'help' : 'help', \ 'sep' : 'separator', \ 't' : 'template', \ } " "---------------------------------------------------------------------- " s:AddText : Add a text. {{{2 "---------------------------------------------------------------------- " function! s:AddText ( type, name, settings, lines ) " if a:type == 'help' call s:AddTemplate ( 'help', a:name, a:settings, a:lines ) elseif a:type == 'list' call s:AddList ( 'list', a:name, a:settings, a:lines ) elseif a:type == 'template' call s:AddTemplate ( 't', a:name, a:settings, a:lines ) endif " endfunction " ---------- end of function s:AddText ---------- " "---------------------------------------------------------------------- " s:AddList : Add a list. {{{2 "---------------------------------------------------------------------- " function! s:AddList ( type, name, settings, lines ) " " ================================================== " checks " ================================================== " " Error: empty name if empty ( a:name ) call s:ErrorMsg ( 'List name can not be empty.' ) return endif " " Warning: empty list if empty ( a:lines ) call s:ErrorMsg ( 'Warning: Empty list: "'.a:name.'"' ) endif " " Warning: already existing if s:t_runtime.overwrite_warning && has_key ( s:library.resources, 'list!'.a:name ) call s:ErrorMsg ( 'Warning: Overwriting list "'.a:name.'"' ) endif " " ================================================== " settings " ================================================== " let type = 'list' let bare = 0 " for s in a:settings " if s == 'list' let type = 'list' elseif s == 'hash' || s == 'dict' || s == 'dictionary' let type = 'dict' elseif s == 'bare' let bare = 1 else call s:ErrorMsg ( 'Warning: Unknown setting in list "'.a:name.'": "'.s.'"' ) endif " endfor " if type == 'list' if bare let lines = escape( a:lines, '"' ) let lines = substitute( lines, '^\s*', '"', '' ) let lines = substitute( lines, '\s*\n$', '"', '' ) let lines = substitute( lines, '\s*\n\s*', '", "', 'g' ) exe 'let list = [ '.lines.' ]' else exe 'let list = [ '.substitute( a:lines, '\n', ' ', 'g' ).' ]' end call sort ( list ) elseif type == 'dict' if bare s:ErrorMsg ( 'bare hash: to be implemented' ) else exe 'let list = { '.substitute( a:lines, '\n', ' ', 'g' ).' }' end endif " let s:library.resources[ 'list!'.a:name ] = list " endfunction " ---------- end of function s:AddList ---------- " "---------------------------------------------------------------------- " s:AddTemplate : Add a template. {{{2 "---------------------------------------------------------------------- " function! s:AddTemplate ( type, name, settings, lines ) " let name = a:name " " ================================================== " checks " ================================================== " " Error: empty name if empty ( name ) call s:ErrorMsg ( 'Template name can not be empty.' ) return endif " " Warning: empty template if empty ( a:lines ) call s:ErrorMsg ( 'Warning: Empty template: "'.name.'"' ) endif " " ================================================== " new template " ================================================== " if has_key ( s:library.templates, name.'!!type' ) let my_type = a:type let other_type = split ( s:library.templates[ name.'!!type' ], ',' )[0] " if my_type != other_type if my_type == 't' call s:ErrorMsg ( 'Template "'.name.'" can not overwrite an object of the same name of type "'.s:TemplateTypeNames[other_type].'".' ) elseif my_type == 'help' call s:ErrorMsg ( 'Help template "'.name.'" can not overwrite an object of the same name of type "'.s:TemplateTypeNames[other_type].'".' ) endif return endif else " " -------------------------------------------------- " new template " -------------------------------------------------- let type = a:type let placement = 'below' let indentation = '1' " let visual = -1 != stridx ( a:lines, '<SPLIT>' ) let mp = '' let entry = 1 let sc = '' " " -------------------------------------------------- " settings " -------------------------------------------------- for s in a:settings " if s == 'start' || s == 'above' || s == 'below' || s == 'append' || s == 'insert' let placement = s " indentation elseif s == 'indent' let indentation = '1' elseif s == 'noindent' let indentation = '0' " special insertion in visual mode: elseif s == 'visual' let visual = 1 elseif s == 'novisual' let visual = 0 " map: elseif s =~ '^map\s*:' let mp = matchstr ( s, '^map\s*:\s*\zs'.s:library.regex_file.Mapping ) " entry and shortcut: elseif s == 'nomenu' let entry = 0 elseif s == 'expandmenu' let entry = 2 elseif s =~ '^sc\s*:' || s =~ '^shortcut\s*:' let sc = matchstr ( s, '^\w\+\s*:\s*\zs'.s:library.regex_file.Mapping ) else call s:ErrorMsg ( 'Warning: Unknown setting in template "'.name.'": "'.s.'"' ) endif " endfor " " TODO: review this if a:type == 'help' let placement = 'help' endif " " -------------------------------------------------- " new template " -------------------------------------------------- let s:library.templates[ name.'!!type' ] = type.','.placement.','.indentation let s:library.templates[ name.'!!menu' ] = visual.",".string(mp).",".entry.",'',".string(sc) " call add ( s:library.menu_order, name ) " endif " " ================================================== " text " ================================================== " " the styles if a:type == 'help' " Warning: overwriting a style if s:t_runtime.overwrite_warning && has_key ( s:library.templates, name.'!default' ) call s:ErrorMsg ( 'Warning: Overwriting a help template: "'.name.'"' ) endif let s:library.templates[ name.'!default' ] = a:lines return elseif empty ( s:t_runtime.use_styles ) let styles = [ 'default' ] else let styles = s:t_runtime.use_styles endif " " save the lines for s in styles " " Warning: overwriting a style if s:t_runtime.overwrite_warning && has_key ( s:library.templates, name.'!'.s ) call s:ErrorMsg ( 'Warning: Overwriting style in template "'.name.'": "'.s.'"' ) endif " let s:library.templates[ name.'!'.s ] = a:lines " endfor " endfunction " ---------- end of function s:AddTemplate ---------- " "---------------------------------------------------------------------- " s:AddSeparator : Add a menu separator. {{{2 "---------------------------------------------------------------------- " function! s:AddSeparator ( type, name, settings ) " let name = a:name " " ================================================== " checks " ================================================== " " Error: empty name if empty ( name ) call s:ErrorMsg ( 'Separator name can not be empty.' ) return endif " " ================================================== " new separator " ================================================== " if has_key ( s:library.templates, name.'!!type' ) " let my_type = a:type let other_type = split ( s:library.templates[ name.'!!type' ], ',' )[0] " if my_type != other_type call s:ErrorMsg ( 'Separator "'.name.'" can not overwrite an object of the same name of type "'.s:TemplateTypeNames[other_type].'".' ) return endif else " let s:library.templates[ name.'!!type' ] = 'sep,,0' let s:library.templates[ name.'!!menu' ] = "0,'',11,'',''" " call add ( s:library.menu_order, name ) " endif " endfunction " ---------- end of function s:AddSeparator ---------- " "---------------------------------------------------------------------- " s:AddStyles : Add styles to the list. {{{2 "---------------------------------------------------------------------- " function! s:AddStyles ( styles ) " " TODO: check for valid name " add the styles to the list for s in a:styles if -1 == index ( s:library.styles, s ) call add ( s:library.styles, s ) endif endfor " endfunction " ---------- end of function s:AddStyles ---------- " "---------------------------------------------------------------------- " s:UseStyles : Set the styles. {{{2 "---------------------------------------------------------------------- " function! s:UseStyles ( styles ) " " 'use_styles' empty? -> we may have new styles " otherwise -> must be a subset, so no new styles if empty ( s:t_runtime.use_styles ) " add the styles to the list call s:AddStyles ( a:styles ) else " are the styles a sub-set of the currently used styles? for s in a:styles if -1 == index ( s:t_runtime.use_styles, s ) call s:ErrorMsg ( 'Style "'.s.'" currently not in use.' ) return endif endfor endif " " push the new style and use it as the current style call add ( s:t_runtime.styles_stack, a:styles ) let s:t_runtime.use_styles = a:styles " endfunction " ---------- end of function s:UseStyles ---------- " "---------------------------------------------------------------------- " s:RevertStyles : Revert the styles. {{{2 "---------------------------------------------------------------------- " function! s:RevertStyles ( times ) " " get the current top, and check whether any more styles can be removed let state_lim = s:t_runtime.state_stack[ s:StateStackStyleTop ] let state_top = len( s:t_runtime.styles_stack ) " if state_lim > ( state_top - a:times ) call s:ErrorMsg ( 'Can not close any more style sections.' ) return endif " " remove the top call remove ( s:t_runtime.styles_stack, -1 * a:times, -1 ) " " reset the current style if state_top > a:times let s:t_runtime.use_styles = s:t_runtime.styles_stack[ -1 ] else let s:t_runtime.use_styles = [] endif " endfunction " ---------- end of function s:RevertStyles ---------- " "---------------------------------------------------------------------- " === Read Templates: Template File Namespace === {{{1 "---------------------------------------------------------------------- " "---------------------------------------------------------------------- " s:FileReadNameSpace : The set of functions a template file can call. {{{2 "---------------------------------------------------------------------- " let s:FileReadNameSpace = { \ 'IncludeFile' : 'ss\?', \ 'SetFormat' : 'ss', \ 'SetMacro' : 'ss', \ 'SetPath' : 'ss', \ 'SetStyle' : 's', \ \ 'MenuShortcut' : 'ss', \ } " \ 'SetMap' : 'ss', " \ 'SetProperty' : 'ss', " \ 'SetShortcut' : 'ss', " "---------------------------------------------------------------------- " s:SetFormat : Set the format of |DATE|, ... (template function). {{{2 "---------------------------------------------------------------------- " function! s:SetFormat ( name, replacement ) " " check for valid name if a:name !~ 'TIME\|DATE\|YEAR' call s:ErrorMsg ( 'Can not set the format of: '.a:name ) return endif " let s:library.macros[ a:name ] = a:replacement " endfunction " ---------- end of function s:SetFormat ---------- " "---------------------------------------------------------------------- " s:SetMacro : Set a replacement (template function). {{{2 "---------------------------------------------------------------------- " function! s:SetMacro ( name, replacement ) " " check for valid name if a:name !~ s:library.regex_file.MacroName call s:ErrorMsg ( 'Macro name must be a valid identifier: '.a:name ) return elseif has_key ( s:StandardMacros, a:name ) call s:ErrorMsg ( 'The special macro "'.a:name.'" can not be replaced via SetMacro.' ) return endif " let s:library.macros[ a:name ] = a:replacement " endfunction " ---------- end of function s:SetMacro ---------- " "---------------------------------------------------------------------- " s:SetStyle : Set the current style (template function). {{{2 "---------------------------------------------------------------------- " function! s:SetStyle ( name ) " " check for valid name if a:name !~ s:library.regex_file.MacroName call s:ErrorMsg ( 'Style name must be a valid identifier: '.a:name ) return endif " let s:library.current_style = a:name " endfunction " ---------- end of function s:SetStyle ---------- " "---------------------------------------------------------------------- " s:SetPath : Set a path-resource (template function). {{{2 "---------------------------------------------------------------------- " function! s:SetPath ( name, value ) " " check for valid name if a:name !~ s:library.regex_file.MacroName call s:ErrorMsg ( 'Path name must be a valid identifier: '.a:name ) return endif " let s:library.resources[ 'path!'.a:name ] = a:value " endfunction " ---------- end of function s:SetPath ---------- " "---------------------------------------------------------------------- " s:MenuShortcut : Set a shortcut for a sub-menu (template function). {{{2 "---------------------------------------------------------------------- " function! s:MenuShortcut ( name, shortcut ) " " check for valid shortcut if len ( a:shortcut ) > 1 call s:ErrorMsg ( 'The shortcut for "'.a:name.'" must be a single character.' ) return endif " let name = substitute( a:name, '\.$', '', '' ) " let s:library.menu_shortcuts[ name ] = a:shortcut " endfunction " ---------- end of function s:MenuShortcut ---------- " "---------------------------------------------------------------------- " s:SetMap : TODO (template function). {{{2 "---------------------------------------------------------------------- " function! s:SetMap ( name, map ) " echo 'SetMap: TO BE IMPLEMENTED' " endfunction " ---------- end of function s:SetMap ---------- " "---------------------------------------------------------------------- " s:SetProperty : TODO (template function). {{{2 "---------------------------------------------------------------------- " function! s:SetProperty ( name, shortcut ) " echo 'SetProperty: TO BE IMPLEMENTED' " endfunction " ---------- end of function s:SetProperty ---------- " "---------------------------------------------------------------------- " s:SetShortcut : TODO (template function). {{{2 "---------------------------------------------------------------------- " function! s:SetShortcut ( name, shortcut ) " " check for valid shortcut if len ( a:shortcut ) > 1 call s:ErrorMsg ( 'The shortcut for "'.a:name.'" must be a single character.' ) return endif " echo 'SetShortcut: TO BE IMPLEMENTED' " endfunction " ---------- end of function s:SetShortcut ---------- " "---------------------------------------------------------------------- " s:IncludeFile : Read a template file (template function). {{{2 "---------------------------------------------------------------------- " function! s:IncludeFile ( templatefile, ... ) " let regex = s:library.regex_file " let read_abs = 0 if a:0 >= 1 && a:1 == 'abs' let read_abs = 1 endif " " ================================================== " checks " ================================================== " " Expand ~, $HOME, ... and check for absolute path let templatefile = expand( a:templatefile ) " " if templatefile =~ regex.AbsolutePath " let templatefile = s:ConcatNormalizedFilename ( templatefile ) " else " let templatefile = s:ConcatNormalizedFilename ( s:t_runtime.state_stack[ s:StateStackFile ], templatefile ) " endif if read_abs let templatefile = s:ConcatNormalizedFilename ( templatefile ) else let templatefile = s:ConcatNormalizedFilename ( s:t_runtime.state_stack[ s:StateStackFile ], templatefile ) endif " " file does not exists or was already visited? if !filereadable( templatefile ) throw 'Template:Check:file "'.templatefile.'" does not exist or is not readable' elseif has_key ( s:t_runtime.files_visited, templatefile ) throw 'Template:Check:file "'.templatefile.'" already read' endif " " ================================================== " setup " ================================================== " " add to the state stack call add ( s:t_runtime.state_stack, len( s:t_runtime.styles_stack ) ) " length of styles_stack call add ( s:t_runtime.state_stack, s:GetNormalizedPath ( templatefile ) ) " current path " " mark file as read let s:t_runtime.files_visited[templatefile] = 1 " " debug: call s:DebugMsg ( 'Reading '.templatefile.' ...', 2 ) " let state = 'command' let t_start = 0 let last_styles = '' " " ================================================== " go trough the file " ================================================== " let filelines = readfile( templatefile ) " for line in filelines " let firstchar = line[0] " " which state if state == 'command' " ================================================== " state: command " ================================================== " " empty line? if empty ( line ) continue endif " " comment? if firstchar == regex.CommentHint if line =~ regex.CommentLine continue endif endif " " macro line? --- |MACRO| = something if firstchar == regex.MacroHint " let mlist = matchlist ( line, regex.MacroAssign ) if ! empty ( mlist ) " STYLE, includefile or general macro if mlist[1] == 'STYLE' call s:SetStyle ( mlist[3] ) elseif mlist[1] == 'includefile' try call s:IncludeFile ( mlist[3], 'old' ) catch /Template:Check:.*/ let msg = v:exception[ len( 'Template:Check:') : -1 ] call s:ErrorMsg ( 'While loading "'.templatefile.'":', msg ) endtry else call s:SetMacro ( mlist[1], mlist[3] ) endif continue endif " endif " " function call? --- Function( param_list ) if firstchar =~ regex.CommandHint " let mlist = matchlist ( line, regex.FunctionCall ) if ! empty ( mlist ) let [ name, param ] = mlist[ 1 : 2 ] " try " check the call call s:FunctionCheck ( name, param, s:FileReadNameSpace ) " try to call exe 'call s:'.name.' ( '.param.' ) ' catch /Template:Check:.*/ let msg = v:exception[ len( 'Template:Check:') : -1 ] call s:ErrorMsg ( 'While loading "'.templatefile.'":', msg ) catch // call s:ErrorMsg ( 'While calling "'.name.'" in "'.templatefile.'":', v:exception ) endtry " continue endif " endif " " section or text? if firstchar == regex.DelimHint " " switch styles? let mlist = matchlist ( line, regex.Styles1Start ) if ! empty ( mlist ) call s:UseStyles ( [ mlist[1] ] ) let last_styles = mlist[0] continue endif " " switch styles? if line =~ regex.Styles1End call s:RevertStyles ( 1 ) continue endif " " switch styles? let mlist = matchlist ( line, regex.Styles2Start ) if ! empty ( mlist ) call s:UseStyles ( split( mlist[1], '\s*,\s*' ) ) let last_styles = mlist[0] continue endif " " switch styles? if line =~ regex.Styles2End call s:RevertStyles ( 1 ) continue endif " " separator? let mlist = matchlist ( line, regex.MenuSep ) if ! empty ( mlist ) call s:AddSeparator ( 'sep', mlist[1], '' ) continue endif " " start of text? let mlist_template = matchlist ( line, regex.TemplateStart ) let mlist_help = matchlist ( line, regex.HelpStart ) let mlist_list = matchlist ( line, regex.ListStart ) if ! empty ( mlist_template ) let state = 'text' let t_type = 'template' let t_start = 1 elseif ! empty ( mlist_help ) let state = 'text' let t_type = 'help' let t_start = 1 elseif ! empty ( mlist_list ) let state = 'text' let t_type = 'list' let t_start = 1 endif " endif " " empty line? if line =~ regex.EmptyLine continue endif " elseif state == 'text' " ================================================== " state: text " ================================================== " if firstchar == regex.CommentHint || firstchar == regex.DelimHint " " comment or end of template? if line =~ regex.CommentLine \ || line =~ regex.TemplateEnd \ || line =~ regex.ListEnd let state = 'command' call s:AddText ( t_type, t_name, t_settings, t_lines ) continue endif " " start of new text? let mlist_template = matchlist ( line, regex.TemplateStart ) let mlist_help = matchlist ( line, regex.HelpStart ) let mlist_list = matchlist ( line, regex.ListStart ) if ! empty ( mlist_template ) call s:AddText ( t_type, t_name, t_settings, t_lines ) let t_type = 'template' let t_start = 1 elseif ! empty ( mlist_help ) call s:AddText ( t_type, t_name, t_settings, t_lines ) let t_type = 'help' let t_start = 1 elseif ! empty ( mlist_list ) call s:AddText ( t_type, t_name, t_settings, t_lines ) let t_type = 'list' let t_start = 1 else let t_lines .= line."\n" " read the line continue endif " else let t_lines .= line."\n" " read the line continue endif " endif " " start of template? if t_start if t_type == 'template' let t_name = mlist_template[1] let t_settings = split( mlist_template[2], '\s*,\s*' ) elseif t_type == 'list' let t_name = mlist_list[1] let t_settings = split( mlist_list[2], '\s*,\s*' ) elseif t_type == 'help' let t_name = mlist_help[1] let t_settings = split( mlist_help[2], '\s*,\s*' ) endif let t_lines = '' let t_start = 0 continue endif " call s:ErrorMsg ( 'Failed to read line: '.line ) " endfor " " ================================================== " wrap up " ================================================== " if state == 'text' call s:AddText ( t_type, t_name, t_settings, t_lines ) endif " " all style sections closed? let state_lim = s:t_runtime.state_stack[ s:StateStackStyleTop ] let state_top = len( s:t_runtime.styles_stack ) if state_lim < state_top call s:RevertStyles ( state_top - state_lim ) call s:ErrorMsg ( 'Styles section has not been closed: '.last_styles ) endif " " debug: call s:DebugMsg ( '... '.templatefile.' done.', 2 ) " " restore the previous state call remove ( s:t_runtime.state_stack, -1 * s:StateStackLength, -1 ) " endfunction " ---------- end of function s:IncludeFile ---------- " "---------------------------------------------------------------------- " mmtemplates#core#ReadTemplates : Read a template file. {{{1 "---------------------------------------------------------------------- " function! mmtemplates#core#ReadTemplates ( library, ... ) " " ================================================== " parameters " ================================================== " if type( a:library ) == type( '' ) exe 'let t_lib = '.a:library elseif type( a:library ) == type( {} ) let t_lib = a:library else return s:ErrorMsg ( 'Argument "library" must be given as a dict or string.' ) endif " " ================================================== " setup " ================================================== " " library and runtime information let s:library = t_lib let s:t_runtime = { \ 'state_stack' : [], \ 'use_styles' : [], \ 'styles_stack' : [], \ 'files_visited' : {}, \ \ 'overwrite_warning' : 0, \ } " let mode = '' let file = '' " " ================================================== " options " ================================================== " let i = 1 while i <= a:0 " if a:[i] == 'load' && i+1 <= a:0 let mode = 'load' let file = a:[i+1] let i += 2 elseif a:[i] == 'reload' && i+1 <= a:0 let mode = 'reload' let file = a:[i+1] let i += 2 elseif a:[i] == 'overwrite_warning' let s:t_runtime.overwrite_warning = 1 let i += 1 elseif a:[i] == 'debug' && i+1 <= a:0 && ! s:DebugGlobalOverwrite let s:DebugLevel = a:[i+1] let i += 2 else if type ( a:[i] ) == type ( '' ) | call s:ErrorMsg ( 'Unknown option: "'.a:[i].'"' ) else | call s:ErrorMsg ( 'Unknown option at position '.i.'.' ) | endif let i += 1 endif " endwhile " " ================================================== " files " ================================================== " let templatefiles = [] " if mode == 'load' " " check the type if type( file ) != type( '' ) return s:ErrorMsg ( 'Argument "filename" must be given as a string.' ) endif " " expand ~, $HOME, ... and normalize let file = expand ( file ) call add ( templatefiles, s:ConcatNormalizedFilename ( file ) ) " " add to library call add ( t_lib.library_files, s:ConcatNormalizedFilename ( file ) ) " elseif mode == 'reload' " if type( file ) == type( 0 ) call add ( templatefiles, t_lib.library_files[ file ] ) elseif type( file ) == type( '' ) " load all or a specific file if file == 'all' call extend ( templatefiles, t_lib.library_files ) else " " check and add the file let file = expand ( file ) let file = s:ConcatNormalizedFilename ( file ) " if ! filereadable ( file ) return s:ErrorMsg ( 'The file "'.file.'" does not exist.' ) elseif index ( t_lib.library_files, file ) == -1 return s:ErrorMsg ( 'The file "'.file.'" is not part of the template library.' ) endif " call add ( templatefiles, file ) " endif else return s:ErrorMsg ( 'Argument "fileid" must be given as an integer or string.' ) endif " " remove old maps if has_key ( t_lib, 'map_commands' ) call remove ( t_lib, 'map_commands' ) endif " endif " " ================================================== " read the library " ================================================== " " debug: if s:DebugLevel > 0 let time_start = reltime() endif " for f in templatefiles " " file exists? if !filereadable ( f ) call s:ErrorMsg ( 'Template library "'.f.'" does not exist or is not readable.' ) continue endif " " runtime information: " - set up the state stack: length of styles_stack + current path " - reset the current styles let s:t_runtime.state_stack = [ 0, s:GetNormalizedPath ( f ) ] let s:t_runtime.use_styles = [] let s:t_runtime.styles_stack = [] " " read the top-level file call s:IncludeFile ( f, 'abs' ) " endfor " call sort ( s:library.styles ) " sort the styles " " debug: if s:DebugLevel > 0 echo 'Loading library: '.reltimestr( reltime( time_start ) ) endif " if mode == 'reload' echo 'Reloaded the template library.' endif " " ================================================== " wrap up " ================================================== " unlet s:library " remove script variables unlet s:t_runtime " ... " let s:DebugLevel = s:DebugGlobalOverwrite " reset debug " endfunction " ---------- end of function mmtemplates#core#ReadTemplates ---------- " "---------------------------------------------------------------------- " === Templates === {{{1 "---------------------------------------------------------------------- " "---------------------------------------------------------------------- " s:ApplyFlag : Modify a text according to 'flag'. {{{2 "---------------------------------------------------------------------- " function! s:ApplyFlag ( text, flag ) " if a:flag == '' || a:flag == 'i' " i : identity return a:text elseif a:flag == 'l' " l : lowercase return tolower(a:text) elseif a:flag == 'u' " u : uppercase return toupper(a:text) elseif a:flag == 'c' " c : capitalize return toupper(a:text[0]).a:text[1:] elseif a:flag == 'L' " L : legalized name let text = substitute( a:text, '\s\+', '_', 'g' ) " multiple whitespaces let text = substitute( text, '\W\+', '_', 'g' ) " multiple non-word characters let text = substitute( text, '_\+', '_', 'g' ) " multiple underscores return text else " flag not valid return a:text endif " endfunction " ---------- end of function s:ApplyFlag ---------- " "---------------------------------------------------------------------- " s:ReplaceMacros : Replace all the macros in a text. {{{2 "---------------------------------------------------------------------- " function! s:ReplaceMacros ( text, m_local ) " let text1 = '' let text2 = a:text " let regex = '\(\_.\{-}\)'.s:library.regex_template.MacroInsert.'\(\_.*\)' " while 1 " let mlist = matchlist ( text2, regex ) " " no more macros? if empty ( mlist ) break endif " " check for recursion if -1 != index ( s:t_runtime.macro_stack, mlist[2] ) let m_text = '' call add ( s:t_runtime.macro_stack, mlist[2] ) throw 'Template:MacroRecursion' elseif has_key ( a:m_local, mlist[2] ) let m_text = get ( a:m_local, mlist[2] ) else let m_text = get ( s:library.macros, mlist[2], '' ) end " if m_text =~ s:library.regex_template.MacroNoCapture " call add ( s:t_runtime.macro_stack, mlist[2] ) " let m_text = s:ReplaceMacros ( m_text, a:m_local ) " call remove ( s:t_runtime.macro_stack, -1 ) " endif " " apply flag? if ! empty ( mlist[3] ) let m_text = s:ApplyFlag ( m_text, mlist[3] ) endif " let text1 .= mlist[1].m_text let text2 = mlist[4] " endwhile " return text1.text2 " endfunction " ---------- end of function s:ReplaceMacros ---------- " "---------------------------------------------------------------------- " s:CheckHelp : Check a template (help). {{{2 "---------------------------------------------------------------------- " let s:NamespaceHelp = { \ 'Word' : 's', \ 'Pattern' : 's', 'Default' : 's', \ 'Substitute' : 'sss', 'LiteralSub' : 'sss', \ 'System' : 's', 'Vim' : 's', \ } " function! s:CheckHelp ( cmds, text, calls ) return [ a:cmds, a:text ] endfunction " ---------- end of function s:CheckHelp ---------- " " "---------------------------------------------------------------------- " s:CheckStdTempl : Check a template (standard). {{{2 "---------------------------------------------------------------------- " let s:NamespaceStdTempl = { \ 'DefaultMacro' : 's[sl]', \ 'PickFile' : 'ss', \ 'PickList' : 's[sld]', \ 'Prompt' : 'ss', \ 'SurroundWith' : 's[sl]*', \ } let s:NamespaceStdTemplInsert = { \ 'Comment' : 's\?', \ 'Insert' : 's[sl]*', \ 'InsertLine' : 's[sl]*', \ } " function! s:CheckStdTempl ( cmds, text, calls ) " let regex = s:library.regex_template let ms = regex.MacroStart let me = regex.MacroEnd " let cmds = a:cmds let text = a:text " let prompted = {} " " -------------------------------------------------- " replacements " -------------------------------------------------- while 1 " let mlist = matchlist ( text, regex.MacroRequest ) " " no more macros? if empty ( mlist ) break endif " let m_name = mlist[1] let m_flag = mlist[2] " " not a special macro and not already done? if has_key ( s:StandardMacros, m_name ) call s:ErrorMsg ( 'The special macro "'.m_name.'" can not be replaced via |?'.m_name.'|.' ) elseif ! has_key ( prompted, m_name ) let cmds .= "Prompt(".string(m_name).",".string(m_flag).")\n" let prompted[ m_name ] = 1 endif " if ! empty ( m_flag ) | let m_flag = ':'.m_flag | endif " " insert a normal macro let text = s:LiteralReplacement ( text, \ mlist[0], ms.m_name.m_flag.me, 'g' ) " endwhile " " -------------------------------------------------- " lists " -------------------------------------------------- let list_items = [ 'EMPTY', 'SINGLE', 'FIRST', 'LAST' ] " + 'ENTRY' " while 1 " let mlist = matchlist ( text, regex.ListItem ) " " no more macros? if empty ( mlist ) break endif " let l_name = mlist[1] " let mlist = matchlist ( text, \ '\([^'."\n".']*\)'.ms.l_name.':ENTRY_*'.me.'\([^'."\n".']*\)\n' ) " let cmds .= "LIST(".string(l_name)."," \ .string(mlist[1]).",".string(mlist[2]).")\n" let text = s:LiteralReplacement ( text, \ mlist[0], ms.l_name.':LIST'.me."\n", '' ) " for item in list_items " let mlist = matchlist ( text, \ '\([^'."\n".']*\)'.ms.l_name.':'.item.'_*'.me.'\([^'."\n".']*\)\n' ) " if empty ( mlist ) let cmds .= "\n" continue endif " let cmds .= "[".string(mlist[1]).",".string(mlist[2])."]\n" let text = s:LiteralReplacement ( text, mlist[0], '', '' ) endfor " endwhile " " -------------------------------------------------- " comments " -------------------------------------------------- while 1 " let mlist = matchlist ( text, regex.FunctionComment ) " " no more comments? if empty ( mlist ) break endif " let [ f_name, f_param ] = mlist[ 1 : 2 ] " " check the call call s:FunctionCheck ( 'Comment', f_param, s:NamespaceStdTemplInsert ) " exe 'let flist = ['.f_param.']' " if empty ( flist ) | let flag = 'eol' else | let flag = flist[0] | endif " let mlist = matchlist ( text, regex.FunctionComment.'\s*\([^'."\n".']*\)' ) " let text = s:LiteralReplacement ( text, mlist[0], \ ms.'InsertLine("Comments.end-of-line","|CONTENT|",'.string( mlist[3] ).')'.me, '' ) " endwhile " return [ cmds, text ] " endfunction " ---------- end of function s:CheckStdTempl ---------- " "---------------------------------------------------------------------- " s:CheckTemplate : Check a template. {{{2 " " Get the command and text block. "---------------------------------------------------------------------- " function! s:CheckTemplate ( template, type ) " let regex = s:library.regex_template " let cmds = '' let text = '' let calls = [] " " the known functions if a:type == 't' let namespace = s:NamespaceStdTempl " " TODO: remove this code: " elseif a:type == 'pick-file' " let namespace = s:NamespacePickFile " elseif a:type == 'pick-list' " let namespace = s:NamespacePickList elseif a:type == 'help' let namespace = s:NamespaceHelp endif " " go trough the lines let idx = 0 while idx < len ( a:template ) " let idx_n = stridx ( a:template, "\n", idx ) let mlist = matchlist ( a:template[ idx : idx_n ], regex.FunctionLine ) " " no match or 'Comment' or 'Insert' function? if empty ( mlist ) || mlist[ 2 ] =~ regex.TextBlockFunctions break endif " let [ f_name, f_param ] = mlist[ 2 : 3 ] " " check the call call s:FunctionCheck ( f_name, f_param, namespace ) " call add ( calls, [ f_name, f_param ] ) " let cmds .= mlist[1]."\n" let idx += len ( mlist[0] ) " endwhile " let text = a:template[ idx : -1 ] " " checks depending on the type if a:type == 't' return s:CheckStdTempl( cmds, text, calls ) " " TODO: remove this code: " elseif a:type == 'pick-file' " return s:CheckPickFile( cmds, text, calls ) " elseif a:type == 'pick-list' " return s:CheckPickList( cmds, text, calls ) elseif a:type == 'help' return s:CheckHelp( cmds, text, calls ) endif " endfunction " ---------- end of function s:CheckTemplate ---------- " "---------------------------------------------------------------------- " s:GetTemplate : Get a template. {{{2 "---------------------------------------------------------------------- " function! s:GetTemplate ( name, style ) " let name = a:name let style = a:style " " check the template if has_key ( s:library.templates, name.'!!type' ) let info = s:library.templates[ a:name.'!!type' ] let [ type, placement, indentation ] = split ( info, ',' ) else throw 'Template:Prepare:template does not exist' endif " if style == '!any' for s in s:library.styles if has_key ( s:library.templates, name.'!'.s ) let template = get ( s:library.templates, name.'!'.s ) let style = s endif endfor else " check the style if has_key ( s:library.templates, name.'!'.style ) let template = get ( s:library.templates, name.'!'.style ) elseif has_key ( s:library.templates, name.'!default' ) let template = get ( s:library.templates, name.'!default' ) let style = 'default' elseif style == 'default' throw 'Template:Prepare:template does not have the default style' else throw 'Template:Prepare:template has neither the style "'.style.'" nor the default style' endif endif " " check the text let head = template[ 0 : 5 ] " if head == "|P()|\n" " plain text " TODO: special type for plain let cmds = '' let text = template[ 6 : -1 ] elseif head == "|T()|\n" " only text (contains only macros without '?') let cmds = '' let text = template[ 6 : -1 ] elseif head == "|C()|\n" " command and text block let splt = stridx ( template, "|T()|\n" ) - 1 let cmds = template[ 6 : splt ] let text = template[ splt+7 : -1 ] else " " do checks let [ cmds, text ] = s:CheckTemplate ( template, type ) " " save the result if empty ( cmds ) let template = "|T()|\n".text else let template = "|C()|\n".cmds."|T()|\n".text end let s:library.templates[ a:name.'!'.style ] = template " end " return [ cmds, text, type, placement, indentation ] endfunction " ---------- end of function s:GetTemplate ---------- " "---------------------------------------------------------------------- " s:GetPickList : Get the list used in a template. {{{2 "---------------------------------------------------------------------- " function! s:GetPickList ( name ) " let regex = s:library.regex_template " " get the template let [ cmds, text, type, placement, indentation ] = s:GetTemplate ( a:name, '!any' ) " if type == 't' " for line in split( cmds, "\n" ) " the line will match and it will be a valid function let [ f_name, f_param ] = matchlist ( line, regex.FunctionChecked )[ 1 : 2 ] " if f_name == 'PickList' " exe 'let [ _, listarg ] = [ '.f_param.' ]' " let entry = '' " if type ( listarg ) == type ( '' ) if ! has_key ( s:library.resources, 'list!'.listarg ) call s:ErrorMsg ( 'List "'.listarg.'" does not exist.' ) return [] endif let list = s:library.resources[ 'list!'.listarg ] else let list = listarg endif " endif endfor " " " TODO: remove this code: " elseif type == 'pick-list' " " " for line in split( cmds, "\n" ) " " the line will match and it will be a valid function " let [ f_name, f_param ] = matchlist ( line, regex.FunctionChecked )[ 1 : 2 ] " " " if f_name == 'List' " exe 'let list = '.f_param " elseif f_name == 'GetList' " " " let listname = matchstr ( f_param, regex.RemoveQuote ) " if ! has_key ( s:library.resources, 'list!'.listname ) " call s:ErrorMsg ( 'List "'.listname.'" does not exist.' ) " return [] " endif " let list = s:library.resources[ 'list!'.listname ] " " " endif " endfor " " else call s:ErrorMsg ( 'Template "'.a:name.'" is not a list picker.' ) return [] endif " if type ( list ) == type ( [] ) return list else return sort ( keys ( list ) ) endif " endfunction " ---------- end of function s:GetPickList ---------- " "---------------------------------------------------------------------- " s:PrepareHelp : Prepare a template (help). {{{2 "---------------------------------------------------------------------- " function! s:PrepareHelp ( cmds, text ) " let regex = s:library.regex_template " let pick = '' let default = '' let method = '' let call = '' " let buf_line = getline('.') let buf_pos = col('.') - 1 " " ================================================== " command block " ================================================== " for line in split( a:cmds, "\n" ) " " the line will match and it will be a valid function let [ f_name, f_param ] = matchlist ( line, regex.FunctionChecked )[ 1 : 2 ] " if f_name == 'C' " ignore elseif f_name == 'Word' exe 'let switch = '.f_param | " TODO: works differently than 'Pattern': picks up word behind the cursor, too if switch == 'W' | let pick = expand('<cWORD>') else | let pick = expand('<cword>') | endif elseif f_name == 'Pattern' exe 'let pattern = '.f_param let cnt = 1 while 1 let m_end = matchend ( buf_line, pattern, 0, cnt ) - 1 if m_end < 0 let pick = '' break elseif m_end >= buf_pos let m_start = match ( buf_line, pattern, 0, cnt ) if m_start <= buf_pos | let pick = buf_line[ m_start : m_end ] else | let pick = '' | endif break endif let cnt += 1 endwhile elseif f_name == 'Default' exe 'let default = '.f_param elseif f_name == 'LiteralSub' exe 'let [ p, r, f ] = ['.f_param.']' let pick = s:LiteralReplacement ( pick, p, r, f ) elseif f_name == 'Substitute' exe 'let [ p, r, f ] = ['.f_param.']' let pick = substitute ( pick, p, r, f ) elseif f_name == 'System' || f_name == 'Vim' let method = f_name exe 'let call = '.f_param endif " endfor " " ================================================== " call for help " ================================================== " if empty ( pick ) && empty ( default ) \ || empty ( method ) return '' endif " let m_local = copy ( s:t_runtime.macros ) " if ! empty ( pick ) let m_local.PICK = pick let call = s:ReplaceMacros ( call, m_local ) else let call = s:ReplaceMacros ( default, m_local ) endif " if method == 'System' echo 'call system ( '.string ( call ).' )' | " debug exe 'call system ( '.string ( call ).' )' elseif method == 'Vim' echo call | " debug exe call endif " return '' " endfunction " ---------- end of function s:PrepareHelp ---------- " " "---------------------------------------------------------------------- " s:PrepareStdTempl : Prepare a template (standard). {{{2 "---------------------------------------------------------------------- " function! s:PrepareStdTempl ( cmds, text ) " " TODO: revert must work like a stack, first set, last reverted " TODO: revert in case of PickList and PickFile " let regex = s:library.regex_template let ms = regex.MacroStart let me = regex.MacroEnd " let m_local = s:t_runtime.macros let m_global = s:library.macros let prompted = s:t_runtime.prompted " let text = a:text let surround = '' let revert = '' " " " ================================================== " command block " ================================================== " let cmds = split( a:cmds, "\n" ) let i_cmds = 0 let n_cmds = len( cmds ) " while i_cmds < n_cmds " " the line will match and it will be a valid function let [ f_name, f_param ] = matchlist ( cmds[ i_cmds ], regex.FunctionChecked )[ 1 : 2 ] " if f_name == 'C' " ignore elseif f_name == 'SurroundWith' let surround = f_param elseif f_name == 'DefaultMacro' " let [ m_name, m_text ] = eval ( '[ '.f_param.' ]' ) " if ! has_key ( m_local, m_name ) let revert = 'call remove ( m_local, "'.m_name.'" ) | '.revert let m_local[ m_name ] = m_text endif " elseif f_name == 'PickFile' " let [ p_prompt, p_path ] = eval ( '[ '.f_param.' ]' ) " if p_path =~ regex.MacroName if ! has_key ( s:library.resources, 'path!'.p_path ) throw 'Template:Prepare:the resources "'.p_path.'" does not exist' endif let p_path = s:library.resources[ 'path!'.p_path ] endif " let p_path = expand ( p_path ) let file = s:UserInput ( p_prompt.' : ', p_path, 'file' ) " let m_local.PICK_COMPL = file let m_local.PATH_COMPL = fnamemodify ( file, ':h' ) " let file = substitute ( file, '\V\^'.p_path, '', '' ) " let m_local.PICK = file let m_local.PATH = fnamemodify ( file, ':h' ) let m_local.FILENAME = fnamemodify ( file, ':t' ) let m_local.BASENAME = fnamemodify ( file, ':t:r' ) let m_local.SUFFIX = fnamemodify ( file, ':e' ) " elseif f_name == 'PickEntry' " let [ p_which, p_entry ] = eval ( '[ '.f_param.' ]' ) " let l:pick_entry = p_entry " elseif f_name == 'PickList' " let [ p_prompt, p_list ] = eval ( '[ '.f_param.' ]' ) " if type ( p_list ) == type ( '' ) if ! has_key ( s:library.resources, 'list!'.p_list ) throw 'Template:Prepare:the resources "'.p_list.'" does not exist' endif let list = s:library.resources[ 'list!'.p_list ] else let list = p_list end " if type ( list ) == type ( [] ) let type = 'list' let input_list = list else let type = 'dict' let input_list = sort ( keys ( list ) ) endif " if exists ( 'l:pick_entry' ) let entry = l:pick_entry else let entry = s:UserInput ( p_prompt.' : ', '', 'customlist', input_list ) endif " let m_local.KEY = entry " if type == 'dict' if ! has_key ( list, entry ) throw 'Template:Prepare:the entry "'.entry.'" does not exist' endif let entry = list[ entry ] endif " let m_local.VALUE = entry let m_local.PICK = entry " elseif f_name == 'Prompt' " let [ m_name, m_flag ] = eval ( '[ '.f_param.' ]' ) " " not already done and not a local macro? if ! has_key ( prompted, m_name ) \ && ! has_key ( m_local, m_name ) let m_text = get ( m_global, m_name, '' ) " " prompt user for replacement let flagaction = get ( s:Flagactions, m_flag, '' ) " notify flag action, if any let m_text = s:UserInput ( m_name.flagaction.' : ', m_text ) let m_text = s:ApplyFlag ( m_text, m_flag ) " " save the result let m_global[ m_name ] = m_text let prompted[ m_name ] = 1 endif else break endif " let i_cmds += 1 endwhile " " -------------------------------------------------- " lists " -------------------------------------------------- " while i_cmds < n_cmds " let mlist = matchlist ( cmds[ i_cmds ], regex.FunctionList ) " if empty ( mlist ) break endif " exe 'let [ l_name, head_def, tail_def ] = ['.mlist[1].']' let l_text = '' if ! has_key ( m_local, l_name ) let l_len = 0 elseif type ( m_local[ l_name ] ) == type ( '' ) let l_list = [ m_local[ l_name ] ] let l_len = 1 else let l_list = m_local[ l_name ] let l_len = len ( l_list ) endif " if l_len == 0 if ! empty ( cmds[ i_cmds+1 ] ) exe 'let [ head, tail ] = '.cmds[ i_cmds+1 ] let l_text = head.tail."\n" endif elseif l_len == 1 if ! empty ( cmds[ i_cmds+2 ] ) exe 'let [ head, tail ] = '.cmds[ i_cmds+2 ] let l_text = head.l_list[0].tail."\n" elseif ! empty ( cmds[ i_cmds+3 ] ) exe 'let [ head, tail ] = '.cmds[ i_cmds+3 ] let l_text = head.l_list[0].tail."\n" else let l_text = head_def.l_list[0].tail_def."\n" end else " l_len >= 2 " if ! empty ( cmds[ i_cmds+3 ] ) exe 'let [ head, tail ] = '.cmds[ i_cmds+3 ] let l_text .= head.l_list[0].tail."\n" else let l_text .= head_def.l_list[0].tail_def."\n" endif " for idx in range ( 1, l_len-2 ) let l_text .= head_def.l_list[idx].tail_def."\n" endfor " if ! empty ( cmds[ i_cmds+4 ] ) exe 'let [ head, tail ] = '.cmds[ i_cmds+4 ] let l_text .= head.l_list[-1].tail."\n" else let l_text .= head_def.l_list[-1].tail_def."\n" endif endif " let text = s:LiteralReplacement ( text, ms.l_name.':LIST'.me."\n", l_text, '' ) " let i_cmds += 5 endwhile " " ================================================== " text block: macros and templates " ================================================== " " insert other templates while 1 " let mlist = matchlist ( text, regex.FunctionInsert ) " " no more inserts? if empty ( mlist ) break endif " let [ f_name, f_param ] = mlist[ 1 : 2 ] " " check the call call s:FunctionCheck ( f_name, f_param, s:NamespaceStdTemplInsert ) " if f_name == 'InsertLine' " get the replacement exe 'let m_text = s:PrepareTemplate ( '.f_param.' )[0]' let m_text = m_text[ 0 : -2 ] " check if m_text =~ "\n" throw 'Template:Prepare:inserts more than a single line: "'.mlist[0].'"' endif elseif f_name == 'Insert' " get the replacement exe 'let m_text = s:PrepareTemplate ( '.f_param.' )[0]' let m_text = m_text[ 0 : -2 ] " prepare let mlist = matchlist ( text, '\([^'."\n".']*\)'.regex.FunctionInsert.'\([^'."\n".']*\)' ) let head = mlist[1] let tail = mlist[4] let m_text = head.substitute( m_text, "\n", tail."\n".head, 'g' ).tail else throw 'Template:Check:the function "'.f_name.'" does not exist' endif " " insert let text = s:LiteralReplacement ( text, mlist[0], m_text, '' ) " endwhile " " insert the replacements let text = s:ReplaceMacros ( text, m_local ) " " ================================================== " surround the template " ================================================== " if ! empty ( surround ) " get the replacement exe 'let [ s_text, s_place ] = s:PrepareTemplate ( '.surround.', "do_surround" )' " if s_place == 'CONTENT' if -1 == match( s_text, '<CONTENT>' ) throw 'Template:Prepare:surround template: <CONTENT> missing' endif " let mcontext = matchlist ( s_text, '\([^'."\n".']*\)'.'<CONTENT>'.'\([^'."\n".']*\)' ) let head = mcontext[1] let tail = mcontext[2] " insert let text = text[ 0: -2 ] " remove trailing '\n' let text = head.substitute( text, "\n", tail."\n".head, 'g' ).tail let text = s:LiteralReplacement ( s_text, mcontext[0], text, '' ) elseif s_place == 'SPLIT' if -1 == match( s_text, '<SPLIT>' ) throw 'Template:Prepare:surround template: <SPLIT> missing' endif " if match( s_text, '<SPLIT>\s*\n' ) >= 0 let part = split ( s_text, '\s*<SPLIT>\s*\n', 1 ) else let part = split ( s_text, '<SPLIT>', 1 ) endif let text = part[0].text.part[1] endif endif " exe revert " return text " endfunction " ---------- end of function s:PrepareStdTempl ---------- " "---------------------------------------------------------------------- " s:PrepareTemplate : Prepare a template for insertion. {{{2 "---------------------------------------------------------------------- " function! s:PrepareTemplate ( name, ... ) " let regex = s:library.regex_template " " ================================================== " setup and checks " ================================================== " " check for recursion if -1 != index ( s:t_runtime.obj_stack, a:name ) call add ( s:t_runtime.obj_stack, a:name ) throw 'Template:Recursion' endif " call add ( s:t_runtime.obj_stack, a:name ) " " current style let style = s:library.current_style " " get the template let [ cmds, text, type, placement, indentation ] = s:GetTemplate ( a:name, style ) " " current macros let m_local = s:t_runtime.macros let prompted = s:t_runtime.prompted " let remove_cursor = 1 let remove_split = 1 let use_surround = 0 let use_split = 0 " let revert = '' " " ================================================== " parameters " ================================================== " let i = 1 while i <= a:0 " if a:[i] =~ regex.MacroMatch && i+1 <= a:0 let m_name = matchlist ( a:[i], regex.MacroNameC )[1] if has_key ( m_local, m_name ) let revert = 'let m_local["'.m_name.'"] = '.string( m_local[ m_name ] ).' | '.revert else let revert = 'call remove ( m_local, "'.m_name.'" ) | '.revert endif let m_local[ m_name ] = a:[i+1] let i += 2 elseif a:[i] == '<CURSOR>' let remove_cursor = 0 let i += 1 elseif a:[i] == '<SPLIT>' let remove_split = 0 let i += 1 elseif a:[i] == 'do_surround' let use_surround = 1 let i += 1 elseif a:[i] == 'use_split' let use_split = 1 let remove_split = 0 let i += 1 elseif a:[i] == 'pick' && i+1 <= a:0 let cmds = "PickEntry( '', ".string(a:[i+1])." )\n".cmds let i += 2 else if type ( a:[i] ) == type ( '' ) | call s:ErrorMsg ( 'Unknown option: "'.a:[i].'"' ) else | call s:ErrorMsg ( 'Unknown option at position '.i.'.' ) | endif let i += 1 endif " endwhile " " ================================================== " prepare " ================================================== " if type == 't' let text = s:PrepareStdTempl( cmds, text ) " " TODO: remove this code: " elseif type == 'pick-file' " let text = s:PreparePickFile( cmds, text ) " elseif type == 'pick-list' " let text = s:PreparePickList( cmds, text ) elseif type == 'help' let text = s:PrepareHelp( cmds, text ) endif " if remove_cursor let text = s:LiteralReplacement( text, '<CURSOR>', '', 'g' ) endif if remove_split let text = s:LiteralReplacement( text, '<SPLIT>', '', 'g' ) endif if ! use_surround || use_split let text = s:LiteralReplacement( text, '<CONTENT>', '', 'g' ) endif " " ================================================== " wrap up " ================================================== " exe revert " call remove ( s:t_runtime.obj_stack, -1 ) " if use_split return [ text, 'SPLIT' ] elseif use_surround return [ text, 'CONTENT' ] else return [ text, placement, indentation ] endif " endfunction " ---------- end of function s:PrepareTemplate ---------- " "---------------------------------------------------------------------- " === Insert Templates: Auxiliary Functions === {{{1 "---------------------------------------------------------------------- " "---------------------------------------------------------------------- " s:InsertIntoBuffer : Insert a text into the buffer. {{{2 " (thanks to Fritz Mehner) "---------------------------------------------------------------------- " function! s:InsertIntoBuffer ( text, placement, indentation, flag_mode ) " " TODO: syntax let regex = s:library.regex_template " let placement = a:placement let indentation = a:indentation == '1' " if a:flag_mode != 'v' " -------------------------------------------------- " command and insert mode " -------------------------------------------------- " " remove the split point let text = substitute( a:text, '\V'.'<SPLIT>', '', 'g' ) " if placement == 'below' " exe ':'.s:t_runtime.range[1] call s:OpenFold('below') let pos1 = line(".")+1 silent put = text let pos2 = line(".") " elseif placement == 'above' " exe ':'.s:t_runtime.range[0] let pos1 = line(".") silent put! = text let pos2 = line(".") " elseif placement == 'start' " exe ':1' call s:OpenFold('start') let pos1 = 1 silent put! = text let pos2 = line(".") " elseif placement == 'append' || placement == 'insert' " if &foldenable && foldclosed(".") >= 0 throw 'Template:Insert:insertion not available for a closed fold' elseif placement == 'append' let pos1 = line(".") silent put = text let pos2 = line(".")-1 exe ":".pos1 :join! let indentation = 0 elseif placement == 'insert' let text = text[ 0: -2 ] " remove trailing '\n' let currentline = getline( "." ) let pos1 = line(".") let pos2 = pos1 + count( split(text,'\zs'), "\n" ) if a:flag_mode == 'i' exe 'normal! gi'.text else exe 'normal! a'.text endif " reformat only multi-line inserts and previously empty lines if pos1 == pos2 && currentline != '' let indentation = 0 endif endif " else throw 'Template:Insert:unknown placement "'.placement.'"' endif " elseif a:flag_mode == 'v' " -------------------------------------------------- " visual mode " -------------------------------------------------- " " remove the jump targets (2nd type) let text = substitute( a:text, regex.JumpTagType2, '', 'g' ) " " TODO: Is the behaviour well-defined? " Suggestion: The line might include a cursor and a split and nothing else. if match( text, '<SPLIT>' ) >= 0 if match( text, '<SPLIT>\s*\n' ) >= 0 let part = split ( text, '\s*<SPLIT>\s*\n', 1 ) else let part = split ( text, '<SPLIT>', 1 ) endif let part[1] = part[1][ 0: -2 ] " remove trailing '\n' else let part = [ "", text[ 0: -2 ] ] " remove trailing '\n' echomsg 'tag <SPLIT> missing in template.' endif " " 'visual' and placement 'insert': " <part0><marked area><part1> " part0 and part1 can consist of several lines " " 'visual' and placement 'below': " <part0> " <marked area> " <part1> " part0 and part1 can consist of several lines " if placement == 'insert' " [_,line,col,off] = getpos() let [_,l1,c1,o1] = getpos("'<") let [_,l2,c2,o2] = getpos("'>") call cursor ( l2, c2, o2 ) exe 'normal! a'.part[1] call cursor ( l1, c1, o1 ) exe 'normal! i'.part[0] let indentation = 0 let pos1 = l1 let pos2 = l2 + len(split( text, '\n' )) - 1 elseif placement == 'below' silent '<put! = part[0] silent '>put = part[1] let pos1 = line("'<") - len(split( part[0], '\n' )) let pos2 = line("'>") + len(split( part[1], '\n' )) elseif placement =~ '^\%(start\|above\|append\)$' throw 'Template:Insert:usage in split mode not allowed for placement "'.placement.'"' else throw 'Template:Insert:unknown placement "'.placement.'"' endif " endif " " proper indenting if indentation silent exe ":".pos1 silent exe "normal ".( pos2-pos1+1 )."==" endif " return [ pos1, pos2 ] " endfunction " ---------- end of function s:InsertIntoBuffer ---------- " "---------------------------------------------------------------------- " s:PositionCursor : Position the cursor. {{{2 " (thanks to Fritz Mehner) "---------------------------------------------------------------------- " function! s:PositionCursor ( placement, flag_mode, pos1, pos2 ) " " :TODO:12.08.2013 11:03:WM: changeable syntax? " :TODO:12.08.2013 12:00:WM: change behavior? " exe ":".a:pos1 let mtch = search( '<CURSOR>\|{CURSOR}', 'c', a:pos2 ) if mtch != 0 " tag found (and cursor moved, we are now at the position of the match) let line = getline(mtch) if line =~ '<CURSOR>$\|{CURSOR}$' " the tag is at the end of the line call setline( mtch, substitute( line, '<CURSOR>\|{CURSOR}', '', '' ) ) if a:flag_mode == 'v' && getline('.') =~ '^\s*$' "if a:flag_mode == 'v' && getline('.') =~ '^\s*\%(<CURSOR>\|{CURSOR}\)\s*$' " the line contains nothing but the tag: remove and join without " changing the second line normal J "call setline( mtch, '' ) "normal gJ else " the line contains other characters: remove the tag and start appending "call setline( mtch, substitute( line, '<CURSOR>\|{CURSOR}', '', '' ) ) startinsert! endif else " the line contains other characters: remove the tag and start inserting call setline( mtch, substitute( line, '<CURSOR>\|{CURSOR}', '', '' ) ) startinsert endif else " no tag found (and cursor not moved) if a:placement == 'below' " to the end of the block, needed for repeated inserts exe ":".a:pos2 endif endif " endfunction " ---------- end of function s:PositionCursor ---------- " "---------------------------------------------------------------------- " s:HighlightJumpTargets : Highlight the jump targets. {{{2 "---------------------------------------------------------------------- " function! s:HighlightJumpTargets ( regex ) exe 'match Search /'.a:regex.'/' endfunction " ---------- end of function s:HighlightJumpTargets ---------- " "---------------------------------------------------------------------- " mmtemplates#core#InsertTemplate : Insert a template. {{{1 "---------------------------------------------------------------------- " function! mmtemplates#core#InsertTemplate ( library, t_name, ... ) range " " ================================================== " parameters " ================================================== " if type( a:library ) == type( '' ) exe 'let t_lib = '.a:library elseif type( a:library ) == type( {} ) let t_lib = a:library else return s:ErrorMsg ( 'Argument "library" must be given as a dict or string.' ) endif " if type( a:t_name ) != type( '' ) return s:ErrorMsg ( 'Argument "template_name" must be given as a string.' ) endif " " ================================================== " setup " ================================================== " " library and runtime information let s:library = t_lib let s:t_runtime = { \ 'obj_stack' : [], \ 'macro_stack' : [], \ 'macros' : {}, \ 'prompted' : {}, \ \ 'placement' : '', \ 'range' : [ a:firstline, a:lastline ], \ } let regex = s:library.regex_template " " renew the predefined macros let s:t_runtime.macros[ 'BASENAME' ] = expand( '%:t:r' ) let s:t_runtime.macros[ 'FILENAME' ] = expand( '%:t' ) let s:t_runtime.macros[ 'PATH' ] = expand( '%:p:h' ) let s:t_runtime.macros[ 'SUFFIX' ] = expand( '%:e' ) " let s:t_runtime.macros[ 'DATE' ] = strftime( s:library.macros[ 'DATE' ] ) let s:t_runtime.macros[ 'TIME' ] = strftime( s:library.macros[ 'TIME' ] ) let s:t_runtime.macros[ 'YEAR' ] = strftime( s:library.macros[ 'YEAR' ] ) " " handle folds internally (and save the state) if &foldenable let foldmethod_save = &foldmethod set foldmethod=manual endif " use internal formatting to avoid conflicts when using == below " (and save the state) let equalprg_save = &equalprg set equalprg= " let flag_mode = 'n' let options = [] " " ================================================== " options " ================================================== " let i = 1 while i <= a:0 " if a:[i] == 'i' || a:[i] == 'insert' let flag_mode = 'i' let i += 1 elseif a:[i] == 'v' || a:[i] == 'visual' let flag_mode = 'v' let i += 1 elseif a:[i] == 'placement' && i+1 <= a:0 let s:t_runtime.placement = a:[i+1] let i += 2 elseif a:[i] == 'range' && i+2 <= a:0 let s:t_runtime.range[0] = a:[i+1] let s:t_runtime.range[1] = a:[i+2] let i += 3 elseif a:[i] =~ regex.MacroMatch && i+1 <= a:0 let name = matchlist ( a:[i], regex.MacroNameC )[1] let s:t_runtime.macros[ name ] = a:[i+1] let i += 2 elseif a:[i] == 'pick' && i+1 <= a:0 call add ( options, 'pick' ) call add ( options, a:[i+1] ) let i += 2 elseif a:[i] == 'debug' && i+1 <= a:0 && ! s:DebugGlobalOverwrite let s:DebugLevel = a:[i+1] let i += 2 else if type ( a:[i] ) == type ( '' ) | call s:ErrorMsg ( 'Unknown option: "'.a:[i].'"' ) else | call s:ErrorMsg ( 'Unknown option at position '.i.'.' ) | endif let i += 1 endif " endwhile " " ================================================== " do the job " ================================================== " try " " prepare the template for insertion if empty ( options ) let [ text, placement, indentation ] = s:PrepareTemplate ( a:t_name, '<CURSOR>', '<SPLIT>' ) else let [ text, placement, indentation ] = call ( 's:PrepareTemplate', [ a:t_name, '<CURSOR>', '<SPLIT>' ] + options ) endif " if placement == 'help' " job already done, TODO: review this else " if ! empty ( s:t_runtime.placement ) let placement = s:t_runtime.placement endif " " insert the text into the buffer let [ pos1, pos2 ] = s:InsertIntoBuffer ( text, placement, indentation, flag_mode ) " " position the cursor call s:PositionCursor ( placement, flag_mode, pos1, pos2 ) " " highlight jump targets call s:HighlightJumpTargets ( regex.JumpTagBoth ) endif " catch /Template:UserInputAborted/ " noop catch /Template:Check:.*/ " let templ = s:t_runtime.obj_stack[ -1 ] let msg = v:exception[ len( 'Template:Check:') : -1 ] call s:ErrorMsg ( 'Checking "'.templ.'":', msg ) " catch /Template:Prepare:.*/ " let templ = s:t_runtime.obj_stack[ -1 ] let incld = len ( s:t_runtime.obj_stack ) == 1 ? '' : '(included by: "'.s:t_runtime.obj_stack[ -2 ].'")' let msg = v:exception[ len( 'Template:Prepare:') : -1 ] call s:ErrorMsg ( 'Preparing "'.templ.'":', incld, msg ) " catch /Template:Recursion/ " let templ = s:t_runtime.obj_stack[ -1 ] let idx1 = index ( s:t_runtime.obj_stack, templ ) let cont = idx1 == 0 ? [] : [ '...' ] call call ( 's:ErrorMsg', [ 'Recursion detected while including the template/s:' ] + cont + \ s:t_runtime.obj_stack[ idx1 : -1 ] ) " catch /Template:MacroRecursion/ " let macro = s:t_runtime.macro_stack[ -1 ] let idx1 = index ( s:t_runtime.macro_stack, macro ) let cont = idx1 == 0 ? [] : [ '...' ] call call ( 's:ErrorMsg', [ 'Recursion detected while replacing the macro/s:' ] + cont + \ s:t_runtime.macro_stack[ idx1 : -1 ] ) " catch /Template:Insert:.*/ " let msg = v:exception[ len( 'Template:Insert:') : -1 ] call s:ErrorMsg ( 'Inserting "'.a:t_name.'":', msg ) " catch /Template:.*/ " let msg = v:exception[ len( 'Template:') : -1 ] call s:ErrorMsg ( msg ) " finally " " ================================================== " wrap up " ================================================== " " restore the state: folding and formatter program if &foldenable exe "set foldmethod=".foldmethod_save normal zv endif let &equalprg = equalprg_save " unlet s:library " remove script variables unlet s:t_runtime " ... " let s:DebugLevel = s:DebugGlobalOverwrite " reset debug " endtry " endfunction " ---------- end of function mmtemplates#core#InsertTemplate ---------- " "---------------------------------------------------------------------- " mmtemplates#core#CreateMaps : Create maps for a template library. {{{1 "---------------------------------------------------------------------- " function! mmtemplates#core#CreateMaps ( library, localleader, ... ) " " ================================================== " parameters " ================================================== " if type( a:library ) == type( '' ) exe 'let t_lib = '.a:library else return s:ErrorMsg ( 'Argument "library" must be given as a string.' ) endif " if type( a:localleader ) != type( '' ) call s:ErrorMsg ( 'Argument "localleader" must be given as a string.' ) return elseif ! empty ( a:localleader ) if exists ( 'g:maplocalleader' ) let ll_save = g:maplocalleader endif let g:maplocalleader = a:localleader endif " " ================================================== " reuse previous commands " ================================================== " if has_key ( t_lib, 'map_commands' ) "let TimeStart = reltime() exe t_lib.map_commands if ! empty ( a:localleader ) if exists ( 'll_save' ) let g:maplocalleader = ll_save else unlet g:maplocalleader endif endif "echo 'Executing maps: '.reltimestr( reltime( TimeStart ) ) return endif " " ================================================== " setup " ================================================== " " options let options = '<buffer> <silent>' let leader = '<LocalLeader>' let sep = "\n" " let do_jump_map = 0 let do_special_maps = 0 " let cmd = '' " " ================================================== " options " ================================================== " let i = 1 while i <= a:0 " if a:[i] == 'do_jump_map' let do_jump_map = 1 let i += 1 elseif a:[i] == 'do_special_maps' let do_special_maps = 1 let i += 1 else if type ( a:[i] ) == type ( '' ) | call s:ErrorMsg ( 'Unknown option: "'.a:[i].'"' ) else | call s:ErrorMsg ( 'Unknown option at position '.i.'.' ) | endif let i += 1 endif " endwhile " "let TimeStart = reltime() " " ================================================== " generate new commands " ================================================== " " go through all the templates for t_name in t_lib.menu_order " exe 'let [ visual, mp ] = ['.t_lib.templates[ t_name.'!!menu' ].'][0:1]' " " no map? " separators have an empty string "map", so they are skipped here if empty ( mp ) continue endif " for mode in [ 'n', 'v', 'i' ] " " map already existing? if ! empty ( maparg( leader.mp, mode ) ) if g:Templates_MapInUseWarn != 0 call s:ErrorMsg ( 'Mapping already in use: "'.leader.mp.'", mode "'.mode.'"' ) endif continue endif " " insert and visual mode: insert '<Esc>' if mode == 'n' | let esc = '' else | let esc = '<Esc>' | endif " " insert mode, flag 'i': " change behavior of templates with placement 'insert' " visual mode, flag 'v': " template contains a split tag, or the mode is forced if mode == 'i' | let flag = ',"i"' elseif mode == 'v' && visual == 1 | let flag = ',"v"' else | let flag = '' | endif " " assemble the command to create the maps let cmd .= mode.'noremap '.options.' '.leader.mp.' '.esc.':call mmtemplates#core#InsertTemplate('.a:library.',"'.t_name.'"'.flag.')<CR>'.sep endfor " endfor " " jump map if do_jump_map let jump_key = '<C-j>' " TODO: configurable if ! empty ( maparg( jump_key ) ) call s:ErrorMsg ( 'Mapping already in use: "'.jump_key.'"' ) else let jump_regex = string ( escape ( t_lib.regex_template.JumpTagBoth, '|' ) ) let cmd .= 'nnoremap '.options.' '.jump_key.' i<C-R>=mmtemplates#core#JumpToTag('.jump_regex.')<CR>'.sep let cmd .= 'inoremap '.options.' '.jump_key.' <C-R>=mmtemplates#core#JumpToTag('.jump_regex.')<CR>'.sep endif endif " " special maps " TODO: configuration of maps " TODO: edit template if do_special_maps let special_maps = { \ t_lib.properties[ 'Templates::EditTemplates::Map' ] : ':call mmtemplates#core#EditTemplateFiles('.a:library.',-1)<CR>', \ t_lib.properties[ 'Templates::RereadTemplates::Map' ] : ':call mmtemplates#core#ReadTemplates('.a:library.',"reload","all")<CR>', \ t_lib.properties[ 'Templates::ChooseStyle::Map' ] : ':call mmtemplates#core#ChooseStyle('.a:library.',"!pick")<CR>', \ } " for [ mp, action ] in items ( special_maps ) if ! empty ( maparg( leader.mp ) ) call s:ErrorMsg ( 'Mapping already in use: "'.leader.mp.'"' ) else let cmd .= ' noremap '.options.' '.leader.mp.' '.action.sep let cmd .= 'inoremap '.options.' '.leader.mp.' <Esc>'.action.sep endif endfor endif " let t_lib.map_commands = cmd exe cmd " " ================================================== " wrap up " ================================================== " if ! empty ( a:localleader ) if exists ( 'll_save' ) let g:maplocalleader = ll_save else unlet g:maplocalleader endif endif " "echo 'Generating maps: '.reltimestr( reltime( TimeStart ) ) " endfunction " ---------- end of function mmtemplates#core#CreateMaps ---------- " "---------------------------------------------------------------------- " === Create Menus: Auxiliary Functions === {{{1 "---------------------------------------------------------------------- " "---------------------------------------------------------------------- " s:InsertShortcut : Insert a shortcut into a menu entry. {{{2 " " Inserts the shortcut by prefixing the appropriate character with '&', " or by appending " (<shortcut>)". If escaped is true, the appended string is " correctly escaped. "---------------------------------------------------------------------- " function! s:InsertShortcut ( entry, shortcut, escaped ) if empty ( a:shortcut ) return a:entry else let entry = a:entry let sc = a:shortcut if stridx ( tolower( entry ), tolower( sc ) ) == -1 if a:escaped | return entry.'\ (&'.sc.')' else | return entry.' (&'.sc.')' endif else return substitute( entry, '\V\c'.sc, '\&&', '' ) endif endif endfunction " ---------- end of function s:InsertShortcut ---------- " "---------------------------------------------------------------------- " s:CreateSubmenu : Create sub-menus, given they do not already exists. {{{2 " " The menu 'menu' can contain '&' and a trailing '.'. Both are ignored. "---------------------------------------------------------------------- " function! s:CreateSubmenu ( t_lib, root_menu, global_name, menu, priority ) " " split point: " a point, preceded by an even number of backslashes " in turn, the backslashes must be preceded by a different character, or the " beginning of the string let level = len( split( a:root_menu, '\%(\_^\|[^\\]\)\%(\\\\\)*\zs\.' ) ) let parts = split( a:menu, '\%(\_^\|[^\\]\)\%(\\\\\)*\zs\.' ) let n_parts = len( parts ) let level += n_parts " let priority_str = '' " " go through the menu, clean up and check for new menus let submenu = '' for i in range( 1, len( parts ) ) " let part = parts[ i-1 ] " if i == n_parts let priority_str = repeat( '.', level-1 ).a:priority.'. ' endif " let clean = substitute( part, '&', '', 'g' ) if ! has_key ( a:t_lib.menu_existing, submenu.clean ) " a new menu! let a:t_lib.menu_existing[ submenu.clean ] = 0 " " shortcut and menu entry if has_key ( a:t_lib.menu_shortcuts, submenu.clean ) let shortcut = a:t_lib.menu_shortcuts[ submenu.clean ] if stridx ( tolower( clean ), tolower( shortcut ) ) == -1 let assemble = submenu.clean.' (&'.shortcut.')' else let assemble = submenu.substitute( clean, '\c'.shortcut, '\&&', '' ) endif else let assemble = submenu.part endif " let assemble .= '.' " if -1 != stridx ( clean, '<TAB>' ) exe 'amenu '.priority_str.a:root_menu.escape( assemble.clean, ' ' ).' :echo "This is a menu header."<CR>' else exe 'amenu '.priority_str.a:root_menu.escape( assemble.clean, ' ' ).'<TAB>'.escape( a:global_name, ' .' ).' :echo "This is a menu header."<CR>' endif exe 'amenu '.a:root_menu.escape( assemble, ' ' ).'-TSep00- <Nop>' endif let submenu .= clean.'.' endfor " endfunction " ---------- end of function s:CreateSubmenu ---------- " "---------------------------------------------------------------------- " s:CreateTemplateMenus : Create menus for the templates. {{{2 "---------------------------------------------------------------------- " function! s:CreateTemplateMenus ( t_lib, root_menu, global_name, t_lib_name ) " let map_ldr = mmtemplates#core#EscapeMenu ( a:t_lib.properties[ 'Templates::Mapleader' ] ) " " go through all the templates for t_name in a:t_lib.menu_order " exe 'let [ visual, mp, entry, _, shortcut ] = ['.a:t_lib.templates[ t_name.'!!menu' ].']' " " no menu entry? if entry == 0 continue endif " " get the sub-menu and the entry let [ t_menu, t_last ] = matchlist ( t_name, '^\(.*\.\)\?\([^\.]\+\)$' )[1:2] " " menu does not exist? if ! empty ( t_menu ) && ! has_key ( a:t_lib.menu_existing, t_menu[ 0 : -2 ] ) call s:CreateSubmenu ( a:t_lib, a:root_menu, a:global_name, t_menu[ 0 : -2 ], s:StandardPriority ) endif " if entry == 11 let m_key = t_menu[ 0 : -2 ] if empty ( m_key ) let m_key = '!base' endif " let sep_nr = a:t_lib.menu_existing[ m_key ] + 1 let a:t_lib.menu_existing[ m_key ] = sep_nr " exe 'amenu '.a:root_menu.escape( t_menu, ' ' ).'-TSep'.sep_nr.'- :' " continue endif " " shortcut and menu entry if ! empty ( shortcut ) if stridx ( tolower( t_last ), tolower( shortcut ) ) == -1 let t_last .= ' (&'.shortcut.')' else let t_last = substitute( t_last, '\c'.shortcut, '\&&', '' ) endif endif " " assemble the entry, including the map, TODO: escape the map let compl_entry = escape( t_menu.t_last, ' ' ) if empty ( mp ) let map_entry = '' else let map_entry = '<TAB>'.map_ldr.mp end " if entry == 1 " <Esc><Esc> prevents problems in insert mode exe 'amenu <silent> '.a:root_menu.compl_entry.map_entry.' <Esc><Esc>:call mmtemplates#core#InsertTemplate('.a:t_lib_name.',"'.t_name.'")<CR>' exe 'imenu <silent> '.a:root_menu.compl_entry.map_entry.' <Esc><Esc>:call mmtemplates#core#InsertTemplate('.a:t_lib_name.',"'.t_name.'","i")<CR>' if visual == 1 exe 'vmenu <silent> '.a:root_menu.compl_entry.map_entry.' <Esc><Esc>:call mmtemplates#core#InsertTemplate('.a:t_lib_name.',"'.t_name.'","v")<CR>' endif elseif entry == 2 call s:CreateSubmenu ( a:t_lib, a:root_menu, a:global_name, t_menu.t_last.map_entry, s:StandardPriority ) " for item in s:GetPickList ( t_name ) let item_entry = compl_entry.'.'.substitute ( substitute ( escape ( item, ' .' ), '&', '\&\&', 'g' ), '\w', '\&&', '' ) exe 'amenu <silent> '.a:root_menu.item_entry.' <Esc><Esc>:call mmtemplates#core#InsertTemplate('.a:t_lib_name.',"'.t_name.'","pick",'.string(item).')<CR>' exe 'imenu <silent> '.a:root_menu.item_entry.' <Esc><Esc>:call mmtemplates#core#InsertTemplate('.a:t_lib_name.',"'.t_name.'","i","pick",'.string(item).')<CR>' if visual == 1 exe 'vmenu <silent> '.a:root_menu.item_entry.' <Esc><Esc>:call mmtemplates#core#InsertTemplate('.a:t_lib_name.',"'.t_name.'","v","pick",'.string(item).')<CR>' endif endfor " " exe 'amenu '.a:root_menu.compl_entry.'.-\ choose\ -'.map_entry.' <Esc><Esc>:call mmtemplates#core#InsertTemplate('.a:t_lib_name.',"'.t_name.'")<CR>' " if visual == 1 " exe 'vmenu '.a:root_menu.compl_entry.'.-\ choose\ -'.map_entry.' <Esc><Esc>:call mmtemplates#core#InsertTemplate('.a:t_lib_name.',"'.t_name.'","v")<CR>' " endif endif " endfor " endfunction " ---------- end of function s:CreateTemplateMenus ---------- " "---------------------------------------------------------------------- " s:CreateSpecialsMenus : Create menus for a template library. {{{2 "---------------------------------------------------------------------- " function! s:CreateSpecialsMenus ( t_lib, root_menu, global_name, t_lib_name, specials_menu, styles_only ) " " remove trailing point let specials_menu = substitute( a:specials_menu, '\.$', '', '' ) " let map_ldr = mmtemplates#core#EscapeMenu ( a:t_lib.properties[ 'Templates::Mapleader' ] ) let map_edit = map_ldr.mmtemplates#core#EscapeMenu ( a:t_lib.properties[ 'Templates::EditTemplates::Map' ] ) let map_read = map_ldr.mmtemplates#core#EscapeMenu ( a:t_lib.properties[ 'Templates::RereadTemplates::Map' ] ) let map_style = map_ldr.mmtemplates#core#EscapeMenu ( a:t_lib.properties[ 'Templates::ChooseStyle::Map' ] ) let sc_edit = mmtemplates#core#EscapeMenu ( a:t_lib.properties[ 'Templates::EditTemplates::Shortcut' ] ) let sc_read = mmtemplates#core#EscapeMenu ( a:t_lib.properties[ 'Templates::RereadTemplates::Shortcut' ] ) let sc_style = mmtemplates#core#EscapeMenu ( a:t_lib.properties[ 'Templates::ChooseStyle::Shortcut' ] ) " " create the specials menu call s:CreateSubmenu ( a:t_lib, a:root_menu, a:global_name, specials_menu, s:StandardPriority ) " if ! a:styles_only " create edit and reread templates let entry_edit = s:InsertShortcut ( '.edit\ templates', sc_edit, 1 ).'<TAB>'.map_edit let entry_read = s:InsertShortcut ( '.reread\ templates', sc_read, 1 ).'<TAB>'.map_read exe 'amenu <silent> '.a:root_menu.specials_menu.entry_edit \ .' :call mmtemplates#core#EditTemplateFiles('.a:t_lib_name.',-1)<CR>' exe 'amenu <silent> '.a:root_menu.specials_menu.entry_read \ .' :call mmtemplates#core#ReadTemplates('.a:t_lib_name.',"reload","all")<CR>' endif " " create a menu for all the styles if sc_style == 's' | let entry_styles = '.choose &style<TAB>'.map_style else | let entry_styles = s:InsertShortcut ( '.choose style', sc_style, 0 ).'<TAB>'.map_style endif call s:CreateSubmenu ( a:t_lib, a:root_menu, a:global_name, specials_menu.entry_styles, s:StandardPriority ) " for s in a:t_lib.styles exe 'amenu <silent> '.a:root_menu.specials_menu.'.choose\ style.&'.s \ .' :call mmtemplates#core#ChooseStyle('.a:t_lib_name.','.string(s).')<CR>' endfor " endfunction " ---------- end of function s:CreateSpecialsMenus ---------- " "---------------------------------------------------------------------- " mmtemplates#core#CreateMenus : Create menus for a template library. {{{1 "---------------------------------------------------------------------- " function! mmtemplates#core#CreateMenus ( library, root_menu, ... ) " " check for feature if ! has ( 'menu' ) return endif " " ================================================== " parameters " ================================================== " if type( a:library ) == type( '' ) exe 'let t_lib = '.a:library let s:library = t_lib else call s:ErrorMsg ( 'Argument "library" must be given as a string.' ) return endif " if type( a:root_menu ) != type( '' ) call s:ErrorMsg ( 'Argument "root_menu" must be given as a string.' ) return endif " " ================================================== " setup " ================================================== " " options let root_menu = substitute( a:root_menu, '&', '', 'g' ) let global_name = substitute( root_menu, '\.$', '', '' ) let root_menu = global_name.'.' let specials_menu = '&Run' let priority = s:StandardPriority let existing = [] " " jobs let do_reset = 0 let do_templates = 0 let do_specials = 0 " no specials let submenus = [] " " ================================================== " options " ================================================== " let i = 1 while i <= a:0 " if a:[i] == 'global_name' && i+1 <= a:0 let global_name = a:[i+1] let i += 2 elseif a:[i] == 'existing_menu' && i+1 <= a:0 if type ( a:[i+1] ) == type ( '' ) | call add ( existing, a:[i+1] ) else | call extend ( existing, a:[i+1] ) | endif let i += 2 elseif a:[i] == 'sub_menu' && i+1 <= a:0 if type ( a:[i+1] ) == type ( '' ) | call add ( submenus, a:[i+1] ) else | call extend ( submenus, a:[i+1] ) | endif let i += 2 elseif a:[i] == 'specials_menu' && i+1 <= a:0 let specials_menu = a:[i+1] let i += 2 elseif a:[i] == 'priority' && i+1 <= a:0 let priority = a:[i+1] let i += 2 elseif a:[i] == 'do_all' let do_reset = 1 let do_templates = 1 let do_specials = 1 let i += 1 elseif a:[i] == 'do_reset' let do_reset = 1 let i += 1 elseif a:[i] == 'do_templates' let do_templates = 1 let i += 1 elseif a:[i] == 'do_specials' let do_specials = 1 let i += 1 elseif a:[i] == 'do_styles' let do_specials = 2 let i += 1 else if type ( a:[i] ) == type ( '' ) | call s:ErrorMsg ( 'Unknown option: "'.a:[i].'"' ) else | call s:ErrorMsg ( 'Unknown option at position '.i.'.' ) | endif let i += 1 endif " endwhile " " ================================================== " do the jobs " ================================================== " " reset if do_reset let t_lib.menu_existing = { '!base' : 0 } endif " " existing menus for name in existing let name = substitute( name, '&', '', 'g' ) let name = substitute( name, '\.$', '', '' ) let t_lib.menu_existing[ name ] = 0 endfor " " sub-menus for name in submenus call s:CreateSubmenu ( t_lib, root_menu, global_name, name, priority ) endfor " " templates if do_templates call s:CreateTemplateMenus ( t_lib, root_menu, global_name, a:library ) endif " " specials if do_specials == 1 " all specials call s:CreateSpecialsMenus ( t_lib, root_menu, global_name, a:library, specials_menu, 0 ) elseif do_specials == 2 " styles only call s:CreateSpecialsMenus ( t_lib, root_menu, global_name, a:library, specials_menu, 1 ) endif " " ================================================== " wrap up " ================================================== " unlet s:library " remove script variable " endfunction " ---------- end of function mmtemplates#core#CreateMenus ---------- " "---------------------------------------------------------------------- " mmtemplates#core#EscapeMenu : Escape a string so it can be used as a menu item. {{{1 "---------------------------------------------------------------------- " function! mmtemplates#core#EscapeMenu ( str ) " let str = escape ( a:str, ' \.|' ) let str = substitute ( str, '&', '\&\&', 'g' ) " return str " endfunction " ---------- end of function mmtemplates#core#EscapeMenu ---------- " "---------------------------------------------------------------------- " mmtemplates#core#ChooseStyle : Choose a style. {{{1 "---------------------------------------------------------------------- " function! mmtemplates#core#ChooseStyle ( library, style ) " " ================================================== " parameters " ================================================== " if type( a:library ) == type( '' ) exe 'let t_lib = '.a:library elseif type( a:library ) == type( {} ) let t_lib = a:library else call s:ErrorMsg ( 'Argument "library" must be given as a dict or string.' ) return endif " if type( a:style ) != type( '' ) call s:ErrorMsg ( 'Argument "style" must be given as a string.' ) return endif " " ================================================== " change the style " ================================================== " " pick the style if a:style == '!pick' try let style = s:UserInput( 'Style (currently '.t_lib.current_style.') : ', '', \ 'customlist', t_lib.styles ) catch /Template:UserInputAborted/ return endtry else let style = a:style endif " " check and set the new style if style == '' " noop elseif -1 != index ( t_lib.styles, style ) if t_lib.current_style != style let t_lib.current_style = style echo 'Changed style to "'.style.'".' elseif a:style == '!pick' echo 'Style stayed "'.style.'".' endif else call s:ErrorMsg ( 'Style was not changed. Style "'.style.'" is not available.' ) end " endfunction " ---------- end of function mmtemplates#core#ChooseStyle ---------- " "---------------------------------------------------------------------- " mmtemplates#core#Resource : Access to various resources. {{{1 "---------------------------------------------------------------------- " function! mmtemplates#core#Resource ( library, mode, ... ) " " TODO mode 'special' for |DATE|, |TIME| and |year| " " ================================================== " parameters " ================================================== " if type( a:library ) == type( '' ) exe 'let t_lib = '.a:library elseif type( a:library ) == type( {} ) let t_lib = a:library else return [ '', 'Argument "library" must be given as a dict or string.' ] endif " if type( a:mode ) != type( '' ) return [ '', 'Argument "mode" must be given as a string.' ] endif " " ================================================== " special inquiries " ================================================== " if a:mode == 'add' || a:mode == 'get' || a:mode == 'set' " continue below elseif a:mode == 'escaped_mapleader' return [ mmtemplates#core#EscapeMenu( t_lib.properties[ 'Templates::Mapleader' ] ), '' ] elseif a:mode == 'jumptag' return [ t_lib.regex_template.JumpTagBoth, '' ] elseif a:mode == 'style' return [ t_lib.current_style, '' ] else return [ '', 'Mode "'.a:mode.'" is unknown.' ] endif " " ================================================== " options " ================================================== " " type of 'resource' let types = { 'list' : '[ld]', 'macro' : 's', 'path' : 's', 'property' : 's' } " if a:mode == 'add' && a:0 != 3 return [ '', 'Mode "add" requires three additional arguments.' ] elseif a:mode == 'get' && a:0 != 2 return [ '', 'Mode "get" requires two additional arguments.' ] elseif a:mode == 'set' && a:0 != 3 return [ '', 'Mode "set" requires three additional arguments.' ] elseif type( a:1 ) != type( '' ) return [ '', 'Argument "resource" must be given as a string.' ] elseif type( a:2 ) != type( '' ) return [ '', 'Argument "key" must be given as a string.' ] elseif ! has_key ( types, a:1 ) return [ '', 'Resource "'.a:1.'" does not exist.' ] elseif a:mode == 'add' && a:1 != 'property' return [ '', 'Can not execute add for resource of type "'.a:1.'".' ] endif " " ================================================== " add, get or set " ================================================== " let resource = a:1 let key = a:2 " if a:mode == 'add' " let value = a:3 " " add (property only) if type( value ) != type( '' ) return [ '', 'Argument "value" must be given as a string.' ] else let t_lib.properties[ key ] = value return [ '', '' ] endif " return [ '', '' ] elseif a:mode == 'get' " " get if resource == 'list' return [ get( t_lib.resources, 'list!'.key ), '' ] elseif resource == 'macro' return [ get( t_lib.macros, key ), '' ] elseif resource == 'path' return [ get( t_lib.resources, 'path!'.key ), '' ] elseif resource == 'property' if has_key ( t_lib.properties, key ) return [ t_lib.properties[ key ], '' ] else return [ '', 'Property "'.key.'" does not exist.' ] endif endif " elseif a:mode == 'set' " let value = a:3 " " check type and set if s:TypeNames[ type( value ) ] !~ types[ resource ] return [ '', 'Argument "value" has the wrong type.' ] elseif resource == 'list' let t_lib.resources[ 'list!'.key ] = value elseif resource == 'macro' let t_lib.macros[ key ] = value elseif resource == 'path' let t_lib.resources[ 'path!'.key ] = value elseif resource == 'property' if has_key ( t_lib.properties, key ) let t_lib.properties[ key ] = value return [ '', '' ] else return [ '', 'Property "'.key.'" does not exist.' ] endif endif " return [ '', '' ] endif " endfunction " ---------- end of function mmtemplates#core#Resource ---------- " "---------------------------------------------------------------------- " mmtemplates#core#ChangeSyntax : Change the syntax of the templates. {{{1 "------------------------------------------------------------------------------- " function! mmtemplates#core#ChangeSyntax ( library, category, ... ) " " ================================================== " parameters " ================================================== " if type( a:library ) == type( '' ) exe 'let t_lib = '.a:library elseif type( a:library ) == type( {} ) let t_lib = a:library else return s:ErrorMsg ( 'Argument "library" must be given as a dict or string.' ) endif " if type( a:category ) != type( '' ) return s:ErrorMsg ( 'Argument "category" must be given as an integer or string.' ) endif " " ================================================== " set the syntax " ================================================== " if a:category == 'comment' " if a:0 < 1 return s:ErrorMsg ( 'Not enough arguments for '.a:category.'.' ) elseif a:0 == 1 let t_lib.regex_settings.CommentStart = a:1 let t_lib.regex_settings.CommentHint = a:1[0] elseif a:0 == 2 let t_lib.regex_settings.CommentStart = a:1 let t_lib.regex_settings.CommentHint = a:2[0] endif " call s:UpdateFileReadRegex ( t_lib.regex_file, t_lib.regex_settings ) " else return s:ErrorMsg ( 'Unknown category: '.a:category ) endif " endfunction " ---------- end of function mmtemplates#core#ChangeSyntax ---------- " "------------------------------------------------------------------------------- " mmtemplates#core#ExpandText : Expand the macros in a text. {{{1 "---------------------------------------------------------------------- " function! mmtemplates#core#ExpandText ( library, text ) " " ================================================== " parameters " ================================================== " if type( a:library ) == type( '' ) exe 'let t_lib = '.a:library elseif type( a:library ) == type( {} ) let t_lib = a:library else return s:ErrorMsg ( 'Argument "library" must be given as a dict or string.' ) endif " if type( a:text ) != type( '' ) return s:ErrorMsg ( 'Argument "text" must be given as a string.' ) endif " " ================================================== " setup " ================================================== " " library and runtime information let s:library = t_lib let s:t_runtime = { \ 'macro_stack' : [], \ } " " renew the predefined macros let m_local = {} let m_local[ 'BASENAME' ] = expand( '%:t:r' ) let m_local[ 'FILENAME' ] = expand( '%:t' ) let m_local[ 'PATH' ] = expand( '%:p:h' ) let m_local[ 'SUFFIX' ] = expand( '%:e' ) " let m_local[ 'DATE' ] = strftime( t_lib.macros[ 'DATE' ] ) let m_local[ 'TIME' ] = strftime( t_lib.macros[ 'TIME' ] ) let m_local[ 'YEAR' ] = strftime( t_lib.macros[ 'YEAR' ] ) " " ================================================== " do the job " ================================================== " let res = '' " try " let res = s:ReplaceMacros ( a:text, m_local ) " catch /Template:MacroRecursion/ " let macro = s:t_runtime.macro_stack[ -1 ] let idx1 = index ( s:t_runtime.macro_stack, macro ) let cont = idx1 == 0 ? [] : [ '...' ] call call ( 's:ErrorMsg', [ 'Recursion detected while replacing the macro/s:' ] + cont + \ s:t_runtime.macro_stack[ idx1 : -1 ] ) " catch /Template:.*/ " let msg = v:exception[ len( 'Template:') : -1 ] call s:ErrorMsg ( msg ) " finally " " ================================================== " wrap up " ================================================== " unlet s:library " remove script variables unlet s:t_runtime " ... " endtry " return res " endfunction " ---------- end of function mmtemplates#core#ExpandText ---------- " "------------------------------------------------------------------------------- " mmtemplates#core#EditTemplateFiles : Choose and edit a template file. {{{1 "------------------------------------------------------------------------------- " function! mmtemplates#core#EditTemplateFiles ( library, file ) " " ================================================== " parameters " ================================================== " if type( a:library ) == type( '' ) exe 'let t_lib = '.a:library elseif type( a:library ) == type( {} ) let t_lib = a:library else return s:ErrorMsg ( 'Argument "library" must be given as a dict or string.' ) endif " if type( a:file ) == type( 0 ) let file = t_lib.library_files[ a:file ] elseif type( a:file ) == type( '' ) " let file = expand ( a:file ) let file = s:ConcatNormalizedFilename ( file ) " if ! filereadable ( file ) return s:ErrorMsg ( 'The file "'.file.'" does not exist.' ) elseif index ( t_lib.library_files, file ) == -1 return s:ErrorMsg ( 'The file "'.file.'" is not part of the template library.' ) endif " else return s:ErrorMsg ( 'Argument "file" must be given as an integer or string.' ) endif " " ================================================== " do the job " ================================================== " " get the directory let dir = fnamemodify ( file, ':h' ) " " TODO: method configurable let method = 'explore' let templatefile = '' " if ! filereadable ( file ) return s:ErrorMsg ( 'The directory "'.dir.'" does not exist.' ) elseif method == 'explore' " open a file explorer if ! exists ( 'g:loaded_netrwPlugin' ) | return s:ErrorMsg ( 'The plugin "netrw" is not available.' ) | endif exe 'update! | split | Explore '.dir elseif method == 'browse' " open a file browser if ! has ( 'browse' ) | return s:ErrorMsg ( 'The command "browse" is not available.' ) | endif let templatefile = browse ( 0, 'edit a template file', dir, '' ) " returns an empty string if "Cancel" is pressed endif " " open a buffer and start editing if ! empty ( templatefile ) exe 'update! | split | edit '.templatefile endif " endfunction " ---------- end of function mmtemplates#core#EditTemplateFiles ---------- " "---------------------------------------------------------------------- " mmtemplates#core#JumpToTag : Jump to the next tag. {{{1 "---------------------------------------------------------------------- " function! mmtemplates#core#JumpToTag ( regex ) " let match = search( a:regex, 'c' ) if match > 0 " remove the target call setline( match, substitute( getline('.'), a:regex, '', '' ) ) endif " return '' endfunction " ---------- end of function mmtemplates#core#JumpToTag ---------- " " }}}1 " " ===================================================================================== " vim: foldmethod=marker
00000svn-vim-cfg
trunk/vimfiles/autoload/mmtemplates/core.vim
Vim Script
gpl3
116,100
if !exists("g:calendar_action") let g:calendar_action = "calendar#diary" endif if !exists("g:calendar_sign") let g:calendar_sign = "calendar#sign" endif if !exists("g:calendar_mark") \|| (g:calendar_mark != 'left' \&& g:calendar_mark != 'left-fit' \&& g:calendar_mark != 'right') let g:calendar_mark = 'left' endif if !exists("g:calendar_navi") \|| (g:calendar_navi != 'top' \&& g:calendar_navi != 'bottom' \&& g:calendar_navi != 'both' \&& g:calendar_navi != '') let g:calendar_navi = 'top' endif if !exists("g:calendar_navi_label") let g:calendar_navi_label = "Prev,Today,Next" endif if !exists("g:calendar_diary") let g:calendar_diary = "~/diary" endif if !exists("g:calendar_focus_today") let g:calendar_focus_today = 0 endif if !exists("g:calendar_datetime") \|| (g:calendar_datetime != '' \&& g:calendar_datetime != 'title' \&& g:calendar_datetime != 'statusline') let g:calendar_datetime = 'title' endif if !exists("g:calendar_options") let g:calendar_options = "fdc=0 nonu" if has("+relativenumber") let g:calendar_options .= " nornu" endif endif "***************************************************************** "* Default Calendar key bindings "***************************************************************** let s:calendar_keys = { \ 'close' : 'q', \ 'do_action' : '<CR>', \ 'goto_today' : 't', \ 'show_help' : '?', \ 'redisplay' : 'r', \ 'goto_next_month' : '<RIGHT>', \ 'goto_prev_month' : '<LEFT>', \ 'goto_next_year' : '<UP>', \ 'goto_prev_year' : '<DOWN>', \} if exists("g:calendar_keys") && type(g:calendar_keys) == 4 let s:calendar_keys = extend(s:calendar_keys, g:calendar_keys) end "***************************************************************** "* CalendarDoAction : call the action handler function "*---------------------------------------------------------------- "***************************************************************** function! calendar#action(...) " for navi if exists('g:calendar_navi') let navi = (a:0 > 0)? a:1 : expand("<cWORD>") let curl = line(".") if navi == '<' . get(split(g:calendar_navi_label, ','), 0, '') if b:CalendarMonth > 1 call calendar#show(b:CalendarDir, b:CalendarYear, b:CalendarMonth-1) else call calendar#show(b:CalendarDir, b:CalendarYear-1, 12) endif elseif navi == get(split(g:calendar_navi_label, ','), 2, '') . '>' if b:CalendarMonth < 12 call calendar#show(b:CalendarDir, b:CalendarYear, b:CalendarMonth+1) else call calendar#show(b:CalendarDir, b:CalendarYear+1, 1) endif elseif navi == get(split(g:calendar_navi_label, ','), 1, '') call calendar#show(b:CalendarDir) if exists('g:calendar_today') exe "call " . g:calendar_today . "()" endif else let navi = '' endif if navi != '' if g:calendar_focus_today == 1 && search("\*","w") > 0 silent execute "normal! gg/\*\<cr>" return else if curl < line('$')/2 silent execute "normal! gg0/".navi."\<cr>" else silent execute "normal! G$?".navi."\<cr>" endif return endif endif endif " if no action defined return if !exists("g:calendar_action") || g:calendar_action == "" return endif if b:CalendarDir let dir = 'H' if exists('g:calendar_weeknm') let cnr = col('.') - (col('.')%(24+5)) + 1 else let cnr = col('.') - (col('.')%(24)) + 1 endif let week = ((col(".") - cnr - 1 + cnr/49) / 3) else let dir = 'V' let cnr = 1 let week = ((col(".")+1) / 3) - 1 endif let lnr = 1 let hdr = 1 while 1 if lnr > line('.') break endif let sline = getline(lnr) if sline =~ '^\s*$' let hdr = lnr + 1 endif let lnr = lnr + 1 endwhile let lnr = line('.') if(exists('g:calendar_monday')) let week = week + 1 elseif(week == 0) let week = 7 endif if lnr-hdr < 2 return endif let sline = substitute(strpart(getline(hdr),cnr,21),'\s*\(.*\)\s*','\1','') if (col(".")-cnr) > 21 return endif " extract day if g:calendar_mark == 'right' && col('.') > 1 normal! h let day = matchstr(expand("<cword>"), '[^0].*') normal! l else let day = matchstr(expand("<cword>"), '[^0].*') endif if day == 0 return endif " extract year and month if exists('g:calendar_erafmt') && g:calendar_erafmt !~ "^\s*$" let year = matchstr(substitute(sline, '/.*', '', ''), '\d\+') let month = matchstr(substitute(sline, '.*/\(\d\d\=\).*', '\1', ""), '[^0].*') if g:calendar_erafmt =~ '.*,[+-]*\d\+' let veranum = substitute(g:calendar_erafmt,'.*,\([+-]*\d\+\)','\1','') if year-veranum > 0 let year = year-veranum endif endif else let year = matchstr(substitute(sline, '/.*', '', ''), '[^0].*') let month = matchstr(substitute(sline, '\d*/\(\d\d\=\).*', '\1', ""), '[^0].*') endif " call the action function exe "call " . g:calendar_action . "(day, month, year, week, dir)" endfunc "***************************************************************** "* Calendar : build calendar "*---------------------------------------------------------------- "* a1 : direction "* a2 : month(if given a3, it's year) "* a3 : if given, it's month "***************************************************************** function! calendar#show(...) "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ "+++ ready for build "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " remember today " divide strftime('%d') by 1 so as to get "1,2,3 .. 9" instead of "01, 02, 03 .. 09" let vtoday = strftime('%Y').strftime('%m').strftime('%d') " get arguments if a:0 == 0 let dir = 0 let vyear = strftime('%Y') let vmnth = matchstr(strftime('%m'), '[^0].*') elseif a:0 == 1 let dir = a:1 let vyear = strftime('%Y') let vmnth = matchstr(strftime('%m'), '[^0].*') elseif a:0 == 2 let dir = a:1 let vyear = strftime('%Y') let vmnth = matchstr(a:2, '^[^0].*') else let dir = a:1 let vyear = a:2 let vmnth = matchstr(a:3, '^[^0].*') endif " remember constant let vmnth_org = vmnth let vyear_org = vyear " start with last month let vmnth = vmnth - 1 if vmnth < 1 let vmnth = 12 let vyear = vyear - 1 endif " reset display variables let vdisplay1 = '' let vheight = 1 let vmcnt = 0 "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ "+++ build display "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if exists("g:calendar_begin") exe "call " . g:calendar_begin . "()" endif while vmcnt < 3 let vcolumn = 22 let vnweek = -1 "-------------------------------------------------------------- "--- calculating "-------------------------------------------------------------- " set boundary of the month if vmnth == 1 let vmdays = 31 let vparam = 1 let vsmnth = 'Jan' elseif vmnth == 2 let vmdays = 28 let vparam = 32 let vsmnth = 'Feb' elseif vmnth == 3 let vmdays = 31 let vparam = 60 let vsmnth = 'Mar' elseif vmnth == 4 let vmdays = 30 let vparam = 91 let vsmnth = 'Apr' elseif vmnth == 5 let vmdays = 31 let vparam = 121 let vsmnth = 'May' elseif vmnth == 6 let vmdays = 30 let vparam = 152 let vsmnth = 'Jun' elseif vmnth == 7 let vmdays = 31 let vparam = 182 let vsmnth = 'Jul' elseif vmnth == 8 let vmdays = 31 let vparam = 213 let vsmnth = 'Aug' elseif vmnth == 9 let vmdays = 30 let vparam = 244 let vsmnth = 'Sep' elseif vmnth == 10 let vmdays = 31 let vparam = 274 let vsmnth = 'Oct' elseif vmnth == 11 let vmdays = 30 let vparam = 305 let vsmnth = 'Nov' elseif vmnth == 12 let vmdays = 31 let vparam = 335 let vsmnth = 'Dec' else echo 'Invalid Year or Month' return endif if vyear % 400 == 0 if vmnth == 2 let vmdays = 29 elseif vmnth >= 3 let vparam = vparam + 1 endif elseif vyear % 100 == 0 if vmnth == 2 let vmdays = 28 endif elseif vyear % 4 == 0 if vmnth == 2 let vmdays = 29 elseif vmnth >= 3 let vparam = vparam + 1 endif endif " calc vnweek of the day if vnweek == -1 let vnweek = ( vyear * 365 ) + vparam let vnweek = vnweek + ( vyear/4 ) - ( vyear/100 ) + ( vyear/400 ) if vyear % 4 == 0 if vyear % 100 != 0 || vyear % 400 == 0 let vnweek = vnweek - 1 endif endif let vnweek = vnweek - 1 endif " fix Gregorian if vyear <= 1752 let vnweek = vnweek - 3 endif let vnweek = vnweek % 7 if exists('g:calendar_monday') " if given g:calendar_monday, the week start with monday if vnweek == 0 let vnweek = 7 endif let vnweek = vnweek - 1 endif if exists('g:calendar_weeknm') " if given g:calendar_weeknm, show week number(ref:ISO8601) "vparam <= 1. day of month "vnweek <= 1. weekday of month (0-6) "viweek <= number of week "vfweek <= 1. day of year " mo di mi do fr sa so " 6 5 4 3 2 1 0 vfweek " 0 1 2 3 4 5 6 vnweek let vfweek =((vparam % 7) -vnweek+ 14-2) % 7 let viweek = (vparam - vfweek-2+7 ) / 7 +1 if vfweek < 3 let viweek = viweek - 1 endif "vfweekl <=year length let vfweekl = 52 if (vfweek == 3) let vfweekl = 53 endif if viweek == 0 let viweek = 52 if ((vfweek == 2) && (((vyear-1) % 4) != 0)) \ || ((vfweek == 1) && (((vyear-1) % 4) == 0)) let viweek = 53 endif endif let vcolumn = vcolumn + 5 if g:calendar_weeknm == 5 let vcolumn = vcolumn - 2 endif endif "-------------------------------------------------------------- "--- displaying "-------------------------------------------------------------- " build header if exists('g:calendar_erafmt') && g:calendar_erafmt !~ "^\s*$" if g:calendar_erafmt =~ '.*,[+-]*\d\+' let veranum = substitute(g:calendar_erafmt,'.*,\([+-]*\d\+\)','\1','') if vyear+veranum > 0 let vdisplay2 = substitute(g:calendar_erafmt,'\(.*\),.*','\1','') let vdisplay2 = vdisplay2.(vyear+veranum).'/'.vmnth.'(' else let vdisplay2 = vyear.'/'.vmnth.'(' endif else let vdisplay2 = vyear.'/'.vmnth.'(' endif let vdisplay2 = strpart(" ", \ 1,(vcolumn-strlen(vdisplay2))/2-2).vdisplay2 else let vdisplay2 = vyear.'/'.vmnth.'(' let vdisplay2 = strpart(" ", \ 1,(vcolumn-strlen(vdisplay2))/2-2).vdisplay2 endif if exists('g:calendar_mruler') && g:calendar_mruler !~ "^\s*$" let vdisplay2 = vdisplay2 . get(split(g:calendar_mruler, ','), vmnth-1, '').')'."\n" else let vdisplay2 = vdisplay2 . vsmnth.')'."\n" endif let vwruler = "Su Mo Tu We Th Fr Sa" if exists('g:calendar_wruler') && g:calendar_wruler !~ "^\s*$" let vwruler = g:calendar_wruler endif if exists('g:calendar_monday') let vwruler = strpart(vwruler,stridx(vwruler, ' ') + 1).' '.strpart(vwruler,0,stridx(vwruler, ' ')) endif let vdisplay2 = vdisplay2.' '.vwruler."\n" if g:calendar_mark == 'right' let vdisplay2 = vdisplay2.' ' endif " build calendar let vinpcur = 0 while (vinpcur < vnweek) let vdisplay2 = vdisplay2.' ' let vinpcur = vinpcur + 1 endwhile let vdaycur = 1 while (vdaycur <= vmdays) if vmnth < 10 let vtarget = vyear."0".vmnth else let vtarget = vyear.vmnth endif if vdaycur < 10 let vtarget = vtarget."0".vdaycur else let vtarget = vtarget.vdaycur endif if exists("g:calendar_sign") && g:calendar_sign != "" exe "let vsign = " . g:calendar_sign . "(vdaycur, vmnth, vyear)" if vsign != "" let vsign = vsign[0] if vsign !~ "[+!#$%&@?]" let vsign = "+" endif endif else let vsign = '' endif " show mark if g:calendar_mark == 'right' if vdaycur < 10 let vdisplay2 = vdisplay2.' ' endif let vdisplay2 = vdisplay2.vdaycur elseif g:calendar_mark == 'left-fit' if vdaycur < 10 let vdisplay2 = vdisplay2.' ' endif endif if vtarget == vtoday let vdisplay2 = vdisplay2.'*' elseif vsign != '' let vdisplay2 = vdisplay2.vsign else let vdisplay2 = vdisplay2.' ' endif if g:calendar_mark == 'left' if vdaycur < 10 let vdisplay2 = vdisplay2.' ' endif let vdisplay2 = vdisplay2.vdaycur endif if g:calendar_mark == 'left-fit' let vdisplay2 = vdisplay2.vdaycur endif let vdaycur = vdaycur + 1 " fix Gregorian if vyear == 1752 && vmnth == 9 && vdaycur == 3 let vdaycur = 14 endif let vinpcur = vinpcur + 1 if vinpcur % 7 == 0 if exists('g:calendar_weeknm') if g:calendar_mark != 'right' let vdisplay2 = vdisplay2.' ' endif " if given g:calendar_weeknm, show week number if viweek < 10 if g:calendar_weeknm == 1 let vdisplay2 = vdisplay2.'WK0'.viweek elseif g:calendar_weeknm == 2 let vdisplay2 = vdisplay2.'WK '.viweek elseif g:calendar_weeknm == 3 let vdisplay2 = vdisplay2.'KW0'.viweek elseif g:calendar_weeknm == 4 let vdisplay2 = vdisplay2.'KW '.viweek elseif g:calendar_weeknm == 5 let vdisplay2 = vdisplay2.' '.viweek endif else if g:calendar_weeknm <= 2 let vdisplay2 = vdisplay2.'WK'.viweek elseif g:calendar_weeknm == 3 || g:calendar_weeknm == 4 let vdisplay2 = vdisplay2.'KW'.viweek elseif g:calendar_weeknm == 5 let vdisplay2 = vdisplay2.viweek endif endif let viweek = viweek + 1 if viweek > vfweekl let viweek = 1 endif endif let vdisplay2 = vdisplay2."\n" if g:calendar_mark == 'right' let vdisplay2 = vdisplay2.' ' endif endif endwhile " if it is needed, fill with space if vinpcur % 7 while (vinpcur % 7 != 0) let vdisplay2 = vdisplay2.' ' let vinpcur = vinpcur + 1 endwhile if exists('g:calendar_weeknm') if g:calendar_mark != 'right' let vdisplay2 = vdisplay2.' ' endif if viweek < 10 if g:calendar_weeknm == 1 let vdisplay2 = vdisplay2.'WK0'.viweek elseif g:calendar_weeknm == 2 let vdisplay2 = vdisplay2.'WK '.viweek elseif g:calendar_weeknm == 3 let vdisplay2 = vdisplay2.'KW0'.viweek elseif g:calendar_weeknm == 4 let vdisplay2 = vdisplay2.'KW '.viweek elseif g:calendar_weeknm == 5 let vdisplay2 = vdisplay2.' '.viweek endif else if g:calendar_weeknm <= 2 let vdisplay2 = vdisplay2.'WK'.viweek elseif g:calendar_weeknm == 3 || g:calendar_weeknm == 4 let vdisplay2 = vdisplay2.'KW'.viweek elseif g:calendar_weeknm == 5 let vdisplay2 = vdisplay2.viweek endif endif endif endif " build display let vstrline = '' if dir " for horizontal "-------------------------------------------------------------- " +---+ +---+ +------+ " | | | | | | " | 1 | + | 2 | = | 1' | " | | | | | | " +---+ +---+ +------+ "-------------------------------------------------------------- let vtokline = 1 while 1 let vtoken1 = get(split(vdisplay1, "\n"), vtokline-1, '') let vtoken2 = get(split(vdisplay2, "\n"), vtokline-1, '') if vtoken1 == '' && vtoken2 == '' break endif while strlen(vtoken1) < (vcolumn+1)*vmcnt if strlen(vtoken1) % (vcolumn+1) == 0 let vtoken1 = vtoken1.'|' else let vtoken1 = vtoken1.' ' endif endwhile let vstrline = vstrline.vtoken1.'|'.vtoken2.' '."\n" let vtokline = vtokline + 1 endwhile let vdisplay1 = vstrline let vheight = vtokline-1 else " for virtical "-------------------------------------------------------------- " +---+ +---+ +---+ " | 1 | + | 2 | = | | " +---+ +---+ | 1'| " | | " +---+ "-------------------------------------------------------------- let vtokline = 1 while 1 let vtoken1 = get(split(vdisplay1, "\n"), vtokline-1, '') if vtoken1 == '' break endif let vstrline = vstrline.vtoken1."\n" let vtokline = vtokline + 1 let vheight = vheight + 1 endwhile if vstrline != '' let vstrline = vstrline.' '."\n" let vheight = vheight + 1 endif let vtokline = 1 while 1 let vtoken2 = get(split(vdisplay2, "\n"), vtokline-1, '') if vtoken2 == '' break endif while strlen(vtoken2) < vcolumn let vtoken2 = vtoken2.' ' endwhile let vstrline = vstrline.vtoken2."\n" let vtokline = vtokline + 1 let vheight = vtokline + 1 endwhile let vdisplay1 = vstrline endif let vmnth = vmnth + 1 let vmcnt = vmcnt + 1 if vmnth > 12 let vmnth = 1 let vyear = vyear + 1 endif endwhile if exists("g:calendar_end") exe "call " . g:calendar_end . "()" endif if a:0 == 0 return vdisplay1 endif "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ "+++ build window "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " make window let vwinnum = bufnr('__Calendar') if getbufvar(vwinnum, 'Calendar') == 'Calendar' let vwinnum = bufwinnr(vwinnum) else let vwinnum = -1 endif if vwinnum >= 0 " if already exist if vwinnum != bufwinnr('%') exe vwinnum . 'wincmd w' endif setlocal modifiable silent %d _ else " make title if g:calendar_datetime == "title" && (!exists('s:bufautocommandsset')) auto BufEnter *Calendar let b:sav_titlestring = &titlestring | let &titlestring = '%{strftime("%c")}' auto BufLeave *Calendar let &titlestring = b:sav_titlestring let s:bufautocommandsset = 1 endif if exists('g:calendar_navi') && dir if g:calendar_navi == 'both' let vheight = vheight + 4 else let vheight = vheight + 2 endif endif " or not if dir silent execute 'bo '.vheight.'split __Calendar' setlocal winfixheight else silent execute 'to '.vcolumn.'vsplit __Calendar' setlocal winfixwidth endif call s:CalendarBuildKeymap(dir, vyear, vmnth) setlocal noswapfile setlocal buftype=nofile setlocal bufhidden=delete silent! exe "setlocal " . g:calendar_options let nontext_columns = &foldcolumn + &nu * &numberwidth if has("+relativenumber") let nontext_columns += &rnu * &numberwidth endif " Without this, the 'sidescrolloff' setting may cause the left side of the " calendar to disappear if the last inserted element is near the right " window border. setlocal nowrap setlocal norightleft setlocal modifiable setlocal nolist let b:Calendar = 'Calendar' setlocal filetype=calendar " is this a vertical (0) or a horizontal (1) split? exe vcolumn + nontext_columns . "wincmd |" endif if g:calendar_datetime == "statusline" setlocal statusline=%{strftime('%c')} endif let b:CalendarDir = dir let b:CalendarYear = vyear_org let b:CalendarMonth = vmnth_org " navi if exists('g:calendar_navi') let navi_label = '<' \.get(split(g:calendar_navi_label, ','), 0, '').' ' \.get(split(g:calendar_navi_label, ','), 1, '').' ' \.get(split(g:calendar_navi_label, ','), 2, '').'>' if dir let navcol = vcolumn + (vcolumn-strlen(navi_label)+2)/2 else let navcol = (vcolumn-strlen(navi_label)+2)/2 endif if navcol < 3 let navcol = 3 endif if g:calendar_navi == 'top' execute "normal gg".navcol."i " silent exec "normal! a".navi_label."\<cr>\<cr>" silent put! =vdisplay1 endif if g:calendar_navi == 'bottom' silent put! =vdisplay1 silent exec "normal! Gi\<cr>" execute "normal ".navcol."i " silent exec "normal! a".navi_label endif if g:calendar_navi == 'both' execute "normal gg".navcol."i " silent exec "normal! a".navi_label."\<cr>\<cr>" silent put! =vdisplay1 silent exec "normal! Gi\<cr>" execute "normal ".navcol."i " silent exec "normal! a".navi_label endif else silent put! =vdisplay1 endif setlocal nomodifiable " In case we've gotten here from insert mode (via <C-O>:Calendar<CR>)... stopinsert let vyear = vyear_org let vmnth = vmnth_org "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ "+++ build highlight "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " today syn clear if g:calendar_mark =~ 'left-fit' syn match CalToday display "\s*\*\d*" syn match CalMemo display "\s*[+!#$%&@?]\d*" elseif g:calendar_mark =~ 'right' syn match CalToday display "\d*\*\s*" syn match CalMemo display "\d*[+!#$%&@?]\s*" else syn match CalToday display "\*\s*\d*" syn match CalMemo display "[+!#$%&@?]\s*\d*" endif " header syn match CalHeader display "[^ ]*\d\+\/\d\+([^)]*)" " navi if exists('g:calendar_navi') exec "silent! syn match CalNavi display \"\\(<" \.get(split(g:calendar_navi_label, ','), 0, '')."\\|" \.get(split(g:calendar_navi_label, ','), 2, '').">\\)\"" exec "silent! syn match CalNavi display \"\\s" \.get(split(g:calendar_navi_label, ','), 1, '')."\\s\"hs=s+1,he=e-1" endif " saturday, sunday if exists('g:calendar_monday') if dir syn match CalSaturday display /|.\{15}\s\([0-9\ ]\d\)/hs=e-1 contains=ALL syn match CalSunday display /|.\{18}\s\([0-9\ ]\d\)/hs=e-1 contains=ALL else syn match CalSaturday display /^.\{15}\s\([0-9\ ]\d\)/hs=e-1 contains=ALL syn match CalSunday display /^.\{18}\s\([0-9\ ]\d\)/hs=e-1 contains=ALL endif else if dir syn match CalSaturday display /|.\{18}\s\([0-9\ ]\d\)/hs=e-1 contains=ALL syn match CalSunday display /|\s\([0-9\ ]\d\)/hs=e-1 contains=ALL else syn match CalSaturday display /^.\{18}\s\([0-9\ ]\d\)/hs=e-1 contains=ALL syn match CalSunday display /^\s\([0-9\ ]\d\)/hs=e-1 contains=ALL endif endif " week number if !exists('g:calendar_weeknm') || g:calendar_weeknm <= 2 syn match CalWeeknm display "WK[0-9\ ]\d" else syn match CalWeeknm display "KW[0-9\ ]\d" endif " ruler execute 'syn match CalRuler "'.vwruler.'"' if search("\*","w") > 0 silent execute "normal! gg/\*\<cr>" endif return '' endfunction "***************************************************************** "* make_dir : make directory "*---------------------------------------------------------------- "* dir : directory "***************************************************************** function! s:make_dir(dir) if(has("unix")) call system("mkdir " . a:dir) let rc = v:shell_error elseif(has("win16") || has("win32") || has("win95") || \has("dos16") || has("dos32") || has("os2")) call system("mkdir \"" . a:dir . "\"") let rc = v:shell_error else let rc = 1 endif if rc != 0 call confirm("can't create directory : " . a:dir, "&OK") endif return rc endfunc "***************************************************************** "* diary : calendar hook function "*---------------------------------------------------------------- "* day : day you actioned "* month : month you actioned "* year : year you actioned "***************************************************************** function! calendar#diary(day, month, year, week, dir) " build the file name and create directories as needed if !isdirectory(expand(g:calendar_diary)) call confirm("please create diary directory : ".g:calendar_diary, 'OK') return endif let sfile = expand(g:calendar_diary) . "/" . a:year if isdirectory(sfile) == 0 if s:make_dir(sfile) != 0 return endif endif let sfile = sfile . "/" . a:month if isdirectory(sfile) == 0 if s:make_dir(sfile) != 0 return endif endif " let sfile = expand(sfile) . "/" . a:day . ".md" let sfile = expand(sfile) . "/" . a:day . ".cal" "change the postfix '.md' to '.cal' let sfile = substitute(sfile, ' ', '\\ ', 'g') let vbufnr = bufnr('__Calendar') " load the file exe "wincmd w" exe "edit " . sfile let dir = getbufvar(vbufnr, "CalendarDir") let vyear = getbufvar(vbufnr, "CalendarYear") let vmnth = getbufvar(vbufnr, "CalendarMonth") exe "auto BufDelete ".escape(sfile, ' \\')." call calendar#show(" . dir . "," . vyear . "," . vmnth . ")" endfunc "***************************************************************** "* sign : calendar sign function "*---------------------------------------------------------------- "* day : day of sign "* month : month of sign "* year : year of sign "***************************************************************** function! calendar#sign(day, month, year) " let sfile = g:calendar_diary."/".a:year."/".a:month."/".a:day.".md" let sfile = g:calendar_diary."/".a:year."/".a:month."/".a:day.".cal" "change the postfix 'md' to '.cal' return filereadable(expand(sfile)) endfunction "***************************************************************** "* CalendarVar : get variable "*---------------------------------------------------------------- "***************************************************************** function! s:CalendarVar(var) if !exists(a:var) return '' endif exec 'return ' . a:var endfunction "***************************************************************** "* CalendarBuildKeymap : build keymap "*---------------------------------------------------------------- "***************************************************************** function! s:CalendarBuildKeymap(dir, vyear, vmnth) " make keymap nnoremap <silent> <buffer> <Plug>CalendarDoAction :call calendar#action()<cr> nnoremap <silent> <buffer> <Plug>CalendarDoAction :call calendar#action()<cr> nnoremap <silent> <buffer> <Plug>CalendarGotoToday :call calendar#show(b:CalendarDir)<cr> nnoremap <silent> <buffer> <Plug>CalendarShowHelp :call <SID>CalendarHelp()<cr> execute 'nnoremap <silent> <buffer> <Plug>CalendarReDisplay :call calendar#show(' . a:dir . ',' . a:vyear . ',' . a:vmnth . ')<cr>' let pnav = get(split(g:calendar_navi_label, ','), 0, '') let nnav = get(split(g:calendar_navi_label, ','), 2, '') execute 'nnoremap <silent> <buffer> <Plug>CalendarGotoPrevMonth :call calendar#action("<' . pnav . '")<cr>' execute 'nnoremap <silent> <buffer> <Plug>CalendarGotoNextMonth :call calendar#action("' . nnav . '>")<cr>' execute 'nnoremap <silent> <buffer> <Plug>CalendarGotoPrevYear :call calendar#show('.a:dir.','.(a:vyear-1).','.a:vmnth.')<cr>' execute 'nnoremap <silent> <buffer> <Plug>CalendarGotoNextYear :call calendar#show('.a:dir.','.(a:vyear+1).','.a:vmnth.')<cr>' nmap <buffer> <2-LeftMouse> <Plug>CalendarDoAction execute 'nmap <buffer> ' . s:calendar_keys['close'] . ' <C-w>c' execute 'nmap <buffer> ' . s:calendar_keys['do_action'] . ' <Plug>CalendarDoAction' execute 'nmap <buffer> ' . s:calendar_keys['goto_today'] . ' <Plug>CalendarGotoToday' execute 'nmap <buffer> ' . s:calendar_keys['show_help'] . ' <Plug>CalendarShowHelp' execute 'nmap <buffer> ' . s:calendar_keys['redisplay'] . ' <Plug>CalendarRedisplay' execute 'nmap <buffer> ' . s:calendar_keys['goto_next_month'] . ' <Plug>CalendarGotoNextMonth' execute 'nmap <buffer> ' . s:calendar_keys['goto_prev_month'] . ' <Plug>CalendarGotoPrevMonth' execute 'nmap <buffer> ' . s:calendar_keys['goto_next_year'] . ' <Plug>CalendarGotoNextYear' execute 'nmap <buffer> ' . s:calendar_keys['goto_prev_year'] . ' <Plug>CalendarGotoPrevYear' endfunction "***************************************************************** "* CalendarHelp : show help for Calendar "*---------------------------------------------------------------- "***************************************************************** function! s:CalendarHelp() let ck = s:calendar_keys let max_width = max(map(values(ck), 'len(v:val)')) let offsets = map(copy(ck), '1 + max_width - len(v:val)') echohl SpecialKey echo ck['goto_prev_month'] . repeat(' ', offsets['goto_prev_month']) . ': goto prev month' echo ck['goto_next_month'] . repeat(' ', offsets['goto_next_month']) . ': goto next month' echo ck['goto_prev_year'] . repeat(' ', offsets['goto_prev_year']) . ': goto prev year' echo ck['goto_next_year'] . repeat(' ', offsets['goto_next_year']) . ': goto next year' echo ck['goto_today'] . repeat(' ', offsets['goto_today']) . ': goto today' echo ck['close'] . repeat(' ', offsets['close']) . ': close window' echo ck['redisplay'] . repeat(' ', offsets['redisplay']) . ': re-display window' echo ck['show_help'] . repeat(' ', offsets['show_help']) . ': show this help' if g:calendar_action == "calendar#diary" echo ck['do_action'] . repeat(' ', offsets['do_action']) . ': show diary' endif echo '' echohl Question let vk = [ \ 'calendar_erafmt', \ 'calendar_mruler', \ 'calendar_wruler', \ 'calendar_weeknm', \ 'calendar_navi_label', \ 'calendar_diary', \ 'calendar_mark', \ 'calendar_navi', \] let max_width = max(map(copy(vk), 'len(v:val)')) for _ in vk let v = get(g:, _, '') echo _ . repeat(' ', max_width - len(_)) . ' = ' . v endfor echohl MoreMsg echo "[Hit any key]" echohl None call getchar() redraw! endfunction hi def link CalNavi Search hi def link CalSaturday Statement hi def link CalSunday Type hi def link CalRuler StatusLine hi def link CalWeeknm Comment hi def link CalToday Directory hi def link CalHeader Special hi def link CalMemo Identifier " calendar 日历 农历 " http://www.vim.org/scripts/script.php?script_id=3957
00000svn-vim-cfg
trunk/vimfiles/autoload/calendar.vim
Vim Script
gpl3
31,187
"=============================================================================== " " File: perlsupportregex.vim " " Description: Plugin perl-support: " Regular expression explanation and visualization. " " VIM Version: 7.0+ " Author: Dr. Fritz Mehner (mn), mehner@fh-swf.de " Company: FH Südwestfalen, Iserlohn " Version: 1.0 " Created: 16.12.2008 18:16:55 " Revision: $Id: perlsupportregex.vim,v 1.4 2012/02/26 14:07:44 mehner Exp $ " License: Copyright 2008-2010 Dr. Fritz Mehner "=============================================================================== " " Exit quickly when: " - this plugin was already loaded " - when 'compatible' is set " if exists("g:loaded_perlsupportregex") || &compatible finish endif let g:loaded_perlsupportregex = "v1.0" let s:MSWIN = has("win16") || has("win32") || has("win64") || has("win95") "------------------------------------------------------------------------------ " RUN THE REGULAR EXPRESSION VISUALIZOR "------------------------------------------------------------------------------ let s:Perl_PerlRegexVisualizeBufferName = 'REGEX-TEST' let s:Perl_PerlRegexVisualizeBufferNumber = -1 let s:Perl_PerlRegexVisualize_regexp = '' let s:Perl_PerlRegexVisualize_string = '' let s:Perl_PerlRegexVisualizeFlag = '' let s:Perl_PerlRegexCodeEvaluation = 'off' let s:Perl_PerlRegexPrematch = '' let s:Perl_PerlRegexMatch = '' " "------------------------------------------------------------------------------ " run the regular expression analyzer YAPE::Regex::Explain {{{1 "------------------------------------------------------------------------------ let s:Perl_PerlRegexBufferName = 'REGEX-EXPLAIN' let s:Perl_PerlRegexBufferNumber = -1 function! perlsupportregex#Perl_RegexExplain( mode ) if !has('perl') echomsg "*** Your version of Vim was not compiled with Perl interface. ***" return endif if g:Perl_PerlRegexAnalyser == 'no' perl <<INITIALIZE_PERL_INTERFACE # # --------------------------------------------------------------- # Perl_RegexExplain (function) # try to load the regex analyzer module; report failure # --------------------------------------------------------------- eval "require YAPE::Regex::Explain"; if ( !$@ ) { VIM::DoCommand("let g:Perl_PerlRegexAnalyser = 'yes'"); } # INITIALIZE_PERL_INTERFACE endif if g:Perl_PerlRegexAnalyser != 'yes' echomsg "*** The Perl module YAPE::Regex::Explain can not be found. ***" return endif if a:mode == 'v' call perlsupportregex#Perl_RegexPick ( "regexp", "v" ) endif if bufloaded(s:Perl_PerlRegexBufferName) != 0 && bufwinnr(s:Perl_PerlRegexBufferNumber) != -1 silent exe bufwinnr(s:Perl_PerlRegexBufferNumber) . "wincmd w" " buffer number may have changed, e.g. after a 'save as' else silent exe ":new ".s:Perl_PerlRegexBufferName let s:Perl_PerlRegexBufferNumber=bufnr("%") setlocal buftype=nofile setlocal noswapfile setlocal bufhidden=delete setlocal syntax=OFF endif " " remove content if any " setlocal modifiable silent normal ggdG perl <<EOF_RegexExplain my $explanation; my ( $success, $regexp ) = VIM::Eval('s:MSWIN'); my $flag = VIM::Eval('s:Perl_PerlRegexVisualizeFlag'); ( $success, $regexp ) = VIM::Eval('s:Perl_PerlRegexVisualize_regexp'); if ( $success == 1 ) { # get the explanation $explanation = "The regular expression\n\n".${regexp}."\n\nmatches as follows:\n\n"; #$regexp = eval 'qr{'.$regexp.'}'.$flag; $regexp = qr{$regexp}; $explanation .= YAPE::Regex::Explain->new($regexp)->explain('regex'); } else { $explanation = "\n*** VIM failed to evaluate the regular expression ***\n"; } # split explanation into lines my @explanation = split /\n/, $explanation; # put the explanation to the top of the buffer $curbuf->Append( 0, @explanation ); VIM::DoCommand( 'setlocal nomodifiable' ); EOF_RegexExplain endfunction " ---------- end of function Perl_RegexExplain ---------- " "------------------------------------------------------------------------------ " command line switch 'RegexCodeEvaluation' {{{1 "------------------------------------------------------------------------------ function! perlsupportregex#Perl_RegexCodeEvaluation ( onoff ) if a:onoff == 'on' let s:Perl_PerlRegexCodeEvaluation = 'on' else let s:Perl_PerlRegexCodeEvaluation = 'off' endif endfunction " ---------- end of function Perl_RegexCodeEvaluation ---------- "------------------------------------------------------------------------------ " pick up string or regular expression {{{1 " item : regexp | string " mode : n | v "------------------------------------------------------------------------------ function! perlsupportregex#Perl_RegexPick ( item, mode ) range " " the complete line; remove leading and trailing whitespaces " if a:mode == 'n' let line = join( getline( a:firstline, a:lastline ), "\n" ) if s:MSWIN " MSWIN : copy item to the yank-register, remove trailing CR let line = substitute( line, "\n$", '', '' ) endif let line = substitute( line, '^\s\+', '', '' ) " remove leading whitespaces let line = substitute( line, '\s\+$', '', '' ) " remove trailing whitespaces let s:Perl_PerlRegexVisualize_{a:item} = line endif " " the marked area " if a:mode == 'v' " copy item to the yank-register (Windows has no selection register) normal gvy let line = eval('@"') let line = substitute( line, "\n$", '', '' ) let s:Perl_PerlRegexVisualize_{a:item} = line endif " "------------------------------------------------------------------------------- " try to separate the regular expression and the flags in representations " like ' m{^[A-Z]{1,3}-[A-Z]{1,3}-[1-9][0-9]{0,3}$}xm ' "------------------------------------------------------------------------------- " let showtheflags = '' if a:item == 'regexp' " " optional 'm' followed by '/' or '?' let mlist = matchlist( line, '^\s*\(m\|qr\)\?\([/?]\)\(.*\)\(\2\)\([imsxg]*\)\s*$' ) if empty(mlist) " 'm' followed by any delimiter let mlist = matchlist( line, '^\s*\(m\|qr\)\(.\)\(.*\)\(\2\|[})\]>]\)\([imsxg]*\)\s*$' ) endif " if len(mlist) >= 5 && \ ( \ ( mlist[2] == mlist[4] ) \ || ( mlist[2] == "{" && mlist[4] == "}" ) \ || ( mlist[2] == "(" && mlist[4] == ")" ) \ || ( mlist[2] == "[" && mlist[4] == "]" ) \ || ( mlist[2] == "<" && mlist[4] == ">" ) \ ) let s:Perl_PerlRegexVisualize_{a:item} = mlist[3] let s:Perl_PerlRegexVisualizeFlag = mlist[5] let showtheflags = "flag(s) = '".mlist[5]."' | " endif " endif " let message = s:Perl_PerlRegexVisualize_{a:item} let message = substitute( message, '\t', '<Tab>', 'g' ) let message = substitute( message, '\n', '<CR>', 'g' ) let message = showtheflags.a:item." = '".message."'" if len(message) < &columns :redraw | echomsg message else :redraw | echomsg message[:&columns-6].' ...' endif " endfunction " ---------- end of function Perl_RegexPick ---------- " "------------------------------------------------------------------------------ " pick up flags {{{1 "------------------------------------------------------------------------------ function! perlsupportregex#Perl_RegexPickFlag ( mode ) if a:mode == 'v' " copy item to the yank-register normal gvy let s:Perl_PerlRegexVisualizeFlag = eval('@"') else let s:Perl_PerlRegexVisualizeFlag = Perl_Input("regex modifier(s) [imsxg] : ", s:Perl_PerlRegexVisualizeFlag , '') endif let s:Perl_PerlRegexVisualizeFlag=substitute(s:Perl_PerlRegexVisualizeFlag, '[^imsxg]', '', 'g') echomsg "regex modifier(s) : '".s:Perl_PerlRegexVisualizeFlag."'" endfunction " ---------- end of function Perl_RegexPickFlag ---------- " "------------------------------------------------------------------------------ " visualize regular expression {{{1 "------------------------------------------------------------------------------ function! perlsupportregex#Perl_RegexVisualize( ) if !has('perl') echomsg "*** Your version of Vim was not compiled with Perl interface. ***" return endif let l:currentbuffernr = bufnr("%") if bufloaded(s:Perl_PerlRegexVisualizeBufferName) != 0 && bufwinnr(s:Perl_PerlRegexVisualizeBufferNumber) != -1 silent exe bufwinnr(s:Perl_PerlRegexVisualizeBufferNumber) . "wincmd w" " buffer number may have changed, e.g. after a 'save as' else silent exe ":topleft new ".s:Perl_PerlRegexVisualizeBufferName let s:Perl_PerlRegexVisualizeBufferNumber=bufnr("%") setlocal buftype=nofile setlocal noswapfile setlocal bufhidden=delete setlocal syntax=OFF endif " " remove content if any: setlocal modifiable silent normal ggdG let s:Perl_PerlRegexMatch = '' perl <<EOF_regex_evaluate my @substchar= split //, VIM::Eval('g:Perl_PerlRegexSubstitution'); regex_evaluate(); #=== FUNCTION ================================================================ # NAME: regex_evaluate # PURPOSE: evaluate regex an write result into a buffer # PARAMETERS: --- # RETURNS: --- #=============================================================================== sub regex_evaluate { use re 'eval'; my ( $regexp, $string, $flag ); $flag = VIM::Eval('s:Perl_PerlRegexVisualizeFlag'); $string = VIM::Eval('s:Perl_PerlRegexVisualize_string') || ''; $regexp = VIM::Eval('s:Perl_PerlRegexVisualize_regexp'); utf8::decode($string); utf8::decode($regexp); if ( defined($regexp) && $regexp ne '' ) { my $format1 = "%-9s [%3d,%3d] =%s \n"; # see also Perl_RegexVisualize() my $format2 = "%-9s [%3d,%3d] =%s\n"; my $format3 = "REGEXP = m{%s}%s\n\n"; my $format4 = "lines : %-3d = %s\n"; my $format5 = "%-9s [%3d] =%s\n"; my $format6 = "%-9s undefined\n"; my $format7 = "%-9s =%s\n"; my $format8 = "%3d.MATCH [%3d,%3d] =%s\n"; my $linecount = 1; my $lineruler; my $result = ''; my $rgx_1 = q/^[a-ln-z]*m[a-ln-z]*[-]?/; my $stringout = prepare_stringout($string); if ( $flag =~ m{$rgx_1} ) { ($lineruler, $linecount) = lineruler($string); } my $regexp1 = join "\n ", ( split /\n/, $regexp ); $result .= sprintf $format3, $regexp1, $flag; if ( $flag =~ m{$rgx_1} ) { $result .= sprintf $format4, $linecount, $lineruler; } $result .= sprintf $format1, 'STRING', 0, length $string, marker_string( 0, $stringout ); #--------------------------------------------------------------------------- # match (single line / multiline) #--------------------------------------------------------------------------- my $gflag = 0; my $prematch; my $match; my $postmatch; my $lastSubmatchResult; my $lastParenMatch; my $lastRegexpCodeResult; my @lastMatchStart; my @lastMatchEnd; my @parenMatch; my @hit; my @hit_start; my @hit_length; $^R = undef; #------------------------------------------------------------------------------- # g-modifier present # @hit will contain the consecutive matches #------------------------------------------------------------------------------- if ( $flag =~ m{g} ) { $gflag = 1; $flag =~ s/g//; while ( $string =~ m{(?$flag:$regexp)}g ) { push @hit, $&; push @hit_start, $-[0]; push @hit_length, $+[0]-$-[0]; $prematch = $`; $match = $&; $postmatch = $'; $lastSubmatchResult = $^N; $lastParenMatch = $+; $lastRegexpCodeResult = $^R; @lastMatchStart = @-; @lastMatchEnd = @+; } } #------------------------------------------------------------------------------- # no g-modifier # @hit will contain the submatches $1, $2, ... , if any #------------------------------------------------------------------------------- else { @hit = ( $string =~ m{(?$flag:$regexp)} ); $prematch = $`; $match = $&; $postmatch = $'; $lastSubmatchResult = $^N; $lastParenMatch = $+; $lastRegexpCodeResult = $^R; @lastMatchStart = @-; @lastMatchEnd = @+; } if ( @hit ) { # # print the prematch, if not empty # if ( $prematch ne '' ) { $result .= sprintf $format2, 'prematch', 0, length $prematch, marker_string( 0, prepare_stringout($prematch) ); } # # print the match # if ( defined $match ) { $result .= sprintf $format2, 'MATCH', $lastMatchStart[0], length $match, marker_string( $lastMatchStart[0], prepare_stringout($match) ); } # # print the postmatch, if not empty # if ( $postmatch ne '' ) { $result .= sprintf $format2, 'postmatch', $lastMatchEnd[0], length $postmatch, marker_string( $lastMatchEnd[0], prepare_stringout($postmatch) ); } $result .= "\n"; # # print the numbered variables $1, $2, ... # foreach my $n ( 1 .. $#lastMatchStart ) { if ( defined $lastMatchStart[$n] ) { $result .= sprintf $format2, " \$$n", $lastMatchStart[$n], $lastMatchEnd[$n] - $lastMatchStart[$n], marker_string( $lastMatchStart[$n], prepare_stringout(substr( $string, $lastMatchStart[$n], $lastMatchEnd[$n] - $lastMatchStart[$n] )) ); } else { $result .= sprintf $format6, " \$$n"; } } $result .= "\n"; # # print $lastMatchEnd, $lastSubmatchResult, $LAST_SUBMATCH_RESULT (only if not equal $lastMatchEnd ) # if ( defined $lastParenMatch && defined $lastSubmatchResult && $lastParenMatch ne $lastSubmatchResult ) { $result .= sprintf $format5, ' $^N', length $lastSubmatchResult, marker_string( 0, prepare_stringout($lastSubmatchResult) ); } # # print last Regexp code result (if any) # if( defined $lastRegexpCodeResult ) { $result .= sprintf $format7, ' $^R', marker_string( 0, prepare_stringout($lastRegexpCodeResult) ); } # # /g modifier # if ( $gflag == 1 ) { my $hitcount = 0; foreach my $hit ( @hit ) { $result .= sprintf $format8, ($hitcount+1), $hit_start[$hitcount], $hit_length[$hitcount], marker_string( $hit_start[$hitcount], prepare_stringout($hit) ); $hitcount++; } } # # show the control character replacement (if any) # if ( $string ne $stringout ) { $result .= "\nControl character replacement: \\n -> '$substchar[0]' \\t -> '$substchar[1]'" } # # do not assign matches containing ticks for coloring # if ( $prematch !~ m{'} && $match !~ m{'} && $postmatch !~ m{'} ) { VIM::DoCommand("let s:Perl_PerlRegexPrematch = '".prepare_stringout($prematch)."' "); VIM::DoCommand("let s:Perl_PerlRegexMatch = '".prepare_stringout($match)."' "); } else { VIM::DoCommand("let s:Perl_PerlRegexPrematch = '' "); VIM::DoCommand("let s:Perl_PerlRegexMatch = '' "); } } else { $result .= "\n ***** NO MATCH *****" } $curbuf->Append( 0, split(/\n/,$result) ); # put the result to the top of the buffer } else { VIM::DoCommand("echomsg 'regexp is not defined or has zero length'"); } return ; } # ---------- end of subroutine regex_evaluate ---------- #=== FUNCTION ================================================================ # NAME: prepare_stringout # PURPOSE: Sustitute tabs and newlines with printable characters. # PARAMETERS: string # RETURNS: string with replacements #=============================================================================== sub prepare_stringout { my ( $par1 ) = @_; $par1 =~ s/\n/$substchar[0]/g; $par1 =~ s/\t/$substchar[1]/g; return $par1; } # ---------- end of subroutine prepare_stringout ---------- #=== FUNCTION ================================================================ # NAME: marker_string # PURPOSE: Prepend blanks; # surround string with bars if starting/ending with whitespaces # PARAMETERS: 1. first column of the marker bar (>=0) # 2. string # RETURNS: The augmented string. #=============================================================================== sub marker_string { my ( $start, $str ) = @_; my $result = ' ' x ($start); if ( $str =~ m{^\s} || $str =~ m{\s$} ) { $result .= "|".$str."|" } else { $result .= ' '.$str; } return $result; } # ---------- end of subroutine marker_string ---------- #=== FUNCTION ================================================================ # NAME: lineruler # PURPOSE: Generate a line ruler like "|1... |2... |3......." # PARAMETERS: 1. a (multiline) string # RETURNS: ( ruler, number of lines ) #=============================================================================== sub lineruler { my ( $string ) = @_; my $result = ''; # result string (the ruler) my @lines = split /\n/, $string; # lines as an array my $lineno = 0; # current line number my $linecount = 0; # number of lines while ( $string =~/\n/g ) { $linecount++; } if ( $string !~ /\n$/ ) { # last non-empty line $linecount++; } foreach my $line ( @lines ) { $lineno++; if ( $lineno > 1 ) { $result .= ' '; } if ( length($line) == 1 ) { $result .= '|'; } if ( length($line) > 1 ) { $result .= '|'.$lineno; $result .= '.' x ((length $line)-(length $lineno)-1); } } return ($result, $linecount); } # ---------- end of subroutine lineruler ---------- VIM::DoCommand( 'setlocal nomodifiable' ); EOF_regex_evaluate " if line('$') == 1 :close return endif normal gg "------------------------------------------------------------------------------- " Highlight the match by matching MATCH.POSTMATCH.EOL . " Find a character not contained in the string to mark start and end of the " Vim regex pattern (range 33 ... 126 or '!' ... '~'). "------------------------------------------------------------------------------- exe ":match none" if s:Perl_PerlRegexMatch != '' let nr = char2nr('!') let tilde = char2nr('~') let tick1 = char2nr("'") let tick2 = char2nr('"') let tick3 = char2nr('|') while nr <= tilde if nr != tick1 && nr != tick2 && nr != tick3 && \ match( s:Perl_PerlRegexMatch, nr2char(nr) ) < 0 break endif let nr = nr+1 endwhile if nr <= tilde :highlight color_match ctermbg=green guibg=green let delim = nr2char(nr) " escape Vim regexp metacharacters let match0 = escape( s:Perl_PerlRegexPrematch , '][*$~\' ) let match1 = escape( s:Perl_PerlRegexMatch , '][*$~\' ) " " the first part of the following regular expression describes the " beginnning of $format1 in sub regex_evaluate " try exe ':match color_match '.delim.'\(^STRING\s\+\[\s*\d\+,\s*\d\+\] =[ |]'.match0.'\)\@<='.match1.delim catch // echo "Internal error (" . v:exception . ")" echo " - occurred at " . v:throwpoint finally endtry endif endif if winheight(winnr()) >= line("$") exe bufwinnr(l:currentbuffernr) . "wincmd w" endif endfunction " ---------- end of function Perl_RegexVisualize ---------- " "------------------------------------------------------------------------------ " visualize regular expression {{{1 "------------------------------------------------------------------------------ function! perlsupportregex#Perl_RegexMatchSeveral( ) if !has('perl') echomsg "*** Your version of Vim was not compiled with Perl interface. ***" return endif let l:currentbuffernr = bufnr("%") if bufloaded(s:Perl_PerlRegexVisualizeBufferName) != 0 && bufwinnr(s:Perl_PerlRegexVisualizeBufferNumber) != -1 silent exe bufwinnr(s:Perl_PerlRegexVisualizeBufferNumber) . "wincmd w" " buffer number may have changed, e.g. after a 'save as' else silent exe ":topleft new ".s:Perl_PerlRegexVisualizeBufferName let s:Perl_PerlRegexVisualizeBufferNumber=bufnr("%") setlocal buftype=nofile setlocal noswapfile setlocal bufhidden=delete setlocal syntax=OFF endif " " remove content if any: setlocal modifiable silent normal ggdG perl <<EOF_evaluate_multiple regex_evaluate_multiple(); #=== FUNCTION ================================================================ # NAME: regex_evaluate_multiple # PURPOSE: evaluate regex with multiple targets, write result into a buffer # PARAMETERS: --- # RETURNS: --- #=============================================================================== sub regex_evaluate_multiple { use re 'eval'; my ( $regexp, $string, $flag ); my $regexp1; my @string; my @regexp; my $result = ''; my $format3 = "\n%2d. REGEXP = m{%s}%s\n\n"; my $rgxcounter = 0; my $linecount = 0; my $matchstr; my $matchcount; $flag = VIM::Eval('s:Perl_PerlRegexVisualizeFlag'); $string = VIM::Eval('s:Perl_PerlRegexVisualize_string') || ''; $regexp = VIM::Eval('s:Perl_PerlRegexVisualize_regexp'); utf8::decode($string); utf8::decode($regexp); if ( defined($regexp) && $regexp ne '' ) { @regexp = $flag =~ m/x/ ? ( $regexp ) : ( split '\n', $regexp ); @string = $flag =~ m/m/ ? ( $string ) : ( split '\n', $string ); foreach my $rgx ( @regexp ) { $regexp1 = join "\n ", ( split /\n/, $rgx ); $result .= sprintf $format3, ++$rgxcounter, $regexp1, $flag; $linecount = 0; $matchcount = 0; foreach my $str ( @string ) { $matchstr = $str =~ m{(?$flag:$rgx)} ? ( $matchcount++, '<MATCH>' ) : ' '; $result .= sprintf "%4d %s %s\n", ++$linecount, $matchstr, splitstr($str, $flag); } $result .= sprintf "\n ----- matches: %d/%d -----\n", $matchcount, $linecount; } $curbuf->Append( 0, split(/\n/,$result) ); # put the result to the top of the buffer } else { VIM::DoCommand("echomsg 'regexp is not defined or has zero length'"); } return ; } # ---------- end of subroutine regex_evaluate_multiple ---------- #=== FUNCTION ================================================================ # NAME: splitstr # PURPOSE: arrange single-line and multi-line targets for printing #=============================================================================== sub splitstr { my ( $s, $f ) = @_; # string, flag my $result = $s; # single-line target if ( $f =~ m/m/ ) { # flag 'm' ? $result = join "'\n '", split /\n/, $s; } return "'$result'"; } # ---------- end of subroutine splitstr ---------- VIM::DoCommand( 'setlocal nomodifiable' ); EOF_evaluate_multiple " if line('$') == 1 :close return endif normal gg if winheight(winnr()) >= line("$") exe bufwinnr(l:currentbuffernr) . "wincmd w" endif endfunction " ---------- end of function Perl_RegexMatchSeveral ---------- " "------------------------------------------------------------------------------- " read the substitution characters for \n, \t, ... from the command line " used in ftplugin/perl.vim "------------------------------------------------------------------------------- function! perlsupportregex#Perl_PerlRegexSubstitutions ( string ) let result = a:string let result = substitute( result, '^\s\+', '', '' ) " remove leading whitespaces let result = substitute( result, '\s\+$', '', '' ) " remove trailing whitespaces let result = substitute( result, "^'", '', '' ) let result = substitute( result, "'$", '', '' ) " " replacement string: length 2, printable characters, no control characters " if strlen( result ) == 2 && \ match( result, '^[[:print:]]\+$' ) == 0 && \ match( result, '[[:cntrl:]]' ) == -1 let g:Perl_PerlRegexSubstitution = result endif endfunction " ---------- end of function Perl_PerlRegexSubstitutions ---------- " " vim: tabstop=2 shiftwidth=2 foldmethod=marker
00000svn-vim-cfg
trunk/vimfiles/autoload/perlsupportregex.vim
Vim Script
gpl3
26,340
" Script Name: mark.vim " Description: Highlight several words in different colors simultaneously. " " Copyright: (C) 2005-2008 Yuheng Xie " (C) 2008-2013 Ingo Karkat " The VIM LICENSE applies to this script; see ':help copyright'. " " Maintainer: Ingo Karkat <ingo@karkat.de> " " Dependencies: " - SearchSpecial.vim autoload script (optional, for improved search messages). " " Version: 2.8.0 " Changes: " 29-May-2013, Ingo Karkat " - Factor out s:HasVariablePersistence() and include the note in :MarkLoad, " too. " - Use s:ErrorMsg() everywhere, and allow to suppress the output via optional " flag. " - Define s:WarningMsg(), too; we now issue them in two locations. " - ENH: mark#LoadCommand() and mark#SaveCommand() now take an optional marks " variable name to store multiple named marks (and persist them if the name is " all uppercase). Allow completion via mark#MarksVariablesComplete(). " " 31-Jan-2013, Ingo Karkat " - mark#MarkRegex() takes an additional a:groupNum argument to also allow a " [count] for <Leader>r. " - Add mark#DoMarkAndSetCurrent() variant of mark#DoMark() that also sets the " current mark to the used mark group when a mark was set. Use that for " <Leader>r and :Mark so that it is easier to determine whether the entered " pattern actually matches anywhere. Thanks to Xiaopan Zhang for notifying me " about this problem. mark#DoMark() now returns a List of [success, " markGroupNum] to enable the wrapper. " - Let the various search functions return whether the search succeeded. Though " I don't use this (the mark search shouldn't beep like built-in n / N), it " may come handy one day. " - Add mark#SearchGroupMark() to be able to search for a particular mark group " (or the current if none specified), with a specified count. " " 15-Oct-2012, Ingo Karkat " - Issue an error message "No marks defined" instead of moving the cursor by " one character when there are no marks (e.g. initially or after :MarkClear). " - Enable custom integrations via new mark#GetNum() and mark#GetPattern() " functions. " " 13-Sep-2012, Ingo Karkat " - Enable alternative * / # mappings that do not remember the last search type " by adding optional search function argument to mark#SearchNext(). " " 04-Jul-2012, Ingo Karkat " - ENH: Handle on-the-fly change of mark highlighting via mark#ReInit(), which " truncates / expands s:pattern and corrects the indices. Also, w:mwMatch List " size mismatches must be handled in s:MarkMatch(). " " 23-Apr-2012, Ingo Karkat + fanhe " - Force case via \c / \C instead of temporarily unsetting 'smartcase'. " - Allow to override 'ignorecase' setting via g:mwIgnoreCase. Thanks to fanhe " for the idea and sending a patch. " " 26-Mar-2012, Ingo Karkat " - ENH: When a [count] exceeding the number of available mark groups is given, " a summary of marks is given and the user is asked to select a mark group. " This allows to interactively choose a color via 99<Leader>m. " - ENH: Include count of alternative patterns in :Marks list. " - CHG: Use ">" for next mark and "/" for last search in :Marks. " " 23-Mar-2012, Ingo Karkat " - ENH: Add :Marks command that prints all mark highlight groups and their " search patterns, plus information about the current search mark, next mark " group, and whether marks are disabled. " - ENH: Show which mark group a pattern was set / added / removed / cleared. " - Refactoring: Store index into s:pattern instead of pattern itself in " s:lastSearch. For that, mark#CurrentMark() now additionally returns the " index. " - CHG: Show mark group number in same-mark search and rename search types from " "any-mark", "same-mark", and "new-mark" to the shorter "mark-*", "mark-N", " and "mark-N!", respectively. " " 22-Mar-2012, Ingo Karkat " - ENH: Allow [count] for <Leader>m and :Mark to add / subtract match to / from " highlight group [count], and use [count]<Leader>n to clear only highlight " group [count]. This was also requested by Philipp Marek. " - FIX: :Mark and <Leader>n actually toggled marks back on when they were " already off. Now, they stay off on multiple invocations. Use :call " mark#Toggle() / <Plug>MarkToggle if you want toggling. " " 09-Nov-2011, Ingo Karkat " - BUG: With a single match and 'wrapscan' set, a search error was issued " instead of the wrap message. Add check for l:isStuckAtCurrentMark && " l:isWrapped in the no-match part of s:Search(). " - FIX: In backwards search with single match, the :break short-circuits the " l:isWrapped logic, resets l:line and therefore also confuses the logic and " leads to wrong error message instead of wrap message. Don't reset l:line, " set l:isWrapped instead. " - FIX: Wrong logic for determining l:isWrapped lets wrap-around go undetected " when v:count >= number of total matches. [l:startLine, l:startCol] must " be updated on every iteration, and should therefore be named [l:prevLine, " l:prevCol]. " " 17-May-2011, Ingo Karkat " - Make s:GetVisualSelection() public to allow use in suggested " <Plug>MarkSpaceIndifferent vmap. " - FIX: == comparison in s:DoMark() leads to wrong regexp (\A vs. \a) being " cleared when 'ignorecase' is set. Use case-sensitive comparison ==# instead. " " 10-May-2011, Ingo Karkat " - Refine :MarkLoad messages: Differentiate between nonexistent and empty " g:MARK_MARKS; add note when marks are disabled. " " 06-May-2011, Ingo Karkat " - Also print status message on :MarkClear to be consistent with :MarkToggle. " " 21-Apr-2011, Ingo Karkat " - Implement toggling of mark display (keeping the mark patterns, unlike the " clearing of marks), determined by s:enable. s:DoMark() now toggles on empty " regexp, affecting the \n mapping and :Mark. Introduced " s:EnableAndMarkScope() wrapper to correctly handle the highlighting updates " depending on whether marks were previously disabled. " - Implement persistence of s:enable via g:MARK_ENABLED. " - Generalize s:Enable() and combine with intermediate s:Disable() into " s:MarkEnable(), which also performs the persistence of s:enabled. " - Implement lazy-loading of disabled persistent marks via g:mwDoDeferredLoad " flag passed from plugin/mark.vim. " " 20-Apr-2011, Ingo Karkat " - Extract setting of s:pattern into s:SetPattern() and implement the automatic " persistence there. " " 19-Apr-2011, Ingo Karkat " - ENH: Add enabling functions for mark persistence: mark#Load() and " mark#ToPatternList(). " - Implement :MarkLoad and :MarkSave commands in mark#LoadCommand() and " mark#SaveCommand(). " - Remove superfluous update autocmd on VimEnter: Persistent marks trigger the " update themselves, same for :Mark commands which could potentially be issued " e.g. in .vimrc. Otherwise, when no marks are defined after startup, the " autosource script isn't even loaded yet, so the autocmd on the VimEnter " event isn't yet defined. " " 18-Apr-2011, Ingo Karkat " - BUG: Include trailing newline character in check for current mark, so that a " mark that matches the entire line (e.g. created by V<Leader>m) can be " cleared via <Leader>n. Thanks to ping for reporting this. " - Minor restructuring of mark#MarkCurrentWord(). " - FIX: On overlapping marks, mark#CurrentMark() returned the lowest, not the " highest visible mark. So on overlapping marks, the one that was not visible " at the cursor position was removed; very confusing! Use reverse iteration " order. " - FIX: To avoid an arbitrary ordering of highlightings when the highlighting " group names roll over, and to avoid order inconsistencies across different " windows and tabs, we assign a different priority based on the highlighting " group. " - Rename s:cycleMax to s:markNum; the previous name was too " implementation-focused and off-by-one with regards to the actual value. " " 16-Apr-2011, Ingo Karkat " - Move configuration variable g:mwHistAdd to plugin/mark.vim (as is customary) " and make the remaining g:mw... variables script-local, as these contain " internal housekeeping information that does not need to be accessible by the " user. " - Add :MarkSave warning if 'viminfo' doesn't enable global variable " persistence. " " 15-Apr-2011, Ingo Karkat " - Robustness: Move initialization of w:mwMatch from mark#UpdateMark() to " s:MarkMatch(), where the variable is actually used. I had encountered cases " where it w:mwMatch was undefined when invoked through mark#DoMark() -> " s:MarkScope() -> s:MarkMatch(). This can be forced by :unlet w:mwMatch " followed by :Mark foo. " - Robustness: Checking for s:markNum == 0 in mark#DoMark(), trying to " re-detect the mark highlightings and finally printing an error instead of " choking. This can happen when somehow no mark highlightings are defined. " " 14-Jan-2011, Ingo Karkat " - FIX: Capturing the visual selection could still clobber the blockwise yank " mode of the unnamed register. " " 13-Jan-2011, Ingo Karkat " - FIX: Using a named register for capturing the visual selection on " {Visual}<Leader>m and {Visual}<Leader>r clobbered the unnamed register. Now " using the unnamed register. " " 13-Jul-2010, Ingo Karkat " - ENH: The MarkSearch mappings (<Leader>[*#/?]) add the original cursor " position to the jump list, like the built-in [/?*#nN] commands. This allows " to use the regular jump commands for mark matches, like with regular search " matches. " " 19-Feb-2010, Andy Wokula " - BUG: Clearing of an accidental zero-width match (e.g. via :Mark \zs) results " in endless loop. Thanks to Andy Wokula for the patch. " " 17-Nov-2009, Ingo Karkat + Andy Wokula " - BUG: Creation of literal pattern via '\V' in {Visual}<Leader>m mapping " collided with individual escaping done in <Leader>m mapping so that an " escaped '\*' would be interpreted as a multi item when both modes are used " for marking. Replaced \V with s:EscapeText() to be consistent. Replaced the " (overly) generic mark#GetVisualSelectionEscaped() with " mark#GetVisualSelectionAsRegexp() and " mark#GetVisualSelectionAsLiteralPattern(). Thanks to Andy Wokula for the " patch. " " 06-Jul-2009, Ingo Karkat " - Re-wrote s:AnyMark() in functional programming style. " - Now resetting 'smartcase' before the search, this setting should not be " considered for *-command-alike searches and cannot be supported because all " mark patterns are concatenated into one large regexp, anyway. " " 04-Jul-2009, Ingo Karkat " - Re-wrote s:Search() to handle v:count: " - Obsoleted s:current_mark_position; mark#CurrentMark() now returns both the " mark text and start position. " - s:Search() now checks for a jump to the current mark during a backward " search; this eliminates a lot of logic at its calling sites. " - Reverted negative logic at calling sites; using empty() instead of != "". " - Now passing a:isBackward instead of optional flags into s:Search() and " around its callers. " - ':normal! zv' moved from callers into s:Search(). " - Removed delegation to SearchSpecial#ErrorMessage(), because the fallback " implementation is perfectly fine and the SearchSpecial routine changed its " output format into something unsuitable anyway. " - Using descriptive text instead of "@" (and appropriate highlighting) when " querying for the pattern to mark. " " 02-Jul-2009, Ingo Karkat " - Split off functions into autoload script. "- functions ------------------------------------------------------------------ silent! call SearchSpecial#DoesNotExist() " Execute a function to force autoload. if exists('*SearchSpecial#WrapMessage') function! s:WrapMessage( searchType, searchPattern, isBackward ) redraw call SearchSpecial#WrapMessage(a:searchType, a:searchPattern, a:isBackward) endfunction function! s:EchoSearchPattern( searchType, searchPattern, isBackward ) call SearchSpecial#EchoSearchPattern(a:searchType, a:searchPattern, a:isBackward) endfunction else function! s:Trim( message ) " Limit length to avoid "Hit ENTER" prompt. return strpart(a:message, 0, (&columns / 2)) . (len(a:message) > (&columns / 2) ? "..." : "") endfunction function! s:WrapMessage( searchType, searchPattern, isBackward ) redraw let v:warningmsg = printf('%s search hit %s, continuing at %s', a:searchType, (a:isBackward ? 'TOP' : 'BOTTOM'), (a:isBackward ? 'BOTTOM' : 'TOP')) echohl WarningMsg echo s:Trim(v:warningmsg) echohl None endfunction function! s:EchoSearchPattern( searchType, searchPattern, isBackward ) let l:message = (a:isBackward ? '?' : '/') . a:searchPattern echohl SearchSpecialSearchType echo a:searchType echohl None echon s:Trim(l:message) endfunction endif function! s:EscapeText( text ) return substitute( escape(a:text, '\' . '^$.*[~'), "\n", '\\n', 'ge' ) endfunction function! s:IsIgnoreCase( expr ) return ((exists('g:mwIgnoreCase') ? g:mwIgnoreCase : &ignorecase) && a:expr !~# '\\\@<!\\C') endfunction " Mark the current word, like the built-in star command. " If the cursor is on an existing mark, remove it. function! mark#MarkCurrentWord( groupNum ) let l:regexp = (a:groupNum == 0 ? mark#CurrentMark()[0] : '') if empty(l:regexp) let l:cword = expand('<cword>') if ! empty(l:cword) let l:regexp = s:EscapeText(l:cword) " The star command only creates a \<whole word\> search pattern if the " <cword> actually only consists of keyword characters. if l:cword =~# '^\k\+$' let l:regexp = '\<' . l:regexp . '\>' endif endif endif return (empty(l:regexp) ? 0 : mark#DoMark(a:groupNum, l:regexp)[0]) endfunction function! mark#GetVisualSelection() let save_clipboard = &clipboard set clipboard= " Avoid clobbering the selection and clipboard registers. let save_reg = getreg('"') let save_regmode = getregtype('"') silent normal! gvy let res = getreg('"') call setreg('"', save_reg, save_regmode) let &clipboard = save_clipboard return res endfunction function! mark#GetVisualSelectionAsLiteralPattern() return s:EscapeText(mark#GetVisualSelection()) endfunction function! mark#GetVisualSelectionAsRegexp() return substitute(mark#GetVisualSelection(), '\n', '', 'g') endfunction " Manually input a regular expression. function! mark#MarkRegex( groupNum, regexpPreset ) call inputsave() echohl Question let l:regexp = input('Input pattern to mark: ', a:regexpPreset) echohl None call inputrestore() if empty(l:regexp) return 0 endif redraw " This is necessary when the user is queried for the mark group. return mark#DoMarkAndSetCurrent(a:groupNum, l:regexp)[0] endfunction function! s:Cycle( ... ) let l:currentCycle = s:cycle let l:newCycle = (a:0 ? a:1 : s:cycle) + 1 let s:cycle = (l:newCycle < s:markNum ? l:newCycle : 0) return l:currentCycle endfunction function! s:FreeGroupIndex() let i = 0 while i < s:markNum if empty(s:pattern[i]) return i endif let i += 1 endwhile return -1 endfunction " Set match / clear matches in the current window. function! s:MarkMatch( indices, expr ) if ! exists('w:mwMatch') let w:mwMatch = repeat([0], s:markNum) elseif len(w:mwMatch) != s:markNum " The number of marks has changed. if len(w:mwMatch) > s:markNum " Truncate the matches. for l:match in filter(w:mwMatch[s:markNum : ], 'v:val > 0') silent! call matchdelete(l:match) endfor let w:mwMatch = w:mwMatch[0 : (s:markNum - 1)] else " Expand the matches. let w:mwMatch += repeat([0], (s:markNum - len(w:mwMatch))) endif endif for l:index in a:indices if w:mwMatch[l:index] > 0 silent! call matchdelete(w:mwMatch[l:index]) let w:mwMatch[l:index] = 0 endif endfor if ! empty(a:expr) let l:index = a:indices[0] " Can only set one index for now. " Info: matchadd() does not consider the 'magic' (it's always on), " 'ignorecase' and 'smartcase' settings. " Make the match according to the 'ignorecase' setting, like the star command. " (But honor an explicit case-sensitive regexp via the /\C/ atom.) let l:expr = (s:IsIgnoreCase(a:expr) ? '\c' : '') . a:expr " To avoid an arbitrary ordering of highlightings, we assign a different " priority based on the highlight group, and ensure that the highest " priority is -10, so that we do not override the 'hlsearch' of 0, and still " allow other custom highlightings to sneak in between. let l:priority = -10 - s:markNum + 1 + l:index let w:mwMatch[l:index] = matchadd('MarkWord' . (l:index + 1), l:expr, l:priority) endif endfunction " Initialize mark colors in a (new) window. function! mark#UpdateMark() let i = 0 while i < s:markNum if ! s:enabled || empty(s:pattern[i]) call s:MarkMatch([i], '') else call s:MarkMatch([i], s:pattern[i]) endif let i += 1 endwhile endfunction " Set / clear matches in all windows. function! s:MarkScope( indices, expr ) let l:currentWinNr = winnr() " By entering a window, its height is potentially increased from 0 to 1 (the " minimum for the current window). To avoid any modification, save the window " sizes and restore them after visiting all windows. let l:originalWindowLayout = winrestcmd() noautocmd windo call s:MarkMatch(a:indices, a:expr) execute l:currentWinNr . 'wincmd w' silent! execute l:originalWindowLayout endfunction " Update matches in all windows. function! mark#UpdateScope() let l:currentWinNr = winnr() " By entering a window, its height is potentially increased from 0 to 1 (the " minimum for the current window). To avoid any modification, save the window " sizes and restore them after visiting all windows. let l:originalWindowLayout = winrestcmd() noautocmd windo call mark#UpdateMark() execute l:currentWinNr . 'wincmd w' silent! execute l:originalWindowLayout endfunction function! s:MarkEnable( enable, ...) if s:enabled != a:enable " En-/disable marks and perform a full refresh in all windows, unless " explicitly suppressed by passing in 0. let s:enabled = a:enable if g:mwAutoSaveMarks let g:MARK_ENABLED = s:enabled endif if ! a:0 || ! a:1 call mark#UpdateScope() endif endif endfunction function! s:EnableAndMarkScope( indices, expr ) if s:enabled " Marks are already enabled, we just need to push the changes to all " windows. call s:MarkScope(a:indices, a:expr) else call s:MarkEnable(1) endif endfunction " Toggle visibility of marks, like :nohlsearch does for the regular search " highlighting. function! mark#Toggle() if s:enabled call s:MarkEnable(0) echo 'Disabled marks' else call s:MarkEnable(1) let l:markCnt = len(filter(copy(s:pattern), '! empty(v:val)')) echo 'Enabled' (l:markCnt > 0 ? l:markCnt . ' ' : '') . 'marks' endif endfunction " Mark or unmark a regular expression. function! s:SetPattern( index, pattern ) let s:pattern[a:index] = a:pattern if g:mwAutoSaveMarks call s:SavePattern() endif endfunction function! mark#ClearAll() let i = 0 let indices = [] while i < s:markNum if ! empty(s:pattern[i]) call s:SetPattern(i, '') call add(indices, i) endif let i += 1 endwhile let s:lastSearch = -1 " Re-enable marks; not strictly necessary, since all marks have just been " cleared, and marks will be re-enabled, anyway, when the first mark is added. " It's just more consistent for mark persistence. But save the full refresh, as " we do the update ourselves. call s:MarkEnable(0, 0) call s:MarkScope(l:indices, '') if len(indices) > 0 echo 'Cleared all' len(indices) 'marks' else echo 'All marks cleared' endif endfunction function! s:SetMark( index, regexp, ... ) if a:0 if s:lastSearch == a:index let s:lastSearch = a:1 endif endif call s:SetPattern(a:index, a:regexp) call s:EnableAndMarkScope([a:index], a:regexp) endfunction function! s:ClearMark( index ) " A last search there is reset. call s:SetMark(a:index, '', -1) endfunction function! s:EchoMark( groupNum, regexp ) call s:EchoSearchPattern('mark-' . a:groupNum, a:regexp, 0) endfunction function! s:EchoMarkCleared( groupNum ) echohl SearchSpecialSearchType echo 'mark-' . a:groupNum echohl None echon ' cleared' endfunction function! s:EchoMarksDisabled() echo 'All marks disabled' endfunction " Return [success, markGroupNum]. success is true when the mark has been set or " cleared. markGroupNum is the mark group number where the mark was set. It is 0 " if the group was cleared. function! mark#DoMark( groupNum, ...) if s:markNum <= 0 " Uh, somehow no mark highlightings were defined. Try to detect them again. call mark#Init() if s:markNum <= 0 " Still no mark highlightings; complain. call s:ErrorMsg('No mark highlightings defined') return [0, 0] endif endif let l:groupNum = a:groupNum if l:groupNum > s:markNum " This highlight group does not exist. let l:groupNum = mark#QueryMarkGroupNum() if l:groupNum < 1 || l:groupNum > s:markNum return [0, 0] endif endif let regexp = (a:0 ? a:1 : '') if empty(regexp) if l:groupNum == 0 " Disable all marks. call s:MarkEnable(0) call s:EchoMarksDisabled() else " Clear the mark represented by the passed highlight group number. call s:ClearMark(l:groupNum - 1) call s:EchoMarkCleared(l:groupNum) endif return [1, 0] endif if l:groupNum == 0 " Clear the mark if it has been marked. let i = 0 while i < s:markNum if regexp ==# s:pattern[i] call s:ClearMark(i) call s:EchoMarkCleared(i + 1) return [1, 0] endif let i += 1 endwhile else " Add / subtract the pattern as an alternative to the mark represented " by the passed highlight group number. let existingPattern = s:pattern[l:groupNum - 1] if ! empty(existingPattern) " Split only on \|, but not on \\|. let alternatives = split(existingPattern, '\%(\%(^\|[^\\]\)\%(\\\\\)*\\\)\@<!\\|') if index(alternatives, regexp) == -1 let regexp = existingPattern . '\|' . regexp else let regexp = join(filter(alternatives, 'v:val !=# regexp'), '\|') if empty(regexp) call s:ClearMark(l:groupNum - 1) call s:EchoMarkCleared(l:groupNum) return [1, 0] endif endif endif endif " add to history if stridx(g:mwHistAdd, '/') >= 0 call histadd('/', regexp) endif if stridx(g:mwHistAdd, '@') >= 0 call histadd('@', regexp) endif if l:groupNum == 0 let i = s:FreeGroupIndex() if i != -1 " Choose an unused highlight group. The last search is kept untouched. call s:Cycle(i) call s:SetMark(i, regexp) else " Choose a highlight group by cycle. A last search there is reset. let i = s:Cycle() call s:SetMark(i, regexp, -1) endif else let i = l:groupNum - 1 " Use and extend the passed highlight group. A last search is updated " and thereby kept active. call s:SetMark(i, regexp, i) endif call s:EchoMark(i + 1, regexp) return [1, i + 1] endfunction function! mark#DoMarkAndSetCurrent( groupNum, ... ) let l:result = call('mark#DoMark', [a:groupNum] + a:000) let l:markGroupNum = l:result[1] if l:markGroupNum > 0 let s:lastSearch = l:markGroupNum - 1 endif return l:result endfunction " Return [mark text, mark start position, mark index] of the mark under the " cursor (or ['', [], -1] if there is no mark). " The mark can include the trailing newline character that concludes the line, " but marks that span multiple lines are not supported. function! mark#CurrentMark() let line = getline('.') . "\n" " Highlighting groups with higher numbers take precedence over lower numbers, " and therefore its marks appear "above" other marks. To retrieve the visible " mark in case of overlapping marks, we need to check from highest to lowest " highlight group. let i = s:markNum - 1 while i >= 0 if ! empty(s:pattern[i]) let matchPattern = (s:IsIgnoreCase(s:pattern[i]) ? '\c' : '\C') . s:pattern[i] " Note: col() is 1-based, all other indexes zero-based! let start = 0 while start >= 0 && start < strlen(line) && start < col('.') let b = match(line, matchPattern, start) let e = matchend(line, matchPattern, start) if b < col('.') && col('.') <= e return [s:pattern[i], [line('.'), (b + 1)], i] endif if b == e break endif let start = e endwhile endif let i -= 1 endwhile return ['', [], -1] endfunction " Search current mark. function! mark#SearchCurrentMark( isBackward ) let l:result = 0 let [l:markText, l:markPosition, l:markIndex] = mark#CurrentMark() if empty(l:markText) if s:lastSearch == -1 let l:result = mark#SearchAnyMark(a:isBackward) let s:lastSearch = mark#CurrentMark()[2] else let l:result = s:Search(s:pattern[s:lastSearch], v:count1, a:isBackward, [], 'mark-' . (s:lastSearch + 1)) endif else let l:result = s:Search(l:markText, v:count1, a:isBackward, l:markPosition, 'mark-' . (l:markIndex + 1) . (l:markIndex ==# s:lastSearch ? '' : '!')) let s:lastSearch = l:markIndex endif return l:result endfunction function! mark#SearchGroupMark( groupNum, count, isBackward, isSetLastSearch ) if a:groupNum == 0 " No mark group number specified; use last search, and fall back to " current mark if possible. if s:lastSearch == -1 let [l:markText, l:markPosition, l:markIndex] = mark#CurrentMark() if empty(l:markText) return 0 endif else let l:markIndex = s:lastSearch let l:markText = s:pattern[l:markIndex] let l:markPosition = [] endif else let l:groupNum = a:groupNum if l:groupNum > s:markNum " This highlight group does not exist. let l:groupNum = mark#QueryMarkGroupNum() if l:groupNum < 1 || l:groupNum > s:markNum return 0 endif endif let l:markIndex = l:groupNum - 1 let l:markText = s:pattern[l:markIndex] let l:markPosition = [] endif let l:result = s:Search(l:markText, a:count, a:isBackward, l:markPosition, 'mark-' . (l:markIndex + 1) . (l:markIndex ==# s:lastSearch ? '' : '!')) if a:isSetLastSearch let s:lastSearch = l:markIndex endif return l:result endfunction function! s:ErrorMsg( text, ... ) let v:errmsg = a:text if a:0 && ! a:1 | return | endif echohl ErrorMsg echomsg v:errmsg echohl None endfunction function! s:WarningMsg( text ) let v:warningmsg = a:text echohl WarningMsg echomsg v:warningmsg echohl None endfunction function! s:NoMarkErrorMessage() call s:ErrorMsg('No marks defined') endfunction function! s:ErrorMessage( searchType, searchPattern, isBackward ) if &wrapscan let l:errmsg = a:searchType . ' not found: ' . a:searchPattern else let l:errmsg = printf('%s search hit %s without match for: %s', a:searchType, (a:isBackward ? 'TOP' : 'BOTTOM'), a:searchPattern) endif call s:ErrorMsg(l:errmsg) endfunction " Wrapper around search() with additonal search and error messages and "wrapscan" warning. function! s:Search( pattern, count, isBackward, currentMarkPosition, searchType ) if empty(a:pattern) call s:NoMarkErrorMessage() return 0 endif let l:save_view = winsaveview() " searchpos() obeys the 'smartcase' setting; however, this setting doesn't " make sense for the mark search, because all patterns for the marks are " concatenated as branches in one large regexp, and because patterns that " result from the *-command-alike mappings should not obey 'smartcase' (like " the * command itself), anyway. If the :Mark command wants to support " 'smartcase', it'd have to emulate that into the regular expression. " Instead of temporarily unsetting 'smartcase', we force the correct " case-matching behavior through \c / \C. let l:searchPattern = (s:IsIgnoreCase(a:pattern) ? '\c' : '\C') . a:pattern let l:count = a:count let l:isWrapped = 0 let l:isMatch = 0 let l:line = 0 while l:count > 0 let [l:prevLine, l:prevCol] = [line('.'), col('.')] " Search for next match, 'wrapscan' applies. let [l:line, l:col] = searchpos( l:searchPattern, (a:isBackward ? 'b' : '') ) "****D echomsg '****' a:isBackward string([l:line, l:col]) string(a:currentMarkPosition) l:count if a:isBackward && l:line > 0 && [l:line, l:col] == a:currentMarkPosition && l:count == a:count " On a search in backward direction, the first match is the start of the " current mark (if the cursor was positioned on the current mark text, and " not at the start of the mark text). " In contrast to the normal search, this is not considered the first " match. The mark text is one entity; if the cursor is positioned anywhere " inside the mark text, the mark text is considered the current mark. The " built-in '*' and '#' commands behave in the same way; the entire <cword> " text is considered the current match, and jumps move outside that text. " In normal search, the cursor can be positioned anywhere (via offsets) " around the search, and only that single cursor position is considered " the current match. " Thus, the search is retried without a decrease of l:count, but only if " this was the first match; repeat visits during wrapping around count as " a regular match. The search also must not be retried when this is the " first match, but we've been here before (i.e. l:isMatch is set): This " means that there is only the current mark in the buffer, and we must " break out of the loop and indicate that search wrapped around and no " other mark was found. if l:isMatch let l:isWrapped = 1 break endif " The l:isMatch flag is set so if the final mark cannot be reached, the " original cursor position is restored. This flag also allows us to detect " whether we've been here before, which is checked above. let l:isMatch = 1 elseif l:line > 0 let l:isMatch = 1 let l:count -= 1 " Note: No need to check 'wrapscan'; the wrapping can only occur if " 'wrapscan' is actually on. if ! a:isBackward && (l:prevLine > l:line || l:prevLine == l:line && l:prevCol >= l:col) let l:isWrapped = 1 elseif a:isBackward && (l:prevLine < l:line || l:prevLine == l:line && l:prevCol <= l:col) let l:isWrapped = 1 endif else break endif endwhile " We're not stuck when the search wrapped around and landed on the current " mark; that's why we exclude a possible wrap-around via a:count == 1. let l:isStuckAtCurrentMark = ([l:line, l:col] == a:currentMarkPosition && a:count == 1) "****D echomsg '****' l:line l:isStuckAtCurrentMark l:isWrapped l:isMatch string([l:line, l:col]) string(a:currentMarkPosition) if l:line > 0 && ! l:isStuckAtCurrentMark let l:matchPosition = getpos('.') " Open fold at the search result, like the built-in commands. normal! zv " Add the original cursor position to the jump list, like the " [/?*#nN] commands. " Implementation: Memorize the match position, restore the view to the state " before the search, then jump straight back to the match position. This " also allows us to set a jump only if a match was found. (:call " setpos("''", ...) doesn't work in Vim 7.2) call winrestview(l:save_view) normal! m' call setpos('.', l:matchPosition) " Enable marks (in case they were disabled) after arriving at the mark (to " avoid unnecessary screen updates) but before the error message (to avoid " it getting lost due to the screen updates). call s:MarkEnable(1) if l:isWrapped call s:WrapMessage(a:searchType, a:pattern, a:isBackward) else call s:EchoSearchPattern(a:searchType, a:pattern, a:isBackward) endif return 1 else if l:isMatch " The view has been changed by moving through matches until the end / " start of file, when 'nowrapscan' forced a stop of searching before the " l:count'th match was found. " Restore the view to the state before the search. call winrestview(l:save_view) endif " Enable marks (in case they were disabled) after arriving at the mark (to " avoid unnecessary screen updates) but before the error message (to avoid " it getting lost due to the screen updates). call s:MarkEnable(1) if l:line > 0 && l:isStuckAtCurrentMark && l:isWrapped call s:WrapMessage(a:searchType, a:pattern, a:isBackward) return 1 else call s:ErrorMessage(a:searchType, a:pattern, a:isBackward) return 0 endif endif endfunction " Combine all marks into one regexp. function! s:AnyMark() return join(filter(copy(s:pattern), '! empty(v:val)'), '\|') endfunction " Search any mark. function! mark#SearchAnyMark( isBackward ) let l:markPosition = mark#CurrentMark()[1] let l:markText = s:AnyMark() let s:lastSearch = -1 return s:Search(l:markText, v:count1, a:isBackward, l:markPosition, 'mark-*') endfunction " Search last searched mark. function! mark#SearchNext( isBackward, ... ) let l:markText = mark#CurrentMark()[0] if empty(l:markText) return 0 " Fall back to the built-in * / # command (done by the mapping). endif " Use the provided search type or choose depending on last use of " <Plug>MarkSearchCurrentNext / <Plug>MarkSearchAnyNext. call call(a:0 ? a:1 : (s:lastSearch == -1 ? 'mark#SearchAnyMark' : 'mark#SearchCurrentMark'), [a:isBackward]) return 1 endfunction " Load mark patterns from list. function! mark#Load( pattern, enabled ) if s:markNum > 0 && len(a:pattern) > 0 " Initialize mark patterns with the passed list. Ensure that, regardless of " the list length, s:pattern contains exactly s:markNum elements. let s:pattern = a:pattern[0:(s:markNum - 1)] let s:pattern += repeat([''], (s:markNum - len(s:pattern))) let s:enabled = a:enabled call mark#UpdateScope() " The list of patterns may be sparse, return only the actual patterns. return len(filter(copy(a:pattern), '! empty(v:val)')) endif return 0 endfunction " Access the list of mark patterns. function! mark#ToPatternList() " Trim unused patterns from the end of the list, the amount of available marks " may differ on the next invocation (e.g. due to a different number of " highlight groups in Vim and GVIM). We want to keep empty patterns in the " front and middle to maintain the mapping to highlight groups, though. let l:highestNonEmptyIndex = s:markNum - 1 while l:highestNonEmptyIndex >= 0 && empty(s:pattern[l:highestNonEmptyIndex]) let l:highestNonEmptyIndex -= 1 endwhile return (l:highestNonEmptyIndex < 0 ? [] : s:pattern[0 : l:highestNonEmptyIndex]) endfunction " Common functions for :MarkLoad and :MarkSave function! mark#MarksVariablesComplete( ArgLead, CmdLine, CursorPos ) return sort(map(filter(keys(g:), 'v:val !~# "^MARK_\\%(MARKS\\|ENABLED\\)$" && v:val =~# "\\V\\^MARK_' . (empty(a:ArgLead) ? '\\S' : escape(a:ArgLead, '\')) . '"'), 'v:val[5:]')) endfunction function! s:HasVariablePersistence() return (index(split(&viminfo, ','), '!') != -1) endfunction " :MarkLoad command. function! mark#LoadCommand( isShowMessages, ... ) if a:0 let l:marksVariable = printf('g:MARK_%s', a:1) if exists(l:marksVariable) let l:marks = eval(l:marksVariable) let l:isEnabled = 1 else call s:ErrorMsg('No marks stored under ' . l:marksVariable . (s:HasVariablePersistence() || a:1 !~# '^\u\+$' ? '' : ", and persistence not configured via ! flag in 'viminfo'"), a:isShowMessages) return endif else if exists('g:MARK_MARKS') let l:marks = g:MARK_MARKS let l:isEnabled = (exists('g:MARK_ENABLED') ? g:MARK_ENABLED : 1) else call s:ErrorMsg('No persistent marks found' . (s:HasVariablePersistence() ? '' : ", and persistence not configured via ! flag in 'viminfo'"), a:isShowMessages) return endif endif try " Persistent global variables cannot be of type List, so we actually store " the string representation, and eval() it back to a List. execute printf('let l:loadedMarkNum = mark#Load(%s, %d)', l:marks, l:isEnabled) if a:isShowMessages if l:loadedMarkNum == 0 echomsg 'No persistent marks defined' . (exists('l:marksVariable') ? ' in ' . l:marksVariable : '') else echomsg printf('Loaded %d mark%s', l:loadedMarkNum, (l:loadedMarkNum == 1 ? '' : 's')) . (s:enabled ? '' : '; marks currently disabled') endif endif catch /^Vim\%((\a\+)\)\=:E/ if exists('l:marksVariable') call s:ErrorMsg(printf('Corrupted persistent mark info in %s', l:marksVariable), a:isShowMessages) execute 'unlet!' l:marksVariable else call s:ErrorMsg('Corrupted persistent mark info in g:MARK_MARKS and g:MARK_ENABLED', a:isShowMessages) unlet! g:MARK_MARKS unlet! g:MARK_ENABLED endif endtry endfunction " :MarkSave command. function! s:SavePattern( ... ) let l:savedMarks = mark#ToPatternList() if a:0 try if empty(l:savedMarks) unlet! g:MARK_{a:1} else let g:MARK_{a:1} = string(l:savedMarks) endif catch /^Vim\%((\a\+)\)\=:E/ " v:exception contains what is normally in v:errmsg, but with extra " exception source info prepended, which we cut away. call s:ErrorMsg(substitute(v:exception, '^Vim\%((\a\+)\)\=:', '', '')) return -1 endtry else let g:MARK_MARKS = string(l:savedMarks) let g:MARK_ENABLED = s:enabled endif return ! empty(l:savedMarks) endfunction function! mark#SaveCommand( ... ) if ! s:HasVariablePersistence() if ! a:0 call s:ErrorMsg("Cannot persist marks, need ! flag in 'viminfo': :set viminfo+=!") elseif a:1 =~# '^\u\+$' call s:WarningMsg("Cannot persist marks, need ! flag in 'viminfo': :set viminfo+=!") endif endif if ! call('s:SavePattern', a:000) call s:WarningMsg('No marks defined') endif endfunction " Query mark group number. function! s:GetNextGroupIndex() let l:nextGroupIndex = s:FreeGroupIndex() if l:nextGroupIndex == -1 let l:nextGroupIndex = s:cycle endif return l:nextGroupIndex endfunction function! s:GetMarker( index, nextGroupIndex ) let l:marker = '' if s:lastSearch == a:index let l:marker .= '/' endif if a:index == a:nextGroupIndex let l:marker .= '>' endif return l:marker endfunction function! s:GetAlternativeCount( pattern ) return len(split(a:pattern, '\%(\%(^\|[^\\]\)\%(\\\\\)*\\\)\@<!\\|')) endfunction function! s:PrintMarkGroup( nextGroupIndex ) for i in range(s:markNum) echon ' ' execute 'echohl MarkWord' . (i + 1) let c = s:GetAlternativeCount(s:pattern[i]) echon printf('%1s%s%2d ', s:GetMarker(i, a:nextGroupIndex), (c ? (c > 1 ? c : '') . '*' : ''), (i + 1)) echohl None endfor endfunction function! mark#QueryMarkGroupNum() echohl Question echo 'Mark?' echohl None let l:nextGroupIndex = s:GetNextGroupIndex() call s:PrintMarkGroup(l:nextGroupIndex) let l:nr = 0 while 1 let l:char = nr2char(getchar()) if l:char ==# "\<CR>" return (l:nr == 0 ? l:nextGroupIndex + 1 : l:nr) elseif l:char !~# '\d' return -1 endif echon l:char let l:nr = 10 * l:nr + l:char if s:markNum < 10 * l:nr return l:nr endif endwhile endfunction " :Marks command. function! mark#List() echohl Title echo 'mark cnt Pattern' echohl None echon ' (> next mark group / current search mark)' let l:nextGroupIndex = s:GetNextGroupIndex() for i in range(s:markNum) execute 'echohl MarkWord' . (i + 1) let c = s:GetAlternativeCount(s:pattern[i]) echo printf('%1s%3d%4s %s', s:GetMarker(i, l:nextGroupIndex), (i + 1), (c > 1 ? '('.c.')' : ''), s:pattern[i]) echohl None endfor if ! s:enabled echo 'Marks are currently disabled.' endif endfunction function! mark#GetGroupNum() return s:markNum endfunction "- integrations ---------------------------------------------------------------- " Access the number of possible marks. function! mark#GetNum() return s:markNum endfunction " Access the current / passed index pattern. function! mark#GetPattern( ... ) if a:0 return s:pattern[a:1] else return (s:lastSearch == -1 ? '' : s:pattern[s:lastSearch]) endif endfunction "- initializations ------------------------------------------------------------ augroup Mark autocmd! autocmd WinEnter * if ! exists('w:mwMatch') | call mark#UpdateMark() | endif autocmd TabEnter * call mark#UpdateScope() augroup END " Define global variables and initialize current scope. function! mark#Init() let s:markNum = 0 while hlexists('MarkWord' . (s:markNum + 1)) let s:markNum += 1 endwhile let s:pattern = repeat([''], s:markNum) let s:cycle = 0 let s:lastSearch = -1 let s:enabled = 1 endfunction function! mark#ReInit( newMarkNum ) if a:newMarkNum < s:markNum " There are less marks than before. " Clear the additional highlight groups. for i in range(a:newMarkNum + 1, s:markNum) execute 'highlight clear MarkWord' . (i + 1) endfor " Truncate the mark patterns. let s:pattern = s:pattern[0 : (a:newMarkNum - 1)] " Correct any indices. let s:cycle = min([s:cycle, (a:newMarkNum - 1)]) let s:lastSearch = (s:lastSearch < a:newMarkNum ? s:lastSearch : -1) elseif a:newMarkNum > s:markNum " There are more marks than before. " Expand the mark patterns. let s:pattern += repeat([''], (a:newMarkNum - s:markNum)) endif let s:markNum = a:newMarkNum endfunction call mark#Init() if exists('g:mwDoDeferredLoad') && g:mwDoDeferredLoad unlet g:mwDoDeferredLoad call mark#LoadCommand(0) else call mark#UpdateScope() endif " vim: ts=4 sts=0 sw=4 noet
00000svn-vim-cfg
trunk/vimfiles/autoload/mark.vim
Vim Script
gpl3
40,937
"=============================================================================== " " File: perlsupportgui.vim " " Description: Plugin perl-support: Menu definitions. " " VIM Version: 7.0+ " Author: Dr. Fritz Mehner (mn), mehner@fh-swf.de " Company: FH Südwestfalen, Iserlohn " Version: 1.0 " Created: 16.12.2008 18:16:55 " Revision: $Id: perlsupportgui.vim,v 1.40 2011/08/19 13:39:51 mehner Exp $ " License: Copyright 2008-2011 Dr. Fritz Mehner "=============================================================================== " " Exit quickly when: " - this plugin was already loaded " - when 'compatible' is set " if exists("g:loaded_perlsupportgui") || &compatible finish endif let g:loaded_perlsupportgui = "v1.0" let s:MSWIN = has("win16") || has("win32") || has("win64") || has("win95") " "------------------------------------------------------------------------------ " Perl Menu Initializations {{{1 " Against the advice of every style guide this function has overlong lines " to enable the use of block commands when editing. "------------------------------------------------------------------------------ function! perlsupportgui#Perl_InitMenu () "=============================================================================================== "----- Menu : Main menu {{{2 "=============================================================================================== if g:Perl_MenuHeader == "yes" call Perl_InitMenuHeader() endif " "=============================================================================================== "----- Menu : Comments menu {{{2 "=============================================================================================== " exe "amenu <silent> ".g:Perl_Root.'&Comments.end-of-&line\ com\.<Tab>\\cl :call Perl_EndOfLineComment()<CR>A' exe "imenu <silent> ".g:Perl_Root.'&Comments.end-of-&line\ com\.<Tab>\\cl <C-C>:call Perl_EndOfLineComment()<CR>A' exe "vmenu <silent> ".g:Perl_Root.'&Comments.end-of-&line\ com\.<Tab>\\cl :call Perl_MultiLineEndComments()<CR>A' " exe "amenu <silent> ".g:Perl_Root.'&Comments.ad&just\ end-of-line\ com\.<Tab>\\cj :call Perl_AlignLineEndComm()<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Comments.ad&just\ end-of-line\ com\.<Tab>\\cj :call Perl_AlignLineEndComm()<CR>' " exe "amenu <silent> ".g:Perl_Root.'&Comments.&set\ end-of-line\ com\.\ col\.<Tab>\\cs :call Perl_GetLineEndCommCol()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Comments.&frame\ comm\.<Tab>\\cfr :call Perl_InsertTemplate("comment.frame")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Comments.f&unction\ descr\.<Tab>\\cfu :call Perl_InsertTemplate("comment.function")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Comments.&method\ descr\.<Tab>\\cm :call Perl_InsertTemplate("comment.method")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Comments.file\ &header\ (\.pl)<Tab>\\chpl :call Perl_InsertTemplate("comment.file-description-pl")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Comments.file\ h&eader\ (\.pm)<Tab>\\chpm :call Perl_InsertTemplate("comment.file-description-pm")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Comments.file\ he&ader\ (\.t)<Tab>\\cht :call Perl_InsertTemplate("comment.file-description-t")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Comments.file\ hea&der\ (\.pod)<Tab>\\chpo :call Perl_InsertTemplate("comment.file-description-pod")<CR>' exe "amenu ".g:Perl_Root.'&Comments.-SEP1- :' " exe "amenu <silent> ".g:Perl_Root.'&Comments.toggle\ &comment<Tab>\\cc :call Perl_CommentToggle()<CR>j' exe "imenu <silent> ".g:Perl_Root.'&Comments.toggle\ &comment<Tab>\\cc <C-C>:call Perl_CommentToggle()<CR>j' exe "vmenu <silent> ".g:Perl_Root.'&Comments.toggle\ &comment<Tab>\\cc :call Perl_CommentToggle()<CR>j' exe "amenu <silent> ".g:Perl_Root.'&Comments.comment\ &block<Tab>\\cb :call Perl_CommentBlock("a")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Comments.comment\ &block<Tab>\\cb <C-C>:call Perl_CommentBlock("a")<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Comments.comment\ &block<Tab>\\cb <C-C>:call Perl_CommentBlock("v")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Comments.u&ncomment\ block<Tab>\\cn :call Perl_UncommentBlock()<CR>' " exe "amenu ".g:Perl_Root.'&Comments.-SEP2- :' " exe " menu ".g:Perl_Root.'&Comments.&date<Tab>\\cd <Esc>:call Perl_InsertDateAndTime("d")<CR>' exe "imenu ".g:Perl_Root.'&Comments.&date<Tab>\\cd <Esc>:call Perl_InsertDateAndTime("d")<CR>a' exe "vmenu ".g:Perl_Root.'&Comments.&date<Tab>\\cd s<Esc>:call Perl_InsertDateAndTime("d")<CR>a' exe " menu ".g:Perl_Root.'&Comments.date\ &time<Tab>\\ct <Esc>:call Perl_InsertDateAndTime("dt")<CR>' exe "imenu ".g:Perl_Root.'&Comments.date\ &time<Tab>\\ct <Esc>:call Perl_InsertDateAndTime("dt")<CR>a' exe "vmenu ".g:Perl_Root.'&Comments.date\ &time<Tab>\\ct s<Esc>:call Perl_InsertDateAndTime("dt")<CR>a' exe "amenu ".g:Perl_Root.'&Comments.-SEP3- :' " "--------- submenu : KEYWORD ------------------------------------------------------------- " if g:Perl_MenuHeader == "yes" exe "amenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..Comments-1<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..-Sep0- :' exe "amenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).Comments-2<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).-Sep0- :' endif " exe "amenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..\:&BUG\: $:call Perl_InsertTemplate("comment.keyword-bug")<CR>' exe "amenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..\:&TODO\: $:call Perl_InsertTemplate("comment.keyword-todo")<CR>' exe "amenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..\:&WARNING\: $:call Perl_InsertTemplate("comment.keyword-warning")<CR>' exe "amenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..\:W&ORKAROUND\: $:call Perl_InsertTemplate("comment.keyword-workaround")<CR>' exe "amenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..\:&new\ keyword\: $:call Perl_InsertTemplate("comment.keyword-keyword")<CR>' " exe "imenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..\:&BUG\: <Esc>$:call Perl_InsertTemplate("comment.keyword-bug")<CR>' exe "imenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..\:&TODO\: <Esc>$:call Perl_InsertTemplate("comment.keyword-todo")<CR>' exe "imenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..\:&WARNING\: <Esc>$:call Perl_InsertTemplate("comment.keyword-warning")<CR>' exe "imenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..\:W&ORKAROUND\: <Esc>$:call Perl_InsertTemplate("comment.keyword-workaround")<CR>' exe "imenu ".g:Perl_Root.'&Comments.&KEYWORD+comm\..\:&new\ keyword\: <Esc>$:call Perl_InsertTemplate("comment.keyword-keyword")<CR>' " " "----- Submenu : Tags ---------------------------------------------------------- " exe "anoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&AUTHOR :call Perl_InsertMacroValue("AUTHOR")<CR>' exe "anoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).AUTHOR&REF :call Perl_InsertMacroValue("AUTHORREF")<CR>' exe "anoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&COMPANY :call Perl_InsertMacroValue("COMPANY")<CR>' exe "anoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).C&OPYRIGHTHOLDER :call Perl_InsertMacroValue("COPYRIGHTHOLDER")<CR>' exe "anoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&EMAIL :call Perl_InsertMacroValue("EMAIL")<CR>' exe "anoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&PROJECT :call Perl_InsertMacroValue("PROJECT")<CR>' " exe "inoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&AUTHOR <Esc>:call Perl_InsertMacroValue("AUTHOR")<CR>a' exe "inoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).AUTHOR&REF <Esc>:call Perl_InsertMacroValue("AUTHORREF")<CR>a' exe "inoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&COMPANY <Esc>:call Perl_InsertMacroValue("COMPANY")<CR>a' exe "inoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).C&OPYRIGHTHOLDER <Esc>:call Perl_InsertMacroValue("COPYRIGHTHOLDER")<CR>a' exe "inoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&EMAIL <Esc>:call Perl_InsertMacroValue("EMAIL")<CR>a' exe "inoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&PROJECT <Esc>:call Perl_InsertMacroValue("PROJECT")<CR>a' " exe "vnoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&AUTHOR s<Esc>:call Perl_InsertMacroValue("AUTHOR")<CR>a' exe "vnoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).AUTHOR&REF s<Esc>:call Perl_InsertMacroValue("AUTHORREF")<CR>a' exe "vnoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&COMPANY s<Esc>:call Perl_InsertMacroValue("COMPANY")<CR>a' exe "vnoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).C&OPYRIGHTHOLDER s<Esc>:call Perl_InsertMacroValue("COPYRIGHTHOLDER")<CR>a' exe "vnoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&EMAIL s<Esc>:call Perl_InsertMacroValue("EMAIL")<CR>a' exe "vnoremenu ".g:Perl_Root.'&Comments.ta&gs\ (plugin).&PROJECT s<Esc>:call Perl_InsertMacroValue("PROJECT")<CR>a' " exe "amenu <silent> ".g:Perl_Root.'&Comments.&vim\ modeline<Tab>\\cv :call Perl_CommentVimModeline()<CR>' "=============================================================================================== "----- Menu : Statements Menu {{{2 "=============================================================================================== " exe "amenu <silent> ".g:Perl_Root.'&Statements.&do\ \{\ \}\ while<Tab>\\sd :call Perl_InsertTemplate("statements.do-while")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Statements.&for\ \{\ \}<Tab>\\sf :call Perl_InsertTemplate("statements.for")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Statements.f&oreach\ \{\ \}<Tab>\\sfe :call Perl_InsertTemplate("statements.foreach")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Statements.&if\ \{\ \}<Tab>\\si :call Perl_InsertTemplate("statements.if")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Statements.if\ \{\ \}\ &else\ \{\ \}<Tab>\\sie :call Perl_InsertTemplate("statements.if-else")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Statements.&else\ \{\ \}<Tab>\\se :call Perl_InsertTemplate("statements.else")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Statements.e&lsif\ \{\ \}<Tab>\\sei :call Perl_InsertTemplate("statements.elsif")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Statements.&unless\ \{\ \}<Tab>\\su :call Perl_InsertTemplate("statements.unless")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Statements.u&nless\ \{\ \}\ else\ \{\ \}<Tab>\\sue :call Perl_InsertTemplate("statements.unless-else")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Statements.un&til\ \{\ \}<Tab>\\st :call Perl_InsertTemplate("statements.until")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Statements.&while\ \{\ \}<Tab>\\sw :call Perl_InsertTemplate("statements.while")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Statements.&\{\ \}<Tab>\\sb :call Perl_InsertTemplate("statements.block")<CR>' " exe "imenu <silent> ".g:Perl_Root.'&Statements.&do\ \{\ \}\ while<Tab>\\sd <C-C>:call Perl_InsertTemplate("statements.do-while")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Statements.&for\ \{\ \}<Tab>\\sf <C-C>:call Perl_InsertTemplate("statements.for")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Statements.f&oreach\ \{\ \}<Tab>\\sfe <C-C>:call Perl_InsertTemplate("statements.foreach")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Statements.&if\ \{\ \}<Tab>\\si <C-C>:call Perl_InsertTemplate("statements.if")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Statements.if\ \{\ \}\ &else\ \{\ \}<Tab>\\sie <C-C>:call Perl_InsertTemplate("statements.if-else")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Statements.&else\ \{\ \}<Tab>\\se <C-C>:call Perl_InsertTemplate("statements.else")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Statements.e&lsif\ \{\ \}<Tab>\\sei <C-C>:call Perl_InsertTemplate("statements.elsif")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Statements.&unless\ \{\ \}<Tab>\\su <C-C>:call Perl_InsertTemplate("statements.unless")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Statements.u&nless\ \{\ \}\ else\ \{\ \}<Tab>\\sue <C-C>:call Perl_InsertTemplate("statements.unless-else")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Statements.un&til\ \{\ \}<Tab>\\st <C-C>:call Perl_InsertTemplate("statements.until")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Statements.&while\ \{\ \}<Tab>\\sw <C-C>:call Perl_InsertTemplate("statements.while")<CR>' exe "imenu <silent> ".g:Perl_Root.'&Statements.&\{\ \}<Tab>\\sb <C-C>:call Perl_InsertTemplate("statements.block")<CR>' " exe "vmenu <silent> ".g:Perl_Root.'&Statements.&do\ \{\ \}\ while<Tab>\\sd <C-C>:call Perl_InsertTemplate("statements.do-while", "v" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Statements.&for\ \{\ \}<Tab>\\sf <C-C>:call Perl_InsertTemplate("statements.for", "v" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Statements.f&oreach\ \{\ \}<Tab>\\sfe <C-C>:call Perl_InsertTemplate("statements.foreach", "v" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Statements.&if\ \{\ \}<Tab>\\si <C-C>:call Perl_InsertTemplate("statements.if", "v" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Statements.if\ \{\ \}\ &else\ \{\ \}<Tab>\\sie <C-C>:call Perl_InsertTemplate("statements.if-else", "v" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Statements.&else\ \{\ \}<Tab>\\se <C-C>:call Perl_InsertTemplate("statements.else", "v" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Statements.e&lsif\ \{\ \}<Tab>\\sei <C-C>:call Perl_InsertTemplate("statements.elsif", "v" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Statements.&unless\ \{\ \}<Tab>\\su <C-C>:call Perl_InsertTemplate("statements.unless", "v" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Statements.u&nless\ \{\ \}\ else\ \{\ \}<Tab>\\sue <C-C>:call Perl_InsertTemplate("statements.unless-else", "v" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Statements.un&til\ \{\ \}<Tab>\\st <C-C>:call Perl_InsertTemplate("statements.until", "v" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Statements.&while\ \{\ \}<Tab>\\sw <C-C>:call Perl_InsertTemplate("statements.while", "v" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Statements.&\{\ \}<Tab>\\sb <C-C>:call Perl_InsertTemplate("statements.block", "v" )<CR>' " "=============================================================================================== "----- Menu : Idioms menu {{{2 "=============================================================================================== " exe "nnoremenu <silent> ".g:Perl_Root.'&Idioms.my\ &$;<Tab>\\id :call Perl_InsertTemplate("idioms.scalar")<CR>' exe "nnoremenu <silent> ".g:Perl_Root.'&Idioms.my\ $\ &=\ ;<Tab>\\id= :call Perl_InsertTemplate("idioms.scalar-assign")<CR>' exe "nnoremenu <silent> ".g:Perl_Root.'&Idioms.my\ (\ $&,\ $\ );<Tab>\\idd :call Perl_InsertTemplate("idioms.scalar2")<CR>' exe "nnoremenu <silent> ".g:Perl_Root.'&Idioms.my\ &@;<Tab>\\ia :call Perl_InsertTemplate("idioms.array")<CR>' exe "nnoremenu <silent> ".g:Perl_Root.'&Idioms.my\ &@\ =\ (,,);<Tab>\\ia= :call Perl_InsertTemplate("idioms.array-assign")<CR>' exe "nnoremenu <silent> ".g:Perl_Root.'&Idioms.my\ &%;<Tab>\\ih :call Perl_InsertTemplate("idioms.hash")<CR>' exe "nnoremenu <silent> ".g:Perl_Root.'&Idioms.my\ &%\ =\ (=>,);<Tab>\\ih= :call Perl_InsertTemplate("idioms.hash-assign")<CR>' exe "nnoremenu <silent> ".g:Perl_Root.'&Idioms.my\ $&rgx_\ =\ qr//;<Tab>\\ir :call Perl_InsertTemplate("idioms.regex")<CR>' " exe "inoremenu <silent> ".g:Perl_Root.'&Idioms.my\ &$;<Tab>\\id <C-C>:call Perl_InsertTemplate("idioms.scalar")<CR>' exe "inoremenu <silent> ".g:Perl_Root.'&Idioms.my\ $\ &=\ ;<Tab>\\id= <C-C>:call Perl_InsertTemplate("idioms.scalar-assign")<CR>' exe "inoremenu <silent> ".g:Perl_Root.'&Idioms.my\ (\ $&,\ $\ );<Tab>\\idd <C-C>:call Perl_InsertTemplate("idioms.scalar2")<CR>' exe "inoremenu <silent> ".g:Perl_Root.'&Idioms.my\ &@;<Tab>\\ia <C-C>:call Perl_InsertTemplate("idioms.array")<CR>' exe "inoremenu <silent> ".g:Perl_Root.'&Idioms.my\ &@\ =\ (,,);<Tab>\\ia= <C-C>:call Perl_InsertTemplate("idioms.array-assign")<CR>' exe "inoremenu <silent> ".g:Perl_Root.'&Idioms.my\ &%;<Tab>\\ih <C-C>:call Perl_InsertTemplate("idioms.hash")<CR>' exe "inoremenu <silent> ".g:Perl_Root.'&Idioms.my\ &%\ =\ (=>,);<Tab>\\ih= <C-C>:call Perl_InsertTemplate("idioms.hash-assign")<CR>' exe "inoremenu <silent> ".g:Perl_Root.'&Idioms.my\ $&rgx_\ =\ qr//;<Tab>\\ir <C-C>:call Perl_InsertTemplate("idioms.regex")<CR>' " exe "anoremenu ".g:Perl_Root.'&Idioms.-SEP3- :' exe "anoremenu ".g:Perl_Root.'&Idioms.$\ =~\ &m/\ /<Tab>\\im :call Perl_InsertTemplate("idioms.match")<CR>' exe "inoremenu ".g:Perl_Root.'&Idioms.$\ =~\ &m/\ /<Tab>\\im <C-C>:call Perl_InsertTemplate("idioms.match")<CR>' exe "anoremenu ".g:Perl_Root.'&Idioms.$\ =~\ &s/\ /\ /<Tab>\\is :call Perl_InsertTemplate("idioms.substitute")<CR>' exe "inoremenu ".g:Perl_Root.'&Idioms.$\ =~\ &s/\ /\ /<Tab>\\is <C-C>:call Perl_InsertTemplate("idioms.substitute")<CR>' exe "anoremenu ".g:Perl_Root.'&Idioms.$\ =~\ &tr/\ /\ /<Tab>\\it :call Perl_InsertTemplate("idioms.translate")<CR>' exe "inoremenu ".g:Perl_Root.'&Idioms.$\ =~\ &tr/\ /\ /<Tab>\\it <C-C>:call Perl_InsertTemplate("idioms.translate")<CR>' " exe " noremenu ".g:Perl_Root.'&Idioms.-SEP4- :' exe "anoremenu ".g:Perl_Root.'&Idioms.s&ubroutine<Tab>\\isu :call Perl_InsertTemplate("idioms.subroutine")<CR>' exe "vnoremenu ".g:Perl_Root.'&Idioms.s&ubroutine<Tab>\\isu <C-C>:call Perl_InsertTemplate("idioms.subroutine", "v")<CR>' " exe "anoremenu ".g:Perl_Root.'&Idioms.&print\ \"\.\.\.\\n\";<Tab>\\ip :call Perl_InsertTemplate("idioms.print")<CR>' exe "inoremenu ".g:Perl_Root.'&Idioms.&print\ \"\.\.\.\\n\";<Tab>\\ip <C-C>:call Perl_InsertTemplate("idioms.print")<CR>' " exe "anoremenu ".g:Perl_Root.'&Idioms.open\ &input\ file<Tab>\\ii :call Perl_InsertTemplate("idioms.open-input-file")<CR>' exe "inoremenu ".g:Perl_Root.'&Idioms.open\ &input\ file<Tab>\\ii <C-C>:call Perl_InsertTemplate("idioms.open-input-file")<CR>' exe "vnoremenu ".g:Perl_Root.'&Idioms.open\ &input\ file<Tab>\\ii <C-C>:call Perl_InsertTemplate("idioms.open-input-file", "v" )<CR>' " exe "anoremenu ".g:Perl_Root.'&Idioms.open\ &output\ file<Tab>\\io :call Perl_InsertTemplate("idioms.open-output-file")<CR>' exe "inoremenu ".g:Perl_Root.'&Idioms.open\ &output\ file<Tab>\\io <C-C>:call Perl_InsertTemplate("idioms.open-output-file")<CR>' exe "vnoremenu ".g:Perl_Root.'&Idioms.open\ &output\ file<Tab>\\io <C-C>:call Perl_InsertTemplate("idioms.open-output-file", "v" )<CR>' " exe "anoremenu ".g:Perl_Root.'&Idioms.open\ pip&e<Tab>\\ipi :call Perl_InsertTemplate("idioms.open-pipe")<CR>' exe "inoremenu ".g:Perl_Root.'&Idioms.open\ pip&e<Tab>\\ipi <C-C>:call Perl_InsertTemplate("idioms.open-pipe")<CR>' exe "vnoremenu ".g:Perl_Root.'&Idioms.open\ pip&e<Tab>\\ipi <C-C>:call Perl_InsertTemplate("idioms.open-pipe", "v" )<CR>' " exe "anoremenu ".g:Perl_Root.'&Idioms.-SEP5- :' exe "anoremenu ".g:Perl_Root.'&Idioms.<STDIN> a<STDIN>' exe "anoremenu ".g:Perl_Root.'&Idioms.<STDOUT> a<STDOUT>' exe "anoremenu ".g:Perl_Root.'&Idioms.<STDERR> a<STDERR>' exe "inoremenu ".g:Perl_Root.'&Idioms.<STDIN> <STDIN>' exe "inoremenu ".g:Perl_Root.'&Idioms.<STDOUT> <STDOUT>' exe "inoremenu ".g:Perl_Root.'&Idioms.<STDERR> <STDERR>' " "=============================================================================================== "----- Menu : Regex menu {{{2 "=============================================================================================== " " The menu entries for code snippet support will not appear if the following string is empty if g:Perl_CodeSnippets != "" exe "amenu <silent> ".g:Perl_Root.'S&nippets.&read\ code\ snippet<Tab>\\nr :call Perl_CodeSnippet("r")<CR>' exe "amenu <silent> ".g:Perl_Root.'S&nippets.&write\ code\ snippet<Tab>\\nw :call Perl_CodeSnippet("w")<CR>' exe "vmenu <silent> ".g:Perl_Root.'S&nippets.&write\ code\ snippet<Tab>\\nw :call Perl_CodeSnippet("wv")<CR>' exe "amenu <silent> ".g:Perl_Root.'S&nippets.e&dit\ code\ snippet<Tab>\\ne :call Perl_CodeSnippet("e")<CR>' exe "amenu <silent> ".g:Perl_Root.'S&nippets.-SEP1- :' endif " exe "amenu <silent> ".g:Perl_Root.'S&nippets.edit\ &local\ templates<Tab>\\ntl :call Perl_BrowseTemplateFiles("Local")<CR>' exe "imenu <silent> ".g:Perl_Root.'S&nippets.edit\ &local\ templates<Tab>\\ntl <C-C>:call Perl_BrowseTemplateFiles("Local")<CR>' if g:Perl_Installation == 'system' exe "amenu <silent> ".g:Perl_Root.'S&nippets.edit\ &global\ templates<Tab>\\ntg :call Perl_BrowseTemplateFiles("Global")<CR>' exe "imenu <silent> ".g:Perl_Root.'S&nippets.edit\ &global\ templates<Tab>\\ntg <C-C>:call Perl_BrowseTemplateFiles("Global")<CR>' endif exe "amenu <silent> ".g:Perl_Root.'S&nippets.reread\ &templates<Tab>\\ntr :call Perl_RereadTemplates("yes")<CR>' exe "imenu <silent> ".g:Perl_Root.'S&nippets.reread\ &templates <Tab>\\ntr <C-C>:call Perl_RereadTemplates("yes")<CR>' " "=============================================================================================== "----- Menu : Regex menu {{{2 "=============================================================================================== " exe "anoremenu ".g:Perl_Root.'Rege&x.&grouping,\ (\ ) a()<Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.&alternation,\ (\ \|\ ) a(\|)<Left><Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.char\.\ &class,\ [\ ] a[]<Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.c&ount,\ {\ } a{}<Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.co&unt\ (at\ least),\ {\ ,\ } a{,}<Left><Left>' " exe "inoremenu ".g:Perl_Root.'Rege&x.&grouping,\ (\ ) ()<Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.&alternation,\ (\ \|\ ) (\|)<Left><Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.char\.\ &class,\ [\ ] []<Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.c&ount,\ {\ } {}<Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.co&unt\ (at\ least),\ {\ ,\ } {,}<Left><Left>' exe "vnoremenu ".g:Perl_Root.'Rege&x.&grouping,\ (\ ) s()<Esc>P' exe "vnoremenu ".g:Perl_Root.'Rege&x.&alternation,\ (\ \|\ ) s(\|)<Esc>hPf)i' exe "vnoremenu ".g:Perl_Root.'Rege&x.char\.\ &class,\ [\ ] s[]<Esc>P' exe "vnoremenu ".g:Perl_Root.'Rege&x.c&ount,\ {\ } s{}<Esc>P' exe "vnoremenu ".g:Perl_Root.'Rege&x.co&unt\ (at\ least),\ {\ ,\ } s{,}<Esc>hPf}i' " exe " menu ".g:Perl_Root.'Rege&x.-SEP3- :' " exe "anoremenu ".g:Perl_Root.'Rege&x.word\ &boundary,\ \\b a\b' exe "inoremenu ".g:Perl_Root.'Rege&x.word\ &boundary,\ \\b \b' exe "anoremenu ".g:Perl_Root.'Rege&x.&digit,\ \\d a\d' exe "inoremenu ".g:Perl_Root.'Rege&x.&digit,\ \\d \d' exe "anoremenu ".g:Perl_Root.'Rege&x.white&space,\ \\s a\s' exe "inoremenu ".g:Perl_Root.'Rege&x.white&space,\ \\s \s' exe "anoremenu ".g:Perl_Root.'Rege&x.&word\ character,\ \\w a\w' exe "inoremenu ".g:Perl_Root.'Rege&x.&word\ character,\ \\w \w' exe "anoremenu ".g:Perl_Root.'Rege&x.match\ &property,\ \\p{} a\p{}<Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.match\ &property,\ \\p{} \p{}<Left>' exe "vnoremenu ".g:Perl_Root.'Rege&x.match\ &property,\ \\p{} s\p{}<Esc>P' exe "anoremenu ".g:Perl_Root.'Rege&x.-SEP4- :' exe "anoremenu ".g:Perl_Root.'Rege&x.non-word\ &bound\.,\ \\B a\B' exe "inoremenu ".g:Perl_Root.'Rege&x.non-word\ &bound\.,\ \\B \B' exe "anoremenu ".g:Perl_Root.'Rege&x.non-&digit,\ \\D a\D' exe "inoremenu ".g:Perl_Root.'Rege&x.non-&digit,\ \\D \D' exe "anoremenu ".g:Perl_Root.'Rege&x.non-white&space,\ \\S a\S' exe "inoremenu ".g:Perl_Root.'Rege&x.non-white&space,\ \\S \S' exe "anoremenu ".g:Perl_Root.'Rege&x.non-&word\ char\.,\ \\W a\W' exe "inoremenu ".g:Perl_Root.'Rege&x.non-&word\ char\.,\ \\W \W' exe "anoremenu ".g:Perl_Root.'Rege&x.do\ not\ match\ &prop\.,\ \\P{} a\P{}<Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.do\ not\ match\ &prop\.,\ \\P{} \P{}<Left>' exe "vnoremenu ".g:Perl_Root.'Rege&x.do\ not\ match\ &prop\.,\ \\P{} s\P{}<Esc>P' " "---------- submenu : POSIX character classes -------------------------------------------- " exe " noremenu ".g:Perl_Root.'Rege&x.-SEP5- :' if g:Perl_MenuHeader == "yes" exe "amenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.Regex-1<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.-Sep0- :' exe "amenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.Regex-2<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.-Sep0- :' exe "amenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.Regex-3<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.-Sep0- :' endif " exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&alnum:]<Tab>\\pa a[:alnum:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:alp&ha:]<Tab>\\ph a[:alpha:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:asc&ii:]<Tab>\\pi a[:ascii:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&blank:]<Tab>\\pb a[:blank:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&cntrl:]<Tab>\\pc a[:cntrl:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&digit:]<Tab>\\pd a[:digit:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&graph:]<Tab>\\pg a[:graph:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&lower:]<Tab>\\pl a[:lower:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&print:]<Tab>\\pp a[:print:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:pu&nct:]<Tab>\\pn a[:punct:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&space:]<Tab>\\ps a[:space:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&upper:]<Tab>\\pu a[:upper:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&word:]<Tab>\\pw a[:word:]' exe "nnoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&xdigit:]<Tab>\\px a[:xdigit:]' " exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&alnum:]<Tab>\\pa [:alnum:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:alp&ha:]<Tab>\\ph [:alpha:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:asc&ii:]<Tab>\\pi [:ascii:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&blank:]<Tab>\\pb [:blank:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&cntrl:]<Tab>\\pc [:cntrl:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&digit:]<Tab>\\pd [:digit:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&graph:]<Tab>\\pg [:graph:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&lower:]<Tab>\\pl [:lower:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&print:]<Tab>\\pp [:print:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:pu&nct:]<Tab>\\pn [:punct:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&space:]<Tab>\\ps [:space:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&upper:]<Tab>\\pu [:upper:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&word:]<Tab>\\pw [:word:]' exe "inoremenu ".g:Perl_Root.'Rege&x.POSIX\ char\.\ c&lasses.[:&xdigit:]<Tab>\\px [:xdigit:]' " "---------- submenu : Unicode properties -------------------------------------------- " exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Letter.L&etter<Tab>\\p{L} a\p{Letter}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Letter.&Lowercase_Letter<Tab>\\p{Ll} a\p{Lowercase_Letter}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Letter.&Uppercase_Letter<Tab>\\p{Lu} a\p{Uppercase_Letter}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Letter.&Titlecase_Letter<Tab>\\p{Lt} a\p{Titlecase_Letter}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Letter.&Modifier_Letter<Tab>\\p{Lm} a\p{Modifier_Letter}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Letter.&Other_Letter<Tab>\\p{Lo} a\p{Other_Letter}' " exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Mark.&Mark<Tab>\\p{M} a\p{Mark}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Mark.&Non_Spacing_Mark<Tab>\\p{Mn} a\p{Non_Spacing_Mark}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Mark.Spacing_&Combining_Mark<Tab>\\p{Mc} a\p{Spacing_Combining_Mark}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Mark.&Enclosing_Mark<Tab>\\p{Me} a\p{Enclosing_Mark}' " exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.Separator\ (&Z).S&eparator<Tab>\\p{Z} a\p{Separator}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.Separator\ (&Z).&Space_Separator<Tab>\\p{Zs} a\p{Space_Separator}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.Separator\ (&Z).&Line_Separator<Tab>\\p{Zl} a\p{Line_Separator}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.Separator\ (&Z).&Paragraph_Separator<Tab>\\p{Zp} a\p{Paragraph_Separator}' " exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Symbol.&Symbol<Tab>\\p{S} a\p{Symbol}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Symbol.&Math_Symbol<Tab>\\p{Sm} a\p{Math_Symbol}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Symbol.&Currency_Symbol<Tab>\\p{Sc} a\p{Currency_Symbol}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Symbol.Modifier_Symbol\ (&k)<Tab>\\p{Sk} a\p{Modifier_Symbol}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Symbol.&Other_Symbol<Tab>\\p{So} a\p{Other_Symbol}' " exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Number.&Number<Tab>\\p{N} a\p{Number}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Number.&Decimal_Digit_Number<Tab>\\p{Nd} a\p{Decimal_Digit_Number}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Number.&Letter_Number<Tab>\\p{Nl} a\p{Letter_Number}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Number.&Other_Number<Tab>\\p{No} a\p{Other_Number}' " exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Punctuation.&Punctuation<Tab>\\p{P} a\p{Punctuation}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Punctuation.&Dash_Punctuation<Tab>\\p{Pd} a\p{Dash_Punctuation}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Punctuation.Open_Punctuation\ (&s)<Tab>\\p{Ps} a\p{Open_Punctuation}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Punctuation.Close_Punctuation\ (&e)<Tab>\\p{Pe} a\p{Close_Punctuation}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Punctuation.&Initial_Punctuation<Tab>\\p{Pi} a\p{Initial_Punctuation}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Punctuation.&Final_Punctuation<Tab>\\p{Pf} a\p{Final_Punctuation}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Punctuation.&Connector_Punctuation<Tab>\\p{Pc} a\p{Connector_Punctuation}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.&Punctuation.&Other_Punctuation<Tab>\\p{Po} a\p{Other_Punctuation}' " exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.Other\ (&C).O&ther<Tab>\\p{C} a\p{Other}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.Other\ (&C).&Control<Tab>\\p{Cc} a\p{Control}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.Other\ (&C).&Format<Tab>\\p{Cf} a\p{Format}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.Other\ (&C).Private_Use\ (&o)<Tab>\\p{Co} a\p{Private_Use}' exe "anoremenu ".g:Perl_Root.'Rege&x.Unicode\ propert&y.Other\ (&C).U&nassigned<Tab>\\p{Cn} a\p{Unassigned}' " "---------- subsubmenu : Regular Expression Suport ----------------------------------------- " exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.&comment<Tab>(?#\ \.\.\.\ ) a(?#)<Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.cl&uster\ only\ paren\.<Tab>(?-imsx:\ \.\.\.\ ) a(?-imsx:)<Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.pattern\ &modifier<Tab>(?-imsx) a(?-imsx)<Left><Left><Left><Left><Left><Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.e&xecute\ code<Tab>(?\{\ \.\.\.\ \}) a(?{})<Left><Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.match\ &regex\ from\ code<Tab>(??\{\ \.\.\.\ \}) a(??{})<Left><Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.match-if-&then<Tab>(?(\.\.)\.\.) a(?())<Left><Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.match-if-t&hen-else<Tab>(?(\.\.)\.\.\|\.\.) a(?()\|)<Left><Left><Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.-SEP11- :' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.look&ahead\ succeeds<Tab>(?=\ \.\.\.\ ) a(?=)<Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.looka&head\ fails<Tab>(?!\ \.\.\.\ ) a(?!)<Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.look&behind\ succeeds<Tab>(?<=\ \.\.\.\ ) a(?<=)<Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.lookb&ehind\ fails<Tab>(?<!\ \.\.\.\ ) a(?<!)<Left>' exe "anoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.&prohibit\ backtracking<Tab>(?>\ \.\.\.\ ) a(?>)<Left>' " exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.&comment<Tab>(?#\ \.\.\.\ ) (?#)<Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.cl&uster\ only\ paren\.<Tab>(?-imsx:\ \.\.\.\ ) (?-imsx:)<Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.pattern\ &modifier<Tab>(?-imsx) (?-imsx)<Left><Left><Left><Left><Left><Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.e&xecute\ code<Tab>(?\{\ \.\.\.\ \}) (?{})<Left><Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.match\ &regex\ from\ code<Tab>(??\{\ \.\.\.\ \}) (??{})<Left><Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.match-if-&then<Tab>(?(\.\.)\.\.) (?())<Left><Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.match-if-t&hen-else<Tab>(?(\.\.)\.\.\|\.\.) (?()\|)<Left><Left><Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.-SEP11- :' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.look&ahead\ succeeds<Tab>(?=\ \.\.\.\ ) (?=)<Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.looka&head\ fails<Tab>(?!\ \.\.\.\ ) (?!)<Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.look&behind\ succeeds<Tab>(?<=\ \.\.\.\ ) (?<=)<Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.lookb&ehind\ fails<Tab>(?<!\ \.\.\.\ ) (?<!)<Left>' exe "inoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.&prohibit\ backtracking<Tab>(?>\ \.\.\.\ ) (?>)<Left>' exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.&comment<Tab>(?#\ \.\.\.\ ) s(?#)<Esc>P' exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.cl&uster\ only\ paren\.<Tab>(?-imsx:\ \.\.\.\ ) s(?-imsx:)<Esc>P' " exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.e&xecute\ code<Tab>(?\{\ \.\.\.\ \}) s(?{})<Esc>hP' exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.match\ &regex\ from\ code<Tab>(??\{\ \.\.\.\ \}) s(??{})<Esc>hP' exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.match-if-&then<Tab>(?(\.\.)\.\.) s(?())<Esc>hPla' exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.match-if-t&hen-else<Tab>(?(\.\.)\.\.\|\.\.) s(?()\|)<Esc>3hlPla' exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.-SEP11- :' exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.look&ahead\ succeeds<Tab>(?=\ \.\.\.\ ) s(?=)<Esc>P' exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.looka&head\ fails<Tab>(?!\ \.\.\.\ ) s(?!)<Esc>P' exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.look&behind\ succeeds<Tab>(?<=\ \.\.\.\ ) s(?<=)<Esc>P' exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.lookb&ehind\ fails<Tab>(?<!\ \.\.\.\ ) s(?<!)<Esc>P' exe "vnoremenu ".g:Perl_Root.'Rege&x.e&xtended\ Regex.&prohibit\ backtracking<Tab>(?>\ \.\.\.\ ) s(?>)<Esc>P' " " exe " noremenu ".g:Perl_Root.'Rege&x.-SEP7- :' exe "amenu <silent> ".g:Perl_Root.'Rege&x.pick\ up\ &regex<Tab>\\xr :call perlsupportregex#Perl_RegexPick( "regexp", "n" )<CR>j' exe "amenu <silent> ".g:Perl_Root.'Rege&x.pick\ up\ s&tring<Tab>\\xs :call perlsupportregex#Perl_RegexPick( "string", "n" )<CR>j' exe "amenu <silent> ".g:Perl_Root.'Rege&x.pick\ up\ &flag(s)<Tab>\\xf :call perlsupportregex#Perl_RegexPickFlag( "n" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'Rege&x.pick\ up\ &regex<Tab>\\xr <C-C>:call perlsupportregex#Perl_RegexPick( "regexp", "v" )<CR>'."'>j" exe "vmenu <silent> ".g:Perl_Root.'Rege&x.pick\ up\ s&tring<Tab>\\xs <C-C>:call perlsupportregex#Perl_RegexPick( "string", "v" )<CR>'."'>j" exe "vmenu <silent> ".g:Perl_Root.'Rege&x.pick\ up\ &flag(s)<Tab>\\xf <C-C>:call perlsupportregex#Perl_RegexPickFlag( "v" )<CR>'."'>j" " exe "amenu <silent> ".g:Perl_Root.'Rege&x.&match<Tab>\\xm :call perlsupportregex#Perl_RegexVisualize( )<CR>' exe "amenu <silent> ".g:Perl_Root.'Rege&x.matc&h\ several\ targets<Tab>\\xmm :call perlsupportregex#Perl_RegexMatchSeveral( )<CR>' exe "amenu <silent> ".g:Perl_Root.'Rege&x.&explain\ regex<Tab>\\xe :call perlsupportregex#Perl_RegexExplain( "n" )<CR>' exe "vmenu <silent> ".g:Perl_Root.'Rege&x.&explain\ regex<Tab>\\xe <C-C>:call perlsupportregex#Perl_RegexExplain( "v" )<CR>' " "=============================================================================================== "----- Menu : File-Tests menu {{{2 "=============================================================================================== " exe "anoremenu ".g:Perl_Root.'&File-Tests.exists<Tab>-e a-e ' exe "anoremenu ".g:Perl_Root.'&File-Tests.has\ zero\ size<Tab>-z a-z ' exe "anoremenu ".g:Perl_Root.'&File-Tests.has\ nonzero\ size<Tab>-s a-s ' exe "anoremenu ".g:Perl_Root.'&File-Tests.plain\ file<Tab>-f a-f ' exe "anoremenu ".g:Perl_Root.'&File-Tests.directory<Tab>-d a-d ' exe "anoremenu ".g:Perl_Root.'&File-Tests.symbolic\ link<Tab>-l a-l ' exe "anoremenu ".g:Perl_Root.'&File-Tests.named\ pipe<Tab>-p a-p ' exe "anoremenu ".g:Perl_Root.'&File-Tests.socket<Tab>-S a-S ' exe "anoremenu ".g:Perl_Root.'&File-Tests.block\ special\ file<Tab>-b a-b ' exe "anoremenu ".g:Perl_Root.'&File-Tests.character\ special\ file<Tab>-c a-c ' exe "inoremenu ".g:Perl_Root.'&File-Tests.exists<Tab>-e -e ' exe "inoremenu ".g:Perl_Root.'&File-Tests.has\ zero\ size<Tab>-z -z ' exe "inoremenu ".g:Perl_Root.'&File-Tests.has\ nonzero\ size<Tab>-s -s ' exe "inoremenu ".g:Perl_Root.'&File-Tests.plain\ file<Tab>-f -f ' exe "inoremenu ".g:Perl_Root.'&File-Tests.directory<Tab>-d -d ' exe "inoremenu ".g:Perl_Root.'&File-Tests.symbolic\ link<Tab>-l -l ' exe "inoremenu ".g:Perl_Root.'&File-Tests.named\ pipe<Tab>-p -p ' exe "inoremenu ".g:Perl_Root.'&File-Tests.socket<Tab>-S -S ' exe "inoremenu ".g:Perl_Root.'&File-Tests.block\ special\ file<Tab>-b -b ' exe "inoremenu ".g:Perl_Root.'&File-Tests.character\ special\ file<Tab>-c -c ' " exe " menu ".g:Perl_Root.'&File-Tests.-SEP1- :' " exe "anoremenu ".g:Perl_Root.'&File-Tests.readable\ by\ eff\.\ UID/GID<Tab>-r a-r ' exe "anoremenu ".g:Perl_Root.'&File-Tests.writable\ by\ eff\.\ UID/GID<Tab>-w a-w ' exe "anoremenu ".g:Perl_Root.'&File-Tests.executable\ by\ eff\.\ UID/GID<Tab>-x a-x ' exe "anoremenu ".g:Perl_Root.'&File-Tests.owned\ by\ eff\.\ UID<Tab>-o a-o ' exe "inoremenu ".g:Perl_Root.'&File-Tests.readable\ by\ eff\.\ UID/GID<Tab>-r -r ' exe "inoremenu ".g:Perl_Root.'&File-Tests.writable\ by\ eff\.\ UID/GID<Tab>-w -w ' exe "inoremenu ".g:Perl_Root.'&File-Tests.executable\ by\ eff\.\ UID/GID<Tab>-x -x ' exe "inoremenu ".g:Perl_Root.'&File-Tests.owned\ by\ eff\.\ UID<Tab>-o -o ' " exe "anoremenu ".g:Perl_Root.'&File-Tests.-SEP2- :' " exe "anoremenu ".g:Perl_Root.'&File-Tests.readable\ by\ real\ UID/GID<Tab>-R a-R ' exe "anoremenu ".g:Perl_Root.'&File-Tests.writable\ by\ real\ UID/GID<Tab>-W a-W ' exe "anoremenu ".g:Perl_Root.'&File-Tests.executable\ by\ real\ UID/GID<Tab>-X a-X ' exe "anoremenu ".g:Perl_Root.'&File-Tests.owned\ by\ real\ UID<Tab>-O a-O ' exe "inoremenu ".g:Perl_Root.'&File-Tests.readable\ by\ real\ UID/GID<Tab>-R -R ' exe "inoremenu ".g:Perl_Root.'&File-Tests.writable\ by\ real\ UID/GID<Tab>-W -W ' exe "inoremenu ".g:Perl_Root.'&File-Tests.executable\ by\ real\ UID/GID<Tab>-X -X ' exe "inoremenu ".g:Perl_Root.'&File-Tests.owned\ by\ real\ UID<Tab>-O -O ' exe "anoremenu ".g:Perl_Root.'&File-Tests.-SEP3- :' exe "anoremenu ".g:Perl_Root.'&File-Tests.setuid\ bit\ set<Tab>-u a-u ' exe "anoremenu ".g:Perl_Root.'&File-Tests.setgid\ bit\ set<Tab>-g a-g ' exe "anoremenu ".g:Perl_Root.'&File-Tests.sticky\ bit\ set<Tab>-k a-k ' exe "inoremenu ".g:Perl_Root.'&File-Tests.setuid\ bit\ set<Tab>-u -u ' exe "inoremenu ".g:Perl_Root.'&File-Tests.setgid\ bit\ set<Tab>-g -g ' exe "inoremenu ".g:Perl_Root.'&File-Tests.sticky\ bit\ set<Tab>-k -k ' exe "inoremenu ".g:Perl_Root.'&File-Tests.-SEP4- :' exe "anoremenu ".g:Perl_Root.'&File-Tests.age\ since\ modification<Tab>-M a-M ' exe "anoremenu ".g:Perl_Root.'&File-Tests.age\ since\ last\ access<Tab>-A a-A ' exe "anoremenu ".g:Perl_Root.'&File-Tests.age\ since\ inode\ change<Tab>-C a-C ' exe "inoremenu ".g:Perl_Root.'&File-Tests.age\ since\ modification<Tab>-M -M ' exe "inoremenu ".g:Perl_Root.'&File-Tests.age\ since\ last\ access<Tab>-A -A ' exe "inoremenu ".g:Perl_Root.'&File-Tests.age\ since\ inode\ change<Tab>-C -C ' exe "inoremenu ".g:Perl_Root.'&File-Tests.-SEP5- :' exe "anoremenu ".g:Perl_Root.'&File-Tests.text\ file<Tab>-T a-T ' exe "anoremenu ".g:Perl_Root.'&File-Tests.binary\ file<Tab>-B a-B ' exe "anoremenu ".g:Perl_Root.'&File-Tests.handle\ opened\ to\ a\ tty<Tab>-t a-t ' exe "inoremenu ".g:Perl_Root.'&File-Tests.text\ file<Tab>-T -T ' exe "inoremenu ".g:Perl_Root.'&File-Tests.binary\ file<Tab>-B -B ' exe "inoremenu ".g:Perl_Root.'&File-Tests.handle\ opened\ to\ a\ tty<Tab>-t -t ' " "=============================================================================================== "----- Menu : Special-Variables menu {{{2 "=============================================================================================== " "-------- submenu errors ------------------------------------------------- " if g:Perl_MenuHeader == "yes" exe "amenu ".g:Perl_Root.'Spec-&Var.&errors.Spec-Var-1<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'Spec-&Var.&errors.-Sep0- :' exe "amenu ".g:Perl_Root.'Spec-&Var.&files.Spec-Var-2<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'Spec-&Var.&files.-Sep0- :' exe "amenu ".g:Perl_Root.'Spec-&Var.&IDs.Spec-Var-3<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'Spec-&Var.&IDs.-Sep0- :' exe "amenu ".g:Perl_Root.'Spec-&Var.I&O.Spec-Var-4<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'Spec-&Var.I&O.-Sep0- :' exe "amenu ".g:Perl_Root.'Spec-&Var.&regexp.Spec-Var-5<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'Spec-&Var.&regexp.-Sep0- :' endif " exe "anoremenu ".g:Perl_Root.'Spec-&Var.&errors.$CHILD_ERROR<Tab>$? a$CHILD_ERROR' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&errors.$ERRNO<Tab>$! a$ERRNO' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&errors.$EVAL_ERROR<Tab>$@ a$EVAL_ERROR' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&errors.$EXTENDED_OS_ERROR<Tab>$^E a$EXTENDED_OS_ERROR' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&errors.$WARNING<Tab>$^W a$WARNING' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&errors.$CHILD_ERROR<Tab>$? $CHILD_ERROR' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&errors.$ERRNO<Tab>$! $ERRNO' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&errors.$EVAL_ERROR<Tab>$@ $EVAL_ERROR' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&errors.$EXTENDED_OS_ERROR<Tab>$^E $EXTENDED_OS_ERROR' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&errors.$WARNING<Tab>$^W $WARNING' " "-------- submenu files ------------------------------------------------- " exe "anoremenu ".g:Perl_Root.'Spec-&Var.&files.$AUTOFLUSH<Tab>$\| a$AUTOFLUSH' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_LINES_LEFT<Tab>$- a$FORMAT_LINES_LEFT' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_LINES_PER_PAGE<Tab>$= a$FORMAT_LINES_PER_PAGE' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_LINE_BREAK_CHARACTER<Tab>$: a$FORMAT_LINES_PER_PAGE' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_NAME<Tab>$~ a$FORMAT_NAME' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_PAGE_NUMBER<Tab>$% a$FORMAT_PAGE_NUMBER' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_TOP_NAME<Tab>$^ a$FORMAT_TOP_NAME' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&files.$OUTPUT_AUTOFLUSH<Tab>$\| a$OUTPUT_AUTOFLUSH' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&files.$AUTOFLUSH<Tab>$\| $AUTOFLUSH' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_LINES_LEFT<Tab>$- $FORMAT_LINES_LEFT' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_LINES_PER_PAGE<Tab>$= $FORMAT_LINES_PER_PAGE' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_LINE_BREAK_CHARACTER<Tab>$: $FORMAT_LINES_PER_PAGE' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_NAME<Tab>$~ $FORMAT_NAME' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_PAGE_NUMBER<Tab>$% $FORMAT_PAGE_NUMBER' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&files.$FORMAT_TOP_NAME<Tab>$^ $FORMAT_TOP_NAME' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&files.$OUTPUT_AUTOFLUSH<Tab>$\| $OUTPUT_AUTOFLUSH' "-------- submenu IDs ------------------------------------------------- " exe "anoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$PID<Tab>$$ a$PID' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$PROCESS_ID<Tab>$$ a$PROCESS_ID' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$UID<Tab>$< a$UID' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$REAL_USER_ID<Tab>$< a$REAL_USER_ID' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$EUID<Tab>$> a$EUID' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$EFFECTIVE_USER_ID<Tab>$> a$EFFECTIVE_USER_ID' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$GID<Tab>$( a$GID' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$REAL_GROUP_ID<Tab>$( a$REAL_GROUP_ID' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$EGID<Tab>$) a$EGID' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$EFFECTIVE_GROUP_ID<Tab>$) a$EFFECTIVE_GROUP_ID' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$PID<Tab>$$ $PID' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$PROCESS_ID<Tab>$$ $PROCESS_ID' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$UID<Tab>$< $UID' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$REAL_USER_ID<Tab>$< $REAL_USER_ID' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$EUID<Tab>$> $EUID' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$EFFECTIVE_USER_ID<Tab>$> $EFFECTIVE_USER_ID' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$GID<Tab>$( $GID' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$REAL_GROUP_ID<Tab>$( $REAL_GROUP_ID' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$EGID<Tab>$) $EGID' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&IDs.$EFFECTIVE_GROUP_ID<Tab>$) $EFFECTIVE_GROUP_ID' "-------- submenu IO ------------------------------------------------- " exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$ARG<Tab>$_ a$ARG' exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$INPUT_LINE_NUMBER<Tab>$\. a$INPUT_LINE_NUMBER' exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$NR<Tab>$\. a$NR' exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$INPUT_RECORD_SEPARATOR<Tab>$/ a$INPUT_RECORD_SEPARATOR' exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$RS<Tab>$/ a$RS' exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$LIST_SEPARATOR<Tab>$" a$LIST_SEPARATOR' exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$OUTPUT_FIELD_SEPARATOR<Tab>$, a$OUTPUT_FIELD_SEPARATOR' exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$OFS<Tab>$, a$OFS' exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$OUTPUT_RECORD_SEPARATOR<Tab>$\\ a$OUTPUT_RECORD_SEPARATOR' exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$ORS<Tab>$\\ a$ORS' exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$SUBSCRIPT_SEPARATOR<Tab>$; a$SUBSCRIPT_SEPARATOR' exe "anoremenu ".g:Perl_Root.'Spec-&Var.I&O.$SUBSEP<Tab>$; a$SUBSEP' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$ARG<Tab>$_ $ARG' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$INPUT_LINE_NUMBER<Tab>$\. $INPUT_LINE_NUMBER' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$NR<Tab>$\. $NR' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$INPUT_RECORD_SEPARATOR<Tab>$/ $INPUT_RECORD_SEPARATOR' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$RS<Tab>$/ $RS' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$LIST_SEPARATOR<Tab>$" $LIST_SEPARATOR' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$OUTPUT_FIELD_SEPARATOR<Tab>$, $OUTPUT_FIELD_SEPARATOR' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$OFS<Tab>$, $OFS' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$OUTPUT_RECORD_SEPARATOR<Tab>$\\ $OUTPUT_RECORD_SEPARATOR' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$ORS<Tab>$\\ $ORS' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$SUBSCRIPT_SEPARATOR<Tab>$; $SUBSCRIPT_SEPARATOR' exe "inoremenu ".g:Perl_Root.'Spec-&Var.I&O.$SUBSEP<Tab>$; $SUBSEP' "-------- submenu regexp ------------------------------------------------- " exe "anoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$MATCH<Tab>$& a$MATCH' exe "anoremenu ".g:Perl_Root."Spec-&Var.&regexp.$POSTMATCH<Tab>$' a$POSTMATCH" exe "anoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$PREMATCH<Tab>$` a$PREMATCH' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$digits a$digits' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&regexp.@LAST_MATCH_END<Tab>@+ a@LAST_MATCH_END' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&regexp.@LAST_MATCH_START<Tab>@- a@LAST_MATCH_START' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$LAST_PAREN_MATCH<Tab>$+ a$LAST_PAREN_MATCH' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$LAST_SUBMATCH_RESULT<Tab>$^N a$LAST_SUBMATCH_RESULT' exe "anoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$LAST_REGEXP_CODE_RESULT<Tab>$^R a$LAST_REGEXP_CODE_RESULT' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$MATCH<Tab>$& $MATCH' exe "inoremenu ".g:Perl_Root."Spec-&Var.&regexp.$POSTMATCH<Tab>$' $POSTMATCH" exe "inoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$PREMATCH<Tab>$` $PREMATCH' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$digits $digits' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&regexp.@LAST_MATCH_END<Tab>@+ @LAST_MATCH_END' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&regexp.@LAST_MATCH_START<Tab>@- @LAST_MATCH_START' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$LAST_PAREN_MATCH<Tab>$+ $LAST_PAREN_MATCH' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$LAST_SUBMATCH_RESULT<Tab>$^N $LAST_SUBMATCH_RESULT' exe "inoremenu ".g:Perl_Root.'Spec-&Var.&regexp.$LAST_REGEXP_CODE_RESULT<Tab>$^R $LAST_REGEXP_CODE_RESULT' exe "anoremenu ".g:Perl_Root.'Spec-&Var.$BASETIME<Tab>$^T a$BASETIME' exe "anoremenu ".g:Perl_Root.'Spec-&Var.$PERL_VERSION<Tab>$^V a$PERL_VERSION' exe "anoremenu ".g:Perl_Root.'Spec-&Var.$PROGRAM_NAME<Tab>$0 a$PROGRAM_NAME' exe "anoremenu ".g:Perl_Root.'Spec-&Var.$OSNAME<Tab>$^O a$OSNAME' exe "anoremenu ".g:Perl_Root.'Spec-&Var.$SYSTEM_FD_MAX<Tab>$^F a$SYSTEM_FD_MAX' exe "anoremenu ".g:Perl_Root.'Spec-&Var.$ENV{\ } a$ENV{}<Left>' exe "anoremenu ".g:Perl_Root.'Spec-&Var.$INC{\ } a$INC{}<Left>' exe "anoremenu ".g:Perl_Root.'Spec-&Var.$SIG{\ } a$SIG{}<Left>' exe "inoremenu ".g:Perl_Root.'Spec-&Var.$BASETIME<Tab>$^T $BASETIME' exe "inoremenu ".g:Perl_Root.'Spec-&Var.$PERL_VERSION<Tab>$^V $PERL_VERSION' exe "inoremenu ".g:Perl_Root.'Spec-&Var.$PROGRAM_NAME<Tab>$0 $PROGRAM_NAME' exe "inoremenu ".g:Perl_Root.'Spec-&Var.$OSNAME<Tab>$^O $OSNAME' exe "inoremenu ".g:Perl_Root.'Spec-&Var.$SYSTEM_FD_MAX<Tab>$^F $SYSTEM_FD_MAX' exe "inoremenu ".g:Perl_Root.'Spec-&Var.$ENV{\ } $ENV{}<Left>' exe "inoremenu ".g:Perl_Root.'Spec-&Var.$INC{\ } $INC{}<Left>' exe "inoremenu ".g:Perl_Root.'Spec-&Var.$SIG{\ } $SIG{}<Left>' " "---------- submenu : POSIX signals -------------------------------------- " if g:Perl_MenuHeader == "yes" exe "amenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.Spec-Var-6<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.-Sep0- :' endif exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.HUP aHUP' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.INT aINT' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.QUIT aQUIT' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.ILL aILL' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.ABRT aABRT' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.FPE aFPE' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.KILL aKILL' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.SEGV aSEGV' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.PIPE aPIPE' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.ALRM aALRM' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.TERM aTERM' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.USR1 aUSR1' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.USR2 aUSR2' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.CHLD aCHLD' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.CONT aCONT' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.STOP aSTOP' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.TSTP aTSTP' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.TTIN aTTIN' exe "anoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.TTOU aTTOU' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.HUP HUP' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.INT INT' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.QUIT QUIT' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.ILL ILL' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.ABRT ABRT' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.FPE FPE' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.KILL KILL' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.SEGV SEGV' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.PIPE PIPE' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.ALRM ALRM' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.TERM TERM' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.USR1 USR1' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.USR2 USR2' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.CHLD CHLD' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.CONT CONT' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.STOP STOP' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.TSTP TSTP' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.TTIN TTIN' exe "inoremenu ".g:Perl_Root.'Spec-&Var.POSIX\ signals.TTOU TTOU' " exe "anoremenu ".g:Perl_Root.'Spec-&Var.-SEP2- :' exe "anoremenu ".g:Perl_Root."Spec-&Var.\'IGNORE\' a'IGNORE'" exe "anoremenu ".g:Perl_Root."Spec-&Var.\'DEFAULT\' a'DEFAULT'" exe "inoremenu ".g:Perl_Root."Spec-&Var.\'IGNORE\' 'IGNORE'" exe "inoremenu ".g:Perl_Root."Spec-&Var.\'DEFAULT\' 'DEFAULT'" exe "anoremenu ".g:Perl_Root.'Spec-&Var.-SEP3- :' exe "anoremenu ".g:Perl_Root.'Spec-&Var.use\ English; ouse English qw( -no_match_vars );<ESC>' " "=============================================================================================== "----- Menu : POD menu {{{2 "=============================================================================================== " exe "amenu ".g:Perl_Root.'&POD.=&pod\ /\ =cut :call Perl_InsertTemplate("pod.pod-cut")<CR>' exe "imenu ".g:Perl_Root.'&POD.=&pod\ /\ =cut <C-C>:call Perl_InsertTemplate("pod.pod-cut")<CR>' exe "vmenu ".g:Perl_Root.'&POD.=&pod\ /\ =cut <C-C>:call Perl_InsertTemplate("pod.pod-cut", "v")<CR>' " exe "amenu ".g:Perl_Root.'&POD.=c&ut :call Perl_InsertTemplate("pod.cut")<CR>' " exe "amenu ".g:Perl_Root.'&POD.=fo&r\ /\ =cut :call Perl_InsertTemplate("pod.for-cut")<CR>' exe "imenu ".g:Perl_Root.'&POD.=fo&r\ /\ =cut <C-C>:call Perl_InsertTemplate("pod.for-cut")<CR>' exe "vmenu ".g:Perl_Root.'&POD.=fo&r\ /\ =cut <C-C>:call Perl_InsertTemplate("pod.for-cut", "v")<CR>' " exe "amenu ".g:Perl_Root.'&POD.=begin\ &html\ /\ =end :call Perl_InsertTemplate("pod.html")<CR>' exe "amenu ".g:Perl_Root.'&POD.=begin\ &man\ /\ =end :call Perl_InsertTemplate("pod.man")<CR>' exe "amenu ".g:Perl_Root.'&POD.=begin\ &text\ /\ =end :call Perl_InsertTemplate("pod.text")<CR>' exe "imenu ".g:Perl_Root.'&POD.=begin\ &html\ /\ =end <C-C>:call Perl_InsertTemplate("pod.html")<CR>' exe "imenu ".g:Perl_Root.'&POD.=begin\ &man\ /\ =end <C-C>:call Perl_InsertTemplate("pod.man")<CR>' exe "imenu ".g:Perl_Root.'&POD.=begin\ &text\ /\ =end <C-C>:call Perl_InsertTemplate("pod.text")<CR>' exe "vmenu ".g:Perl_Root.'&POD.=begin\ &html\ /\ =end <C-C>:call Perl_InsertTemplate("pod.html", "v")<CR>' exe "vmenu ".g:Perl_Root.'&POD.=begin\ &man\ /\ =end <C-C>:call Perl_InsertTemplate("pod.man", "v")<CR>' exe "vmenu ".g:Perl_Root.'&POD.=begin\ &text\ /\ =end <C-C>:call Perl_InsertTemplate("pod.text", "v")<CR>' " exe "amenu ".g:Perl_Root.'&POD.=head&1 :call Perl_InsertTemplate("pod.head1")<CR>' exe "amenu ".g:Perl_Root.'&POD.=head&2 :call Perl_InsertTemplate("pod.head2")<CR>' exe "amenu ".g:Perl_Root.'&POD.=head&3 :call Perl_InsertTemplate("pod.head3")<CR>' exe "amenu ".g:Perl_Root.'&POD.-Sep1- :' " exe "amenu ".g:Perl_Root.'&POD.=&over\ \.\.\ =back :call Perl_InsertTemplate("pod.over-back")<CR>' exe "imenu ".g:Perl_Root.'&POD.=&over\ \.\.\ =back <C-C>:call Perl_InsertTemplate("pod.over-back")<CR>' exe "vmenu ".g:Perl_Root.'&POD.=&over\ \.\.\ =back <C-C>:call Perl_InsertTemplate("pod.over-back", "v")<CR>' " exe "amenu ".g:Perl_Root.'&POD.=item\ &* :call Perl_InsertTemplate("pod.item")<CR>' exe "amenu ".g:Perl_Root.'&POD.-Sep2- :' " if g:Perl_MenuHeader == "yes" exe "amenu ".g:Perl_Root.'&POD.in&visible\ POD.invisible\ POD<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&POD.in&visible\ POD.-Sep0- :' endif exe "amenu <silent> ".g:Perl_Root.'&POD.in&visible\ POD.&Improvement :call Perl_InsertTemplate("pod.invisible-pod-improvement")<CR>' exe "amenu <silent> ".g:Perl_Root.'&POD.in&visible\ POD.&Optimization :call Perl_InsertTemplate("pod.invisible-pod-optimization")<CR>' exe "amenu <silent> ".g:Perl_Root.'&POD.in&visible\ POD.&Rationale :call Perl_InsertTemplate("pod.invisible-pod-rationale")<CR>' exe "amenu <silent> ".g:Perl_Root.'&POD.in&visible\ POD.&Workaround :call Perl_InsertTemplate("pod.invisible-pod-workaround")<CR>' exe "vmenu <silent> ".g:Perl_Root.'&POD.in&visible\ POD.&Improvement <C-C>:call Perl_InsertTemplate("pod.invisible-pod-improvement")<CR>' exe "vmenu <silent> ".g:Perl_Root.'&POD.in&visible\ POD.&Optimization <C-C>:call Perl_InsertTemplate("pod.invisible-pod-optimization")<CR>' exe "vmenu <silent> ".g:Perl_Root.'&POD.in&visible\ POD.&Rationale <C-C>:call Perl_InsertTemplate("pod.invisible-pod-rationale")<CR>' exe "vmenu <silent> ".g:Perl_Root.'&POD.in&visible\ POD.&Workaround <C-C>:call Perl_InsertTemplate("pod.invisible-pod-workaround")<CR>' exe "amenu ".g:Perl_Root.'&POD.-Sep3- :' " "---------- submenu : Sequences -------------------------------------- " exe "anoremenu ".g:Perl_Root.'&POD.&B<>\ \ (bold) aB<><Left>' exe "anoremenu ".g:Perl_Root.'&POD.&C<>\ \ (literal) aC<><Left>' exe "anoremenu ".g:Perl_Root.'&POD.&E<>\ \ (escape) aE<><Left>' exe "anoremenu ".g:Perl_Root.'&POD.&F<>\ \ (filename) aF<><Left>' exe "anoremenu ".g:Perl_Root.'&POD.&I<>\ \ (italic) aI<><Left>' exe "anoremenu ".g:Perl_Root.'&POD.&L<>\ \ (link) aL<\|><Left><Left>' exe "anoremenu ".g:Perl_Root.'&POD.&S<>\ \ nonbr\.\ spaces) aS<><Left>' exe "anoremenu ".g:Perl_Root.'&POD.&X<>\ \ (index) aX<><Left>' exe "anoremenu ".g:Perl_Root.'&POD.&Z<>\ \ (zero-width) aZ<><Left>' " exe "inoremenu ".g:Perl_Root.'&POD.&B<>\ \ (bold) B<><Left>' exe "inoremenu ".g:Perl_Root.'&POD.&C<>\ \ (literal) C<><Left>' exe "inoremenu ".g:Perl_Root.'&POD.&E<>\ \ (escape) E<><Left>' exe "inoremenu ".g:Perl_Root.'&POD.&F<>\ \ (filename) F<><Left>' exe "inoremenu ".g:Perl_Root.'&POD.&I<>\ \ (italic) I<><Left>' exe "inoremenu ".g:Perl_Root.'&POD.&L<>\ \ (link) L<\|><Left><Left>' exe "inoremenu ".g:Perl_Root.'&POD.&S<>\ \ nonbr\.\ spaces) S<><Left>' exe "inoremenu ".g:Perl_Root.'&POD.&X<>\ \ (index) X<><Left>' exe "inoremenu ".g:Perl_Root.'&POD.&Z<>\ \ (zero-width) Z<><Left>' " exe "vnoremenu ".g:Perl_Root.'&POD.&B<>\ \ (bold) sB<><Esc>P2l' exe "vnoremenu ".g:Perl_Root.'&POD.&C<>\ \ (literal) sC<><Esc>P2l' exe "vnoremenu ".g:Perl_Root.'&POD.&E<>\ \ (escape) sE<><Esc>P2l' exe "vnoremenu ".g:Perl_Root.'&POD.&F<>\ \ (filename) sF<><Esc>P2l' exe "vnoremenu ".g:Perl_Root.'&POD.&I<>\ \ (italic) sI<><Esc>P2l' exe "vnoremenu ".g:Perl_Root.'&POD.&L<>\ \ (link) sL<\|><Esc>hPl' exe "vnoremenu ".g:Perl_Root.'&POD.&S<>\ \ nonbr\.\ spaces) sS<><Esc>P2l' exe "vnoremenu ".g:Perl_Root.'&POD.&X<>\ \ (index) sX<><Esc>P2l' exe "amenu ".g:Perl_Root.'&POD.-SEP4- :' exe "amenu <silent> ".g:Perl_Root.'&POD.run\ podchecker\ \ (&4)<Tab>\\pod\ :call Perl_PodCheck()<CR>' exe "amenu <silent> ".g:Perl_Root.'&POD.POD\ ->\ html\ \ (&5)<Tab>\\podh\ :call Perl_POD("html")<CR>' exe "amenu <silent> ".g:Perl_Root.'&POD.POD\ ->\ man\ \ (&6)<Tab>\\podm\ :call Perl_POD("man")<CR>' exe "amenu <silent> ".g:Perl_Root.'&POD.POD\ ->\ text\ \ (&7)<Tab>\\podt\ :call Perl_POD("text")<CR>' if executable('pod2pdf') == 1 exe "amenu <silent> ".g:Perl_Root.'&POD.POD\ ->\ pdf\ \ (&7) :call Perl_POD("pdf")<CR>' endif " "=============================================================================================== "----- Menu : Profiling {{{2 "=============================================================================================== " exe "amenu <silent> ".g:Perl_Root.'&Profiling.&SmallProf<Tab>\\rps.&run\ profiler<Tab>\\rps :call perlsupportprofiling#Perl_Smallprof()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&SmallProf<Tab>\\rps.sort\ report:\ &file\ name :call perlsupportprofiling#Perl_SmallProfSortQuickfix("file-name")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&SmallProf<Tab>\\rps.sort\ report:\ &line\ number :call perlsupportprofiling#Perl_SmallProfSortQuickfix("line-number")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&SmallProf<Tab>\\rps.sort\ report:\ line\ &count :call perlsupportprofiling#Perl_SmallProfSortQuickfix("line-count")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&SmallProf<Tab>\\rps.sort\ report:\ &wall\ time\ (time) :call perlsupportprofiling#Perl_SmallProfSortQuickfix("time")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&SmallProf<Tab>\\rps.sort\ report:\ &cpu\ time\ \ (ctime) :call perlsupportprofiling#Perl_SmallProfSortQuickfix("ctime")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&SmallProf<Tab>\\rps.open\ existing\ profiler\ results :call perlsupportprofiling#Perl_Smallprof_OpenQuickfix()<CR>' " if !s:MSWIN exe "amenu <silent> ".g:Perl_Root.'&Profiling.&FastProf<Tab>\\rpf.&run\ profiler<Tab>\\rpf :call perlsupportprofiling#Perl_Fastprof()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&FastProf<Tab>\\rpf.sort\ report:\ &file\ name :call perlsupportprofiling#Perl_FastProfSortQuickfix("file-name")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&FastProf<Tab>\\rpf.sort\ report:\ &line\ number :call perlsupportprofiling#Perl_FastProfSortQuickfix("line-number")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&FastProf<Tab>\\rpf.sort\ report:\ &time :call perlsupportprofiling#Perl_FastProfSortQuickfix("time")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&FastProf<Tab>\\rpf.sort\ report:\ line\ &count :call perlsupportprofiling#Perl_FastProfSortQuickfix("line-count")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&FastProf<Tab>\\rps.open\ existing\ profiler\ results :call perlsupportprofiling#Perl_FastProf_OpenQuickfix()<CR>' endif " exe "amenu <silent> ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.&run\ profiler<Tab>\\rpn :call perlsupportprofiling#Perl_NYTprof()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.-Sep4131- :' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.show\ &HTML\ file :call perlsupportprofiling#Perl_NYTprofReadHtml()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.-Sep4132- :' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.read\ &CSV\ file<Tab>\\rpnc :call perlsupportprofiling#Perl_NYTprofReadCSV("read","line")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.sort\ report:\ &file\ name :call perlsupportprofiling#Perl_NYTprofReadCSV("sort","file")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.sort\ report:\ &line\ number :call perlsupportprofiling#Perl_NYTprofReadCSV("sort","line")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.sort\ report:\ &time :call perlsupportprofiling#Perl_NYTprofReadCSV("sort","time")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.sort\ report:\ &calls :call perlsupportprofiling#Perl_NYTprofReadCSV("sort","calls")<CR>' exe "amenu <silent> ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.sort\ report:\ t&ime/call :call perlsupportprofiling#Perl_NYTprofReadCSV("sort","time_per_call")<CR>' " " "=============================================================================================== "----- Menu : Run menu {{{2 "=============================================================================================== " " run the script from the local directory " ( the one which is being edited; other versions may exist elsewhere ! ) " exe "amenu <silent> ".g:Perl_Root.'&Run.update,\ &run\ script<Tab>\\rr\ \ <C-F9> :call Perl_Run()<CR>' exe "amenu ".g:Perl_Root.'&Run.update,\ check\ &syntax<Tab>\\rs\ \ <A-F9> :call Perl_SyntaxCheck()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Run.cmd\.\ line\ &arg\.<Tab>\\ra\ \ <S-F9> :call Perl_Arguments()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Run.perl\ s&witches<Tab>\\rw :call Perl_PerlSwitches()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Run.run\ &make<Tab>\\rm :call Perl_Make()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Run.cmd\.\ line\ ar&g\.\ for\ make<Tab>\\rma :call Perl_MakeArguments()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Run.start\ &debugger<Tab>\\rd\ \ <F9> :call Perl_Debugger()<CR>' " " set execution rights for user only ( user may be root ! ) " if !s:MSWIN exe "amenu <silent> ".g:Perl_Root.'&Run.make\ script\ &executable<Tab>\\re :call Perl_MakeScriptExecutable()<CR>' endif exe "amenu ".g:Perl_Root.'&Run.-SEP2- :' exe "amenu <silent> ".g:Perl_Root.'&Run.show\ &installed\ Perl\ modules<Tab>\\ri :call Perl_perldoc_show_module_list()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Run.&generate\ Perl\ module\ list<Tab>\\rg :call Perl_perldoc_generate_module_list()<CR><CR>' " exe "amenu ".g:Perl_Root.'&Run.-SEP4- :' exe "amenu <silent> ".g:Perl_Root.'&Run.run\ perltid&y<Tab>\\ry :call Perl_Perltidy("n")<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Run.run\ perltid&y<Tab>\\ry <C-C>:call Perl_Perltidy("v")<CR>' " " exe "amenu ".g:Perl_Root.'&Run.-SEP3- :' exe "amenu <silent> ".g:Perl_Root.'&Run.run\ perl&critic<Tab>\\rc :call Perl_Perlcritic()<CR>' " if g:Perl_MenuHeader == "yes" exe "amenu <silent> ".g:Perl_Root.'&Run.perlcritic\ severity\ \ (&1).perlcritic :call Perl_Perlcritic()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Run.perlcritic\ severity\ \ (&1).severity :call Perl_Perlcritic()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Run.perlcritic\ severity\ \ (&1).-Sep5- :' endif let levelnumber = 1 for level in [ "brutal", "cruel", "harsh", "stern", "gentle" ] exe "amenu <silent> ".g:Perl_Root.'&Run.perlcritic\ severity\ \ (&1).&'.level.'<Tab>(='.levelnumber.') :call Perl_PerlCriticSeverity("'.level.'")<CR>' let levelnumber = levelnumber+1 endfor " if g:Perl_MenuHeader == "yes" exe "amenu <silent> ".g:Perl_Root.'&Run.perlcritic\ &verbosity.perlcritic :call Perl_Perlcritic()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Run.perlcritic\ &verbosity.verbosity :call Perl_Perlcritic()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Run.perlcritic\ &verbosity.-Sep6- :' endif for level in [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ] exe "amenu <silent> ".g:Perl_Root.'&Run.perlcritic\ &verbosity.&'.level.' :call Perl_PerlCriticVerbosity('.level.')<CR>' endfor exe "amenu ".g:Perl_Root.'&Run.-SEP5- :' exe "amenu <silent> ".g:Perl_Root.'&Run.save\ buffer\ with\ &timestamp<Tab>\\rt :call Perl_SaveWithTimestamp()<CR>' exe "amenu <silent> ".g:Perl_Root.'&Run.&hardcopy\ to\ FILENAME\.ps<Tab>\\rh :call Perl_Hardcopy("n")<CR>' exe "vmenu <silent> ".g:Perl_Root.'&Run.&hardcopy\ to\ FILENAME\.ps<Tab>\\rh <C-C>:call Perl_Hardcopy("v")<CR>' exe "amenu ".g:Perl_Root.'&Run.-SEP6- :' exe "amenu <silent> ".g:Perl_Root.'&Run.settings\ and\ hot\ &keys<Tab>\\rk :call Perl_Settings()<CR>' " if !s:MSWIN exe "amenu <silent> ".g:Perl_Root.'&Run.&xterm\ size<Tab>\\rx :call Perl_XtermSize()<CR>' endif if g:Perl_OutputGvim == "vim" exe "amenu <silent> ".g:Perl_Root.'&Run.&output:\ VIM->buffer->xterm<Tab>\\ro :call Perl_Toggle_Gvim_Xterm()<CR>' else if g:Perl_OutputGvim == "buffer" exe "amenu <silent> ".g:Perl_Root.'&Run.&output:\ BUFFER->xterm->vim<Tab>\\ro :call Perl_Toggle_Gvim_Xterm()<CR>' else exe "amenu <silent> ".g:Perl_Root.'&Run.&output:\ XTERM->vim->buffer<Tab>\\ro :call Perl_Toggle_Gvim_Xterm()<CR>' endif endif " "=============================================================================================== "----- Menu : help menu {{{2 "=============================================================================================== " exe "amenu <silent> ".g:Perl_Root.'read\ &perldoc<Tab><S-F1>\ \ \\h :call Perl_perldoc()<CR><CR>' exe "amenu <silent> ".g:Perl_Root.'&help\ \(plugin\)<Tab>\\hp :call Perl_HelpPerlsupport()<CR>' " endfunction " ---------- end of function Perl_InitMenu ---------- "------------------------------------------------------------------------------ " Perl Menu Header Initialization {{{1 "------------------------------------------------------------------------------ function! Perl_InitMenuHeader () exe "amenu ".g:Perl_Root.'Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'-Sep0- :' exe "amenu ".g:Perl_Root.'&Comments.&Comments<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&Comments.-Sep0- :' exe "amenu ".g:Perl_Root.'&Statements.&Statements<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&Statements.-Sep0- :' exe "amenu ".g:Perl_Root.'&Idioms.&Idioms<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&Idioms.-Sep0- :' exe "amenu ".g:Perl_Root.'S&nippets.S&nippets<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'S&nippets.-Sep0- :' exe "amenu ".g:Perl_Root.'Rege&x.Rege&x<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'Rege&x.-Sep0- :' exe "amenu ".g:Perl_Root.'&File-Tests.&File-Tests<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&File-Tests.-Sep0- :' exe "amenu ".g:Perl_Root.'Spec-&Var.Spec-&Var<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'Spec-&Var.-Sep0- :' exe "amenu ".g:Perl_Root.'&POD.&POD<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&POD.-Sep0- :' exe "amenu ".g:Perl_Root.'&Profiling.Profiling :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&Profiling.-Sep41- :' exe "amenu ".g:Perl_Root.'&Profiling.&SmallProf<Tab>\\rps.SmallProf :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&Profiling.&SmallProf<Tab>\\rps.-Sep411- :' if !s:MSWIN exe "amenu ".g:Perl_Root.'&Profiling.&FastProf<Tab>\\rpf.FastProf :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&Profiling.&FastProf<Tab>\\rpf.-Sep412- :' endif exe "amenu ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.NYTProf :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&Profiling.&NYTProf<Tab>\\rpn.-Sep413- :' exe "amenu ".g:Perl_Root.'&Run.&Run<Tab>Perl :call Perl_MenuTitle()<CR>' exe "amenu ".g:Perl_Root.'&Run.-Sep0- :' endfunction " ---------- end of function Perl_InitMenuHeader ---------- function! Perl_MenuTitle () echo "This is a menu title." endfunction " ---------- end of function Perl_MenuTitle ---------- " " vim: tabstop=2 shiftwidth=2 foldmethod=marker
00000svn-vim-cfg
trunk/vimfiles/autoload/perlsupportgui.vim
Vim Script
gpl3
80,191
" Vim color file " Maintainer: Tiza " Last Change: 2002/08/28 Wed 00:28. " version: 1.3 " This color scheme uses a light background. set background=light hi clear if exists("syntax_on") syntax reset endif let colors_name = "fruit" hi Normal guifg=#404040 guibg=#f8f8f8 " Search hi IncSearch gui=UNDERLINE guifg=#404040 guibg=#40ffff hi Search gui=NONE guifg=#404040 guibg=#ffff60 " Messages hi ErrorMsg gui=NONE guifg=#ff0000 guibg=#ffe4e4 hi WarningMsg gui=NONE guifg=#ff0000 guibg=#ffe4e4 hi ModeMsg gui=NONE guifg=#ff4080 guibg=NONE hi MoreMsg gui=NONE guifg=#009070 guibg=NONE hi Question gui=NONE guifg=#f030d0 guibg=NONE " Split area hi StatusLine gui=BOLD guifg=#f8f8f8 guibg=#404040 hi StatusLineNC gui=NONE guifg=#a4a4a4 guibg=#404040 hi VertSplit gui=NONE guifg=#f8f8f8 guibg=#404040 hi WildMenu gui=BOLD guifg=#f8f8f8 guibg=#ff4080 " Diff hi DiffText gui=NONE guifg=#e04040 guibg=#ffd8d8 hi DiffChange gui=NONE guifg=#408040 guibg=#d0f0d0 hi DiffDelete gui=NONE guifg=#4848ff guibg=#ffd0ff hi DiffAdd gui=NONE guifg=#4848ff guibg=#ffd0ff " Cursor hi Cursor gui=NONE guifg=#0000ff guibg=#00e0ff hi lCursor gui=NONE guifg=#f8f8f8 guibg=#8000ff hi CursorIM gui=NONE guifg=#f8f8f8 guibg=#8000ff " Fold hi Folded gui=NONE guifg=#20605c guibg=#b8e8dc hi FoldColumn gui=NONE guifg=#40a098 guibg=#f0f0f0 " Other hi Directory gui=NONE guifg=#0070b8 guibg=NONE hi LineNr gui=NONE guifg=#acacac guibg=NONE hi NonText gui=BOLD guifg=#00a0c0 guibg=#ececec hi SpecialKey gui=NONE guifg=#4040ff guibg=NONE hi Title gui=NONE guifg=#0050a0 guibg=#c0e8ff hi Visual gui=NONE guifg=#484848 guibg=#e0e0e0 " hi VisualNOS gui=NONE guifg=#484848 guibg=#e0e0e0 " Syntax group hi Comment gui=NONE guifg=#ff4080 guibg=NONE hi Constant gui=NONE guifg=#8016ff guibg=NONE hi Error gui=BOLD guifg=#ffffff guibg=#ff4080 hi Identifier gui=NONE guifg=#008888 guibg=NONE hi Ignore gui=NONE guifg=#f8f8f8 guibg=NONE hi PreProc gui=NONE guifg=#e06800 guibg=NONE hi Special gui=NONE guifg=#4a9400 guibg=NONE hi Statement gui=NONE guifg=#f030d0 guibg=NONE hi Todo gui=UNDERLINE guifg=#ff0070 guibg=#ffe0f4 hi Type gui=NONE guifg=#0070e6 guibg=NONE hi Underlined gui=UNDERLINE guifg=fg guibg=NONE
00000svn-vim-cfg
trunk/vimfiles/colors/rainbow_fruit.vim
Vim Script
gpl3
2,423
" Vim color file " Maintainer: Gergely Kontra <kgergely@mcl.hu> " Last Change: 2002. 04. 09. " I'm a bit red-blind, so if you have suggestions, don't hesitate :) " ^^^^^^^^^ Sorry, I cannot speak English well, just want to say, " that in some rare cases I cannot distinguish between some colors " (I've just realized it, when I see some special tests) set background=light hi clear if exists("syntax_on") syntax reset endif "colorscheme default let g:colors_name = "scite" " hardcoded colors : " GUI "highlight Normal guifg=#7F6F5F guibg=#eeeeee "highlight Normal guifg=#7F6F5F guibg=#ffffff highlight Normal guifg=#7F6F5F guibg=NONE highlight Search guibg=#bbbbbb gui=bold highlight Visual guifg=#DADADA highlight Folded guifg=#ffffff guibg=#666666 highlight Cursor guifg=#666666 guibg=#000000 gui=bold highlight Special guifg=#7F007F guibg=#eeeeff gui=bold highlight Comment guifg=#007F00 guibg=#eeeeee highlight StatusLine guifg=#000000 guibg=#aacccc highlight StatusLineNC guifg=#557777 guibg=#ffffff highlight Statement guifg=#007F7F gui=bold highlight Type guifg=#0000ff gui=NONE highlight Function guifg=#007F7F gui=bold highlight LineNr guifg=#000000 guibg=#bbbbbb highlight FoldColumn guifg=#000000 guibg=#dddddd highlight Define guifg=#00007F guibg=#ddddff gui=bold highlight Number guifg=#000000 guibg=#eeffff gui=bold highlight Subtitle guifg=#000000 guibg=#66bbbb gui=bold,underline highlight String guifg=#7F007F guibg=#ffdddd highlight Delimiter guifg=#000000 guibg=#dde0dd gui=bold highlight PreProc guifg=#0000ff guibg=#ffffff gui=bold highlight Constant guifg=#000000 guibg=#aaaaaa gui=underline,bold "{{{ "}}}
00000svn-vim-cfg
trunk/vimfiles/colors/scite.vim
Vim Script
gpl3
1,674
" Vim color file " Maintainer: Jani Nurminen <slinky@iki.fi> " Last Change: $Id: zenburn.vim,v 2.3 2008/07/30 17:34:37 slinky Exp $ " URL: http://slinky.imukuppi.org/zenburnpage/ " License: GPL " " Nothing too fancy, just some alien fruit salad to keep you in the zone. " This syntax file was designed to be used with dark environments and " low light situations. Of course, if it works during a daybright office, go " ahead :) " " Owes heavily to other Vim color files! With special mentions " to "BlackDust", "Camo" and "Desert". " " To install, copy to ~/.vim/colors directory. Then :colorscheme zenburn. " See also :help syntax " " Credits: " - Jani Nurminen - original Zenburn " - Steve Hall & Cream posse - higher-contrast Visual selection " - Kurt Maier - 256 color console coloring, low and high contrast toggle, " bug fixing " - Charlie - spotted too bright StatusLine in non-high contrast mode " - Pablo Castellazzi - CursorLine fix for 256 color mode " " CONFIGURABLE PARAMETERS: " " You can use the default (don't set any parameters), or you can " set some parameters to tweak the Zenburn colours. " " * You can now set a darker background for bright environments. To activate, use: " contrast Zenburn, use: " " let g:zenburn_high_Contrast = 1 " " * To get more contrast to the Visual selection, use " " let g:zenburn_alternate_Visual = 1 " " * To use alternate colouring for Error message, use " " let g:zenburn_alternate_Error = 1 " " * The new default for Include is a duller orange. To use the original " colouring for Include, use " " let g:zenburn_alternate_Include = 1 " " * To turn the parameter(s) back to defaults, use UNLET: " " unlet g:zenburn_alternate_Include " " Setting to 0 won't work! " " That's it, enjoy! " " TODO " - Visual alternate color is broken? Try GVim >= 7.0.66 if you have trouble " - IME colouring (CursorIM) set background=dark hi clear if exists("syntax_on") syntax reset endif let g:colors_name="zenburn" hi Boolean guifg=#dca3a3 hi Character guifg=#dca3a3 gui=bold hi Comment guifg=#7f9f7f gui=italic hi Conditional guifg=#f0dfaf gui=bold hi Constant guifg=#dca3a3 gui=bold hi Cursor guifg=#000d18 guibg=#8faf9f gui=bold hi Debug guifg=#bca3a3 gui=bold hi Define guifg=#ffcfaf gui=bold hi Delimiter guifg=#8f8f8f hi DiffAdd guifg=#709080 guibg=#313c36 gui=bold hi DiffChange guibg=#333333 hi DiffDelete guifg=#333333 guibg=#464646 hi DiffText guifg=#ecbcbc guibg=#41363c gui=bold hi Directory guifg=#dcdccc gui=bold hi ErrorMsg guifg=#80d4aa guibg=#2f2f2f gui=bold hi Exception guifg=#c3bf9f gui=bold hi Float guifg=#c0bed1 hi FoldColumn guifg=#93b3a3 guibg=#3f4040 hi Folded guifg=#93b3a3 guibg=#3f4040 hi Function guifg=#efef8f hi Identifier guifg=#efdcbc hi IncSearch guibg=#f8f893 guifg=#385f38 hi Keyword guifg=#f0dfaf gui=bold hi Label guifg=#dfcfaf gui=underline hi LineNr guifg=#9fafaf guibg=#262626 hi Macro guifg=#ffcfaf gui=bold hi ModeMsg guifg=#ffcfaf gui=none hi MoreMsg guifg=#ffffff gui=bold hi NonText guifg=#404040 hi Number guifg=#8cd0d3 hi Operator guifg=#f0efd0 hi PreCondit guifg=#dfaf8f gui=bold hi PreProc guifg=#ffcfaf gui=bold hi Question guifg=#ffffff gui=bold hi Repeat guifg=#ffd7a7 gui=bold hi Search guifg=#ffffe0 guibg=#284f28 hi SpecialChar guifg=#dca3a3 gui=bold hi SpecialComment guifg=#82a282 gui=bold hi Special guifg=#cfbfaf hi SpecialKey guifg=#9ece9e hi Statement guifg=#e3ceab gui=none hi StatusLine guifg=#313633 guibg=#ccdc90 hi StatusLineNC guifg=#2e3330 guibg=#88b090 hi StorageClass guifg=#c3bf9f gui=bold hi String guifg=#cc9393 hi Structure guifg=#efefaf gui=bold hi Tag guifg=#e89393 gui=bold hi Title guifg=#efefef gui=bold hi Todo guifg=#dfdfdf guibg=bg gui=bold hi Typedef guifg=#dfe4cf gui=bold hi Type guifg=#dfdfbf gui=bold hi Underlined guifg=#dcdccc gui=underline hi VertSplit guifg=#2e3330 guibg=#688060 hi VisualNOS guifg=#333333 guibg=#f18c96 gui=bold,underline hi WarningMsg guifg=#ffffff guibg=#333333 gui=bold hi WildMenu guibg=#2c302d guifg=#cbecd0 gui=underline hi SpellBad guisp=#bc6c4c guifg=#dc8c6c hi SpellCap guisp=#6c6c9c guifg=#8c8cbc hi SpellRare guisp=#bc6c9c guifg=#bc8cbc hi SpellLocal guisp=#7cac7c guifg=#9ccc9c " Entering Kurt zone if &t_Co > 255 hi Boolean ctermfg=181 hi Character ctermfg=181 cterm=bold hi Comment ctermfg=108 hi Conditional ctermfg=223 cterm=bold hi Constant ctermfg=181 cterm=bold hi Cursor ctermfg=233 ctermbg=109 cterm=bold hi Debug ctermfg=181 cterm=bold hi Define ctermfg=223 cterm=bold hi Delimiter ctermfg=245 hi DiffAdd ctermfg=66 ctermbg=237 cterm=bold hi DiffChange ctermbg=236 hi DiffDelete ctermfg=236 ctermbg=238 hi DiffText ctermfg=217 ctermbg=237 cterm=bold hi Directory ctermfg=188 cterm=bold hi ErrorMsg ctermfg=115 ctermbg=236 cterm=bold hi Exception ctermfg=249 cterm=bold hi Float ctermfg=251 hi FoldColumn ctermfg=109 ctermbg=238 hi Folded ctermfg=109 ctermbg=238 hi Function ctermfg=228 hi Identifier ctermfg=223 hi IncSearch ctermbg=228 ctermfg=238 hi Keyword ctermfg=223 cterm=bold hi Label ctermfg=187 cterm=underline hi LineNr ctermfg=248 ctermbg=235 hi Macro ctermfg=223 cterm=bold hi ModeMsg ctermfg=223 cterm=none hi MoreMsg ctermfg=15 cterm=bold hi NonText ctermfg=238 hi Number ctermfg=116 hi Operator ctermfg=230 hi PreCondit ctermfg=180 cterm=bold hi PreProc ctermfg=223 cterm=bold hi Question ctermfg=15 cterm=bold hi Repeat ctermfg=223 cterm=bold hi Search ctermfg=230 ctermbg=236 hi SpecialChar ctermfg=181 cterm=bold hi SpecialComment ctermfg=108 cterm=bold hi Special ctermfg=181 hi SpecialKey ctermfg=151 hi Statement ctermfg=187 ctermbg=234 cterm=none hi StatusLine ctermfg=236 ctermbg=186 hi StatusLineNC ctermfg=235 ctermbg=108 hi StorageClass ctermfg=249 cterm=bold hi String ctermfg=174 hi Structure ctermfg=229 cterm=bold hi Tag ctermfg=181 cterm=bold hi Title ctermfg=7 ctermbg=234 cterm=bold hi Todo ctermfg=108 ctermbg=234 cterm=bold hi Typedef ctermfg=253 cterm=bold hi Type ctermfg=187 cterm=bold hi Underlined ctermfg=188 ctermbg=234 cterm=bold hi VertSplit ctermfg=236 ctermbg=65 hi VisualNOS ctermfg=236 ctermbg=210 cterm=bold hi WarningMsg ctermfg=15 ctermbg=236 cterm=bold hi WildMenu ctermbg=236 ctermfg=194 cterm=bold hi CursorLine ctermbg=236 cterm=none if exists("g:zenburn_high_Contrast") hi Normal ctermfg=188 ctermbg=234 else hi Normal ctermfg=188 ctermbg=237 hi Cursor ctermbg=109 hi diffadd ctermbg=237 hi diffdelete ctermbg=238 hi difftext ctermbg=237 hi errormsg ctermbg=237 hi foldcolumn ctermbg=238 hi folded ctermbg=238 hi incsearch ctermbg=228 hi linenr ctermbg=238 hi search ctermbg=238 hi statement ctermbg=237 hi statusline ctermbg=144 hi statuslinenc ctermbg=108 hi title ctermbg=237 hi todo ctermbg=237 hi underlined ctermbg=237 hi vertsplit ctermbg=65 hi visualnos ctermbg=210 hi warningmsg ctermbg=236 hi wildmenu ctermbg=236 endif endif if exists("g:zenburn_high_Contrast") " use new darker background hi Normal guifg=#dcdccc guibg=#1f1f1f hi CursorLine guibg=#121212 gui=bold hi Pmenu guibg=#242424 guifg=#ccccbc hi PMenuSel guibg=#353a37 guifg=#ccdc90 gui=bold hi PmenuSbar guibg=#2e3330 guifg=#000000 hi PMenuThumb guibg=#a0afa0 guifg=#040404 hi MatchParen guifg=#f0f0c0 guibg=#383838 gui=bold hi SignColumn guifg=#9fafaf guibg=#181818 gui=bold hi TabLineFill guifg=#cfcfaf guibg=#181818 gui=bold hi TabLineSel guifg=#efefef guibg=#1c1c1b gui=bold hi TabLine guifg=#b6bf98 guibg=#181818 gui=bold hi CursorColumn guifg=#dcdccc guibg=#2b2b2b else " Original, lighter background hi Normal guifg=#dcdccc guibg=#3f3f3f hi CursorLine guibg=#434443 hi Pmenu guibg=#2c2e2e guifg=#9f9f9f hi PMenuSel guibg=#242424 guifg=#d0d0a0 gui=bold hi PmenuSbar guibg=#2e3330 guifg=#000000 hi PMenuThumb guibg=#a0afa0 guifg=#040404 hi MatchParen guifg=#b2b2a0 guibg=#2e2e2e gui=bold hi SignColumn guifg=#9fafaf guibg=#343434 gui=bold hi TabLineFill guifg=#cfcfaf guibg=#353535 gui=bold hi TabLineSel guifg=#efefef guibg=#3a3a39 gui=bold hi TabLine guifg=#b6bf98 guibg=#353535 gui=bold hi CursorColumn guifg=#dcdccc guibg=#4f4f4f endif if exists("g:zenburn_alternate_Visual") " Visual with more contrast, thanks to Steve Hall & Cream posse " gui=none fixes weird highlight problem in at least GVim 7.0.66, thanks to Kurt Maier hi Visual guifg=#000000 guibg=#71d3b4 gui=none hi VisualNOS guifg=#000000 guibg=#71d3b4 gui=none else " use default visual hi Visual guifg=#233323 guibg=#71d3b4 gui=none hi VisualNOS guifg=#233323 guibg=#71d3b4 gui=none endif if exists("g:zenburn_alternate_Error") " use a bit different Error hi Error guifg=#ef9f9f guibg=#201010 gui=bold else " default hi Error guifg=#e37170 guibg=#332323 gui=none endif if exists("g:zenburn_alternate_Include") " original setting hi Include guifg=#ffcfaf gui=bold else " new, less contrasted one hi Include guifg=#dfaf8f gui=bold endif " TODO check for more obscure syntax groups that they're ok
00000svn-vim-cfg
trunk/vimfiles/colors/zenburn.vim
Vim Script
gpl3
10,831
" LIGHT colorscheme. The purpose of this colorscheme is to make small " adjustments to the default. " Restore default colors hi clear set background=light if exists("syntax_on") syntax reset endif let g:colors_name = "LightDefault" "hi Normal guifg=black guibg=#D6D3CE hi Normal guifg=black guibg=ivory3 hi NonText guibg=#BDBDB1 " slightly darker than ivory3 hi Constant guifg=Magenta3 hi WarningMsg gui=bold hi Search guibg=Yellow2 hi Function guifg=IndianRed
00000svn-vim-cfg
trunk/vimfiles/colors/LightDefault.vim
Vim Script
gpl3
471
" Vim color file " Maintainer: Juan frias <juandfrias at gmail dot com> " Last Change: 2007 Feb 25 " Version: 1.0.1 " URL: http://www.axisym3.net/jdany/vim-the-editor/#eclipse set background=light highlight clear if exists("syntax_on") syntax reset endif let g:colors_name = "eclipse" highlight Normal gui=none guifg=#000000 guibg=#ffffff ctermfg=Gray " Search highlight IncSearch gui=underline guifg=#404040 guibg=#e0e040 highlight Search gui=none guifg=#544060 guibg=#f0c0ff ctermbg=1 " Messages highlight ErrorMsg gui=none guifg=#f8f8f8 guibg=#4040ff highlight WarningMsg gui=none guifg=#f8f8f8 guibg=#4040ff highlight ModeMsg gui=none guifg=#d06000 guibg=bg highlight MoreMsg gui=none guifg=#0090a0 guibg=bg highlight Question gui=none guifg=#8000ff guibg=bg " Split area highlight StatusLine gui=none guifg=#ffffff guibg=#4570aa cterm=bold ctermbg=blue ctermfg=white highlight StatusLineNC gui=none guifg=#ffffff guibg=#75a0da cterm=none ctermfg=darkgrey ctermbg=blue highlight VertSplit gui=none guifg=#f8f8f8 guibg=#904838 ctermfg=darkgrey cterm=none ctermbg=blue highlight WildMenu gui=none guifg=#f8f8f8 guibg=#ff3030 " Diff highlight DiffText gui=none guifg=red guibg=#ffd0d0 cterm=bold ctermbg=5 ctermfg=3 highlight DiffChange gui=none guifg=black guibg=#ffe7e7 cterm=none ctermbg=5 ctermfg=7 highlight DiffDelete gui=none guifg=bg guibg=#e7e7ff ctermbg=black highlight DiffAdd gui=none guifg=blue guibg=#e7e7ff ctermbg=green cterm=bold " Cursor highlight Cursor gui=none guifg=#ffffff guibg=#0080f0 highlight lCursor gui=none guifg=#ffffff guibg=#8040ff highlight CursorIM gui=none guifg=#ffffff guibg=#8040ff " Fold highlight Folded gui=none guifg=#804030 guibg=#fff0d0 ctermbg=black ctermfg=black cterm=bold highlight FoldColumn gui=none guifg=#6b6b6b guibg=#e7e7e7 ctermfg=black ctermbg=white " Popup Menu highlight PMenu ctermbg=green ctermfg=white highlight PMenuSel ctermbg=white ctermfg=black highlight PMenuSBar ctermbg=red ctermfg=white highlight PMenuThumb ctermbg=white ctermfg=red " Other highlight Directory gui=none guifg=#7050ff guibg=bg highlight LineNr gui=none guifg=#6b6b6b guibg=#eeeeee highlight NonText gui=none guifg=#707070 guibg=#e7e7e7 highlight SpecialKey gui=none guifg=#c0c0c0 guibg=bg cterm=none ctermfg=4 highlight Title gui=bold guifg=#0033cc guibg=bg highlight Visual gui=none guifg=#804020 guibg=#ffc0a0 ctermfg=DarkCyan " Syntax group highlight Comment gui=none guifg=#236e25 guibg=bg ctermfg=2 highlight Constant gui=none guifg=#00884c guibg=bg ctermfg=White highlight Error gui=none guifg=#f8f8f8 guibg=#4040ff term=reverse ctermbg=Red ctermfg=White highlight Identifier gui=none guifg=#b07800 guibg=bg ctermfg=Green highlight Ignore gui=none guifg=bg guibg=bg ctermfg=black highlight PreProc gui=none guifg=#683821 guibg=bg ctermfg=Green highlight Special gui=none guifg=#8040f0 guibg=bg ctermfg=DarkMagenta highlight Statement gui=none guifg=#b64f90 guibg=bg ctermfg=White highlight Todo gui=none guifg=#ff5050 guibg=white term=standout ctermbg=Yellow ctermfg=Black highlight Type gui=bold guifg=#7f0055 guibg=bg ctermfg=LightGreen highlight Underlined gui=none guifg=blue guibg=bg highlight String gui=none guifg=#8010a0 guibg=bg ctermfg=Yellow highlight Number gui=none guifg=#0000ff guibg=bg ctermfg=White if !has("gui_running") hi link Float Number hi link Conditional Repeat hi link Include PreProc hi link Macro PreProc hi link PreCondit PreProc hi link StorageClass Type hi link Structure Type hi link Typedef Type hi link Tag Special hi link Delimiter Normal hi link SpecialComment Special hi link Debug Special endif " vim:ff=unix:
00000svn-vim-cfg
trunk/vimfiles/colors/eclipse.vim
Vim Script
gpl3
4,052
" Vim color file " Maintainer: Bryant Casteel " Web Site: http://bethings.provoplatinum.com " Last Change: 2004 Jan. 22 " turbo -- Intended to look like the color scheme " from Borland's Turbo C++ and Turbo Pascal. set bg=dark hi clear if exists("syntax_on") syntax reset endif let colors_name = "turbo" hi Normal guifg=yellow guibg=#000040 ctermfg=yellow ctermbg=black hi ErrorMsg guifg=#ffffff guibg=#287eff ctermfg=white ctermbg=lightblue hi Visual guifg=#8080ff guibg=fg gui=reverse ctermfg=lightblue ctermbg=fg cterm=reverse hi VisualNOS guifg=#8080ff guibg=fg gui=reverse,underline ctermfg=lightblue ctermbg=fg cterm=reverse,underline hi Todo guifg=#d14a14 guibg=#1248d1 ctermfg=red ctermbg=darkblue hi Search guifg=#90fff0 guibg=#2050d0 ctermfg=white ctermbg=darkblue cterm=underline hi IncSearch guifg=#b0ffff guibg=#2050d0 ctermfg=darkblue ctermbg=gray hi SpecialKey guifg=cyan ctermfg=darkcyan hi Directory guifg=cyan ctermfg=cyan hi Title guifg=magenta gui=none ctermfg=magenta cterm=bold hi WarningMsg guifg=red ctermfg=red hi WildMenu guifg=yellow guibg=black ctermfg=yellow ctermbg=black cterm=none hi ModeMsg guifg=#22cce2 ctermfg=lightblue hi MoreMsg guifg=darkgreen ctermfg=darkgreen hi Question guifg=green gui=none ctermfg=green cterm=none hi NonText guifg=#0030ff ctermfg=darkblue " Split window status bar hi StatusLine guifg=blue guibg=yellow gui=none ctermfg=blue ctermbg=gray cterm=none hi StatusLineNC guifg=black guibg=green gui=none ctermfg=black ctermbg=gray cterm=none hi VertSplit guifg=black guibg=orange gui=none ctermfg=black ctermbg=gray cterm=none " Folded code hi Folded guifg=#808080 guibg=#000040 ctermfg=darkgrey ctermbg=black cterm=bold hi FoldColumn guifg=#808080 guibg=#000040 ctermfg=darkgrey ctermbg=black cterm=bold hi LineNr guifg=#90f020 ctermfg=green cterm=none hi DiffAdd guibg=darkblue ctermbg=darkblue cterm=none hi DiffChange guibg=darkmagenta ctermbg=magenta cterm=none hi DiffDelete guifg=Blue guibg=DarkCyan gui=bold ctermfg=blue ctermbg=cyan hi DiffText guibg=Red gui=bold ctermbg=red cterm=bold " Cursor hi Cursor guifg=#000020 guibg=#ffaf38 ctermfg=bg ctermbg=brown hi lCursor guifg=#ffffff guibg=#000000 ctermfg=bg ctermbg=darkgreen " Syntax highlighting: hi Comment guifg=darkcyan ctermfg=darkcyan hi Constant guifg=darkred ctermfg=darkred cterm=none hi Special guifg=magenta gui=none ctermfg=magenta cterm=none hi Identifier guifg=green ctermfg=green cterm=none hi Statement guifg=white gui=bold ctermfg=white cterm=bold hi PreProc guifg=darkgreen gui=none ctermfg=darkgreen cterm=none hi type guifg=grey gui=bold ctermfg=grey cterm=bold hi Underlined gui=underline cterm=underline hi Ignore guifg=bg ctermfg=bg
00000svn-vim-cfg
trunk/vimfiles/colors/turbo.vim
Vim Script
gpl3
2,997
" " Native Vim Color Scheme " ======================= " " author: Armin Ronacher <armin.ronacher@active-4.com> " set background=dark hi clear if exists("syntax_on") syntax reset endif let colors_name = "native" " Default Colors hi Normal guifg=#f2f2f2 guibg=#222222 hi NonText guifg=#444444 guibg=#111111 hi Cursor guibg=#aaaaaa hi lCursor guibg=#aaaaaa " Search hi Search guibg=peru guifg=wheat hi IncSearch cterm=NONE ctermfg=yellow ctermbg=green hi Search cterm=NONE ctermfg=grey ctermbg=blue " Window Elements hi StatusLine guifg=white guibg=#8090a0 gui=bold hi StatusLineNC guifg=#506070 guibg=#a0b0c0 hi VertSplit guifg=#a0b0c0 guibg=#a0b0c0 hi Folded guifg=#111111 guibg=#8090a0 hi IncSearch guifg=slategrey guibg=khaki " Specials hi Todo guifg=#e50808 guibg=#520000 gui=bold hi Title guifg=#ffffff gui=bold " Strings hi String guifg=#ed9d13 hi Constant guifg=#ed9d13 " Syntax hi Number guifg=#3677a9 hi Statement guifg=#6ab825 gui=bold hi Function guifg=#447fcf hi PreProc guifg=#cd2828 gui=bold hi Comment guifg=#999999 gui=italic hi Type guifg=#bbbbbb gui=bold " Diff hi DiffAdd ctermbg=4 hi DiffChange ctermbg=5 hi DiffDelete cterm=bold ctermfg=4 ctermbg=6 hi DiffText cterm=bold ctermbg=1
00000svn-vim-cfg
trunk/vimfiles/colors/native.vim
Vim Script
gpl3
1,318
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " File Name: winter.vim " Abstract: A color sheme file (only for GVIM) which uses a light grey " background makes the VIM look like the scenes of winter. " Author: CHE Wenlong <chewenlong AT buaa.edu.cn> " Version: 1.0 " Last Change: September 19, 2008 """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" if !has("gui_running") runtime! colors/default.vim finish endif set background=light hi clear " Version control if version > 580 hi clear if exists("syntax_on") syntax reset endif endif let colors_name = "winter" " Common hi Normal guifg=#000000 guibg=#d4d0c8 gui=NONE hi Visual guibg=#ccffff gui=NONE hi Cursor guifg=#d4d0c8 guibg=#cd0000 gui=NONE hi Cursorline guibg=#ccffff hi lCursor guifg=#000000 guibg=#ffffff gui=NONE hi LineNr guifg=#707070 guibg=#e0e0e0 gui=NONE hi Title guifg=#202020 guibg=NONE gui=bold hi Underlined guifg=#202020 guibg=NONE gui=underline " Split hi StatusLine guifg=#e0e0e0 guibg=#707070 gui=NONE hi StatusLineNC guifg=#e0e0e0 guibg=#909090 gui=NONE hi VertSplit guifg=#909090 guibg=#909090 gui=NONE " Folder hi Folded guifg=#707070 guibg=#e0e0e0 gui=NONE " Syntax hi Type guifg=#009933 guibg=NONE gui=bold hi Define guifg=#1060a0 guibg=NONE gui=bold hi Comment guifg=#0080ff guibg=NONE gui=NONE hi Constant guifg=#a07040 guibg=NONE gui=NONE hi String guifg=#a07040 guibg=NONE gui=NONE hi Number guifg=#cd0000 guibg=NONE gui=NONE hi Statement guifg=#fc548f guibg=NONE gui=bold " Others hi PreProc guifg=#1060a0 guibg=NONE gui=NONE hi Error guifg=#ff0000 guibg=#ffffff gui=bold,underline hi Todo guifg=#ff0000 guibg=#ffff00 gui=bold,underline hi Special guifg=#8b038d guibg=NONE gui=NONE hi SpecialKey guifg=#a07040 guibg=#e0e0e0 gui=NONE """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " vim:tabstop=4 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
00000svn-vim-cfg
trunk/vimfiles/colors/winter.vim
Vim Script
gpl3
2,399
" Vim color file " Maintainer: Donald Ephraim Curtis <dcurtis@gmail.com> " Last Change: 09. january 2007. " URL: http://milkbox.net " Kate default color themes. " version 1.1 set background=light hi clear if exists("syntax_on") syntax reset endif let g:colors_name="DevC++" hi Comment gui=italic guifg=#808080 guibg=NONE hi Identifier gui=NONE guifg=Black guibg=NONE hi Statement gui=bold guifg=DarkBlue guibg=NONE hi PreProc gui=NONE guifg=#008000 guibg=NONE hi Statement gui=bold guifg=Black guibg=NONE hi Type gui=bold guifg=#800000 guibg=NONE hi link Constant Type hi Special gui=NONE guifg=Black guibg=NONE hi Structure gui=bold guifg=Black guibg=NONE hi String gui=NONE guifg=#DD0000 guibg=NONE hi Number gui=NONE guifg=#0000FF guibg=NONE hi SpecialKey gui=NONE guifg=#0000FF guibg=NONE hi Float gui=NONE guifg=#800080 guibg=NONE hi Boolean gui=bold guifg=Black guibg=NONE hi Gutter gui=NONE guifg=Black guibg=Grey hi Todo gui=bold guifg=black guibg=#FFCCCC hi LineNr gui=NONE guifg=Black guibg=#EBE9ED hi NonText gui=bold guifg=black guibg=#EBE9ED hi Visual gui=reverse guifg=NONE guibg=NONE hi MatchParen gui=NONE guifg=Black guibg=#FFFF99 hi Question gui=NONE guifg=DarkGreen guibg=NONE hi More gui=bold guifg=DarkGreen guibg=NONE hi StatusLine gui=bold guifg=Black guibg=#EBE9ED " C/C++ Colors hi link cIncluded PreProc hi cOctal gui=NONE guifg=#008080 guibg=NONE hi cSpecial gui=NONE guifg=#FF00FF guibg=NONE hi link cSpecialCharacter cSpecial " Latex Colors "hi texStatement guifg=#606000 hi link texType Normal hi link texDocType Type hi link texDefParm Normal hi link texInput Normal hi link texInputFile Normal hi link texNewCmd texDocType hi link texSection String hi link texSectionName SpecialKey hi link texDelimiter Normal hi link texRefZone Normal hi link texMath PreProc hi link texLigature texMath hi texStatement gui=NONE guifg=#800000 guibg=NONE
00000svn-vim-cfg
trunk/vimfiles/colors/kate.vim
Vim Script
gpl3
2,262
" Vim color file " Maintainer: Michael Piefel <piefel@informatik.hu-berlin.de> " Last Change: 2001 Aug 16 " Licence: Public Domain " This color scheme uses a White background. It's based on Bram's " morning theme, but doesn't try to work for non-GUI editing. " " It's supposed to look like the Emacs standard colors, at least " for C. But Emacs has different categories, so it's not very good. " First remove all existing highlighting. set background=light hi clear if exists("syntax_on") syntax reset endif let colors_name = "emacs" hi Normal guifg=Black guibg=White " Groups used in the 'highlight' and 'guicursor' options default value. hi ErrorMsg guibg=Red guifg=White hi IncSearch gui=reverse hi ModeMsg gui=bold hi StatusLine gui=reverse,bold hi StatusLineNC gui=reverse hi VertSplit gui=reverse hi Visual gui=reverse guifg=Grey guibg=fg hi VisualNOS gui=underline,bold hi DiffText gui=bold guibg=Red hi Cursor guibg=Black guifg=NONE hi lCursor guibg=Cyan guifg=NONE hi Directory guifg=Blue hi LineNr guifg=Brown hi MoreMsg gui=bold guifg=SeaGreen hi NonText gui=bold guifg=Blue guibg=grey90 hi Question gui=bold guifg=SeaGreen hi Search guibg=Yellow guifg=NONE hi SpecialKey guifg=Blue hi Title gui=bold guifg=Magenta hi WarningMsg guifg=Red hi WildMenu guibg=Yellow guifg=Black hi Folded guibg=White guifg=DarkBlue hi FoldColumn guibg=Grey guifg=DarkBlue hi DiffAdd guibg=LightBlue hi DiffChange guibg=LightMagenta hi DiffDelete gui=bold guifg=Blue guibg=LightCyan " Colors for syntax highlighting hi Comment guifg=#AC2020 guibg=White hi Constant guifg=#C28F8F guibg=White hi PreProc guifg=#D569D5 guibg=White hi Statement gui=NONE guifg=#9C20EE guibg=White hi Type guifg=#9C20EE guibg=White hi Special guifg=SlateBlue guibg=White hi Ignore guifg=White " Some specials (override hilinks) " vim: sw=2
00000svn-vim-cfg
trunk/vimfiles/colors/emacs.vim
Vim Script
gpl3
1,821
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " File Name: spring.vim " Abstract: A color sheme file (only for GVIM), which make the VIM " bright with colors. It looks like the flowers are in " blossom in Spring. " Author: CHE Wenlong <chewenlong AT buaa.edu.cn> " Version: 1.0 " Last Change: September 16, 2008 """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" if !has("gui_running") runtime! colors/default.vim finish endif set background=light hi clear " Version control if version > 580 hi clear if exists("syntax_on") syntax reset endif endif let colors_name = "spring" " Common hi Normal guifg=#000000 guibg=#cce8cf gui=NONE hi Visual guibg=#ccffff gui=NONE hi Cursor guifg=#f5deb3 guibg=#2f4f4f gui=NONE hi Cursorline guibg=#ccffff hi lCursor guifg=#000000 guibg=#ffffff gui=NONE hi LineNr guifg=#1060a0 guibg=#e0e0e0 gui=NONE hi Title guifg=#202020 guibg=NONE gui=bold hi Underlined guifg=#202020 guibg=NONE gui=underline " Split hi StatusLine guifg=#f5deb3 guibg=#2f4f4f gui=bold hi StatusLineNC guifg=#f5deb3 guibg=#2f4f4f gui=NONE hi VertSplit guifg=#2f4f4f guibg=#2f4f4f gui=NONE " Folder hi Folded guifg=#006699 guibg=#e0e0e0 gui=NONE " Syntax hi Type guifg=#009933 guibg=NONE gui=bold hi Define guifg=#1060a0 guibg=NONE gui=bold hi Comment guifg=#1e90ff guibg=NONE gui=NONE hi Constant guifg=#a07040 guibg=NONE gui=NONE hi String guifg=#a07040 guibg=NONE gui=NONE hi Number guifg=#cd0000 guibg=NONE gui=NONE hi Statement guifg=#fc548f guibg=NONE gui=bold " Others hi PreProc guifg=#1060a0 guibg=NONE gui=NONE hi Error guifg=#ff0000 guibg=#ffffff gui=bold,underline hi Todo guifg=#a0b0c0 guibg=NONE gui=bold,underline hi Special guifg=#8B038D guibg=NONE gui=NONE hi SpecialKey guifg=#d8a080 guibg=#e8e8e8 gui=NONE """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " vim:tabstop=4 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
00000svn-vim-cfg
trunk/vimfiles/colors/spring.vim
Vim Script
gpl3
2,428
" Vim color file " Maintainer: tranquility@portugalmail.pt " Last Change: 5 June 2002 " cool help screens " :he group-name " :he highlight-groups " :he cterm-colors set background=dark hi clear if exists("syntax_on") syntax reset endif let g:colors_name="xemacs" hi Normal guibg=#cdcecd guifg=black hi Cursor guibg=red guifg=grey gui=bold hi VertSplit guibg=grey60 guifg=black gui=none hi Folded guibg=royalblue3 guifg=white hi FoldColumn guibg=royalblue4 guifg=white hi ModeMsg guifg=#cdcecd guibg=black hi MoreMsg guifg=#cdcecd guibg=black hi NonText guifg=black guibg=#cdcecd gui=none hi Question guifg=black hi Search guibg=#aceeee hi SpecialKey guifg=navyblue hi Special guifg=navyblue hi StatusLine guibg=#b7b7b7 guifg=black gui=none hi StatusLineNC guibg=#a6b7b7 guifg=black gui=none hi Title guifg=bisque3 hi Subtitle guifg=black hi Visual guibg=#a4a5a3 guifg=black gui=none hi WarningMsg guibg=#cdcecd guifg=black gui=bold hi Comment guifg=#00008b hi Constant guifg=#008900 hi Identifier guibg=#cdcecd guifg=black hi Statement guifg=royalblue4 hi PreProc guifg=#0000cd hi Type guifg=#4a81b4 gui=NONE hi Ignore guifg=grey29 hi Todo guibg=gold guifg=black hi WildMenu guibg=#b7b7b7 guibg=grey91 hi Directory guibg=#cdcecd guifg=navyblue hi LineNr guifg=#804040 guibg=NONE
00000svn-vim-cfg
trunk/vimfiles/colors/xemacs.vim
Vim Script
gpl3
1,348
" Vim color file " Maintainer: Vladimir Vrzic <random@bsd.org.yu> " Last Change: 28. june 2003. " URL: http://galeb.etf.bg.ac.yu/~random/pub/vim/ set background=light hi clear if exists("syntax_on") syntax reset endif let g:colors_name="nedit" hi Normal guifg=Black guibg=grey90 hi Comment gui=italic guifg=gray20 guibg=NONE hi Constant gui=NONE guifg=darkGreen guibg=NONE hi Identifier gui=bold guifg=red guibg=NONE hi Statement gui=bold guifg=black guibg=NONE hi PreProc gui=NONE guifg=RoyalBlue4 guibg=NONE hi Type gui=bold guifg=brown guibg=NONE hi Special gui=NONE guifg=darkGreen guibg=NONE "hi Underlined "hi Ignore "hi Error "hi Todo
00000svn-vim-cfg
trunk/vimfiles/colors/nedit.vim
Vim Script
gpl3
693
" Maintainer: iyerns <iyerns AT gmail DOT com> " Last Change: 25 August 2005 " Version:1.0 set background=light hi clear if exists("syntax_on") syntax reset endif let g:colors_name="peppers" hi Normal guifg=#ffffcc guibg=#003366 hi LineNr guifg=white guibg=#003366 hi Statusline gui=none guibg=#0099cc guifg=#ffffff hi StatuslineNC gui=none guibg=#003399 guifg=#ffffff hi Title guifg=black guibg=white gui=BOLD hi lCursor guibg=Cyan guifg=NONE " syntax highlighting groups hi Comment gui=NONE guifg=#cccccc hi Operator guifg=#ff0000 hi Identifier guifg=#33ff99 gui=NONE hi Statement guifg=#cc9966 gui=NONE hi TypeDef guifg=#c000c8 gui=NONE hi Type guifg=#ccffff gui=NONE hi Boolean guifg=#ff00aa gui=NONE hi String guifg=#99ccff gui=NONE hi Number guifg=#66ff66 gui=NONE hi Constant guifg=#f0f080 gui=NONE hi Function gui=NONE guifg=#fffcfc hi PreProc guifg=#ffff00 gui=NONE hi Define gui=bold guifg=#f0f0f0 hi Special gui=none guifg=#cccccc hi BrowseDirectory gui=bold guifg=#FFFF00 hi Keyword guifg=#ff8088 gui=NONE hi Search gui=NONE guibg=#ffff00 guifg=#330000 hi IncSearch gui=NONE guifg=#fcfcfc guibg=#8888ff hi SpecialKey gui=NONE guifg=#fcfcfc guibg=#8888ff hi NonText gui=NONE guifg=#fcfcfc hi Directory gui=NONE guifg=#999900 hi browseDirectory gui=NONE guifg=#00F0FF
00000svn-vim-cfg
trunk/vimfiles/colors/cloudy.vim
Vim Script
gpl3
1,480
" Vim color file " Maintainer: iyerns <iyerns AT gmail DOT com> " " Comments are welcome ! " Spammers will be shot. Survivors will be shot again " " Last Change: 10 Sep 2005 " Version:1.4 " Changes:Changed background color for better tone " Comment: Atlast, a professional colorscheme for Vim " Released by popular demand. in case other highlighting " terms are to be included, please feel free to add those " and send me your updated .vim file :) to be included in " the next version.If there are enough requests, I will " release a cterm version also. " Recolored comments and Statement " Uses only safe HTML colors " set background=light hi clear if exists("syntax_on") syntax reset endif let g:colors_name="professional" hi Normal guifg=black guibg=#ffffdd hi Statusline gui=none guibg=#006666 guifg=#ffffff hi VertSplit gui=none guibg=#006666 guifg=#ffffff hi StatuslineNC gui=none guibg=#666633 guifg=#ffffff hi Title guifg=black guibg=white gui=BOLD hi lCursor guibg=Cyan guifg=NONE hi LineNr guifg=white guibg=#006666 "guibg=#8c9bfa " syntax highlighting groups hi Comment gui=NONE guifg=SteelBlue hi Operator guifg=#ff0000 hi Identifier guifg=#339900 gui=NONE hi Statement guifg=orange gui=NONE hi TypeDef guifg=#c000c8 gui=NONE hi Type guifg=#0000c8 gui=NONE hi Boolean guifg=#0000aa gui=NONE hi String guifg=#006600 gui=NONE hi Number guifg=#9933ff gui=NONE hi Constant guifg=#ff8080 gui=NONE hi Function gui=NONE guifg=#6600ff hi PreProc guifg=#993300 gui=NONE hi Define gui=bold guifg=#ff0000 hi Keyword guifg=#ff8088 gui=NONE hi Search gui=NONE guibg=#ffff00 "guibg=#339900 hi IncSearch gui=NONE guifg=#ffff00 guibg=#990000 hi Conditional gui=none guifg=#660000 guibg=#ffffff hi browseDirectory gui=none guifg=#660000 guibg=#ffffff
00000svn-vim-cfg
trunk/vimfiles/colors/professional.vim
Vim Script
gpl3
1,941
"=============================================================================== " " File: qf.vim " " Description: " " VIM Version: 7.0+ " Author: Dr. Fritz Mehner (fgm), mehner.fritz@fh-swf.de " Organization: FH Südwestfalen, Iserlohn " Version: 1.0 " Created: 18.02.2012 19:51 " Revision: $Id: qf.vim,v 1.2 2012/02/19 21:28:31 mehner Exp $ " License: Copyright (c) 2012, Dr. Fritz Mehner "=============================================================================== " " Only do this when not done yet for this buffer " if exists("b:did_PERL_quickfix") finish endif let b:did_PERL_quickfix = 1 noremap <buffer> <silent> <LocalLeader>rpss :call perlsupportprofiling#Perl_SmallProfSortInput()<CR> noremap <buffer> <silent> <LocalLeader>rpfs :call perlsupportprofiling#Perl_FastProfSortInput()<CR> noremap <buffer> <silent> <LocalLeader>rpns :call perlsupportprofiling#Perl_NYTProfSortInput()<CR>
00000svn-vim-cfg
trunk/vimfiles/ftplugin/qf.vim
Vim Script
gpl3
991
" Vim filetype plugin file " " Language : Perl " Plugin : perl-support.vim " Maintainer : Fritz Mehner <mehner@fh-swf.de> " Revision : $Id: pod.vim,v 1.3 2012/02/20 13:45:03 mehner Exp $ " " ---------------------------------------------------------------------------- " " Only do this when not done yet for this buffer " if exists("b:did_POD_ftplugin") finish endif let b:did_POD_ftplugin = 1 " " ---------- tabulator / shiftwidth ------------------------------------------ " Set tabulator and shift width to 4 conforming to the Perl Style Guide. " Uncomment the next two lines to force these settings for all files with " filetype 'perl' . " setlocal tabstop=4 setlocal shiftwidth=4 if exists('g:Perl_Perltidy') && g:Perl_Perltidy == 'on' && executable("perltidy") setlocal equalprg='perltidy' endif " " ---------- Add ':' to the keyword characters ------------------------------- " Tokens like 'File::Find' are recognized as " one keyword " setlocal iskeyword+=: " " ---------- Do we have a mapleader other than '\' ? ------------ " if exists("g:Perl_MapLeader") let maplocalleader = g:Perl_MapLeader endif " " ---------- Perl dictionary ------------------------------------------------- " This will enable keyword completion for Perl " using Vim's dictionary feature |i_CTRL-X_CTRL-K|. " if exists("g:Perl_Dictionary_File") let save=&dictionary silent! exe 'setlocal dictionary='.g:Perl_Dictionary_File silent! exe 'setlocal dictionary+='.save endif " " " ---------- Key mappings : function keys ------------------------------------ " " Shift-F1 read Perl documentation " Vim (non-GUI) : shifted keys are mapped to their unshifted key !!! " if has("gui_running") " map <buffer> <silent> <S-F1> :call Perl_perldoc()<CR><CR> imap <buffer> <silent> <S-F1> <C-C>:call Perl_perldoc()<CR><CR> endif " "------------------------------------------------------------------------------- " Key mappings for menu entries " The mappings can be switched on and off by g:Perl_NoKeyMappings "------------------------------------------------------------------------------- " if !exists("g:Perl_NoKeyMappings") || ( exists("g:Perl_NoKeyMappings") && g:Perl_NoKeyMappings!=1 ) " ---------- plugin help ----------------------------------------------------- " nnoremap <buffer> <silent> <LocalLeader>hp :call Perl_HelpPerlsupport()<CR> inoremap <buffer> <silent> <LocalLeader>hp <C-C>:call Perl_HelpPerlsupport()<CR> " " ---------------------------------------------------------------------------- " Comments " ---------------------------------------------------------------------------- " nnoremap <buffer> <silent> <LocalLeader>cb :call Perl_CommentBlock("a")<CR> vnoremap <buffer> <silent> <LocalLeader>cb <C-C>:call Perl_CommentBlock("v")<CR> nnoremap <buffer> <silent> <LocalLeader>cn :call Perl_UncommentBlock()<CR> " " ---------------------------------------------------------------------------- " Snippets " ---------------------------------------------------------------------------- " nnoremap <buffer> <silent> <LocalLeader>nr :call Perl_CodeSnippet("read")<CR> nnoremap <buffer> <silent> <LocalLeader>nw :call Perl_CodeSnippet("write")<CR> vnoremap <buffer> <silent> <LocalLeader>nw <Esc>:call Perl_CodeSnippet("wv")<CR> nnoremap <buffer> <silent> <LocalLeader>ne :call Perl_CodeSnippet("edit")<CR> nnoremap <buffer> <silent> <LocalLeader>nv :call Perl_CodeSnippet("view")<CR> " inoremap <buffer> <silent> <LocalLeader>nr <Esc>:call Perl_CodeSnippet("read")<CR> inoremap <buffer> <silent> <LocalLeader>nw <Esc>:call Perl_CodeSnippet("write")<CR> inoremap <buffer> <silent> <LocalLeader>ne <Esc>:call Perl_CodeSnippet("edit")<CR> inoremap <buffer> <silent> <LocalLeader>nv <Esc>:call Perl_CodeSnippet("view")<CR> " " ---------------------------------------------------------------------------- " POD " ---------------------------------------------------------------------------- " nnoremap <buffer> <silent> <LocalLeader>pod :call Perl_PodCheck()<CR> nnoremap <buffer> <silent> <LocalLeader>podh :call Perl_POD('html')<CR> nnoremap <buffer> <silent> <LocalLeader>podm :call Perl_POD('man')<CR> nnoremap <buffer> <silent> <LocalLeader>podt :call Perl_POD('text')<CR> " inoremap <buffer> <silent> <LocalLeader>pod <Esc>:call Perl_PodCheck()<CR> inoremap <buffer> <silent> <LocalLeader>podh <Esc>:call Perl_POD('html')<CR> inoremap <buffer> <silent> <LocalLeader>podm <Esc>:call Perl_POD('man')<CR> inoremap <buffer> <silent> <LocalLeader>podt <Esc>:call Perl_POD('text')<CR> " endif " ---------------------------------------------------------------------------- "
00000svn-vim-cfg
trunk/vimfiles/ftplugin/pod.vim
Vim Script
gpl3
4,949
" Vim filetype plugin file " " Language : Perl " Plugin : perl-support.vim " Maintainer : Fritz Mehner <mehner@fh-swf.de> " Revision : $Id: perl.vim,v 1.8 2012/04/15 18:00:54 mehner Exp $ " " ---------------------------------------------------------------------------- " " Only do this when not done yet for this buffer " if exists("b:did_PERL_ftplugin") finish endif let b:did_PERL_ftplugin = 1 " "------------------------------------------------------------------------------- " additional mapping : {<CR> always opens a block "------------------------------------------------------------------------------- inoremap <buffer> {<CR> {<CR>}<Esc>O vnoremap <buffer> {<CR> s{<CR>}<Esc>kp=iB "
00000svn-vim-cfg
trunk/vimfiles/ftplugin/perl.vim
Vim Script
gpl3
714
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("1138cl-sync-client")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("1138cl-sync-client")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("eaee335f-7b49-430e-b2c6-f584f98f64e5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
1138cl-sync
trunk/client/Properties/AssemblyInfo.cs
C#
gpl3
1,448
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace _1138cl_sync_client { public partial class Form1 : Form { public Form1() { InitializeComponent(); } } }
1138cl-sync
trunk/client/Form1.cs
C#
gpl3
400
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace _1138cl_sync_client { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
1138cl-sync
trunk/client/Program.cs
C#
gpl3
542
using System; namespace clsyncserver { class MainClass { public static void Main (string[] args) { Console.WriteLine ("Hello World!"); } } }
1138cl-sync
trunk/server/Main.cs
C#
gpl3
154
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("1138cl-sync-server")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("bob")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
1138cl-sync
trunk/server/AssemblyInfo.cs
C#
gpl3
987
(ns a-thousand-things-to-do.core) (use '[clojure.java.io :only (reader)]) (use '[clojure-csv.core]) (defstruct album :year :title :artist) (defn as-album-map [album-data] (struct-map :year (album-data 0) :title (album-data 1) :artist (album-data 2))) (defn load-album-sequence [file-name] (binding [*delimiter* \;] (parse-csv (char-seq (reader file-name)))))
1001-things-to-do
trunk/src/a_thousand_things_to_do/core.clj
Clojure
mpl11
402
(defproject a-thousand-things-to-do "1.0.0-SNAPSHOT" :description "My first experiments with Clojure" :dependencies [[org.clojure/clojure "1.2.1"] [clojure-csv "1.2.4"]] :main a-thousand-things-to-do.core :dev-dependencies [[lein-eclipse "1.0.0"]] )
1001-things-to-do
trunk/project.clj
Clojure
mpl11
277
(ns a-thousand-things-to-do.test.core (:use [a-thousand-things-to-do.core]) (:use [clojure.test])) (deftest replace-me ;; FIXME: write (is false "No tests have been written."))
1001-things-to-do
trunk/test/a_thousand_things_to_do/test/core.clj
Clojure
mpl11
184
/* * fIRC - a free IRC client for the Android platform. * http://code.google.com/p/firc-chat/ * * Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com> * http://www.multigesture.net/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.falcon4ever.fIRC3; import java.util.ArrayList; import android.app.ListActivity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.falcon4ever.fIRC3.service.ChatService; import com.falcon4ever.fIRC3.service.ChatService.LocalBinder; import com.falcon4ever.fIRC3.service.IRCConnection; import com.falcon4ever.fIRC3.utils.DBProfileManager; import com.falcon4ever.fIRC3.utils.ProfileState; // TODO: Update server connection status public class ServerlistActivity extends ListActivity { private ArrayList<ProfileState> mServers = new ArrayList<ProfileState>(); private ServerlistAdapter mAdapter; private ChatService mService; private boolean mBound = false; private Handler IncomingHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { // Initialize panels case ChatService.MSG_UI_SERVERLIST_UPDATE: { updateConnectionStatus(); } break; default: Log.e(getClass().getSimpleName(), "Unhandled message IncomingHandler " + msg.what); } } }; private void updateConnectionStatus() { // Cycle over current server list for(int i = 0; i < mServers.size(); i++) { mServers.get(i).setConnected( mService.getConnectionStatus( mServers.get(i).getProfileId() ) ); } mAdapter.notifyDataSetChanged(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.serverlist); // Set and Update listview mAdapter = new ServerlistAdapter(this, R.layout.serverlist_row, mServers); setListAdapter(mAdapter); registerForContextMenu(getListView()); } @Override protected void onResume() { super.onResume(); // Bind to LocalService Intent intent = new Intent(this, ChatService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); queryProfiles(); } @Override protected void onPause() { super.onPause(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } private void queryProfiles() { DBProfileManager db = new DBProfileManager(this); ArrayList<ArrayList<Object>> profiles = db.getAllRowsAsArrays(); db.close(); mServers.clear(); for(int i = 0; i < profiles.size(); i++) { ArrayList<Object> values = profiles.get(i); ProfileState ps = new ProfileState(); ps.setProfileId(Integer.parseInt(values.get(0).toString())); ps.setProfileName(values.get(1).toString()); ps.setConnected(IRCConnection.CONNECTION_OFFLINE); Log.d(getClass().getSimpleName(), "Loading: pID " + values.get(0).toString() + ", ProfileName " + values.get(1).toString()); mServers.add(ps); } mAdapter.notifyDataSetChanged(); } /////////////////////////////////////////////////////////////////////////////////////////////// // ServiceConnection /////////////////////////////////////////////////////////////////////////////////////////////// private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; mService.setHandler(IncomingHandler); updateConnectionStatus(); } public void onServiceDisconnected(ComponentName arg0) { mBound = false; mService.setHandler(null); } }; /////////////////////////////////////////////////////////////////////////////////////////////// // Menu at bottom /////////////////////////////////////////////////////////////////////////////////////////////// @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.serverlist_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.serverlist_new_profile: { Intent intent = new Intent(); intent.setClassName(ServerlistActivity.this, "com.falcon4ever.fIRC3.ProfileActivity"); intent.putExtra("profile_type", "new_profile"); startActivity(intent); } return true; case R.id.serverlist_connect_all: if (mBound) { mService.connectAll(); } return true; case R.id.serverlist_disconnect_all: if (mBound) { mService.disconnectAll(); } // check status return true; case R.id.serverlist_help: Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.multigesture.net/projects/firc/")); startActivity(browserIntent); return true; default: return super.onOptionsItemSelected(item); } } /////////////////////////////////////////////////////////////////////////////////////////////// // Enter ChatView /////////////////////////////////////////////////////////////////////////////////////////////// @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); if(mService.getConnectionStatus(mServers.get(position).getProfileId()) < 1) { Toast.makeText(this, "Profile is not connected", Toast.LENGTH_SHORT).show(); return; } Intent intent = new Intent(); intent.setClassName(ServerlistActivity.this, "com.falcon4ever.fIRC3.ChatActivity"); intent.putExtra("profile_id", mServers.get(position).getProfileId()); startActivity(intent); } /////////////////////////////////////////////////////////////////////////////////////////////// // Context menu /////////////////////////////////////////////////////////////////////////////////////////////// @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, 0, 0, "Edit profile"); menu.add(0, 1, 0, "Remove profile"); menu.add(0, 2, 0, "Connect"); menu.add(0, 3, 0, "Disconnect"); } public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); switch(item.getItemId()) { case 0: { Intent intent = new Intent(); intent.setClassName(ServerlistActivity.this, "com.falcon4ever.fIRC3.ProfileActivity"); intent.putExtra("profile_type", "edit_profile"); intent.putExtra("profile_id", mServers.get(info.position).getProfileId()); startActivity(intent); } break; case 1: { // Disconnect ! mService.disconnect(mServers.get(info.position).getProfileId()); // Remove from service DBProfileManager db = new DBProfileManager(this); db.deleteRow(mServers.get(info.position).getProfileId()); db.close(); queryProfiles(); } return true; case 2: { // Connect mService.connect(mServers.get(info.position).getProfileId()); } break; case 3: { // Disconnect mService.disconnect(mServers.get(info.position).getProfileId()); } break; } return super.onContextItemSelected(item); } /////////////////////////////////////////////////////////////////////////////////////////////// // ServerlistAdapter /////////////////////////////////////////////////////////////////////////////////////////////// private class ServerlistAdapter extends ArrayAdapter<ProfileState> { private ArrayList<ProfileState> mItems; private LayoutInflater mInflater; public ServerlistAdapter(Context context, int textViewResourceId, ArrayList<ProfileState> items) { super(context, textViewResourceId, items); mItems = items; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Inflate XML gui template if (convertView == null) { convertView = mInflater.inflate(R.layout.serverlist_row, parent, false); } // Get item from adapter ProfileState o = mItems.get(position); if (o != null) { // Get Views TextView tvServerAddress = (TextView)convertView.findViewById(R.id.serverlist_profile); TextView tvServerStatus = (TextView)convertView.findViewById(R.id.serverlist_status); ImageView ivServerStatus = (ImageView)convertView.findViewById(R.id.serverlist_status_icon); // Set Views if(tvServerAddress != null) { tvServerAddress.setText("Profile: " + o.getProfile_name()); } if(tvServerStatus != null) { if(o.getConnected() == IRCConnection.CONNECTION_OFFLINE) tvServerStatus.setText("Status: Offline"); else if(o.getConnected() == IRCConnection.CONNECTION_CONNECTING) tvServerStatus.setText("Status: Connecting..."); else if(o.getConnected() == IRCConnection.CONNECTION_ONLINE) tvServerStatus.setText("Status: Online"); else tvServerStatus.setText("Status: Unknown"); } if(ivServerStatus != null) { if(o.getConnected() == IRCConnection.CONNECTION_OFFLINE) ivServerStatus.setImageDrawable(getContext().getResources().getDrawable(android.R.drawable.presence_offline)); else if(o.getConnected() == IRCConnection.CONNECTION_CONNECTING) ivServerStatus.setImageDrawable(getContext().getResources().getDrawable(android.R.drawable.presence_invisible)); else if(o.getConnected() == IRCConnection.CONNECTION_ONLINE) ivServerStatus.setImageDrawable(getContext().getResources().getDrawable(android.R.drawable.presence_online)); else ivServerStatus.setImageDrawable(getContext().getResources().getDrawable(android.R.drawable.presence_offline)); } } return convertView; } } }
0skillz63-irc
fIRC3/src/com/falcon4ever/fIRC3/ServerlistActivity.java
Java
gpl3
13,661
/* * fIRC - a free IRC client for the Android platform. * http://code.google.com/p/firc-chat/ * * Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com> * http://www.multigesture.net/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.falcon4ever.fIRC3.service; public class DCCConnection { // Used for incoming and outgoing transfers }
0skillz63-irc
fIRC3/src/com/falcon4ever/fIRC3/service/DCCConnection.java
Java
gpl3
1,004
/* * fIRC - a free IRC client for the Android platform. * http://code.google.com/p/firc-chat/ * * Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com> * http://www.multigesture.net/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.falcon4ever.fIRC3.service; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map.Entry; import android.util.Log; import com.falcon4ever.fIRC3.utils.ChatMessage; import com.falcon4ever.fIRC3.utils.ProfileState; // http://www.ietf.org/rfc/rfc1459.txt // http://www.zigwap.com/mirc/raw_events.php // http://www.mirc.net/raws/ // TODO: Output to logfile on SDcard public class IRCConnection implements Runnable { // Thread private Thread mIrcThread; private volatile boolean mThreadDone = false; // Connection private Socket mIrcSocket = null; private BufferedReader mIrcInput = null; private BufferedWriter mIrcOutput = null; private int mConnectionStatus = CONNECTION_OFFLINE; public synchronized int getConnectionStatus() { return mConnectionStatus; } // Profile and encoding private ProfileState mProfile; private String mEncoding; private int mCurrentScreen = 0; private ChatService mParent; //[channel name][channel msg] private HashMap<String, ArrayList<ChatMessage>> mChatMessagesList = new HashMap<String, ArrayList<ChatMessage>>(); private synchronized HashMap<String, ArrayList<ChatMessage>> getChatMessagesList() { return mChatMessagesList; } private SimpleDateFormat mDateFormat = new SimpleDateFormat("HH:mm"); // ("HH:mm:ss"); // Constants public static final int MAX_CHAT_HISTORY = 1000; public static final int CONNECTION_OFFLINE = 0; public static final int CONNECTION_CONNECTING = 1; public static final int CONNECTION_ONLINE = 2; /////////////////////////////////////////////////////////////////////////////////////////////// // IRCConnection /////////////////////////////////////////////////////////////////////////////////////////////// // Constructor public IRCConnection(ProfileState profile, String encoding, ChatService parent) { mProfile = profile; mEncoding = encoding; mParent = parent; mCurrentScreen = 0; updateConnectionStatus(CONNECTION_OFFLINE); } public synchronized void updateConnectionStatus(int connectionStatus) { mConnectionStatus = connectionStatus; if(mParent.getHandler() != null) { mParent.getHandler().obtainMessage(ChatService.MSG_UI_SERVERLIST_UPDATE).sendToTarget(); } } public void run() { addChannel("server"); Log.d(getClass().getSimpleName(), "Starting profile: " + mProfile.getProfile_name()); updateConnectionStatus(CONNECTION_CONNECTING); try { //1. creating a socket to connect to the server mIrcSocket = new Socket(mProfile.getProfileServer(), mProfile.getProfilePort()); Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": Connected to " + mProfile.getProfileServer() + " in port " + mProfile.getProfilePort()); //2. get Input and Output streams mIrcInput = new BufferedReader(new InputStreamReader(mIrcSocket.getInputStream(), mEncoding)); mIrcOutput = new BufferedWriter(new OutputStreamWriter(mIrcSocket.getOutputStream(), mEncoding)); mIrcOutput.flush(); // 4.1.2 Nick message TODO: set limit int nickname_limit =9; if(mProfile.getProfileNickname().length() > nickname_limit) mProfile.setProfileName(mProfile.getProfileNickname().substring(0, nickname_limit)); sendMessage("NICK " + mProfile.getProfileNickname()); // 4.1.3 User message sendMessage("USER " + mProfile.getProfileIdent() + " 0 * :" + mProfile.getProfileRealname()); //3: Communicating with the server do { processMessage(mIrcInput.readLine()); } while(!mThreadDone); } catch(UnknownHostException unknownHost) { Log.e(getClass().getSimpleName(), mProfile.getProfile_name() + ": You are trying to connect to an unknown host!"); } catch(IOException ioException) { //Log.e(getClass().getSimpleName(), connName + " Error1" + ioException.getMessage(), ioException); Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": Forcing shutdown? " + ioException.getMessage()); } finally { if(mIrcOutput != null) sendMessage("QUIT :Powered by fIRC v3.0, the android IRC client."); //4: Closing connection try { if(mIrcInput != null) mIrcInput.close(); if(mIrcOutput != null) mIrcOutput.close(); if(mIrcSocket != null) mIrcSocket.close(); Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": Closed socket"); } catch(IOException ioException) { ioException.printStackTrace(); Log.e(getClass().getSimpleName(), mProfile.getProfile_name() + ": ioException while closing connection", ioException); } } Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": Finished"); updateConnectionStatus(CONNECTION_OFFLINE); mIrcThread = null; } /////////////////////////////////////////////////////////////////////////////////////////////// // Process /////////////////////////////////////////////////////////////////////////////////////////////// // http://www.ietf.org/rfc/rfc1459.txt private void processMessage(String msg) { Log.d(getClass().getSimpleName(), "Incoming message: " + msg); // If something went wrong, kill thread if(msg == null) { mThreadDone = true; return; } // 4.6.2 Ping message if(msg.substring(0,4).equalsIgnoreCase("PING")) { addMessage("server", "< " + msg, 2); int values = msg.indexOf(":"); // 4.6.3 Pong message sendMessage("PONG " + msg.substring(values)); return; } // Figure out what's happening String cmds_text = msg; String[] cmds_item = null; cmds_item = cmds_text.split(" "); if(cmds_item[1].equalsIgnoreCase("001")) { sendMessage("USERHOST " + mProfile.getProfileNickname()); } //else if(cmds_item[1].equalsIgnoreCase("422")) else if(cmds_item[1].equalsIgnoreCase("376")) { updateConnectionStatus(CONNECTION_ONLINE); String[] chatrooms = null; chatrooms = mProfile.getProfileChatrooms().split("\n"); for(String room : chatrooms) { sendMessage("JOIN " + room); //addChannel(room); } } else if(cmds_item[1].equalsIgnoreCase("JOIN")) { // TODO Handle join by others // Handle own channel join String[] values_item = cmds_item[0].substring(1).split("!"); if(values_item[0].equalsIgnoreCase(mProfile.getProfileNickname())) { int values = cmds_item[2].indexOf(":") + 1; addMessage(cmds_item[2].substring(values), "Now talking in " + cmds_item[2].substring(values), 2); } } if(cmds_item[1].equalsIgnoreCase("PRIVMSG")) { int values = msg.indexOf(":",1) + 1; String nickname = cmds_item[0].substring(1, cmds_item[0].indexOf("!")); Date date = new Date(); String line = "[" + mDateFormat.format(date) + "] <" + nickname + "> " + msg.substring(values); addMessage(cmds_item[2], line, 1); } else addMessage("server", "< " + msg, 2); } /////////////////////////////////////////////////////////////////////////////////////////////// // Public Methods /////////////////////////////////////////////////////////////////////////////////////////////// public void sendMessage(String msg) { try { mIrcOutput.write(msg); mIrcOutput.newLine(); mIrcOutput.flush(); Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": RAW sendMessage: " + msg); // LOG OUTPUT addMessage("server", "> " + msg, 2); // Incase of privmsg String[] cmds_item = msg.split(" "); if(cmds_item[0].equalsIgnoreCase("PRIVMSG")) { Date date = new Date(); //String line = "[" + mDateFormat.format(date) + "] <" + mProfile.getProfile_nickname() + "> " + cmds_item[2].substring(1); //String[] chatmsg = msg.split(":"); String chatmsg = msg.substring(msg.indexOf(":")+1); String line = "[" + mDateFormat.format(date) + "] <" + mProfile.getProfileNickname() + "> " + chatmsg; addMessage(cmds_item[1], line, 0); } } catch(IOException ioException) { ioException.printStackTrace(); } } public int getCurrentScreen() { return mCurrentScreen; } public void setCurrentScreen(int currentScreen) { mCurrentScreen = currentScreen; } public String getConnectionName() { return mProfile.getProfile_name(); } public int getConnectionID() { return mProfile.getProfileId(); } /////////////////////////////////////////////////////////////////////////////////////////////// // Thread /////////////////////////////////////////////////////////////////////////////////////////////// public void startThread() { if ( mIrcThread == null ) { mIrcThread = new Thread(this); mThreadDone = false; mIrcThread.start(); } } public void stopThread() { mThreadDone = true; try { if(mIrcSocket != null) mIrcSocket.close(); Log.d(getClass().getSimpleName(), mProfile.getProfile_name() + ": Forcing shutdown (closing socket)"); } catch(IOException ioException) { ioException.printStackTrace(); Log.e(getClass().getSimpleName(), mProfile.getProfile_name() + ": Error while forcing shutdown", ioException); } } /////////////////////////////////////////////////////////////////////////////////////////////// // Chat History /////////////////////////////////////////////////////////////////////////////////////////////// public synchronized void initializePanels() { if(mParent.getHandler() != null) { if(mParent.getActiveProfile() == mProfile.getProfileId()) { // Dirty replay messages for (Entry<String, ArrayList<ChatMessage>> entry : getChatMessagesList().entrySet()) { for(ChatMessage chatmsg : entry.getValue()) { mParent.getHandler().obtainMessage(ChatService.MSG_UI_INIT, 0, 0, chatmsg).sendToTarget(); } } // Finished update panels mParent.getHandler().obtainMessage(ChatService.MSG_UI_INIT_DONE).sendToTarget(); } } } private void addChannel(String channelName) { getChatMessagesList().put(channelName, new ArrayList<ChatMessage>()); } private void addMessage(String channel, String message, int type) { ChatMessage msg = new ChatMessage(); msg.setChatMessage(message); msg.setChannel(channel); msg.setType(type); if(getChatMessagesList().containsKey(channel)) { if(getChatMessagesList().get(channel).size() >= MAX_CHAT_HISTORY) getChatMessagesList().get(channel).remove(0); getChatMessagesList().get(channel).add(msg); } else { getChatMessagesList().put(channel, new ArrayList<ChatMessage>()); getChatMessagesList().get(channel).add(msg); } if(mParent.getHandler() != null) { if(mParent.getActiveProfile() == mProfile.getProfileId()) mParent.getHandler().obtainMessage(ChatService.MSG_UI_UPDATE,0,0,msg).sendToTarget(); } } }
0skillz63-irc
fIRC3/src/com/falcon4ever/fIRC3/service/IRCConnection.java
Java
gpl3
12,601
/* * fIRC - a free IRC client for the Android platform. * http://code.google.com/p/firc-chat/ * * Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com> * http://www.multigesture.net/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.falcon4ever.fIRC3.service; import java.util.ArrayList; import java.util.Hashtable; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.util.Log; import com.falcon4ever.fIRC3.utils.DBProfileManager; import com.falcon4ever.fIRC3.utils.ProfileState; public class ChatService extends Service { public static final int MSG_UI_INIT = 1; public static final int MSG_UI_INIT_DONE = 2; public static final int MSG_UI_UPDATE = 3; public static final int MSG_UI_SERVERLIST_UPDATE = 4; private Handler mHandler; private int mActiveProfile = -1; private final IBinder mBinder = new LocalBinder(); // List of Connections private Hashtable<Integer, IRCConnection> mConnectionList = new Hashtable<Integer, IRCConnection>(); @Override public void onCreate() { super.onCreate(); Log.d(getClass().getSimpleName(),"Start fIRC3 background service"); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d(getClass().getSimpleName(),"Shutting down fIRC3 background service"); disconnectAll(); } public class LocalBinder extends Binder { public ChatService getService() { // Return this instance of LocalService so clients can call public methods return ChatService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } public void connect(int profile_id) { DBProfileManager db = new DBProfileManager(this); ArrayList<Object> curProfile = db.getRowAsArray(profile_id); db.close(); ProfileState ps = new ProfileState(); ps.setProfileId(Integer.parseInt(curProfile.get(0).toString())); ps.setProfileName(curProfile.get(1).toString()); ps.setProfileNickname(curProfile.get(2).toString()); ps.setProfileAltnick(curProfile.get(3).toString()); ps.setProfileServer(curProfile.get(4).toString()); ps.setProfilePort(Integer.parseInt(curProfile.get(5).toString())); ps.setProfileChatrooms(curProfile.get(6).toString()); ps.setProfileIdent(curProfile.get(7).toString()); ps.setProfileRealname(curProfile.get(8).toString()); ps.setProfileEncoding(Integer.parseInt(curProfile.get(9).toString())); ps.setProfileOnconnect(curProfile.get(10).toString()); //ps.setConnected(false); String[] encoding_array = getResources().getStringArray(com.falcon4ever.fIRC3.R.array.encoding_array); String profile_encoding = encoding_array[Integer.parseInt(curProfile.get(9).toString())]; addConnection(ps, profile_encoding); Log.d(getClass().getSimpleName(), "Launching single profile: " + mConnectionList.get(profile_id).getConnectionName()); mConnectionList.get(profile_id).startThread(); } public void disconnect(int profile_id) { if(mConnectionList.containsKey(profile_id)) { mConnectionList.get(profile_id).stopThread(); mConnectionList.remove(profile_id); } } private void addConnection(ProfileState ps, String encoding) { if(mConnectionList.containsKey(ps.getProfileId())) { mConnectionList.get(ps.getProfileId()).stopThread(); mConnectionList.remove(ps.getProfileId()); } IRCConnection myConn = new IRCConnection(ps, encoding, this); mConnectionList.put(ps.getProfileId(), myConn); } public void connectAll() { // Query all connections from db DBProfileManager db = new DBProfileManager(this); ArrayList<ArrayList<Object>> profiles = db.getAllRowsAsArrays(); db.close(); // Fill profiles for(int i = 0; i < profiles.size(); i++) { ArrayList<Object> values = profiles.get(i); ProfileState ps = new ProfileState(); ps.setProfileId(Integer.parseInt(values.get(0).toString())); ps.setProfileName(values.get(1).toString()); ps.setProfileNickname(values.get(2).toString()); ps.setProfileAltnick(values.get(3).toString()); ps.setProfileServer(values.get(4).toString()); ps.setProfilePort(Integer.parseInt(values.get(5).toString())); ps.setProfileChatrooms(values.get(6).toString()); ps.setProfileIdent(values.get(7).toString()); ps.setProfileRealname(values.get(8).toString()); ps.setProfileEncoding(Integer.parseInt(values.get(9).toString())); ps.setProfileOnconnect(values.get(10).toString()); //ps.setConnected(false); String[] encoding_array = getResources().getStringArray(com.falcon4ever.fIRC3.R.array.encoding_array); String profile_encoding = encoding_array[Integer.parseInt(values.get(9).toString())]; addConnection(ps, profile_encoding); } for(IRCConnection conn : mConnectionList.values()) { Log.d(getClass().getSimpleName(), "Launching profile: " + conn.getConnectionName()); conn.startThread(); } } public void disconnectAll() { for(IRCConnection conn : mConnectionList.values()) conn.stopThread(); mConnectionList.clear(); // TODO: Update status? } public int getConnectionStatus(int profileId) { if(mConnectionList.containsKey(profileId)) return mConnectionList.get(profileId).getConnectionStatus(); else return IRCConnection.CONNECTION_OFFLINE; } public IRCConnection getIrcConn(int profileId) { if(mConnectionList.containsKey(profileId)) return mConnectionList.get(profileId); else return null; } public synchronized Handler getHandler() { return mHandler; } public synchronized void setHandler(Handler mHandler) { this.mHandler = mHandler; } public synchronized void setActiveProfile(int activeProfile) { mActiveProfile = activeProfile; } public synchronized int getActiveProfile() { return mActiveProfile; } }
0skillz63-irc
fIRC3/src/com/falcon4ever/fIRC3/service/ChatService.java
Java
gpl3
7,339
/* * fIRC - a free IRC client for the Android platform. * http://code.google.com/p/firc-chat/ * * Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com> * http://www.multigesture.net/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.falcon4ever.fIRC3; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TextView; import com.falcon4ever.fIRC3.service.ChatService; public class HomeActivity extends Activity { private Shortcut mIcons[] = { new Shortcut(R.drawable.ic_menu_start_conversation, "Chat", "com.falcon4ever.fIRC3.ServerlistActivity"), new Shortcut(R.drawable.ic_menu_refresh, "File transfers", "com.falcon4ever.fIRC3.PlaceholderActivity"), new Shortcut(R.drawable.ic_menu_preferences, "Settings", "com.falcon4ever.fIRC3.PlaceholderActivity"), new Shortcut(R.drawable.ic_menu_help, "Manual", "homepage"), new Shortcut(R.drawable.ic_menu_info_details, "About", "about"), new Shortcut(R.drawable.ic_lock_power_off, "Logout", "logout"), }; private LinearLayout mIconRows[] = new LinearLayout[4]; private String mVersion; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home); try { PackageInfo manager = getPackageManager().getPackageInfo(getPackageName(), 0); mVersion = manager.versionName; setTitle("fIRC - The Android IRC Client (v" + mVersion + ")"); } catch (NameNotFoundException e) { mVersion = ""; } // Initialize icon rows for(int i = 0; i < mIconRows.length; i++) { mIconRows[i] = new LinearLayout(this); mIconRows[i].setOrientation(LinearLayout.HORIZONTAL); } // Place icons switch(getResources().getConfiguration().orientation) { case Configuration.ORIENTATION_UNDEFINED: case Configuration.ORIENTATION_SQUARE: case Configuration.ORIENTATION_PORTRAIT: { for(int i = 0; i < mIconRows.length; i++) mIconRows[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1)); addIcons(Configuration.ORIENTATION_PORTRAIT, 3); } break; case Configuration.ORIENTATION_LANDSCAPE: { mIconRows[1].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1)); mIconRows[2].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1)); addIcons(Configuration.ORIENTATION_LANDSCAPE, 5); } break; default: } // Add views final LinearLayout homeIcons = (LinearLayout)findViewById(R.id.home_screen); for(int i = 0; i < mIconRows.length; i++) homeIcons.addView(mIconRows[i]); // Start background service startService(new Intent(this, ChatService.class)); // One time disclaimer SharedPreferences settings = getSharedPreferences("fIRC_settings", 0); boolean disclaimer = settings.getBoolean("firc_disclaimer", false); if(!disclaimer) { AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setTitle(R.string.alert_dialog_title); builder.setMessage(R.string.alert_dialog_msg); builder.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { SharedPreferences settings = getSharedPreferences("fIRC_settings", 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("firc_disclaimer", true); editor.commit(); } }); builder.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { stopService(new Intent(HomeActivity.this, ChatService.class)); finish(); } }); builder.show(); } } private void addIcons(int orientation, int maxicons) { int row = 0, counter = 0; if(orientation == Configuration.ORIENTATION_LANDSCAPE) row = 1; for(int i = 0; i < mIcons.length; i++) { final int j = i; ++counter; LinearLayout iconWrap = new LinearLayout(this); iconWrap.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1)); iconWrap.setOrientation(LinearLayout.VERTICAL); LinearLayout iconImageWrap = new LinearLayout(this); iconImageWrap.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1)); iconImageWrap.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM); ImageView iconImage = new ImageView(this); iconImage.setImageResource(mIcons[i].getResId()); iconImage.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); TextView iconText = new TextView(this); iconText.setText(mIcons[i].getLabel()); iconText.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP); iconText.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, (float) 1.35)); iconImageWrap.addView(iconImage); iconWrap.addView(iconImageWrap); iconWrap.addView(iconText); iconWrap.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Set action if(mIcons[j].getClassname().equals("logout")) { stopService(new Intent(HomeActivity.this, ChatService.class)); finish(); } else if(mIcons[j].getClassname().equals("homepage")) { Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.multigesture.net/projects/firc/")); startActivity(browserIntent); } else if(mIcons[j].getClassname().equals("about")) { AlertDialog alertDialog = new AlertDialog.Builder(HomeActivity.this).create(); alertDialog.setTitle("About"); alertDialog.setMessage( "Author: Laurence Muller\n" + "E-mail: info@falcon4ever.com\n" + "Website: multigesture.net/firc\n\n" + "fIRC version: v" + mVersion + "\n" + "License type: Freeware\n\n" + "Special thanks to (*donated):\n\nThisRob*, SanMehat, languish, Disconnect, hmepass, JesusFreke, kirberich, rashed2020, kash and everyone else I forgot."); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { return; } }); alertDialog.show(); } else { Intent intent = new Intent(); intent.setClassName(HomeActivity.this, mIcons[j].getClassname()); startActivity(intent); } } }); mIconRows[row].addView(iconWrap); if(counter == maxicons) { ++row; counter = 0; } } } private class Shortcut { public int mResId; public String mLabel; public String mClassname; Shortcut(int resId, String label, String classname) { mResId = resId; mLabel = label; mClassname = classname; } public int getResId() { return mResId; } public String getLabel() { return mLabel; } public String getClassname() { return mClassname; } } }
0skillz63-irc
fIRC3/src/com/falcon4ever/fIRC3/HomeActivity.java
Java
gpl3
9,520
/* * fIRC - a free IRC client for the Android platform. * http://code.google.com/p/firc-chat/ * * Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com> * http://www.multigesture.net/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.falcon4ever.fIRC3; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.List; import java.util.Random; import org.jared.commons.ui.R; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import com.falcon4ever.fIRC3.utils.DBProfileManager; public class ProfileActivity extends Activity { private final String mDefaultNetwork = "EFnet"; private final Random mGenerator = new Random(); private Hashtable<String, Network> mNetworksList; /* * Silly hack since setOnItemSelectedListener(new ServerOnItemSelectedListener()); * is calling onItemSelected on initialization. * http://stackoverflow.com/questions/5624825/spinner-onitemselected-executes-when-it-is-not-suppose-to/5918177#5918177 */ private int mCount=0; private int mInitializedCount=0; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Hide keyboard on Activity launch this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); setContentView(R.layout.profile); // Load hardcoded serverlist (Slow?) loadServerlist(); // Get extras final Bundle extras = getIntent().getExtras(); String profileType = extras.getString("profile_type"); if(profileType.equals("new_profile")) { newProfile(); } else if(profileType.equals("edit_profile")) { setTitle(R.string.profile_title_edit); editProfile(extras.getInt("profile_id")); } else { Log.d(getClass().getSimpleName(), "no extras"); finish(); } } private void setupSpinners() { // Enumerate Networks (Groups) // Get list of networks, store it and sort the List Enumeration<String> e = mNetworksList.keys(); List<String> ircNetworksNames = new ArrayList<String>(); while(e.hasMoreElements()) ircNetworksNames.add(mNetworksList.get(e.nextElement()).getName()); Collections.sort(ircNetworksNames); // Prepare to copy list to ircnetworks so it can be attached to the Adapter int defaultPos = 0; List<CharSequence> ircNetworks = new ArrayList<CharSequence>(); for (int i=0; i< ircNetworksNames.size(); i++) { // Set default Network if(ircNetworksNames.get(i).equals(mDefaultNetwork)) defaultPos = ircNetworks.size(); ircNetworks.add((CharSequence)ircNetworksNames.get(i)); } final Spinner profileNetworkSpinner = (Spinner) findViewById(R.id.profile_network_spinner); ArrayAdapter<CharSequence> adapter1 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, ircNetworks); adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); profileNetworkSpinner.setAdapter(adapter1); profileNetworkSpinner.setOnItemSelectedListener(new NetworkOnItemSelectedListener()); profileNetworkSpinner.setSelection(defaultPos); // Enumerate Servers final Spinner profileServerSpinner = (Spinner)findViewById(R.id.profile_server_spinner); ArrayAdapter<CharSequence> adapter2 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, new ArrayList<CharSequence>()); adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); profileServerSpinner.setAdapter(adapter2); profileServerSpinner.setOnItemSelectedListener(new ServerOnItemSelectedListener()); setServerValues(); // Enumerate encodings final Spinner profileEncodingSpinner = (Spinner) findViewById(R.id.profile_encoding_spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.encoding_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); profileEncodingSpinner.setAdapter(adapter); } private void newProfile() { final Button profileSave = (Button)findViewById(R.id.profile_save); profileSave.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Prepare values String r01 = ((EditText)findViewById(R.id.profile_name)).getText().toString(); String r02 = ((EditText)findViewById(R.id.profile_nickname)).getText().toString(); String r03 = ((EditText)findViewById(R.id.profile_altnick)).getText().toString(); String r04 = ((EditText)findViewById(R.id.profile_server_address)).getText().toString(); String port= ((EditText)findViewById(R.id.profile_server_port)).getText().toString(); int r05 = Integer.parseInt(port); String r06 = ((EditText)findViewById(R.id.profile_chatrooms)).getText().toString(); String r07 = ((EditText)findViewById(R.id.profile_ident)).getText().toString(); String r08 = ((EditText)findViewById(R.id.profile_realname)).getText().toString(); final Spinner profile_encoding_spinner = (Spinner) findViewById(R.id.profile_encoding_spinner); int r09 = profile_encoding_spinner.getSelectedItemPosition(); String r10 = ((EditText)findViewById(R.id.profile_onconnect)).getText().toString(); // Connect to db and submit DBProfileManager db = new DBProfileManager(ProfileActivity.this); db.addRow(r01, r02, r03, r04, r05, r06, r07, r08, r09, r10); db.close(); finish(); } }); final Button profileCancel = (Button)findViewById(R.id.profile_cancel); profileCancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Ignore changes finish(); } }); setupSpinners(); // Set defaults final EditText profileNickname = (EditText)findViewById(R.id.profile_nickname); profileNickname.setText("Android" + mGenerator.nextInt(100)); final EditText profileAltnick = (EditText)findViewById(R.id.profile_altnick); profileAltnick.setText("Android" + mGenerator.nextInt(100)); final EditText profileName = (EditText)findViewById(R.id.profile_name); profileName.setText("New profile"); } private void editProfile(final int profile_id) { setupSpinners(); // Set values DBProfileManager db = new DBProfileManager(ProfileActivity.this); ArrayList<Object> row = db.getRowAsArray(profile_id); db.close(); final EditText profileName = (EditText)findViewById(R.id.profile_name); profileName.setText((String)row.get(1)); final EditText profileNickname = (EditText)findViewById(R.id.profile_nickname); profileNickname.setText((String)row.get(2)); final EditText profileAltnick = (EditText)findViewById(R.id.profile_altnick); profileAltnick.setText((String)row.get(3)); final EditText profileServerAddress = (EditText)findViewById(R.id.profile_server_address); profileServerAddress.setText((String)row.get(4)); final EditText profileServerPort = (EditText)findViewById(R.id.profile_server_port); profileServerPort.setText((String)row.get(5).toString()); final EditText profileChatrooms = (EditText)findViewById(R.id.profile_chatrooms); profileChatrooms.setText((String)row.get(6)); final EditText profileIdent = (EditText)findViewById(R.id.profile_ident); profileIdent.setText((String)row.get(7)); final EditText profileRealname = (EditText)findViewById(R.id.profile_realname); profileRealname.setText((String)row.get(8)); final Spinner profileEncodingSpinner = (Spinner) findViewById(R.id.profile_encoding_spinner); profileEncodingSpinner.setSelection(Integer.parseInt(row.get(9).toString())); final EditText profileOnconnect = (EditText)findViewById(R.id.profile_onconnect); profileOnconnect.setText((String)row.get(10)); final Button profileSave = (Button)findViewById(R.id.profile_save); profileSave.setText("Update profile"); profileSave.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Prepare values String r01 = ((EditText)findViewById(R.id.profile_name)).getText().toString(); String r02 = ((EditText)findViewById(R.id.profile_nickname)).getText().toString(); String r03 = ((EditText)findViewById(R.id.profile_altnick)).getText().toString(); String r04 = ((EditText)findViewById(R.id.profile_server_address)).getText().toString(); String port= ((EditText)findViewById(R.id.profile_server_port)).getText().toString(); int r05 = Integer.parseInt(port); String r06 = ((EditText)findViewById(R.id.profile_chatrooms)).getText().toString(); String r07 = ((EditText)findViewById(R.id.profile_ident)).getText().toString(); String r08 = ((EditText)findViewById(R.id.profile_realname)).getText().toString(); final Spinner profile_encoding_spinner = (Spinner) findViewById(R.id.profile_encoding_spinner); int r09 = profile_encoding_spinner.getSelectedItemPosition(); String r10 = ((EditText)findViewById(R.id.profile_onconnect)).getText().toString(); // Connect to db and submit DBProfileManager db = new DBProfileManager(ProfileActivity.this); db.updateRow(profile_id, r01, r02, r03, r04, r05, r06, r07, r08, r09, r10); db.close(); finish(); } }); final Button profileCancel = (Button)findViewById(R.id.profile_cancel); profileCancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Ignore changes finish(); } }); // hack to ignore 2 OnItemSelectedListener items mCount = 2; } public void setWizardValues() { Log.d(getClass().getSimpleName(),"setWizardValues()"); final Spinner profileServerSpinner = (Spinner)findViewById(R.id.profile_server_spinner); int pos = profileServerSpinner.getSelectedItemPosition(); if(pos == AdapterView.INVALID_POSITION) return; String[] values = profileServerSpinner.getItemAtPosition(pos).toString().split(":"); if(values.length == 2) { final EditText profileServerAddress = (EditText)findViewById(R.id.profile_server_address); final EditText profileServerPort = (EditText)findViewById(R.id.profile_server_port); profileServerAddress.setText(values[0]); profileServerPort.setText(values[1]); } } public void setServerValues() { Log.d(getClass().getSimpleName(),"setServerValues()"); final Spinner profileNetworkSpinner = (Spinner) findViewById(R.id.profile_network_spinner); String currentNetwork = profileNetworkSpinner.getItemAtPosition(profileNetworkSpinner.getSelectedItemPosition()).toString(); Network n = (Network)mNetworksList.get(currentNetwork); final Spinner profileServerSpinner = (Spinner)findViewById(R.id.profile_server_spinner); @SuppressWarnings("unchecked") ArrayAdapter<CharSequence> adapter = (ArrayAdapter<CharSequence>) profileServerSpinner.getAdapter(); adapter.clear(); // empty adapter // Iterate over all servers from current network for(int i = 0; i < n.getServers().size(); i++) { // Iterate over all available ports for (int j = 0; j < n.getServers().get(i).getPorts().size(); j++) adapter.add(n.getServers().get(i).getAddress() + ":" + Integer.toString(n.getServers().get(i).getPorts().get(j))); } // Choose a random server from the list after selecting a network to balance load profileServerSpinner.setSelection(mGenerator.nextInt(profileServerSpinner.getCount())); // Apply values setWizardValues(); } public class NetworkOnItemSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if (mInitializedCount < mCount) mInitializedCount++; else setServerValues(); } public void onNothingSelected(AdapterView<?> parent) { } } public class ServerOnItemSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if (mInitializedCount < mCount) mInitializedCount++; else setWizardValues(); } public void onNothingSelected(AdapterView<?> parent) { } } private void loadServerlist() { ServerList serverlist = new ServerList(); mNetworksList = serverlist.getNetworksList(); } private class ServerList { Hashtable<String, Network> networksList = new Hashtable<String, Network>(); public ServerList() { importServerlist(); } private void importServerlist() { // Original source: http://www.mirc.com/servers.html InputStream is = getResources().openRawResource(R.raw.servers); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String readLine = null; int label = 0; try { // While the BufferedReader readLine is not null while ((readLine = br.readLine()) != null) { // Read Label to set label state if(readLine.equals("[timestamp]")) // Reading timestamp { label = 0; continue; } else if(readLine.equals("[networks]")) // Reading networks { label = 1; continue; } else if(readLine.equals("[servers]")) // Reading server addresses { label = 2; // Used for networks without group name networksList.put("Random", new Network("Random")); continue; } else if(readLine.equals("")) { continue; } // Values if(label == 1) { String networks[] = readLine.split("="); // Add Groups networksList.put(networks[1], new Network(networks[1])); } else if(label == 2) { List<Integer> portsList = new ArrayList<Integer>(); String servers[] = readLine.split("="); // Get name, group, address and portlist String name = servers[1].split("SERVER:")[0]; String group = servers[1].split("GROUP:")[1]; String address = servers[1].split(":")[1]; String ports = servers[1].split(":")[2].split("GROUP")[0]; // Split up port array String portArray[] = ports.split(","); for(int i=0; i < portArray.length; i++) { // Check if entry is a range String portNumbers[] = portArray[i].split("-"); if(portNumbers.length == 2) { // Add all ports one by one for(int p = Integer.parseInt(portNumbers[0]); p <= Integer.parseInt(portNumbers[1]); p++) portsList.add(p); } else { // Add single port, no clue why some have a + sign if(portArray[i].charAt(0) == "+".charAt(0)) portsList.add(Integer.parseInt(portArray[i].substring(1))); else portsList.add(Integer.parseInt(portArray[i])); } } // All data is know, create a server object Server sv = new Server(name); sv.setAddress(address); sv.setPorts(portsList); // Add server object to the network list (check if the group exists) if(networksList.containsKey(group)) networksList.get(group).getServers().add(sv); else { //Log.d("group", "Group does not exist in list: " + group); networksList.get("Random").getServers().add(sv); } } } // Close the InputStream and BufferedReader is.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } public Hashtable<String, Network> getNetworksList() { return networksList; } } public class Network { private String mName; private List<Server> mServers = new ArrayList<Server>(); public Network(String name) { mName = name; } public String getName() { return mName; } public List<Server> getServers() { return mServers; } } public class Server { private String mName; private String mAddress; private List<Integer> mPorts = new ArrayList<Integer>(); public Server(String name) { mName = name; } public String getName() { return mName; } public String getAddress() { return mAddress; } public void setAddress(String address) { mAddress = address; } public List<Integer> getPorts() { return mPorts; } public void setPorts(List<Integer> ports) { mPorts = ports; } } }
0skillz63-irc
fIRC3/src/com/falcon4ever/fIRC3/ProfileActivity.java
Java
gpl3
20,248
/* * fIRC - a free IRC client for the Android platform. * http://code.google.com/p/firc-chat/ * * Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com> * http://www.multigesture.net/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.falcon4ever.fIRC3; import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import org.jared.commons.ui.R; import org.jared.commons.ui.WorkspaceView; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.TextView; import com.falcon4ever.fIRC3.service.ChatService; import com.falcon4ever.fIRC3.service.ChatService.LocalBinder; import com.falcon4ever.fIRC3.utils.ChatMessage; public class ChatActivity extends Activity { private HashMap<String, ArrayList<ChatMessage>> mChatMessagesList = new HashMap<String, ArrayList<ChatMessage>>(); private HashMap<String, ChatAdapter> mChatAdapterList = new HashMap<String, ChatAdapter>(); private HashMap<Integer, String> mScreenLUT = new HashMap<Integer, String>(); private ChatService mService; private boolean mBound = false; private int mProfileId; private EditText mChatInput; private WorkspaceView mWorkView = null; private LayoutInflater mInflater; private Handler IncomingHandler = new Handler() { public void handleMessage(Message msg) { //Log.d("IncomingHandler", "UI msg: " + msg.what); switch (msg.what) { // Replay messages case ChatService.MSG_UI_INIT: { ChatMessage chatmsg = (ChatMessage) msg.obj; if(mChatMessagesList.containsKey(chatmsg.getChannel())) { mChatMessagesList.get(chatmsg.getChannel()).add(chatmsg); } else { // Add channel mChatMessagesList.put(chatmsg.getChannel(), new ArrayList<ChatMessage>()); mChatMessagesList.get(chatmsg.getChannel()).add(chatmsg); } } break; // Initialize panels case ChatService.MSG_UI_INIT_DONE: { addPanels(); } break; // Update UI case ChatService.MSG_UI_UPDATE: { ChatMessage chatmsg = (ChatMessage)msg.obj; if(mChatMessagesList.containsKey(chatmsg.getChannel())) { mChatMessagesList.get(chatmsg.getChannel()).add(chatmsg); } else { mChatMessagesList.put(chatmsg.getChannel(), new ArrayList<ChatMessage>()); mChatMessagesList.get(chatmsg.getChannel()).add(chatmsg); addPanels(); return; } // update adapter mChatAdapterList.get(chatmsg.getChannel()).notifyDataSetChanged(); } break; default: Log.e(getClass().getSimpleName(), "Unhandled message IncomingHandler " + msg.what); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View mainLayout = mInflater.inflate(R.layout.chat, null, false); setContentView(mainLayout); mChatInput = (EditText)findViewById(R.id.chat_input); final Button submitButton = (Button)findViewById(R.id.chat_submit); submitButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { submitMessage(); } }); final Bundle extras = getIntent().getExtras(); mProfileId = extras.getInt("profile_id"); Log.d(getClass().getSimpleName(),"Chat: profile_id: " + Integer.toString(mProfileId)); // Hide keyboard on Activity launch this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // Bind to LocalService Intent intent = new Intent(this, ChatService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); mChatMessagesList.put("server", new ArrayList<ChatMessage>()); } @Override protected void onDestroy() { super.onDestroy(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } @Override protected void onPause() { super.onPause(); if (mBound) { if(mWorkView != null) mService.getIrcConn(mProfileId).setCurrentScreen(mWorkView.getCurrentScreen()); mService.setHandler(null); mService.setActiveProfile(-1); } } private void submitMessage() { String msg = mChatInput.getText().toString(); if(msg.length() > 0) { String newmessage = ""; if(mScreenLUT.get(mWorkView.getCurrentScreen()).equalsIgnoreCase("server")) { // Send RAW message to server newmessage = msg; } else { // PRIVMSG dest :msg newmessage = "PRIVMSG " + mScreenLUT.get(mWorkView.getCurrentScreen()) + " :" + msg; } if (mBound) { if(mService.getIrcConn(mProfileId) != null) mService.getIrcConn(mProfileId).sendMessage(newmessage); } } mChatInput.setText(""); } private void addPanels() { Log.d(getClass().getSimpleName(), "addPanels()"); mChatAdapterList.clear(); FrameLayout chatFrame = (FrameLayout)findViewById(R.id.chat_frame); chatFrame.removeAllViews(); mWorkView = null; // Create new WorkspaceView mWorkView = new WorkspaceView(this, null); mWorkView.setTouchSlop(32); boolean hasChannels = false; int i = 0; if(mBound) { for (Entry<String, ArrayList<ChatMessage>> entry: mChatMessagesList.entrySet()) { hasChannels = true; View view = mInflater.inflate(R.layout.chat_view, null, false); mWorkView.addView(view); TextView chatTitlebar = (TextView)view.findViewById(R.id.chat_titlebar); chatTitlebar.setText(entry.getKey()); ListView lv = (ListView)view.findViewById(R.id.chat_list); lv.setFastScrollEnabled(true); ChatAdapter ca = new ChatAdapter(this, R.layout.chat_row, (ArrayList<ChatMessage>)entry.getValue()); mChatAdapterList.put(entry.getKey(), ca); mScreenLUT.put(i++, entry.getKey()); lv.setAdapter(ca); } if(hasChannels) { chatFrame.addView(mWorkView); if(mWorkView != null) mWorkView.setCurrentScreen(mService.getIrcConn(mProfileId).getCurrentScreen()); } } } /////////////////////////////////////////////////////////////////////////////////////////////// // ServiceConnection /////////////////////////////////////////////////////////////////////////////////////////////// private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; Log.d("ChatActivity", "onServiceConnected"); mService.setHandler(IncomingHandler); mService.setActiveProfile(mProfileId); mService.getIrcConn(mProfileId).initializePanels(); } public void onServiceDisconnected(ComponentName className) { mBound = false; } }; /////////////////////////////////////////////////////////////////////////////////////////////// // ChatAdapter /////////////////////////////////////////////////////////////////////////////////////////////// private class ChatAdapter extends ArrayAdapter<ChatMessage> { public static final int USER_TEXT_COLOR = 0xff000000; public static final int USER_BACKGROUND_COLOR = 0xfff8d8f8; public static final int CHANNEL_TEXT_COLOR = 0xff000000; public static final int CHANNEL_BACKGROUND_COLOR = 0xffd8e8f8; public static final int SERVER_TEXT_COLOR = 0xff000000; public static final int SERVER_BACKGROUND_COLOR = 0xffe0e0e0; private ArrayList<ChatMessage> mItems; private LayoutInflater mInflater; public ChatAdapter(Context context, int textViewResourceId, ArrayList<ChatMessage> items) { super(context, textViewResourceId, items); mItems = items; mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mInflater.inflate(R.layout.chat_row, parent, false); } ChatMessage o = mItems.get(position); if (o != null) { TextView tt = (TextView) convertView.findViewById(R.id.label); if (tt != null) { if(o.getType() == 0) { tt.setTextColor(USER_TEXT_COLOR); tt.setBackgroundColor(USER_BACKGROUND_COLOR); } else if(o.getType() == 1) { tt.setTextColor(CHANNEL_TEXT_COLOR); tt.setBackgroundColor(CHANNEL_BACKGROUND_COLOR); } else { tt.setTextColor(SERVER_TEXT_COLOR); tt.setBackgroundColor(SERVER_BACKGROUND_COLOR); } tt.setText(o.getChatMessage()); } } return convertView; } } }
0skillz63-irc
fIRC3/src/com/falcon4ever/fIRC3/ChatActivity.java
Java
gpl3
11,182
/* * fIRC - a free IRC client for the Android platform. * http://code.google.com/p/firc-chat/ * * Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com> * http://www.multigesture.net/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.falcon4ever.fIRC3.utils; import java.util.ArrayList; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; // Based on: http://www.anotherandroidblog.com/2010/08/04/android-database-tutorial/ public class DBProfileManager { private Context context; private SQLiteDatabase db; private final String DB_NAME = "firc_db"; private final int DB_VERSION = 1; private final String TABLE_NAME = "db_profiles"; private final String TABLE_ROW_ID = "id"; private final String TABLE_ROW_01 = "profile_name"; // TEXT private final String TABLE_ROW_02 = "profile_nickname"; // TEXT private final String TABLE_ROW_03 = "profile_altnick"; // TEXT private final String TABLE_ROW_04 = "profile_server_address";//TEXT private final String TABLE_ROW_05 = "profile_port"; // INTEGER private final String TABLE_ROW_06 = "profile_chatrooms"; // TEXT private final String TABLE_ROW_07 = "profile_ident"; // TEXT private final String TABLE_ROW_08 = "profile_realname"; // TEXT private final String TABLE_ROW_09 = "profile_encoding"; // INTEGER private final String TABLE_ROW_10 = "profile_onconnect"; // TEXT private CustomSQLiteOpenHelper helper; public DBProfileManager(Context context) { this.setContext(context); // create or open the database helper = new CustomSQLiteOpenHelper(context); this.db = helper.getWritableDatabase(); } public void close() { if (helper != null) helper.close(); if (db != null) db.close(); } public void addRow(String r01, String r02, String r03, String r04, int r05, String r06, String r07, String r08, int r09, String r10) { ContentValues values = new ContentValues(); values.put(TABLE_ROW_01, r01); values.put(TABLE_ROW_02, r02); values.put(TABLE_ROW_03, r03); values.put(TABLE_ROW_04, r04); values.put(TABLE_ROW_05, r05); values.put(TABLE_ROW_06, r06); values.put(TABLE_ROW_07, r07); values.put(TABLE_ROW_08, r08); values.put(TABLE_ROW_09, r09); values.put(TABLE_ROW_10, r10); // ask the database object to insert the new data try { long rowID = db.insert(TABLE_NAME, null, values); Log.d(getClass().getSimpleName(), "SQLiteDatabase addRow - Row ID: " + Integer.toString((int)rowID)); } catch(Exception e) { Log.e("DB ERROR", e.toString()); e.printStackTrace(); } } public void deleteRow(long rowID) { Log.d(getClass().getSimpleName(), "SQLiteDatabase delete - Row ID: " + Integer.toString((int)rowID)); // ask the database manager to delete the row of given id try { db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null); } catch (Exception e) { Log.e("DB ERROR", e.toString()); e.printStackTrace(); } } public void updateRow(long rowID, String r01, String r02, String r03, String r04, int r05, String r06, String r07, String r08, int r09, String r10) { Log.d(getClass().getSimpleName(), "SQLiteDatabase update - Row ID: " + Integer.toString((int)rowID)); // this is a key value pair holder used by android's SQLite functions ContentValues values = new ContentValues(); values.put(TABLE_ROW_01, r01); values.put(TABLE_ROW_02, r02); values.put(TABLE_ROW_03, r03); values.put(TABLE_ROW_04, r04); values.put(TABLE_ROW_05, r05); values.put(TABLE_ROW_06, r06); values.put(TABLE_ROW_07, r07); values.put(TABLE_ROW_08, r08); values.put(TABLE_ROW_09, r09); values.put(TABLE_ROW_10, r10); // ask the database object to update the database row of given rowID try { db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null); } catch (Exception e) { Log.e("DB Error", e.toString()); e.printStackTrace(); } } public ArrayList<Object> getRowAsArray(long rowID) { ArrayList<Object> rowArray = new ArrayList<Object>(); Cursor cursor; try { cursor = db.query ( TABLE_NAME, new String[] { TABLE_ROW_ID, TABLE_ROW_01, TABLE_ROW_02, TABLE_ROW_03, TABLE_ROW_04, TABLE_ROW_05, TABLE_ROW_06, TABLE_ROW_07, TABLE_ROW_08, TABLE_ROW_09, TABLE_ROW_10 }, TABLE_ROW_ID + "=" + rowID, null, null, null, null, null ); // move the pointer to position zero in the cursor. cursor.moveToFirst(); // if there is data available after the cursor's pointer, add // it to the ArrayList that will be returned by the method. if (!cursor.isAfterLast()) { do { rowArray.add(cursor.getLong(0)); rowArray.add(cursor.getString(1)); rowArray.add(cursor.getString(2)); rowArray.add(cursor.getString(3)); rowArray.add(cursor.getString(4)); rowArray.add(cursor.getLong(5)); rowArray.add(cursor.getString(6)); rowArray.add(cursor.getString(7)); rowArray.add(cursor.getString(8)); rowArray.add(cursor.getLong(9)); rowArray.add(cursor.getString(10)); } while (cursor.moveToNext()); } // let java know that you are through with the cursor. cursor.close(); } catch (SQLException e) { Log.e("DB ERROR", e.toString()); e.printStackTrace(); } // return the ArrayList containing the given row from the database. return rowArray; } public ArrayList<ArrayList<Object>> getAllRowsAsArrays() { // create an ArrayList that will hold all of the data collected from // the database. ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>(); // this is a database call that creates a "cursor" object. // the cursor object store the information collected from the // database and is used to iterate through the data. Cursor cursor; try { // ask the database object to create the cursor. cursor = db.query( TABLE_NAME, new String[]{TABLE_ROW_ID, TABLE_ROW_01, TABLE_ROW_02, TABLE_ROW_03, TABLE_ROW_04, TABLE_ROW_05, TABLE_ROW_06, TABLE_ROW_07, TABLE_ROW_08, TABLE_ROW_09, TABLE_ROW_10}, null, null, null, null, null ); // move the cursor's pointer to position zero. cursor.moveToFirst(); // if there is data after the current cursor position, add it // to the ArrayList. if (!cursor.isAfterLast()) { do { ArrayList<Object> dataList = new ArrayList<Object>(); dataList.add(cursor.getLong(0)); dataList.add(cursor.getString(1)); dataList.add(cursor.getString(2)); dataList.add(cursor.getString(3)); dataList.add(cursor.getString(4)); dataList.add(cursor.getLong(5)); dataList.add(cursor.getString(6)); dataList.add(cursor.getString(7)); dataList.add(cursor.getString(8)); dataList.add(cursor.getLong(9)); dataList.add(cursor.getString(10)); dataArrays.add(dataList); } // move the cursor's pointer up one position. while (cursor.moveToNext()); } } catch (SQLException e) { Log.e("DB Error", e.toString()); e.printStackTrace(); } // return the ArrayList that holds the data collected from // the database. return dataArrays; } public void setContext(Context context) { this.context = context; } public Context getContext() { return context; } private class CustomSQLiteOpenHelper extends SQLiteOpenHelper { public CustomSQLiteOpenHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { Log.d(getClass().getSimpleName(), "onCreate(SQLiteDatabase db)"); // This string is used to create the database. It should // be changed to suit your needs. String newTableQueryString = "create table " + TABLE_NAME + " (" + TABLE_ROW_ID + " integer primary key autoincrement not null," + TABLE_ROW_01 + " text," + TABLE_ROW_02 + " text," + TABLE_ROW_03 + " text," + TABLE_ROW_04 + " text," + TABLE_ROW_05 + " integer," + TABLE_ROW_06 + " text," + TABLE_ROW_07 + " text," + TABLE_ROW_08 + " text," + TABLE_ROW_09 + " integer," + TABLE_ROW_10 + " text" + ");"; // execute the query string to the database. db.execSQL(newTableQueryString); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // only used when updating database } } }
0skillz63-irc
fIRC3/src/com/falcon4ever/fIRC3/utils/DBProfileManager.java
Java
gpl3
9,579
/* * fIRC - a free IRC client for the Android platform. * http://code.google.com/p/firc-chat/ * * Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com> * http://www.multigesture.net/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.falcon4ever.fIRC3.utils; import android.os.Parcel; import android.os.Parcelable; public class ChatMessage implements Parcelable { private int mType; private String mChannel; private String mChatMessage; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeInt(mType); out.writeString(mChannel); out.writeString(mChatMessage); } public static final Parcelable.Creator<ChatMessage> CREATOR = new Parcelable.Creator<ChatMessage>() { public ChatMessage createFromParcel(Parcel in) { return new ChatMessage(in); } public ChatMessage[] newArray(int size) { return new ChatMessage[size]; } }; private ChatMessage(Parcel in) { mType = in.readInt(); mChannel = in.readString(); mChatMessage = in.readString(); } /////// public ChatMessage(){ } public String getChatMessage() { return mChatMessage; } public void setChatMessage(String chatMessage) { mChatMessage = chatMessage; } public int getType() { return mType; } public void setType(int type) { mType = type; } public String getChannel() { return mChannel; } public void setChannel(String channel) { mChannel = channel; } }
0skillz63-irc
fIRC3/src/com/falcon4ever/fIRC3/utils/ChatMessage.java
Java
gpl3
2,306
/* * fIRC - a free IRC client for the Android platform. * http://code.google.com/p/firc-chat/ * * Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com> * http://www.multigesture.net/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.falcon4ever.fIRC3.utils; public class ProfileState { private int mProfileId; private String mProfileName; private String mProfileNickname; private String mProfileAltnick; private String mProfileServer; private int mProfilePort; private String mProfileChatrooms; private String mProfileIdent; private String mProfileRealname; private int mProfileEncoding; private String mProfileOnconnect; private int mConnected; public int getProfileId() { return mProfileId; } public void setProfileId(int profileId) { mProfileId = profileId; } public String getProfile_name() { return mProfileName; } public void setProfileName(String profileName) { mProfileName = profileName; } public String getProfileNickname() { return mProfileNickname; } public void setProfileNickname(String profileNickname) { mProfileNickname = profileNickname; } public String getProfileAltnick() { return mProfileAltnick; } public void setProfileAltnick(String profileAltnick) { mProfileAltnick = profileAltnick; } public String getProfileServer() { return mProfileServer; } public void setProfileServer(String profileServer) { mProfileServer = profileServer; } public int getProfilePort() { return mProfilePort; } public void setProfilePort(int profilePort) { mProfilePort = profilePort; } public String getProfileChatrooms() { return mProfileChatrooms; } public void setProfileChatrooms(String profileChatrooms) { mProfileChatrooms = profileChatrooms; } public String getProfileIdent() { return mProfileIdent; } public void setProfileIdent(String profileIdent) { mProfileIdent = profileIdent; } public String getProfileRealname() { return mProfileRealname; } public void setProfileRealname(String profileRealname) { mProfileRealname = profileRealname; } public int getProfileEncoding() { return mProfileEncoding; } public void setProfileEncoding(int profileEncoding) { mProfileEncoding = profileEncoding; } public String getProfileOnconnect() { return mProfileOnconnect; } public void setProfileOnconnect(String profileOnconnect) { mProfileOnconnect = profileOnconnect; } public int getConnected() { return mConnected; } public void setConnected(int connected) { mConnected = connected; } }
0skillz63-irc
fIRC3/src/com/falcon4ever/fIRC3/utils/ProfileState.java
Java
gpl3
3,316
/* * fIRC - a free IRC client for the Android platform. * http://code.google.com/p/firc-chat/ * * Copyright (C) 2008-2011 Laurence Muller <laurence.muller@gmail.com> * http://www.multigesture.net/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.falcon4ever.fIRC3; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; // Notes: Just an experiment to show current playing track info public class PlaceholderActivity extends Activity { private String mTrack = null; private String mArtist = null; private String mAlbum = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.placeholder); } @Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction("com.android.music.metachanged"); registerReceiver(mReceiver, filter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(mReceiver); } private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mTrack = intent.getStringExtra("track"); mArtist = intent.getStringExtra("artist"); mAlbum = intent.getStringExtra("album"); String lastSong = "Playing: \"" + mArtist + " - " + mTrack + " (" + mAlbum + ")\""; Log.d("NowPlaying", lastSong); } }; }
0skillz63-irc
fIRC3/src/com/falcon4ever/fIRC3/PlaceholderActivity.java
Java
gpl3
2,411
package org.jared.commons.ui; /** * Copyright 2010 Eric Taix (eric.taix@gmail.com) Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and limitations under the * License. */ import android.content.Context; import android.graphics.*; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.view.animation.Interpolator; import android.widget.Scroller; /** * The workspace is a wide area with a infinite number of screens. Each screen contains a view. A workspace is meant to * be used with a fixed width only.<br/> * <br/> * This code has been done by using com.android.launcher.Workspace.java */ public class WorkspaceView extends ViewGroup { private static final int INVALID_POINTER = -1; private int mActivePointerId = INVALID_POINTER; private static final int INVALID_SCREEN = -1; // The velocity at which a fling gesture will cause us to snap to the next screen private static final int SNAP_VELOCITY = 500; // the default screen index private int defaultScreen; // The current screen index private int currentScreen; // The next screen index private int nextScreen = INVALID_SCREEN; // Wallpaper properties private Bitmap wallpaper; private Paint paint; private int wallpaperWidth; private int wallpaperHeight; private float wallpaperOffset; private boolean wallpaperLoaded; private boolean firstWallpaperLayout = true; private static final int TAB_INDICATOR_HEIGHT_PCT = 1; private RectF selectedTab; // The scroller which scroll each view private Scroller scroller; // A tracker which to calculate the velocity of a mouvement private VelocityTracker mVelocityTracker; // Tha last known values of X and Y private float lastMotionX; private float lastMotionY; private final static int TOUCH_STATE_REST = 0; private final static int TOUCH_STATE_SCROLLING = 1; // The current touch state private int touchState = TOUCH_STATE_REST; // The minimal distance of a touch slop private int touchSlop; // An internal flag to reset long press when user is scrolling private boolean allowLongPress; // A flag to know if touch event have to be ignored. Used also in internal private boolean locked; private WorkspaceOvershootInterpolator mScrollInterpolator; private int mMaximumVelocity; private Paint selectedTabPaint; private Canvas canvas; private RectF bar; private Paint tabIndicatorBackgroundPaint; private static class WorkspaceOvershootInterpolator implements Interpolator { private static final float DEFAULT_TENSION = 1.3f; private float mTension; public WorkspaceOvershootInterpolator() { mTension = DEFAULT_TENSION; } public void setDistance(int distance) { mTension = distance > 0 ? DEFAULT_TENSION / distance : DEFAULT_TENSION; } public void disableSettle() { mTension = 0.f; } public float getInterpolation(float t) { // _o(t) = t * t * ((tension + 1) * t + tension) // o(t) = _o(t - 1) + 1 t -= 1.0f; return t * t * ((mTension + 1) * t + mTension) + 1.0f; } } /** * Used to inflate the Workspace from XML. * * @param context The application's context. * @param attrs The attribtues set containing the Workspace's customization values. */ public WorkspaceView(Context context, AttributeSet attrs) { this(context, attrs, 0); } /** * Used to inflate the Workspace from XML. * * @param context The application's context. * @param attrs The attribtues set containing the Workspace's customization values. * @param defStyle Unused. */ public WorkspaceView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); defaultScreen = 0; initWorkspace(); } /** * Initializes various states for this workspace. */ private void initWorkspace() { mScrollInterpolator = new WorkspaceOvershootInterpolator(); scroller = new Scroller(getContext(),mScrollInterpolator); currentScreen = defaultScreen; paint = new Paint(); paint.setDither(false); // Does this do anything for me? final ViewConfiguration configuration = ViewConfiguration.get(getContext()); touchSlop = configuration.getScaledTouchSlop(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); selectedTabPaint = new Paint(); //selectedTabPaint.setColor(Color.rgb(0x99, 0xC2, 0x24)/*Color.CYAN*/); //selectedTabPaint.setColor(Color.RED); selectedTabPaint.setColor(Color.rgb(0x98, 0xc8, 0xe8)); selectedTabPaint.setStyle(Paint.Style.FILL_AND_STROKE); tabIndicatorBackgroundPaint = new Paint(); tabIndicatorBackgroundPaint.setColor(Color.GRAY); tabIndicatorBackgroundPaint.setStyle(Paint.Style.FILL); } /** * Set a new distance that a touch can wander before we think the user is scrolling in pixels slop<br/> * * @param touchSlopP */ public void setTouchSlop(int touchSlopP) { touchSlop = touchSlopP; } /** * Set the background's wallpaper. */ public void loadWallpaper(Bitmap bitmap) { wallpaper = bitmap; wallpaperLoaded = true; requestLayout(); invalidate(); } boolean isDefaultScreenShowing() { return currentScreen == defaultScreen; } /** * Returns the index of the currently displayed screen. * * @return The index of the currently displayed screen. */ public int getCurrentScreen() { return currentScreen; } /** * Sets the current screen. * * @param currentScreen */ public void setCurrentScreen(int theCurrentScreen) { if (!scroller.isFinished()) scroller.abortAnimation(); currentScreen = Math.max(0, Math.min(theCurrentScreen, getChildCount())); scrollTo(currentScreen * getWidth(), 0); //Log.d("workspace", "setCurrentScreen: width is " + getWidth()); invalidate(); } /** * Shows the default screen (defined by the firstScreen attribute in XML.) */ void showDefaultScreen() { setCurrentScreen(defaultScreen); } /** * Registers the specified listener on each screen contained in this workspace. * * @param l The listener used to respond to long clicks. */ @Override public void setOnLongClickListener(OnLongClickListener l) { final int count = getChildCount(); for (int i = 0; i < count; i++) { getChildAt(i).setOnLongClickListener(l); } } @Override public void computeScroll() { if (scroller.computeScrollOffset()) { scrollTo(scroller.getCurrX(), scroller.getCurrY()); postInvalidate(); } else if (nextScreen != INVALID_SCREEN) { currentScreen = Math.max(0, Math.min(nextScreen, getChildCount() - 1)); nextScreen = INVALID_SCREEN; } } /** * ViewGroup.dispatchDraw() supports many features we don't need: clip to padding, layout animation, animation * listener, disappearing children, etc. The following implementation attempts to fast-track the drawing dispatch by * drawing only what we know needs to be drawn. */ @Override protected void dispatchDraw(Canvas canvas) { // First draw the wallpaper if needed if (wallpaper != null) { float x = getScrollX() * wallpaperOffset; if (x + wallpaperWidth < getRight() - getLeft()) { x = getRight() - getLeft() - wallpaperWidth; } canvas.drawBitmap(wallpaper, x, (getBottom() - getTop() - wallpaperHeight) / 2, paint); } // Determine if we need to draw every child or only the current screen boolean fastDraw = touchState != TOUCH_STATE_SCROLLING && nextScreen == INVALID_SCREEN; // If we are not scrolling or flinging, draw only the current screen if (fastDraw) { View v = getChildAt(currentScreen); drawChild(canvas, v, getDrawingTime()); } else { final long drawingTime = getDrawingTime(); // If we are flinging, draw only the current screen and the target screen if (nextScreen >= 0 && nextScreen < getChildCount() && Math.abs(currentScreen - nextScreen) == 1) { drawChild(canvas, getChildAt(currentScreen), drawingTime); drawChild(canvas, getChildAt(nextScreen), drawingTime); } else { // If we are scrolling, draw all of our children final int count = getChildCount(); for (int i = 0; i < count; i++) { drawChild(canvas, getChildAt(i), drawingTime); } } } updateTabIndicator(); canvas.drawBitmap(bitmap, getScrollX(), getMeasuredHeight()*(100-TAB_INDICATOR_HEIGHT_PCT)/100, paint); } /** * Measure the workspace AND also children */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int width = MeasureSpec.getSize(widthMeasureSpec); final int height = MeasureSpec.getSize(heightMeasureSpec); // Log.d("workspace","Height is " + height); final int widthMode = MeasureSpec.getMode(widthMeasureSpec); if (widthMode != MeasureSpec.EXACTLY) { throw new IllegalStateException("Workspace can only be used in EXACTLY mode."); } final int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode != MeasureSpec.EXACTLY) { throw new IllegalStateException("Workspace can only be used in EXACTLY mode."); } // The children are given the same width and height as the workspace final int count = getChildCount(); for (int i = 0; i < count; i++) { int adjustedHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height*(100-TAB_INDICATOR_HEIGHT_PCT)/100, heightMode); getChildAt(i).measure(widthMeasureSpec,adjustedHeightMeasureSpec); } // Compute wallpaper if (wallpaperLoaded) { wallpaperLoaded = false; wallpaper = centerToFit(wallpaper, width, height, getContext()); wallpaperWidth = wallpaper.getWidth(); wallpaperHeight = wallpaper.getHeight(); } wallpaperOffset = wallpaperWidth > width ? (count * width - wallpaperWidth) / ((count - 1) * (float) width) : 1.0f; if (firstWallpaperLayout) { scrollTo(currentScreen * width, 0); firstWallpaperLayout = false; } // Log.d("workspace","Top is "+getTop()+", bottom is "+getBottom()+", left is "+getLeft()+", right is "+getRight()); updateTabIndicator(); invalidate(); } Bitmap bitmap; private OnLoadListener load; private int lastEvHashCode; private void updateTabIndicator(){ int width = getMeasuredWidth(); int height = getMeasuredHeight(); //For drawing in its own bitmap: bar = new RectF(0, 0, width, (TAB_INDICATOR_HEIGHT_PCT*height/100)); int startPos = getScrollX()/(getChildCount()); selectedTab = new RectF(startPos, 0, startPos+width/getChildCount(), (TAB_INDICATOR_HEIGHT_PCT*height/100)); bitmap = Bitmap.createBitmap(width, (TAB_INDICATOR_HEIGHT_PCT*height/100), Bitmap.Config.ARGB_8888); canvas = new Canvas(bitmap); canvas.drawRoundRect(bar,0,0, tabIndicatorBackgroundPaint); canvas.drawRoundRect(selectedTab, 5,5, selectedTabPaint); } /** * Overrided method to layout child */ @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int childLeft = 0; final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != View.GONE) { final int childWidth = child.getMeasuredWidth(); child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight()); childLeft += childWidth; } } if (load!=null) { load.onLoad(); } } @Override public boolean dispatchUnhandledMove(View focused, int direction) { if (direction == View.FOCUS_LEFT) { if (getCurrentScreen() > 0) { scrollToScreen(getCurrentScreen() - 1); return true; } } else if (direction == View.FOCUS_RIGHT) { if (getCurrentScreen() < getChildCount() - 1) { scrollToScreen(getCurrentScreen() + 1); return true; } } return super.dispatchUnhandledMove(focused, direction); } /** * This method JUST determines whether we want to intercept the motion. If we return true, onTouchEvent will be called * and we do the actual scrolling there. */ @Override public boolean onInterceptTouchEvent(MotionEvent ev) { // Log.d("workspace","Intercepted a touch event"); if (locked) { return true; } /* * Shortcut the most recurring case: the user is in the dragging state and he is moving his finger. We want to * intercept this motion. */ final int action = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (touchState != TOUCH_STATE_REST)) { return true; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); // switch (action & MotionEvent.ACTION_MASK) { switch (action) { case MotionEvent.ACTION_MOVE: // Log.d("workspace","Intercepted a move event"); /* * Locally do absolute value. mLastMotionX is set to the y value of the down event. */ handleInterceptMove(ev); break; case MotionEvent.ACTION_DOWN: // Remember location of down touch final float x1 = ev.getX(); final float y1 = ev.getY(); lastMotionX = x1; lastMotionY = y1; allowLongPress = true; mActivePointerId = ev.getPointerId(0); /* * If being flinged and user touches the screen, initiate drag; otherwise don't. mScroller.isFinished should be * false when being flinged. */ touchState = scroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING; break; case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: mActivePointerId = INVALID_POINTER; allowLongPress = false; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } touchState = TOUCH_STATE_REST; break; case MotionEvent.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } /* * The only time we want to intercept motion events is if we are in the drag mode. */ return touchState != TOUCH_STATE_REST; } private void handleInterceptMove(MotionEvent ev) { final int pointerIndex = ev.findPointerIndex(mActivePointerId); final float x = ev.getX(pointerIndex); final float y = ev.getY(pointerIndex); final int xDiff = (int) Math.abs(x - lastMotionX); final int yDiff = (int) Math.abs(y - lastMotionY); boolean xMoved = xDiff > touchSlop; boolean yMoved = yDiff > touchSlop; if (xMoved || yMoved) { //Log.d("workspace","Detected move. Checking to scroll."); if (xMoved && !yMoved) { //Log.d("workspace","Detected X move. Scrolling."); // Scroll if the user moved far enough along the X axis touchState = TOUCH_STATE_SCROLLING; lastMotionX = x; } // Either way, cancel any pending longpress if (allowLongPress) { allowLongPress = false; // Try canceling the long press. It could also have been scheduled // by a distant descendant, so use the mAllowLongPress flag to block // everything final View currentView = getChildAt(currentScreen); currentView.cancelLongPress(); } } } private void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT; final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; lastMotionX = ev.getX(newPointerIndex); lastMotionY = ev.getY(newPointerIndex); mActivePointerId = ev.getPointerId(newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } /** * Track the touch event */ @Override public boolean onTouchEvent(MotionEvent ev) { // Log.d("workspace","caught a touch event"); if (locked) { return true; } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final int action = ev.getAction(); final float x = ev.getX(); switch (action) { case MotionEvent.ACTION_DOWN: //We can still get here even if we returned false from the intercept function. //That's the only way we can get a TOUCH_STATE_REST (0) here. //That means that our child hasn't handled the event, so we need to // Log.d("workspace","caught a down touch event and touchstate =" + touchState); if(touchState != TOUCH_STATE_REST){ /* * If being flinged and user touches, stop the fling. isFinished will be false if being flinged. */ if (!scroller.isFinished()) { scroller.abortAnimation(); } // Remember where the motion event started lastMotionX = x; mActivePointerId = ev.getPointerId(0); } break; case MotionEvent.ACTION_MOVE: if (touchState == TOUCH_STATE_SCROLLING) { handleScrollMove(ev); } else { // Log.d("workspace","caught a move touch event but not scrolling"); //NOTE: We will never hit this case in Android 2.2. This is to fix a 2.1 bug. //We need to do the work of interceptTouchEvent here because we don't intercept the move //on children who don't scroll. Log.d("workspace","handling move from onTouch"); if(onInterceptTouchEvent(ev) && touchState == TOUCH_STATE_SCROLLING){ handleScrollMove(ev); } } break; case MotionEvent.ACTION_UP: // Log.d("workspace","caught an up touch event"); if (touchState == TOUCH_STATE_SCROLLING) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int velocityX = (int) velocityTracker.getXVelocity(); if (velocityX > SNAP_VELOCITY && currentScreen > 0) { // Fling hard enough to move left scrollToScreen(currentScreen - 1); } else if (velocityX < -SNAP_VELOCITY && currentScreen < getChildCount() - 1) { // Fling hard enough to move right scrollToScreen(currentScreen + 1); } else { snapToDestination(); } if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } touchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; break; case MotionEvent.ACTION_CANCEL: Log.d("workspace","caught a cancel touch event"); touchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; break; case MotionEvent.ACTION_POINTER_UP: Log.d("workspace","caught a pointer up touch event"); onSecondaryPointerUp(ev); break; } return true; } private void handleScrollMove(MotionEvent ev){ // Scroll to follow the motion event final int pointerIndex = ev.findPointerIndex(mActivePointerId); final float x1 = ev.getX(pointerIndex); final int deltaX = (int) (lastMotionX - x1); lastMotionX = x1; if (deltaX < 0) { if (getScrollX() > 0) { //Scrollby invalidates automatically scrollBy(Math.max(-getScrollX(), deltaX), 0); } } else if (deltaX > 0) { final int availableToScroll = getChildAt(getChildCount() - 1).getRight() - getScrollX() - getWidth(); if (availableToScroll > 0) { //Scrollby invalidates automatically scrollBy(Math.min(availableToScroll, deltaX), 0); } } else { awakenScrollBars(); } } /** * Scroll to the appropriated screen depending of the current position */ private void snapToDestination() { final int screenWidth = getWidth(); final int whichScreen = (getScrollX() + (screenWidth / 2)) / screenWidth; //Log.d("workspace", "snapToDestination"); scrollToScreen(whichScreen); } /** * Scroll to a specific screen * * @param whichScreen */ public void scrollToScreen(int whichScreen) { scrollToScreen(whichScreen, false); } private void scrollToScreen(int whichScreen, boolean immediate){ //Log.d("workspace", "snapToScreen=" + whichScreen); boolean changingScreens = whichScreen != currentScreen; nextScreen = whichScreen; View focusedChild = getFocusedChild(); if (focusedChild != null && changingScreens && focusedChild == getChildAt(currentScreen)) { focusedChild.clearFocus(); } final int newX = whichScreen * getWidth(); final int delta = newX - getScrollX(); //Log.d("workspace", "newX=" + newX + " scrollX=" + getScrollX() + " delta=" + delta); scroller.startScroll(getScrollX(), 0, delta, 0, immediate ? 0 : Math.abs(delta) * 2); invalidate(); } public void scrollToScreenImmediate(int whichScreen){ scrollToScreen(whichScreen, true); } /** * Return the parceable instance to be saved */ @Override protected Parcelable onSaveInstanceState() { final SavedState state = new SavedState(super.onSaveInstanceState()); state.currentScreen = currentScreen; return state; } /** * Restore the previous saved current screen */ @Override protected void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); if (savedState.currentScreen != -1) { currentScreen = savedState.currentScreen; } } /** * Scroll to the left right screen */ public void scrollLeft() { if (nextScreen == INVALID_SCREEN && currentScreen > 0 && scroller.isFinished()) { scrollToScreen(currentScreen - 1); } } /** * Scroll to the next right screen */ public void scrollRight() { if (nextScreen == INVALID_SCREEN && currentScreen < getChildCount() - 1 && scroller.isFinished()) { scrollToScreen(currentScreen + 1); } } /** * Return the screen's index where a view has been added to. * * @param v * @return */ public int getScreenForView(View v) { int result = -1; if (v != null) { ViewParent vp = v.getParent(); int count = getChildCount(); for (int i = 0; i < count; i++) { if (vp == getChildAt(i)) { return i; } } } return result; } /** * Return a view instance according to the tag parameter or null if the view could not be found * * @param tag * @return */ public View getViewForTag(Object tag) { int screenCount = getChildCount(); for (int screen = 0; screen < screenCount; screen++) { View child = getChildAt(screen); if (child.getTag() == tag) { return child; } } return null; } /** * Unlocks the SlidingDrawer so that touch events are processed. * * @see #lock() */ public void unlock() { locked = false; } /** * Locks the SlidingDrawer so that touch events are ignores. * * @see #unlock() */ public void lock() { locked = true; } /** * @return True is long presses are still allowed for the current touch */ public boolean allowLongPress() { return allowLongPress; } /** * Move to the default screen */ public void moveToDefaultScreen() { scrollToScreen(defaultScreen); getChildAt(defaultScreen).requestFocus(); } // ========================= INNER CLASSES ============================== /** * A SavedState which save and load the current screen */ public static class SavedState extends BaseSavedState { int currentScreen = -1; /** * Internal constructor * * @param superState */ SavedState(Parcelable superState) { super(superState); } /** * Private constructor * * @param in */ private SavedState(Parcel in) { super(in); currentScreen = in.readInt(); } /** * Save the current screen */ @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(currentScreen); } /** * Return a Parcelable creator */ public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } //Added for "flipper" compatibility public int getDisplayedChild(){ return getCurrentScreen(); } public void setDisplayedChild(int i){ // setCurrentScreen(i); scrollToScreen(i); getChildAt(i).requestFocus(); } public void setOnLoadListener(OnLoadListener load){ this.load = load; } public void flipLeft(){ scrollLeft(); } public void flipRight(){ scrollRight(); } // ======================== UTILITIES METHODS ========================== /** * Return a centered Bitmap * * @param bitmap * @param width * @param height * @param context * @return */ static Bitmap centerToFit(Bitmap bitmap, int width, int height, Context context) { final int bitmapWidth = bitmap.getWidth(); final int bitmapHeight = bitmap.getHeight(); if (bitmapWidth < width || bitmapHeight < height) { // Normally should get the window_background color of the context int color = Integer.valueOf("FF191919", 16); Bitmap centered = Bitmap.createBitmap(bitmapWidth < width ? width : bitmapWidth, bitmapHeight < height ? height : bitmapHeight, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(centered); canvas.drawColor(color); canvas.drawBitmap(bitmap, (width - bitmapWidth) / 2.0f, (height - bitmapHeight) / 2.0f, null); bitmap = centered; } return bitmap; } }
0skillz63-irc
andro-views/src/org/jared/commons/ui/WorkspaceView.java
Java
gpl3
34,047
package org.jared.commons.ui; public interface OnLoadListener { void onLoad(); }
0skillz63-irc
andro-views/src/org/jared/commons/ui/OnLoadListener.java
Java
gpl3
85
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> </body> </html>
117shiyanshi
trunk/117comManager/jquerylib/index.html
HTML
asf20
258
<?php include 'configure.php'; $func = $_POST['func']; if($func == "addNum") { $id = $_POST['id']; $result = mysql_query("select * from components where uid = $id"); if($row = mysql_fetch_array($result)) { $num = $row["num"]; $num++; $query = "update components set num = $num where uid = $id"; if(mysql_query($query)) echo "$num"; else echo "0|操作失败"; } } else if($func == "minNum") { $id = $_POST['id']; $result = mysql_query("select * from components where uid = $id"); if($row = mysql_fetch_array($result)) { $num = $row["num"]; $num--; if($num == 0) $query = "delete from components where uid = $id"; else $query = "update components set num = $num where uid = $id"; if(mysql_query($query)) echo "$num"; else echo "0|操作失败"; } } ?>
117shiyanshi
trunk/117comManager/function.php
PHP
asf20
837
<?php include "configure.php"; htmlhead("添加元件"); htmlheadend(); ?> <?php if(isset($_GET['posted'])) { if($_GET['posted'] == "insert") { if($_GET['type'] == "new") { $query = "insert into comptype (name) values ('$_GET[newcomptype]')"; if(!mysql_query($query)) die("dabiaozi,database 出错!!!"); else { $query = "select * from comptype where name='$_GET[newcomptype]'"; $result = mysql_query($query); if($row = mysql_fetch_array($result)) { $type = $row['uid']; } else die("<span class=\"error\">dabiaozi,database 出错!!!</span>"); } } else $type = $_GET['type']; $sql = "insert into components (name, type, value, unit, description, num, position) values ('$_GET[name]','$type','$_GET[value]','$_GET[unit]','$_GET[description]','$_GET[num]','$_GET[position]')"; //echo $sql; if(!mysql_query($sql)) die("<span class=\"error\">dabiaozi,database 出错!!!</span>"); else echo "添加成功"; } else if($_GET['posted'] == "update") { if($_GET['type'] == "new") { $query = "insert into comptype (name) values ('$_GET[newcomptype]')"; if(!mysql_query($query)) die("dabiaozi,database 出错!!!"); else { $query = "select * from comptype where name='$_GET[newcomptype]'"; $result = mysql_query($query); if($row = mysql_fetch_array($result)) { $type = $row['uid']; } else die("<span class=\"error\">dabiaozi,database 出错!!!</span>"); } } else $type = $_GET['type']; $sql = "update components set name = $_GET[name], type = $type, value = $_GET[value], unit = $_GET[unit], description = $_GET[description], num = $_GET[num], position = $_GET[position] where uid = $_GET[uid]"; //echo $sql; if(!mysql_query($sql)) die("<span class=\"error\">dabiaozi,database 出错!!!</span>"); else echo "添加成功"; } } ?> <a class="index" href="index.php">主页</a> <div id="mainform"> <form action="" method="get"> <div> <?php if(isset($_GET['posted']) && $_GET['posted'] == "update") { // TODO 修改元件信息 } ?> <label for="name">元件名:</label> <input name="name" id="name" type="text" value="<?php if(isset($_GET["name"])) echo $_GET["name"]; ?>" /> </div> <div> <label for="type">元件类型:</label> <select name="type" id="type"> <option value="new">新建</option> <?php $sql = "select * from comptype"; $result = mysql_query($sql); while ($row = mysql_fetch_array($result)) { if(isset($_GET["type"])) { if($_GET["type"] == $row["uid"]) echo "<option value=\"$row[uid]\" selected=\"selected\" >$row[name]</option>"; } else echo "<option value=\"$row[uid]\">$row[name]</option>"; } ?> </select> <input type="text" name="newcomptype" /> </div> <div> <label for="value">值:</label> <input type="text" name="value" id="value" value="<?php if(isset($_GET["value"])) echo $_GET["value"]; ?>" /> </div> <div> <label for="num">数量:</label> <input type="text" name="num" id="num" value="<?php if(isset($_GET["num"])) echo $_GET["num"]; ?>" /> </div> <div> <label for="unit">单位:</label> <input type="text" name="unit" id="unit" value="<?php if(isset($_GET["unit"])) echo $_GET["unit"]; ?>" /> </div> <div> <label for="position">位置(保管人):</label> <input type="text" name="position" id="position" value="<?php if(isset($_GET["position"])) echo $_GET["position"]; ?>" /> </div> <div> <label for="description">描述:</label> <textarea name="description" rows="10" cols="50"></textarea> </div> <input type="hidden" name="posted" value="insert" /> <input type="submit" value="添加" class="yage_button" /> </form> </div> <?php htmltail(); ?>
117shiyanshi
trunk/117comManager/addcomp.php
PHP
asf20
3,935
/** * */
117shiyanshi
trunk/117comManager/js/conf.js
JavaScript
asf20
13
/** * */ colors = Array("#ffb","#fbf","#bff","#6ff","#ff6","#f6f","#6ff"); color = 0; $(document).ready(function() { $(".component").hover(function() { $("#"+$(this).children(".position").text()).addClass("myhover"); //$("#"+$(this).attr("value")).css("color","#fff"); },function() { $("#"+$(this).children(".position").text()).removeClass("myhover"); }); $(".component").click(function() { if($(this).hasClass("mystayhover")) { $(this).removeClass("mystayhover"); text = $(this).children(".position").text(); rem = true; $(".mystayhover").each(function() { if($(this).children(".position").text() == text) rem = false; }); if(rem) $("#"+$(this).children(".position").text()).removeClass("mystayhover"); }else { $(this).addClass("mystayhover"); $("#"+$(this).children(".position").text()).addClass("mystayhover"); } }); $(".box").hover(function() { id = $(this).attr("id"); $(".position").each(function() { if($(this).text() == id) { $(this).parent().addClass("myhover"); } }); },function() { $(".position").each(function() { if($(this).text() == id) { $(this).parent().removeClass("myhover"); } }); }); $(".box").click(function() { if($(this).hasClass("mystayhover")) { $(this).removeClass("mystayhover"); id = $(this).attr("id"); $(".position").each(function() { if($(this).text() == id) { $(this).parent().removeClass("mystayhover"); } }); }else { $(this).addClass("mystayhover"); id = $(this).attr("id"); $(".position").each(function() { if($(this).text() == id) { $(this).parent().addClass("mystayhover"); } }); } }); registNumOpera(); $(".box").dblclick(function() { self.location = "./addcomp.php?position=" + $(this).text(); }); }); function registNumOpera() { // TODO 添加数量增减支持 $(".comPlus").click(function() { self = $(this); $.post("function.php",{ id:$(this).parent().parent().attr("value"), func:"addNum" },function(data) { self.parent().html(data + "<input type=\"button\" class=\"comPlus yage_button\" value=\"+\" /><input type=\"button\" class=\"yage_button comMinus\" value=\"-\" />"); registNumOpera(); }); }); $(".comMinus").click(function() { self = $(this); $.post("function.php",{ id:$(this).parent().parent().attr("value"), func:"minNum" },function(data) { if(data == 0) { self.parent().parent().remove(); } else { self.parent().html(data + "<input type=\"button\" class=\"comPlus yage_button\" value=\"+\" /><input type=\"button\" class=\"yage_button comMinus\" value=\"-\" />"); registNumOpera(); } }); }); }
117shiyanshi
trunk/117comManager/js/control.js
JavaScript
asf20
2,770
<?php define('ABSPATH', dirname(dirname(__FILE__)) . '\\'); $domain = ""; $jquerylib = $domain . "jQuerylib/jquery-1.4.4.min.js"; $jqueryui = $domain . "jQuerylib/jquery-ui-1.8.9.custom.min.js"; $jslib = $domain . "js"; $jqueryuitheme = $domain . "css/custom-theme3/jquery-ui-1.8.10.custom.css"; $sql_server = "127.0.0.1"; //sqlserver name $sql_username = "root"; //sqlserver root username $sql_password = ""; //sqlserver root password $sql_database = "117com"; //database name $calendar = CAL_GREGORIAN; /* * connect sqlserver */ if (!($sql_handle = mysql_connect($sql_server,$sql_username,$sql_password))) { //sql_linkerror(); die("connect error"); } else { mysql_select_db($sql_database); mysql_query("SET NAMES UTF8"); } /********************************* */ function sql_link() { if (!mysql_connect($sql_server,$sql_username,$sql_password)) { sql_linkerror(); //die(); return false; } else { mysql_select_db($sql_database); mysql_query("SET NAMES UTF8"); } return true; } /************************************ whenever sql link error,call this fuction *************************************/ function sql_linkerror() { jumphtml('htmls/sqllink_error.html'); } include 'common.php'; session_start(); ?>
117shiyanshi
trunk/117comManager/configure.php
PHP
asf20
1,376
<?php include "configure.php"; htmlhead("117元件管理系统"); addjs("control.js"); htmlheadend(); ?> <img src="css/pic/logo.jpg" /><br> <a href='addcomp.php' title='添加元件' class='yage_button'>添加</a> <a href='inport.php' title='导入csv文件' class='yage_button'>导入</a> <a href="export.php" title="导出csv文件" class="yage_button">导出</a> <?php $query = "select components.uid,components.name,value,unit,num,position,description,comptype.name as type from components,comptype where components.type = comptype.uid"; $result = mysql_query($query); echo "<div><table>"; echo "<tr>"; echo "<td>元件名</td><td>元件类型</td><td>值</td><td>单位</td><td>数量</td><td>保管位置(保管人)</td><td>描述</td>"; echo "</tr>"; while ($row=mysql_fetch_array($result)) { echo "<tr class=\"component\" value=\"$row[uid]\" title=\"$row[description]\">"; echo "<td class=\"name\">$row[name]</td><td class=\"type\">$row[type]</td><td class=\"value\">$row[value]</td><td class=\"unit\">$row[unit]</td><td class=\"num\">$row[num]<input type=\"button\" class=\"comPlus yage_button\" value=\"+\" /><input type=\"button\" class=\"yage_button comMinus\" value=\"-\" /></td><td class=\"position\">$row[position]</td><td class=\"description\">$row[description]</td>"; echo "</tr>"; } echo "</table></div>"; ?> <?php $chars = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'); echo "<div id=\"comboxtable\"><table>"; for($i=0;$i<15;$i++) { echo "<tr>"; for($j=0;$j<15;$j++) { echo "<td class=\"box\" id=\"" . $chars[$j] . (15-$i) . "\">" . $chars[$j] . (15-$i) . "</td>"; } echo "</tr>"; } echo "</table></div>"; ?> <?php htmltail(); ?>
117shiyanshi
trunk/117comManager/index.php
PHP
asf20
1,815
<?php /******************************** * function: jumphtml * paraments: html location * return none */ function jumphtml($location) { echo "<script type='text/javascript'>window.location.replace('" . $domain . $location . "');</script>"; } function htmlhead($title="undefined",$ui="nui") { global $jquerylib,$jslib,$jqueryui,$jqueryuitheme; echo <<< htmlhead <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link type="text/css" href="css/all.css" rel="stylesheet" /> <script type="text/javascript" src="$jquerylib"></script> <script type="text/javascript" src="$jslib/conf.js"></script> htmlhead; if ($ui=="ui") { echo "<script type='text/javascript' src='$jqueryui'></script>"; echo "<link type='text/css' href='$jqueryuitheme' rel='stylesheet' />"; } echo "<title>$title</title>"; } function htmlheadend() { echo <<< head </head> <body> head; } function mapbar($location) { echo "<div class='mapbar' id='mapbar'>"; include $location; echo "</div>"; } function htmltail() { echo <<< htmltail </body> </html> htmltail; } function addjs($jsname) { global $jslib; echo "<script type='text/javascript' src='$jslib/$jsname'></script>"; } //要过滤的非法字符 $ArrFiltrate=array("'",";","\"","<",">"); //出错后要跳转的url,不填则默认前一页 $StrGoUrl=""; //是否存在数组中的值 function FunStringExist($StrFiltrate,$ArrFiltrate){ foreach ($ArrFiltrate as $key=>$value) if (strstr($StrFiltrate,$value)) return true; return false; } //合并$_POST 和 $_GET if(function_exists("array_merge")) { $ArrPostAndGet=array_merge($_POST,$_GET); } else { foreach($HTTP_POST_VARS as $key=>$value) $ArrPostAndGet[]=$value; foreach($HTTP_GET_VARS as $key=>$value) $ArrPostAndGet[]=$value; } //验证开始 foreach($ArrPostAndGet as $key=>$value){ if (FunStringExist($value,$ArrFiltrate)){ die("<script language=\"javascript\">alert(\"非法字符\");</script>"); /*if (emptyempty($StrGoUrl)) echo "<script language=\"javascript\">history.go(-1);</script>"; else echo "<script language=\"javascript\">window.location=\"".$StrGoUrl."\";</script>"; exit;*/ } } ?>
117shiyanshi
trunk/117comManager/common.php
PHP
asf20
2,539
<?php include "configure.php"; $Date = date("Y-m-d"); $Filename = $Date.".csv"; header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:filename=".$Filename); $query = "select * from comptype"; $result = mysql_query($query); while ($row = mysql_fetch_array($result)) $type[$row['uid']] = $row['name']; $query = "select * from components"; $result = mysql_query($query); echo "元件名,元件类型,值,数量,保管位置(保管人),描述\n"; while ($row=mysql_fetch_array($result)) echo "$row[name]," . $type[$row['type']] . ",$row[value],$row[num],$row[position],$row[description]\n"; ?>
117shiyanshi
trunk/117comManager/export.php
PHP
asf20
661
/* CSS Document */ .yage_button { border:#222 1px solid; background:#eee; text-decoration:none; color:#000; padding:3px; cursor:default; } .yage_button:hover { background:#333; color:#ddd; } table { border-collapse:collapse; margin:20px 0; } td { border:#222 solid 1px; } .component:hover,.box:hover { background:#99e; color:#000; cursor:default; } .component,.box { cursor:default; } label { width:100px; } .box { width:50px; height:20px; } #comboxtable { position:fixed; top:10px; right:20px; } .myhover { background:#99e; color:#000; cursor:default; } .mystayhover { background:#fbb; color:#000; cursor:default; }
117shiyanshi
trunk/117comManager/css/all.css
CSS
asf20
714
.itemline.newline:not(.editing) { display:none; } .list { width: 100%; height: 520px; } div[property=title] { width: 200px } div[property=type] { width: 60px } div[property=value] { width: 240px } div[property=enabled] { width: 60px } div[property=userAgent] { width: 70px } div[property=script] { width: 200px } div[property=description] { width: 300px } div[property=url] { width: 300px } div[property=compute], div[property=compute] button{ width: 80px } div[property=checksum] { width: 80px } [property=status] button { width: 70px; } #scriptEditor { display: block; width: 100%; height: 361px; }
007slmg-np-activex
web/editor.css
CSS
mpl11
694
.list { width: 800px; height: 400px; font-family: Arial, sans-serif; overflow-x: hidden; border: 3px solid #0D5995; background-color: #0D5995; padding: 1px; padding-top: 10px; border-top-left-radius: 15px; border-top-right-radius: 15px; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; } .listscroll { overflow-x: scroll; overflow-y: scroll; background-color: white; } .listitems { display: inline-block; } .listvalue, .header { display: inline-block; width: 80px; margin: 0px 6px; } .headers { background-color: transparent; position: relative; white-space: nowrap; display: inline-block; color:white; padding: 5px 0px; } .header{ white-space: normal; } .itemline { height: 32px; } .itemline:nth-child(odd) { background-color: white; } .itemline:nth-child(even) { background-color: whitesmoke; } .itemline.selected { background-color: #aaa; } .itemline:hover { background-color: #bbcee9 } .itemline.error, .itemline.error:hover { background-color: salmon; } .itemline > div { white-space: nowrap; padding: 4px 0px 0 0; } .itemline.editing > div{ padding: 3px 0px 0 0; } .valdisp, .valinput { background-color: transparent; width: 100%; display: block; } .listvalue { overflow-x: hidden; } .itemline.editing .listvalue:not(.readonly) .valdisp { display: none; } .valdisp { font-size: 13px; } .itemline:not(.editing) .valinput, .listvalue.readonly .valinput { display: none; } .itemline :focus { outline: none; } .valinput { border:1px solid #aaa; background-color: white; padding: 3px; margin: 0; } .itemline .valinput:focus { outline-color: rgba(0, 128, 256, 0.5); outline: 5px auto rgba(0, 128, 256, 0.5); }
007slmg-np-activex
web/list.css
CSS
mpl11
1,865
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. /* prop = { header, // String property, // String events, // type, // checkbox, select, input.type, button extra // depend on type } */ function List(config) { this.config = config; this.props = config.props; this.main = config.main; this.selectedLine = -2; this.lines = []; if (!config.getItems) { config.getItems = function() { return config.items; } } if (!config.getItemProp) { config.getItemProp = function(id, prop) { return config.getItem(id)[prop]; } } if (!config.setItemProp) { config.setItemProp = function(id, prop, value) { config.getItem(id)[prop] = value; } } if (!config.getItem) { config.getItem = function(id) { return config.getItems()[id]; } } if (!config.move) { config.move = function(a, b) { if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) { var list = config.getItems(); var tmp = list[a]; // remove a list.splice(a, 1); // insert b list.splice(b, 0, tmp); } } }; if (!config.insert) { config.insert = function(id, newItem) { config.getItems().splice(id, 0, newItem); } } if (!config.remove) { config.remove = function(a) { config.move(a, config.count() - 1); config.getItems().pop(); } } if (!config.validate) { config.validate = function() {return true;}; } if (!config.count) { config.count = function() { return config.getItems().length; } } if (!config.patch) { config.patch = function(id, newVal) { for (var name in newVal) { config.setItemProp(id, name, newVal[name]); } } } if (!config.defaultValue) { config.defaultValue = {}; } config.main.addClass('list'); } List.ids = { noline: -1, }; List.types = {}; List.prototype = { init: function() { with (this) { if (this.inited) { return; } this.inited = true; this.headergroup = $('<div class="headers"></div>'); for (var i = 0; i < props.length; ++i) { var header = $('<div class="header"></div>'). attr('property', props[i].property).html(props[i].header); headergroup.append(header); } this.scrolls = $('<div>').addClass('listscroll'); this.contents = $('<div class="listitems"></div>').appendTo(scrolls); scrolls.scroll(function() { headergroup.css('left', -(scrolls.scrollLeft()) + 'px'); }); contents.click(function(e) { if (e.target == contents[0]) { selectLine(List.ids.noline); } }); $(main).append(headergroup).append(scrolls); var height = this.main.height() - this.headergroup.outerHeight(); this.scrolls.height(height); load(); selectLine(List.ids.noline); } }, editNewLine: function() { this.startEdit(this.lines[this.lines.length - 1]); }, updatePropDisplay : function(line, prop) { var name = prop.property; obj = $('[property=' + name + ']', line); var ctrl = obj[0].listdata; var id = Number(line.attr('row')); if (id == this.config.count()) { var value = this.config.defaultValue[name]; if (value) { ctrl.value = value; } obj.trigger('createNew'); } else { ctrl.value = this.config.getItemProp(id, name); obj.trigger('update'); } }, updateLine: function(line) { for (var i = 0; i < this.props.length; ++i) { this.updatePropDisplay(line, this.props[i]); } if (Number(line.attr('row')) < this.config.count()) { line.trigger('update'); } else { line.addClass('newline'); } }, createLine: function() { with (this) { var line = $('<div></div>').addClass('itemline'); var inner = $('<div>'); line.append(inner); // create input boxes for (var i = 0; i < props.length; ++i) { var prop = props[i]; var ctrl = $('<div></div>').attr('property', prop.property) .addClass('listvalue').attr('tabindex', -1); var valueobj = new List.types[prop.type](ctrl, prop); var data = {list: this, line: line, prop: prop}; for (var e in prop.events) { ctrl.bind(e, data, prop.events[e]); } ctrl.bind('change', function(e) { validate(line); return true; }); ctrl.bind('keyup', function(e) { if (e.keyCode == 27) { cancelEdit(line); } }); ctrl.trigger('create'); inner.append(ctrl); } // Event listeners line.click(function(e) { startEdit(line); }); line.focusin(function(e) { startEdit(line); }); line.focusout(function(e) { finishEdit(line); }); for (var e in this.config.lineEvents) { line.bind(e, {list: this, line: line}, this.config.lineEvents[e]); } var list = this; line.bind('updating', function() { $(list).trigger('updating'); }); line.bind('updated', function() { $(list).trigger('updated'); }); this.bindId(line, this.lines.length); this.lines.push(line); line.appendTo(this.contents); return line; } }, refresh: function(lines) { var all = false; if (lines === undefined) { all = true; lines = []; } for (var i = this.lines.length; i <= this.config.count(); ++i) { var line = this.createLine(); lines.push(i); } while (this.lines.length > this.config.count() + 1) { this.lines.pop().remove(); } $('.newline', this.contents).removeClass('newline'); this.lines[this.lines.length - 1].addClass('newline'); if (all) { for (var i = 0; i < this.lines.length; ++i) { this.updateLine(this.lines[i]); } } else { for (var i = 0; i < lines.length; ++i) { this.updateLine(this.lines[lines[i]]); } } }, load: function() { this.contents.empty(); this.lines = []; this.refresh(); }, bindId: function(line, id) { line.attr('row', id); }, getLineNewValue: function(line) { var ret = {}; for (var i = 0; i < this.props.length; ++i) { this.getPropValue(line, ret, this.props[i]); } return ret; }, getPropValue: function(line, item, prop) { var name = prop.property; obj = $('[property=' + name + ']', line); var ctrl = obj[0].listdata; var value = ctrl.value; if (value !== undefined) { item[name] = value; } return value; }, startEdit: function(line) { if (line.hasClass('editing')) { return; } line.addClass('editing'); this.showLine(line); this.selectLine(line); var list = this; setTimeout(function() { if (!line[0].contains(document.activeElement)) { $('.valinput', line).first().focus(); } list.validate(line); }, 50); }, finishEdit: function(line) { var list = this; function doFinishEdit() { with(list) { if (line[0].contains(document.activeElement)) { return; } var valid = isValid(line); if (valid) { var id = Number(line.attr('row')); var newval = getLineNewValue(line); if (line.hasClass('newline')) { $(list).trigger('updating'); if(!config.insert(id, newval)) { line.removeClass('newline'); list.selectLine(line); $(list).trigger('add', id); addNewLine(); } } else { line.trigger('updating'); config.patch(id, newval); } line.trigger('updated'); } cancelEdit(line); } }; setTimeout(doFinishEdit, 50); }, cancelEdit: function(line) { line.removeClass('editing'); line.removeClass('error'); var id = Number(line.attr('row')); if (id == this.config.count() && this.selectedLine == id) { this.selectedLine = List.ids.noline; } this.updateLine(line); }, addNewLine: function() { with(this) { var line = $('.newline', contents); if (!line.length) { line = createLine().addClass('newline'); } return line; } }, isValid: function(line) { var id = Number(line.attr('row')); var obj = this.getLineNewValue(line); return valid = this.config.validate(id, obj); }, validate: function(line) { if (this.isValid(line)) { line.removeClass('error'); } else { line.addClass('error'); } }, move: function(a, b, keepSelect) { var len = this.config.count(); if (a == b || a < 0 || b < 0 || a >= len || b >= len) { return; } this.config.move(a, b); for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) { this.updateLine(this.getLine(i)); } if (keepSelect) { if (this.selectedLine == a) { this.selectLine(b); } else if (this.selectedLine == b) { this.selectLine(a); } } }, getLine: function(id) { if (id < 0 || id >= this.lines.length) { return null; } return this.lines[id]; }, remove: function(id) { id = Number(id); if (id < 0 || id >= this.config.count()) { return; } $(this).trigger('updating'); var len = this.lines.length; this.getLine(id).trigger('removing'); if (this.config.remove(id)) { return; } this.getLine(len - 1).remove(); this.lines.pop(); for (var i = id; i < len - 1; ++i) { this.updateLine(this.getLine(i)); } if (id >= len - 2) { this.selectLine(id); } else { this.selectLine(List.ids.noline); } $(this).trigger('updated'); }, selectLine: function(id) { var line = id; if (typeof id == "number") { line = this.getLine(id); } else { id = Number(line.attr('row')); } // Can't select the new line. if (line && line.hasClass('newline')) { line = null; id = List.ids.noline; } if (this.selectedLine == id) { return; } var oldline = this.getLine(this.selectedLine); if (oldline) { this.cancelEdit(oldline); oldline.removeClass('selected'); oldline.trigger('deselect'); this.selectedLine = List.ids.noline; } this.selectedLine = id; if (line != null) { line.addClass('selected'); line.trigger('select'); this.showLine(line); } $(this).trigger('select'); }, showLine: function(line) { var showtop = this.scrolls.scrollTop(); var showbottom = showtop + this.scrolls.height(); var top = line.offset().top - this.contents.offset().top; // Include the scroll bar var bottom = top + line.height() + 20; if (top < showtop) { // show at top this.scrolls.scrollTop(top); } else if (bottom > showbottom) { // show at bottom this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height())); } } };
007slmg-np-activex
web/list.js
JavaScript
mpl11
11,700
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. var baseDir = '/setting/'; var rules = []; var scripts = []; var issues = []; var dirty = false; function stringHash(str) { var hash = 0; if (str.length == 0) return hash; for (var i = 0; i < str.length; i++) { ch = str.charCodeAt(i); hash = ((hash << 5) - hash) + ch; hash = hash & hash; // Convert to 32bit integer } return hash; } function setScriptAutoComplete(e) { var last = /[^\s]*$/; var obj = $('input', e.target); $(obj).bind("keydown", function(event) { if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) { event.preventDefault(); } }) .autocomplete({ minLength: 0, source: function(request, response) { // delegate back to autocomplete, but extract the last term response($.ui.autocomplete.filter( scriptItems, last.exec(request.term)[0])); }, focus: function() { // prevent value inserted on focus return false; }, select: function(event, ui) { this.value = this.value.replace(last, ui.item.value); return false; } }); } var ruleProps = [ { header: "Identifier", property: "identifier", type: "input" }, { header: "Name", property: "title", type: "input" }, { header: "Mode", property: "type", type: "select", option: "static", options: [ {value: "wild", text: "WildChar"}, {value: "regex", text: "RegEx"}, {value: "clsid", text: "CLSID"} ] }, { header: "Pattern", property: "value", type: "input" }, { header: "Keyword", property: "keyword", type: "input" }, { header: "testURL", property: "testUrl", type: "input" }, { header: "UserAgent", property: "userAgent", type: "select", option: "static", options: [ {value: "", text: "Chrome"}, {value: "ie9", text: "MSIE9"}, {value: "ie8", text: "MSIE8"}, {value: "ie7", text: "MSIE7"}, {value: "ff7win", text: "Firefox 7 Windows"}, {value: "ff7mac", text: "Firefox 7 Mac"}, {value: "ip5", text: "iPhone"}, {value: "ipad5", text: "iPad"} ] }, { header: "Helper Script", property: "script", type: "input", events: { create: setScriptAutoComplete } }]; var currentScript = -1; function showScript(id) { var url = baseDir + scripts[id].url; currentScript = id; $(scriptEditor).val(''); $.ajax(url, { success: function(value) { origScript = value; $(scriptEditor).val(value); } }); $('#scriptDialog').dialog('open'); } function saveToFile(file, value) { $.ajax(baseDir + 'upload.php', { type: "POST", data: { file: file, data: value } }); } var checksumComputing = 0; function computeScriptChecksum(id) { scripts[id].checksum = "computing"; ++checksumComputing; scriptList.updateLine(scriptList.lines[id]); $.ajax(baseDir + scripts[id].url, { complete: function() { --checksumComputing; }, dataType: "text", success: function(value, status, xhr) { scripts[id].checksum = stringHash(value); scriptList.updateLine(scriptList.lines[id]); } }); } var origScript; function saveScript(id) { var value = $('#scriptEditor').val(); if (value == origScript) { return; } var file = scripts[id].url; ++scripts[id].version; scriptList.updateLine(scriptList.getLine(id)); saveToFile(file, value); dirty = true; } var scriptProps = [{ property: "identifier", header: "Identifier", type: "input" }, { property: "url", header: "URL", type: "input" }, { property: "version", header: "Version", type: "input" }, { property: "context", header: "Context", type: "select", option: "static", options: [ {value: "page", text: "Page"}, {value: "extension", text: "Extension"} ] }, { property: "show", header: "Show", type: "button", events: { create: function(e) { $('button', this).text('Show'); }, command: function(e) { showScript(Number(e.data.line.attr('row')), true); } } }, { property: "checksum", header: "checksum", type: "input", events: { "create": function(e) { $(this).addClass('readonly'); } } }, { property: "compute", header: "Checksum", type: "button", events: { create: function(e) { $('button', this).text('Recompute'); }, command: function(e) { computeScriptChecksum(Number(e.data.line.attr('row'))); } } }]; var issueProps = [{ header: "Identifier", property: "identifier", type: "input" }, { header: "Mode", property: "type", type: "select", option: "static", options: [ {value: "wild", text: "WildChar"}, {value: "regex", text: "RegEx"}, {value: "clsid", text: "CLSID"} ] }, { header: "Pattern", property: "value", type: "input" }, { header: "Description", property: "description", type: "input" }, { header: "IssueId", property: "issueId", type: "input" }, { header: "url", property: "url", type: "input" }]; // The JSON formatter is from http://joncom.be/code/javascript-json-formatter/ function FormatJSON(oData, sIndent) { function RealTypeOf(v) { if (typeof(v) == "object") { if (v === null) return "null"; if (v.constructor == Array) return "array"; if (v.constructor == Date) return "date"; if (v.constructor == RegExp) return "regex"; return "object"; } return typeof(v); } if (arguments.length < 2) { var sIndent = ""; } var sIndentStyle = " "; var sDataType = RealTypeOf(oData); // open object if (sDataType == "array") { if (oData.length == 0) { return "[]"; } var sHTML = "["; } else { var iCount = 0; $.each(oData, function() { iCount++; return; }); if (iCount == 0) { // object is empty return "{}"; } var sHTML = "{"; } // loop through items var iCount = 0; $.each(oData, function(sKey, vValue) { if (iCount > 0) { sHTML += ","; } if (sDataType == "array") { sHTML += ("\n" + sIndent + sIndentStyle); } else { sHTML += ("\n" + sIndent + sIndentStyle + "\"" + sKey + "\"" + ": "); } // display relevant data type switch (RealTypeOf(vValue)) { case "array": case "object": sHTML += FormatJSON(vValue, (sIndent + sIndentStyle)); break; case "boolean": case "number": sHTML += vValue.toString(); break; case "null": sHTML += "null"; break; case "string": sHTML += ("\"" + vValue + "\""); break; default: sHTML += JSON.stringify(vValue); } // loop iCount++; }); // close object if (sDataType == "array") { sHTML += ("\n" + sIndent + "]"); } else { sHTML += ("\n" + sIndent + "}"); } // return return sHTML; } function loadRules(value) { rules = []; for (var i in value) { rules.push(value[i]); } ruleList.refresh(); freezeIdentifier(ruleList); } function loadIssues(value) { issues = []; for (var i in value) { issues.push(value[i]); } issueList.refresh(); freezeIdentifier(issueList); } function loadScripts(value) { scripts = []; for (var i in value) { scripts.push(value[i]); } scriptList.refresh(); freezeIdentifier(scriptList); updateScriptItems(); } function serialize(list) { var obj = {}; for (var i = 0; i < list.length; ++i) { obj[list[i].identifier] = list[i]; } return FormatJSON(obj); } function save() { saveToFile('setting.json', serialize(rules)); saveToFile('scripts.json', serialize(scripts)); saveToFile('issues.json', serialize(issues)); dirty= false; freezeIdentifier(ruleList); freezeIdentifier(scriptList); } function reload() { $.ajax(baseDir + 'setting.json', { success: loadRules }); $.ajax(baseDir + 'scripts.json', { success: loadScripts }); $.ajax(baseDir + 'issues.json', { success: loadIssues }); dirty = false; } function freezeIdentifier(list) { $('.itemline:not(.newline) div[property=identifier]', list.contents) .addClass('readonly'); } var scriptList, ruleList, issueList; var scriptItems = []; function updateScriptItems() { scriptItems = []; for (var i = 0; i < scripts.length; ++i) { scriptItems.push(scripts[i].identifier); } } $(document).ready(function() { window.onbeforeunload=function() { if (dirty) { return 'Page not saved. Continue?'; } } $('#addRule').click(function() { ruleList.editNewLine(); }).button(); $('#deleteRule').click(function() { ruleList.remove(ruleList.selectedLine); }).button(); $('#addScript').click(function() { scriptList.editNewLine(); }).button(); $('#deleteScript').click(function() { scriptList.remove(scriptList.selectedLine); }).button(); $('#compute_checkSum').click(function() { for (var i = 0; i < scripts.length; ++i) { computeScriptChecksum(i); } }).button(); $('#addIssue').click(function() { issueList.editNewLine(); }).button(); $('#deleteIssue').click(function() { issueList.remove(issueList.selectedLine); }).button(); $('.doSave').each(function() { $(this).click(save).button(); }); $('#tabs').tabs(); $('#scriptDialog').dialog({ modal: true, autoOpen: false, height: 500, width: 700, buttons: { "Save": function() { saveScript(currentScript); $(this).dialog('close'); }, "Cancel": function() { $(this).dialog('close'); } } }); $.ajaxSetup({ cache: false }); scriptList = new List({ props: scriptProps, main: $('#scriptTable'), getItems: function() {return scripts;} }); $(scriptList).bind('updated', function() { dirty = true; updateScriptItems(); }); scriptList.init(); ruleList = new List({ props: ruleProps, main: $('#ruleTable'), getItems: function() {return rules;} }); ruleList.init(); $(ruleList).bind('updated', function() { dirty = true; }); issueList = new List({ props: issueProps, main: $('#issueTable'), getItems: function() {return issues;} }); issueList.init(); $(issueList).bind('updated', function() { dirty = true; }); reload(); });
007slmg-np-activex
web/editor.js
JavaScript
mpl11
10,902
<html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></meta> <style> .line { clear: both; margin: 4px 0px; } .item { margin: 4px 3px; float: left; } </style> <script> var link = "https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn" var text = '在Chrome中直接使用各类网银、快播等ActiveX控件,无需使用IE Tab等IE内核插件!数万用户的实践验证!点击链接下载'; </script> </head> <body> <div id="header" style="height:100px"> </div> <div class="line"> <!-- Place this tag where you want the +1 button to render --> <g:plusone annotation="inline" href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn"></g:plusone> <!-- Place this render call where appropriate --> <script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> </div> <div class="line"> <div class="item"> <script type="text/javascript" charset="utf-8"> (function(){ var _w = 106 , _h = 24; var param = { url:link, type:'5', count:'', /**是否显示分享数,1显示(可选)*/ appkey:'', /**您申请的应用appkey,显示分享来源(可选)*/ title:text, pic:'', /**分享图片的路径(可选)*/ ralateUid:'2356524070', /**关联用户的UID,分享微博会@该用户(可选)*/ language:'zh_cn', /**设置语言,zh_cn|zh_tw(可选)*/ rnd:new Date().valueOf() } var temp = []; for( var p in param ){ temp.push(p + '=' + encodeURIComponent( param[p] || '' ) ) } document.write('<iframe allowTransparency="true" frameborder="0" scrolling="no" src="http://hits.sinajs.cn/A1/weiboshare.html?' + temp.join('&') + '" width="'+ _w+'" height="'+_h+'"></iframe>') })() </script> </div> <div class="item"> <a name="xn_share" type="button_count_right" href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn/">分享到人人</a><script src="http://static.connect.renren.com/js/share.js" type="text/javascript"></script></div> <div class="item"> <a href="javascript:void(0)" onclick="postToWb();return false;" class="tmblog"><img src="http://v.t.qq.com/share/images/s/b24.png" border="0" alt="转播到腾讯微博" ></a><script type="text/javascript"> function postToWb(){ var _url = encodeURIComponent(link); var _assname = encodeURI("");//你注册的帐号,不是昵称 var _appkey = encodeURI("");//你从腾讯获得的appkey var _pic = encodeURI('');//(例如:var _pic='图片url1|图片url2|图片url3....) var _t = '';//标题和描述信息 var metainfo = document.getElementsByTagName("meta"); for(var metai = 0;metai < metainfo.length;metai++){ if((new RegExp('description','gi')).test(metainfo[metai].getAttribute("name"))){ _t = metainfo[metai].attributes["content"].value; } } _t = text; if(_t.length > 120){ _t= _t.substr(0,117)+'...'; } _t = encodeURI(_t); var _u = 'http://share.v.t.qq.com/index.php?c=share&a=index&url='+_url+'&appkey='+_appkey+'&pic='+_pic+'&assname='+_assname+'&title='+_t; window.open( _u,'', 'width=700, height=680, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no' ); } </script> </div> </div> <div id="footer" style="height:100px;clear:both"> </div> </body> </html>
007slmg-np-activex
web/share.html
HTML
mpl11
3,718
<html> <head> <link rel="stylesheet" type="text/css" href="list.css" /> <link rel="stylesheet" type="text/css" href="editor.css" /> <link type="text/css" href="jquery-ui-1.8.17.custom.css" rel="stylesheet" /> <script src="jquery-1.7.min.js"></script> <script src="jquery-ui-1.8.17.custom.min.js"></script> <script src="list.js"></script> <script src="listtypes.js"></script> <script src="editor.js"></script> </head> <body> <div id="tabs"> <ul> <li><a href="#rules">Rules</a></li> <li><a href="#scripts">Scripts</a></li> <li><a href="#issues">Issues</a></li> </ul> <div id="rules"> <div id="ruleTable"> </div> <div> <button id="addRule">Add</button> <button id="deleteRule">Delete</button> <button class="doSave">Save</button> </div> </div> <div id="scripts"> <div id="scriptTable"> </div> <div> <button id="addScript">Add</button> <button id="deleteScript">Delete</button> <button id="compute_checkSum">Compute all checksums</button> <button class="doSave">Save</button> </div> </div> <div id="issues"> <div id="issueTable"> </div> <div> <button id="addIssue">Add</button> <button id="deleteIssue">Delete</button> <button class="doSave">Save</button> </div> </div> </div> <div id="scriptDialog"> <textarea id="scriptEditor"></textarea> </div> </body> </html>
007slmg-np-activex
web/editor.html
HTML
mpl11
1,638
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. List.types.input = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<input></input>').addClass('valinput'); this.label = $('<span></span>').addClass('valdisp'); this.label.click(function(e) { setTimeout(function(){ input.focus(); }, 10); }); this.input.focus(function(e) { input.select(); }); this.input.keypress(function(e) { p.trigger('change'); }); this.input.keyup(function(e) { p.trigger('change'); }); this.input.change(function(e) { p.trigger('change'); }); p.append(this.input).append(this.label); }; List.types.input.prototype.__defineSetter__('value', function(val) { this.input.val(val); this.label.text(val); }); List.types.input.prototype.__defineGetter__('value', function() { return this.input.val(); }); List.types.select = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<select></select>').addClass('valinput'); this.label = $('<span></span>').addClass('valdisp'); if (prop.option == 'static') { this.loadOptions(prop.options); } var select = this; this.input.change(function(e) { if (p.hasClass('readonly')) { select.value = select.lastval; } else { p.trigger('change'); } }); this.label.click(function(e) { setTimeout(function(){ input.focus(); }, 10); }); p.append(this.input).append(this.label); }; List.types.select.prototype.loadOptions = function(options) { this.options = options; this.mapping = {}; this.input.html(""); for (var i = 0; i < options.length; ++i) { this.mapping[options[i].value] = options[i].text; var o = $('<option></option>').val(options[i].value).text(options[i].text) this.input.append(o); } } List.types.select.prototype.__defineGetter__('value', function() { return this.input.val(); }); List.types.select.prototype.__defineSetter__('value', function(val) { this.lastval = val; this.input.val(val); this.label.text(this.mapping[val]); }); List.types.checkbox = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<input type="checkbox">').addClass('valcheck'); var box = this; this.input.change(function(e) { if (p.hasClass('readonly')) { box.value = box.lastval; } else { p.trigger('change'); } }); p.append(this.input); }; List.types.checkbox.prototype.__defineGetter__('value', function() { return this.input[0].checked; }); List.types.checkbox.prototype.__defineSetter__('value', function(val) { this.lastval = val; this.input[0].checked = val; }); List.types.button = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<button>'); if (prop.caption) { input.text(prop.caption); } input.click(function(e) { p.trigger('command'); return false; }); p.append(this.input); }; List.types.button.prototype.__defineGetter__('value', function() { return undefined; });
007slmg-np-activex
web/listtypes.js
JavaScript
mpl11
3,295
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <npruntime.h> #include <npapi.h> #include "npactivex.h" class NPVariantProxy : public NPVariant { public: NPVariantProxy() { VOID_TO_NPVARIANT(*this); } ~NPVariantProxy() { NPNFuncs.releasevariantvalue(this); } }; class NPObjectProxy { private: NPObject *object; public: NPObjectProxy() { object = NULL; } NPObjectProxy(NPObject *obj) { object = obj; } void reset() { if (object) NPNFuncs.releaseobject(object); object = NULL; } ~NPObjectProxy() { reset(); } operator NPObject*&() { return object; } NPObjectProxy& operator =(NPObject* obj) { reset(); object = obj; return *this; } };
007slmg-np-activex
ffactivex/objectProxy.h
C++
mpl11
2,216
comment ? /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ ? .386 .model flat PUBLIC _DualProcessCommandWrap _DualProcessCommand proto .code _DualProcessCommandWrap proc push 0 call _DualProcessCommand ; Thanks god we can use ecx, edx for free pop ecx ; length of par pop edx ; command id pop edx ; return address add esp, ecx jmp edx _DualProcessCommandWrap endp end
007slmg-np-activex
ffactivex/FakeDispatcherWrap.asm
Assembly
mpl11
1,879
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <comdef.h> #include "npactivex.h" #include "scriptable.h" #include "common/PropertyList.h" #include "common/PropertyBag.h" #include "common/ItemContainer.h" #include "common/ControlSite.h" #include "common/ControlSiteIPFrame.h" #include "common/ControlEventSink.h" #include "axhost.h" #include "HTMLDocumentContainer.h" #ifdef NO_REGISTRY_AUTHORIZE static const char *WellKnownProgIds[] = { NULL }; static const char *WellKnownClsIds[] = { NULL }; #endif static const bool AcceptOnlyWellKnown = false; static const bool TrustWellKnown = true; static bool isWellKnownProgId(const char *progid) { #ifdef NO_REGISTRY_AUTHORIZE unsigned int i = 0; if (!progid) { return false; } while (WellKnownProgIds[i]) { if (!strnicmp(WellKnownProgIds[i], progid, strlen(WellKnownProgIds[i]))) return true; ++i; } return false; #else return true; #endif } static bool isWellKnownClsId(const char *clsid) { #ifdef NO_REGISTRY_AUTHORIZE unsigned int i = 0; if (!clsid) { return false; } while (WellKnownClsIds[i]) { if (!strnicmp(WellKnownClsIds[i], clsid, strlen(WellKnownClsIds[i]))) return true; ++i; } return false; #else return true; #endif } static LRESULT CALLBACK AxHostWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { LRESULT result; CAxHost *host = (CAxHost *)GetWindowLong(hWnd, GWL_USERDATA); if (!host) { return DefWindowProc(hWnd, msg, wParam, lParam); } switch (msg) { case WM_SETFOCUS: case WM_KILLFOCUS: case WM_SIZE: if (host->Site) { host->Site->OnDefWindowMessage(msg, wParam, lParam, &result); return result; } else { return DefWindowProc(hWnd, msg, wParam, lParam); } // Window being destroyed case WM_DESTROY: break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return true; } CAxHost::CAxHost(NPP inst): CHost(inst), ClsID(CLSID_NULL), isValidClsID(false), Sink(NULL), Site(NULL), Window(NULL), OldProc(NULL), Props_(new PropertyList), isKnown(false), CodeBaseUrl(NULL), noWindow(false) { } CAxHost::~CAxHost() { np_log(instance, 0, "AxHost.~AXHost: destroying the control..."); if (Window){ if (OldProc) { ::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc); OldProc = NULL; } ::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL); } Clear(); delete Props_; } void CAxHost::Clear() { if (Sink) { Sink->UnsubscribeFromEvents(); Sink->Release(); Sink = NULL; } if (Site) { Site->Detach(); Site->Release(); Site = NULL; } if (Props_) { Props_->Clear(); } CoFreeUnusedLibraries(); } CLSID CAxHost::ParseCLSIDFromSetting(LPCSTR str, int length) { CLSID ret; CStringW input(str, length); if (SUCCEEDED(CLSIDFromString(input, &ret))) return ret; int pos = input.Find(':'); if (pos != -1) { CStringW wolestr(_T("{")); wolestr.Append(input.Mid(pos + 1)); wolestr.Append(_T("}")); if (SUCCEEDED(CLSIDFromString(wolestr.GetString(), &ret))) return ret; } return CLSID_NULL; } void CAxHost::setWindow(HWND win) { if (win != Window) { if (win) { // subclass window so we can intercept window messages and // do our drawing to it OldProc = (WNDPROC)::SetWindowLong(win, GWL_WNDPROC, (LONG)AxHostWinProc); // associate window with our CAxHost object so we can access // it in the window procedure ::SetWindowLong(win, GWL_USERDATA, (LONG)this); } else { if (OldProc) ::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc); ::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL); } Window = win; } } void CAxHost::ResetWindow() { UpdateRect(lastRect); } HWND CAxHost::getWinfow() { return Window; } void CAxHost::UpdateRect(RECT rcPos) { HRESULT hr = -1; lastRect = rcPos; if (Site && Window && !noWindow) { if (Site->GetParentWindow() == NULL) { hr = Site->Attach(Window, rcPos, NULL); if (FAILED(hr)) { np_log(instance, 0, "AxHost.UpdateRect: failed to attach control"); SIZEL zero = {0, 0}; SetRectSize(&zero); } } if (Site->CheckAndResetNeedUpdateContainerSize()) { UpdateRectSize(&rcPos); } else { Site->SetPosition(rcPos); } // Ensure clipping on parent to keep child controls happy ::SetWindowLong(Window, GWL_STYLE, ::GetWindowLong(Window, GWL_STYLE) | WS_CLIPCHILDREN); } } void CAxHost::setNoWindow(bool noWindow) { this->noWindow = noWindow; } void CAxHost::UpdateRectSize(LPRECT origRect) { if (noWindow) { return; } SIZEL szControl; if (!Site->IsVisibleAtRuntime()) { szControl.cx = 0; szControl.cy = 0; } else { if (FAILED(Site->GetControlSize(&szControl))) { return; } } SIZEL szIn; szIn.cx = origRect->right - origRect->left; szIn.cy = origRect->bottom - origRect->top; if (szControl.cx != szIn.cx || szControl.cy != szIn.cy) { SetRectSize(&szControl); } } void CAxHost::SetRectSize(LPSIZEL size) { np_log(instance, 1, "Set object size: x = %d, y = %d", size->cx, size->cy); NPObjectProxy object; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &object); static NPIdentifier style = NPNFuncs.getstringidentifier("style"); static NPIdentifier height = NPNFuncs.getstringidentifier("height"); static NPIdentifier width = NPNFuncs.getstringidentifier("width"); NPVariant sHeight, sWidth; CStringA strHeight, strWidth; strHeight.Format("%dpx", size->cy); strWidth.Format("%dpx", size->cx); STRINGZ_TO_NPVARIANT(strHeight, sHeight); STRINGZ_TO_NPVARIANT(strWidth, sWidth); NPVariantProxy styleValue; NPNFuncs.getproperty(instance, object, style, &styleValue); NPObject *styleObject = NPVARIANT_TO_OBJECT(styleValue); NPNFuncs.setproperty(instance, styleObject, height, &sHeight); NPNFuncs.setproperty(instance, styleObject, width, &sWidth); } void CAxHost::SetNPWindow(NPWindow *window) { RECT rcPos; setWindow((HWND)window->window); rcPos.left = 0; rcPos.top = 0; rcPos.right = window->width; rcPos.bottom = window->height; UpdateRect(rcPos); } bool CAxHost::verifyClsID(LPOLESTR oleClsID) { CRegKey keyExplorer; if (ERROR_SUCCESS == keyExplorer.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer\\ActiveX Compatibility"), KEY_READ)) { CRegKey keyCLSID; if (ERROR_SUCCESS == keyCLSID.Open(keyExplorer, W2T(oleClsID), KEY_READ)) { DWORD dwType = REG_DWORD; DWORD dwFlags = 0; DWORD dwBufSize = sizeof(dwFlags); if (ERROR_SUCCESS == ::RegQueryValueEx(keyCLSID, _T("Compatibility Flags"), NULL, &dwType, (LPBYTE) &dwFlags, &dwBufSize)) { // Flags for this reg key const DWORD kKillBit = 0x00000400; if (dwFlags & kKillBit) { np_log(instance, 0, "AxHost.verifyClsID: the control is marked as unsafe by IE kill bits"); return false; } } } } return true; } bool CAxHost::setClsID(const char *clsid) { HRESULT hr = -1; USES_CONVERSION; LPOLESTR oleClsID = A2OLE(clsid); if (isWellKnownClsId(clsid)) { isKnown = true; } else if (AcceptOnlyWellKnown) { np_log(instance, 0, "AxHost.setClsID: the requested CLSID is not on the Well Known list"); return false; } // Check the Internet Explorer list of vulnerable controls if (oleClsID && verifyClsID(oleClsID)) { CLSID vclsid; hr = CLSIDFromString(oleClsID, &vclsid); if (SUCCEEDED(hr)) { return setClsID(vclsid); } } np_log(instance, 0, "AxHost.setClsID: failed to set the requested clsid"); return false; } bool CAxHost::setClsID(const CLSID& clsid) { if (clsid != CLSID_NULL) { this->ClsID = clsid; isValidClsID = true; //np_log(instance, 1, "AxHost.setClsID: CLSID %s set", clsid); return true; } return false; } void CAxHost::setCodeBaseUrl(LPCWSTR codeBaseUrl) { CodeBaseUrl = codeBaseUrl; } bool CAxHost::setClsIDFromProgID(const char *progid) { HRESULT hr = -1; CLSID clsid = CLSID_NULL; USES_CONVERSION; LPOLESTR oleClsID = NULL; LPOLESTR oleProgID = A2OLE(progid); if (AcceptOnlyWellKnown) { if (isWellKnownProgId(progid)) { isKnown = true; } else { np_log(instance, 0, "AxHost.setClsIDFromProgID: the requested PROGID is not on the Well Known list"); return false; } } hr = CLSIDFromProgID(oleProgID, &clsid); if (FAILED(hr)) { np_log(instance, 0, "AxHost.setClsIDFromProgID: could not resolve PROGID"); return false; } hr = StringFromCLSID(clsid, &oleClsID); // Check the Internet Explorer list of vulnerable controls if ( SUCCEEDED(hr) && oleClsID && verifyClsID(oleClsID)) { ClsID = clsid; if (!::IsEqualCLSID(ClsID, CLSID_NULL)) { isValidClsID = true; np_log(instance, 1, "AxHost.setClsIDFromProgID: PROGID %s resolved and set", progid); return true; } } np_log(instance, 0, "AxHost.setClsIDFromProgID: failed to set the resolved CLSID"); return false; } bool CAxHost::hasValidClsID() { return isValidClsID; } static void HTMLContainerDeleter(IUnknown *unk) { CComAggObject<HTMLDocumentContainer>* val = (CComAggObject<HTMLDocumentContainer>*)(unk); val->InternalRelease(); } bool CAxHost::CreateControl(bool subscribeToEvents) { if (!isValidClsID) { np_log(instance, 0, "AxHost.CreateControl: current location is not trusted"); return false; } // Create the control site CComObject<CControlSite>::CreateInstance(&Site); if (Site == NULL) { np_log(instance, 0, "AxHost.CreateControl: CreateInstance failed"); return false; } Site->AddRef(); Site->m_bSupportWindowlessActivation = false; if (TrustWellKnown && isKnown) { Site->SetSecurityPolicy(NULL); Site->m_bSafeForScriptingObjectsOnly = false; } else { Site->m_bSafeForScriptingObjectsOnly = true; } CComAggObject<HTMLDocumentContainer> *document; CComAggObject<HTMLDocumentContainer>::CreateInstance(Site->GetUnknown(), &document); document->m_contained.Init(instance, pHtmlLib); Site->SetInnerWindow(document, HTMLContainerDeleter); // Create the object HRESULT hr; hr = Site->Create(ClsID, *Props(), CodeBaseUrl); if (FAILED(hr)) { np_log(instance, 0, "AxHost.CreateControl: failed to create site for 0x%08x", hr); return false; } #if 0 IUnknown *control = NULL; Site->GetControlUnknown(&control); if (!control) { np_log(instance, 0, "AxHost.CreateControl: failed to create control (was it just downloaded?)"); return false; } // Create the event sink CComObject<CControlEventSink>::CreateInstance(&Sink); Sink->AddRef(); Sink->instance = instance; hr = Sink->SubscribeToEvents(control); control->Release(); if (FAILED(hr) && subscribeToEvents) { np_log(instance, 0, "AxHost.CreateControl: SubscribeToEvents failed"); // return false; // It doesn't matter. } #endif np_log(instance, 1, "AxHost.CreateControl: control created successfully"); return true; } bool CAxHost::AddEventHandler(wchar_t *name, wchar_t *handler) { HRESULT hr; DISPID id = 0; USES_CONVERSION; LPOLESTR oleName = name; if (!Sink) { np_log(instance, 0, "AxHost.AddEventHandler: no valid sink"); return false; } hr = Sink->m_spEventSinkTypeInfo->GetIDsOfNames(&oleName, 1, &id); if (FAILED(hr)) { np_log(instance, 0, "AxHost.AddEventHandler: GetIDsOfNames failed to resolve event name"); return false; } Sink->events[id] = handler; np_log(instance, 1, "AxHost.AddEventHandler: handler %S set for event %S", handler, name); return true; } int16 CAxHost::HandleEvent(void *event) { NPEvent *npEvent = (NPEvent *)event; LRESULT result = 0; if (!npEvent) { return 0; } // forward all events to the hosted control return (int16)Site->OnDefWindowMessage(npEvent->event, npEvent->wParam, npEvent->lParam, &result); } ScriptBase * CAxHost::CreateScriptableObject() { Scriptable *obj = Scriptable::FromAxHost(instance, this); if (Site == NULL) { return obj; } static int markedSafe = 0; if (!Site->m_bSafeForScriptingObjectsOnly && markedSafe == 0) { if (MessageBox(NULL, _T("Some objects are not script-safe, would you continue?"), _T("Warining"), MB_YESNO | MB_ICONINFORMATION | MB_ICONASTERISK) == IDYES) markedSafe = 1; else markedSafe = 2; } if (!Site->m_bSafeForScriptingObjectsOnly && markedSafe != 1) { // Disable scripting. obj->Invalidate(); } return obj; } HRESULT CAxHost::GetControlUnknown(IUnknown **pObj) { if (Site == NULL) { return E_FAIL; } return Site->GetControlUnknown(pObj); } NPP CAxHost::ResetNPP(NPP npp) { NPP ret = CHost::ResetNPP(npp); setWindow(NULL); Site->Detach(); if (Sink) Sink->instance = npp; return ret; }
007slmg-np-activex
ffactivex/axhost.cpp
C++
mpl11
15,006
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // npactivex.cpp : Defines the exported functions for the DLL application. // #include "npactivex.h" #include "axhost.h" #include "atlutil.h" #include "objectProxy.h" #include "authorize.h" #include "common\PropertyList.h" #include "common\ControlSite.h" #include "ObjectManager.h" // A list of trusted domains // Each domain name may start with a '*' to specify that sub domains are // trusted as well // Note that a '.' is not enforced after the '*' static const char *TrustedLocations[] = {NULL}; static const unsigned int numTrustedLocations = 0; static const char *LocalhostName = "localhost"; static const bool TrustLocalhost = true; // // Gecko API // static const char PARAM_ID[] = "id"; static const char PARAM_NAME[] = "name"; static const char PARAM_CLSID[] = "clsid"; static const char PARAM_CLASSID[] = "classid"; static const char PARAM_PROGID[] = "progid"; static const char PARAM_DYNAMIC[] = "dynamic"; static const char PARAM_DEBUG[] = "debugLevel"; static const char PARAM_CODEBASEURL [] = "codeBase"; static const char PARAM_ONEVENT[] = "Event_"; static unsigned int log_level = -1; // For catch breakpoints. HRESULT NotImpl() { return E_NOTIMPL; } void log_activex_logging(NPP instance, unsigned int level, const char* filename, int line, char *message, ...) { if (instance == NULL || level > log_level) { return; } NPObjectProxy globalObj = NULL; NPIdentifier commandId = NPNFuncs.getstringidentifier("__npactivex_log"); NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); if (!NPNFuncs.hasmethod(instance, globalObj, commandId)) { return; } int size = 0; va_list list; ATL::CStringA str; ATL::CStringA str2; va_start(list, message); str.FormatV(message, list); str2.Format("0x%08x %s:%d %s", instance, filename, line, str.GetString()); va_end(list); NPVariant vars[1]; const char* formatted = str2.GetString(); STRINGZ_TO_NPVARIANT(formatted, vars[0]); NPVariantProxy result1; NPNFuncs.invoke(instance, globalObj, commandId, vars, 1, &result1); } void InstallLogAction(NPP instance) { NPVariantProxy result1; NPObjectProxy globalObj = NULL; NPIdentifier commandId = NPNFuncs.getstringidentifier("__npactivex_log"); NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); if (NPNFuncs.hasmethod(instance, globalObj, commandId)) { return; } const char* definition = "function __npactivex_log(message)" "{var controlLogEvent='__npactivex_log_event__';" "var e=document.createEvent('TextEvent');e.initTextEvent(controlLogEvent,false,false,null,message);window.dispatchEvent(e)}"; NPString def; def.UTF8Characters = definition; def.UTF8Length = strlen(definition); NPNFuncs.evaluate(instance, globalObj, &def, &result1); } void log_internal_console(NPP instance, unsigned int level, char *message, ...) { NPVariantProxy result1, result2; NPVariant args; NPObjectProxy globalObj = NULL, consoleObj = NULL; bool rc = false; char *formatted = NULL; char *new_formatted = NULL; int buff_len = 0; int size = 0; va_list list; if (level > log_level) { return; } buff_len = strlen(message); char *new_message = (char *)malloc(buff_len + 10); sprintf(new_message, "%%s %%d: %s", message); buff_len += buff_len / 10; formatted = (char *)calloc(1, buff_len); while (true) { va_start(list, message); size = vsnprintf_s(formatted, buff_len, _TRUNCATE, new_message, list); va_end(list); if (size > -1 && size < buff_len) break; buff_len *= 2; new_formatted = (char *)realloc(formatted, buff_len); if (NULL == new_formatted) { free(formatted); return; } formatted = new_formatted; new_formatted = NULL; } free(new_message); if (instance == NULL) { free(formatted); return; } NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); if (NPNFuncs.getproperty(instance, globalObj, NPNFuncs.getstringidentifier("console"), &result1)) { consoleObj = NPVARIANT_TO_OBJECT(result1); NPIdentifier handler = NPNFuncs.getstringidentifier("log"); STRINGZ_TO_NPVARIANT(formatted, args); bool success = NPNFuncs.invoke(instance, consoleObj, handler, &args, 1, &result2); } free(formatted); } static bool MatchURL2TrustedLocations(NPP instance, LPCTSTR matchUrl) { USES_CONVERSION; BOOL rc = false; CUrl url; if (!numTrustedLocations) { return true; } rc = url.CrackUrl(matchUrl, ATL_URL_DECODE); if (!rc) { np_log(instance, 0, "AxHost.MatchURL2TrustedLocations: failed to parse the current location URL"); return false; } if ( (url.GetScheme() == ATL_URL_SCHEME_FILE) || (!strncmp(LocalhostName, W2A(url.GetHostName()), strlen(LocalhostName)))){ return TrustLocalhost; } for (unsigned int i = 0; i < numTrustedLocations; ++i) { if (TrustedLocations[i][0] == '*') { // sub domains are trusted unsigned int len = strlen(TrustedLocations[i]); bool match = 0; if (url.GetHostNameLength() < len) { // can't be a match continue; } --len; // skip the '*' match = strncmp(W2A(url.GetHostName()) + (url.GetHostNameLength() - len), // anchor the comparison to the end of the domain name TrustedLocations[i] + 1, // skip the '*' len) == 0 ? true : false; if (match) { return true; } } else if (!strncmp(W2A(url.GetHostName()), TrustedLocations[i], url.GetHostNameLength())) { return true; } } return false; } static bool VerifySiteLock(NPP instance) { // This approach is not used. return true; #if 0 USES_CONVERSION; NPObjectProxy globalObj; NPIdentifier identifier; NPVariantProxy varLocation; NPVariantProxy varHref; bool rc = false; // Get the window object. NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); // Create a "location" identifier. identifier = NPNFuncs.getstringidentifier("location"); // Get the location property from the window object (which is another object). rc = NPNFuncs.getproperty(instance, globalObj, identifier, &varLocation); if (!rc){ np_log(instance, 0, "AxHost.VerifySiteLock: could not get the location from the global object"); return false; } // Get a pointer to the "location" object. NPObject *locationObj = varLocation.value.objectValue; // Create a "href" identifier. identifier = NPNFuncs.getstringidentifier("href"); // Get the location property from the location object. rc = NPNFuncs.getproperty(instance, locationObj, identifier, &varHref); if (!rc) { np_log(instance, 0, "AxHost.VerifySiteLock: could not get the href from the location property"); return false; } rc = MatchURL2TrustedLocations(instance, A2W(varHref.value.stringValue.UTF8Characters)); if (false == rc) { np_log(instance, 0, "AxHost.VerifySiteLock: current location is not trusted"); } return rc; #endif } static bool FillProperties(CAxHost *host, NPP instance) { NPObjectProxy embed; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed); // Traverse through childs NPVariantProxy var_childNodes; NPVariantProxy var_length; NPVariant str_name, str_value; if (!NPNFuncs.getproperty(instance, embed, NPNFuncs.getstringidentifier("childNodes"), &var_childNodes)) return true; if (!NPVARIANT_IS_OBJECT(var_childNodes)) return true; NPObject *childNodes = NPVARIANT_TO_OBJECT(var_childNodes); VOID_TO_NPVARIANT(var_length); if (!NPNFuncs.getproperty(instance, childNodes, NPNFuncs.getstringidentifier("length"), &var_length)) return true; USES_CONVERSION; int length = 0; if (NPVARIANT_IS_INT32(var_length)) length = NPVARIANT_TO_INT32(var_length); if (NPVARIANT_IS_DOUBLE(var_length)) length = static_cast<int>(NPVARIANT_TO_DOUBLE(var_length)); NPIdentifier idname = NPNFuncs.getstringidentifier("nodeName"); NPIdentifier idAttr = NPNFuncs.getstringidentifier("getAttribute"); STRINGZ_TO_NPVARIANT("name", str_name); STRINGZ_TO_NPVARIANT("value", str_value); for (int i = 0; i < length; ++i) { NPIdentifier id = NPNFuncs.getintidentifier(i); NPVariantProxy var_par; NPVariantProxy var_nodeName, var_parName, var_parValue; if (!NPNFuncs.getproperty(instance, childNodes, id, &var_par)) continue; if (!NPVARIANT_IS_OBJECT(var_par)) continue; NPObject *param_obj = NPVARIANT_TO_OBJECT(var_par); if (!NPNFuncs.getproperty(instance, param_obj, idname, &var_nodeName)) continue; if (_strnicmp(NPVARIANT_TO_STRING(var_nodeName).UTF8Characters, "embed", NPVARIANT_TO_STRING(var_nodeName).UTF8Length) == 0) { NPVariantProxy type; NPVariant typestr; STRINGZ_TO_NPVARIANT("type", typestr); if (!NPNFuncs.invoke(instance, param_obj, idAttr, &typestr, 1, &type)) continue; if (!NPVARIANT_IS_STRING(type)) continue; CStringA command, mimetype(NPVARIANT_TO_STRING(type).UTF8Characters, NPVARIANT_TO_STRING(type).UTF8Length); command.Format("navigator.mimeTypes[\'%s\'] != null", mimetype); NPString str = {command.GetString(), command.GetLength()}; NPVariantProxy value; NPObjectProxy window; NPNFuncs.getvalue(instance, NPNVWindowNPObject, &window); NPNFuncs.evaluate(instance, window, &str, &value); if (NPVARIANT_IS_BOOLEAN(value) && NPVARIANT_TO_BOOLEAN(value)) { // The embed is supported by chrome. Fallback automatically. return false; } } if (_strnicmp(NPVARIANT_TO_STRING(var_nodeName).UTF8Characters, "param", NPVARIANT_TO_STRING(var_nodeName).UTF8Length) != 0) continue; if (!NPNFuncs.invoke(instance, param_obj, idAttr, &str_name, 1, &var_parName)) continue; if (!NPNFuncs.invoke(instance, param_obj, idAttr, &str_value, 1, &var_parValue)) continue; if (!NPVARIANT_IS_STRING(var_parName) || !NPVARIANT_IS_STRING(var_parValue)) continue; CComBSTR paramName(NPVARIANT_TO_STRING(var_parName).UTF8Length, NPVARIANT_TO_STRING(var_parName).UTF8Characters); CComBSTR paramValue(NPVARIANT_TO_STRING(var_parValue).UTF8Length, NPVARIANT_TO_STRING(var_parValue).UTF8Characters); // Add named parameter to list CComVariant v(paramValue); host->Props()->AddOrReplaceNamedProperty(paramName, v); } return true; } NPError CreateControl(NPP instance, int16 argc, char *argn[], char *argv[], CAxHost **phost) { // Create a plugin instance, the actual control will be created once we // are given a window handle USES_CONVERSION; PropertyList events; CAxHost *host = new CAxHost(instance); *phost = host; if (!host) { np_log(instance, 0, "AxHost.NPP_New: failed to allocate memory for a new host"); return NPERR_OUT_OF_MEMORY_ERROR; } // Iterate over the arguments we've been passed for (int i = 0; i < argc; ++i) { // search for any needed information: clsid, event handling directives, etc. if (strnicmp(argn[i], PARAM_CLASSID, sizeof(PARAM_CLASSID)) == 0) { char clsid[100]; strncpy(clsid, argv[i], 80); strcat(clsid, "}"); char* id = strchr(clsid, ':'); if (id == NULL) continue; *id = '{'; host->setClsID(id); } else if (0 == strnicmp(argn[i], PARAM_NAME, sizeof(PARAM_NAME)) || 0 == strnicmp(argn[i], PARAM_ID, sizeof(PARAM_ID))) { np_log(instance, 1, "instance %s: %s", argn[i], argv[i]); } else if (0 == strnicmp(argn[i], PARAM_CLSID, sizeof(PARAM_CLSID))) { // The class id of the control we are asked to load host->setClsID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_PROGID, sizeof(PARAM_PROGID))) { // The class id of the control we are asked to load host->setClsIDFromProgID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_DEBUG, sizeof(PARAM_DEBUG))) { // Logging verbosity log_level = atoi(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_ONEVENT, sizeof(PARAM_ONEVENT))) { // A request to handle one of the activex's events in JS events.AddOrReplaceNamedProperty(A2W(argn[i] + strlen(PARAM_ONEVENT)), CComVariant(A2W(argv[i]))); } else if(0 == strnicmp(argn[i], PARAM_CODEBASEURL, sizeof(PARAM_CODEBASEURL))) { if (MatchURL2TrustedLocations(instance, A2W(argv[i]))) { host->setCodeBaseUrl(A2W(argv[i])); } else { np_log(instance, 0, "AxHost.NPP_New: codeBaseUrl contains an untrusted location"); } } else if (0 == strnicmp(argn[i], PARAM_DYNAMIC, sizeof(PARAM_DYNAMIC))) { host->setNoWindow(true); } } if (!FillProperties(host, instance)) { return NPERR_GENERIC_ERROR; } // Make sure we have all the information we need to initialize a new instance if (!host->hasValidClsID()) { np_log(instance, 0, "AxHost.NPP_New: no valid CLSID or PROGID"); // create later. return NPERR_NO_ERROR; } instance->pdata = host; // if no events were requested, don't fail if subscribing fails if (!host->CreateControl(events.GetSize() ? true : false)) { np_log(instance, 0, "AxHost.NPP_New: failed to create the control"); return NPERR_GENERIC_ERROR; } for (unsigned int j = 0; j < events.GetSize(); j++) { if (!host->AddEventHandler(events.GetNameOf(j), events.GetValueOf(j)->bstrVal)) { //rc = NPERR_GENERIC_ERROR; //break; } } np_log(instance, 1, "%08x AxHost.NPP_New: Create control finished", instance); return NPERR_NO_ERROR; } /* * Create a new plugin instance, most probably through an embed/object HTML * element. * * Any private data we want to keep for this instance can be saved into * [instance->pdata]. * [saved] might hold information a previous instance that was invoked from the * same URL has saved for us. */ NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved) { NPError rc = NPERR_NO_ERROR; NPObject *browser = NULL; int16 i = 0; if (!instance || (0 == NPNFuncs.size)) { return NPERR_INVALID_PARAM; } instance->pdata = NULL; #ifdef NO_REGISTRY_AUTHORIZE // Verify that we're running from a trusted location if (!VerifySiteLock(instance)) { return NPERR_GENERIC_ERROR; } #else if (!TestAuthorization (instance, argc, argn, argv, pluginType)) { return NPERR_GENERIC_ERROR; } #endif InstallLogAction(instance); if (stricmp(pluginType, "application/x-itst-activex") == 0) { CAxHost *host = NULL; /* ObjectManager* manager = ObjectManager::GetManager(instance); if (manager && !(host = dynamic_cast<CAxHost*>(manager->GetPreviousObject(instance)))) { // Object is created before manager->RequestObjectOwnership(instance, host); } else */ { rc = CreateControl(instance, argc, argn, argv, &host); if (NPERR_NO_ERROR != rc) { delete host; instance->pdata = NULL; host = NULL; return rc; } } if (host) { host->RegisterObject(); instance->pdata = host; } } else if (stricmp(pluginType, "application/activex-manager") == 0) { // disabled now!! return rc = NPERR_GENERIC_ERROR; ObjectManager *manager = new ObjectManager(instance); manager->RegisterObject(); instance->pdata = manager; } return rc; } /* * Destroy an existing plugin instance. * * [save] can be used to save information for a future instance of our plugin * that'll be invoked by the same URL. */ NPError NPP_Destroy(NPP instance, NPSavedData **save) { if (!instance) { return NPERR_INVALID_PARAM; } CHost *host = (CHost *)instance->pdata; if (host) { np_log(instance, 0, "NPP_Destroy: destroying the control..."); //host->UnRegisterObject(); host->Release(); instance->pdata = NULL; /* ObjectManager *manager = ObjectManager::GetManager(instance); CAxHost *axHost = dynamic_cast<CAxHost*>(host); if (manager && axHost) { manager->RetainOwnership(axHost); } else { np_log(instance, 0, "NPP_Destroy: destroying the control..."); host->Release(); instance->pdata = NULL; }*/ } return NPERR_NO_ERROR; } /* * Sets an instance's window parameters. */ NPError NPP_SetWindow(NPP instance, NPWindow *window) { CAxHost *host = NULL; if (!instance || !instance->pdata) { return NPERR_INVALID_PARAM; } host = dynamic_cast<CAxHost*>((CHost *)instance->pdata); if (host) { host->SetNPWindow(window); } return NPERR_NO_ERROR; }
007slmg-np-activex
ffactivex/npactivex.cpp
C++
mpl11
18,363
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "ObjectManager.h" #include "npactivex.h" #include "host.h" #include "axhost.h" #include "objectProxy.h" #include "scriptable.h" #define MANAGER_OBJECT_ID "__activex_manager_IIID_" NPClass ObjectManager::npClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ ObjectManager::_Allocate, /* deallocate */ ObjectManager::Deallocate, /* invalidate */ NULL, /* hasMethod */ ObjectManager::HasMethod, /* invoke */ ObjectManager::Invoke, /* invokeDefault */ NULL, /* hasProperty */ ObjectManager::HasProperty, /* getProperty */ ObjectManager::GetProperty, /* setProperty */ ObjectManager::SetProperty, /* removeProperty */ NULL, /* enumerate */ NULL, /* construct */ NULL }; ObjectManager::ObjectManager(NPP npp_) : CHost(npp_) { } ObjectManager::~ObjectManager(void) { for (uint i = 0; i < hosts.size(); ++i) { hosts[i]->Release(); } for (uint i = 0; i < dynamic_hosts.size(); ++i) { dynamic_hosts[i]->Release(); } } ObjectManager* ObjectManager::GetManager(NPP npp) { NPObjectProxy window; NPNFuncs.getvalue(npp, NPNVWindowNPObject, &window); NPVariantProxy document, obj; NPVariant par; STRINGZ_TO_NPVARIANT(MANAGER_OBJECT_ID, par); if (!NPNFuncs.getproperty(npp, window, NPNFuncs.getstringidentifier("document"), &document)) return NULL; if (!NPNFuncs.invoke(npp, document.value.objectValue, NPNFuncs.getstringidentifier("getElementById"), &par, 1, &obj)) return NULL; if (NPVARIANT_IS_OBJECT(obj)) { NPObject *manager = NPVARIANT_TO_OBJECT(obj); ScriptBase *script = GetInternalObject(npp, manager); if (script) return dynamic_cast<ObjectManager*>(script->host); } return NULL; } CHost* ObjectManager::GetPreviousObject(NPP npp) { NPObjectProxy embed; NPNFuncs.getvalue(npp, NPNVPluginElementNPObject, &embed); return GetMyScriptObject()->host; } bool ObjectManager::HasMethod(NPObject *npobj, NPIdentifier name) { return name == NPNFuncs.getstringidentifier("CreateControlByProgId"); } bool ObjectManager::Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { ScriptManager *obj = static_cast<ScriptManager*>(npobj); if (name == NPNFuncs.getstringidentifier("CreateControlByProgId")) { if (argCount != 1 || !NPVARIANT_IS_STRING(args[0])) { NPNFuncs.setexception(npobj, "Invalid arguments"); return false; } CAxHost* host = new CAxHost(obj->instance); CStringA str(NPVARIANT_TO_STRING(args[0]).UTF8Characters, NPVARIANT_TO_STRING(args[0]).UTF8Length); host->setClsIDFromProgID(str.GetString()); if (!host->CreateControl(false)) { NPNFuncs.setexception(npobj, "Error creating object"); return false; } ObjectManager *manager = static_cast<ObjectManager*>(obj->host); manager->dynamic_hosts.push_back(host); OBJECT_TO_NPVARIANT(host->CreateScriptableObject(), *result); return true; } return false; } bool ObjectManager::HasProperty(NPObject *npObj, NPIdentifier name) { if (name == NPNFuncs.getstringidentifier("internalId")) return true; if (name == NPNFuncs.getstringidentifier("isValid")) return true; return false; } bool ObjectManager::GetProperty(NPObject *npObj, NPIdentifier name, NPVariant *value) { if (name == NPNFuncs.getstringidentifier("internalId")) { int len = strlen(MANAGER_OBJECT_ID); char *stra = (char*)NPNFuncs.memalloc(len + 1); strcpy(stra, MANAGER_OBJECT_ID); STRINGN_TO_NPVARIANT(stra, len, *value); return true; } if (name == NPNFuncs.getstringidentifier("isValid")) { BOOLEAN_TO_NPVARIANT(TRUE, *value); return true; } return false; } bool ObjectManager::SetProperty(NPObject *npObj, NPIdentifier name, const NPVariant *value) { return false; } bool ObjectManager::RequestObjectOwnership(NPP newNpp, CAxHost* host) { // reference count of host not changed. for (uint i = 0; i < hosts.size(); ++i) { if (hosts[i] == host) { hosts[i] = hosts.back(); hosts.pop_back(); host->ResetNPP(newNpp); newNpp->pdata = host; return true; } } return false; } void ObjectManager::RetainOwnership(CAxHost* host) { hosts.push_back(host); host->ResetNPP(instance); } ScriptBase* ObjectManager::CreateScriptableObject() { ScriptBase* obj = static_cast<ScriptBase*>(NPNFuncs.createobject(instance, &npClass)); return obj; } void ObjectManager::Deallocate(NPObject *obj) { delete static_cast<ScriptManager*>(obj); }
007slmg-np-activex
ffactivex/ObjectManager.cpp
C++
mpl11
6,015
; Copyright qiuc12@gmail.com ; This file is generated automatically by python. DON'T MODIFY IT! .386 .model flat _DualProcessCommandWrap proto PUBLIC ?fv0@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv1@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv2@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv3@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv4@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv5@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv6@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv7@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv8@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv9@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv10@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv11@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv12@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv13@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv14@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv15@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv16@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv17@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv18@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv19@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv20@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv21@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv22@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv23@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv24@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv25@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv26@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv27@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv28@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv29@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv30@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv31@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv32@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv33@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv34@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv35@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv36@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv37@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv38@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv39@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv40@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv41@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv42@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv43@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv44@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv45@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv46@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv47@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv48@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv49@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv50@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv51@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv52@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv53@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv54@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv55@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv56@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv57@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv58@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv59@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv60@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv61@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv62@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv63@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv64@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv65@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv66@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv67@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv68@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv69@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv70@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv71@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv72@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv73@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv74@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv75@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv76@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv77@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv78@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv79@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv80@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv81@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv82@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv83@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv84@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv85@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv86@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv87@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv88@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv89@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv90@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv91@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv92@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv93@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv94@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv95@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv96@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv97@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv98@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv99@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv100@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv101@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv102@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv103@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv104@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv105@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv106@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv107@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv108@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv109@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv110@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv111@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv112@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv113@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv114@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv115@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv116@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv117@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv118@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv119@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv120@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv121@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv122@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv123@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv124@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv125@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv126@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv127@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv128@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv129@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv130@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv131@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv132@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv133@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv134@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv135@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv136@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv137@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv138@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv139@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv140@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv141@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv142@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv143@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv144@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv145@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv146@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv147@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv148@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv149@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv150@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv151@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv152@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv153@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv154@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv155@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv156@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv157@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv158@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv159@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv160@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv161@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv162@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv163@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv164@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv165@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv166@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv167@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv168@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv169@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv170@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv171@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv172@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv173@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv174@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv175@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv176@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv177@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv178@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv179@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv180@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv181@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv182@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv183@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv184@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv185@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv186@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv187@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv188@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv189@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv190@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv191@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv192@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv193@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv194@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv195@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv196@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv197@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv198@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv199@FakeDispatcherBase@@EAGJXZ .code ?fv0@FakeDispatcherBase@@EAGJXZ proc push 0 jmp _DualProcessCommandWrap ?fv0@FakeDispatcherBase@@EAGJXZ endp ?fv1@FakeDispatcherBase@@EAGJXZ proc push 1 jmp _DualProcessCommandWrap ?fv1@FakeDispatcherBase@@EAGJXZ endp ?fv2@FakeDispatcherBase@@EAGJXZ proc push 2 jmp _DualProcessCommandWrap ?fv2@FakeDispatcherBase@@EAGJXZ endp ?fv3@FakeDispatcherBase@@EAGJXZ proc push 3 jmp _DualProcessCommandWrap ?fv3@FakeDispatcherBase@@EAGJXZ endp ?fv4@FakeDispatcherBase@@EAGJXZ proc push 4 jmp _DualProcessCommandWrap ?fv4@FakeDispatcherBase@@EAGJXZ endp ?fv5@FakeDispatcherBase@@EAGJXZ proc push 5 jmp _DualProcessCommandWrap ?fv5@FakeDispatcherBase@@EAGJXZ endp ?fv6@FakeDispatcherBase@@EAGJXZ proc push 6 jmp _DualProcessCommandWrap ?fv6@FakeDispatcherBase@@EAGJXZ endp ?fv7@FakeDispatcherBase@@EAGJXZ proc push 7 jmp _DualProcessCommandWrap ?fv7@FakeDispatcherBase@@EAGJXZ endp ?fv8@FakeDispatcherBase@@EAGJXZ proc push 8 jmp _DualProcessCommandWrap ?fv8@FakeDispatcherBase@@EAGJXZ endp ?fv9@FakeDispatcherBase@@EAGJXZ proc push 9 jmp _DualProcessCommandWrap ?fv9@FakeDispatcherBase@@EAGJXZ endp ?fv10@FakeDispatcherBase@@EAGJXZ proc push 10 jmp _DualProcessCommandWrap ?fv10@FakeDispatcherBase@@EAGJXZ endp ?fv11@FakeDispatcherBase@@EAGJXZ proc push 11 jmp _DualProcessCommandWrap ?fv11@FakeDispatcherBase@@EAGJXZ endp ?fv12@FakeDispatcherBase@@EAGJXZ proc push 12 jmp _DualProcessCommandWrap ?fv12@FakeDispatcherBase@@EAGJXZ endp ?fv13@FakeDispatcherBase@@EAGJXZ proc push 13 jmp _DualProcessCommandWrap ?fv13@FakeDispatcherBase@@EAGJXZ endp ?fv14@FakeDispatcherBase@@EAGJXZ proc push 14 jmp _DualProcessCommandWrap ?fv14@FakeDispatcherBase@@EAGJXZ endp ?fv15@FakeDispatcherBase@@EAGJXZ proc push 15 jmp _DualProcessCommandWrap ?fv15@FakeDispatcherBase@@EAGJXZ endp ?fv16@FakeDispatcherBase@@EAGJXZ proc push 16 jmp _DualProcessCommandWrap ?fv16@FakeDispatcherBase@@EAGJXZ endp ?fv17@FakeDispatcherBase@@EAGJXZ proc push 17 jmp _DualProcessCommandWrap ?fv17@FakeDispatcherBase@@EAGJXZ endp ?fv18@FakeDispatcherBase@@EAGJXZ proc push 18 jmp _DualProcessCommandWrap ?fv18@FakeDispatcherBase@@EAGJXZ endp ?fv19@FakeDispatcherBase@@EAGJXZ proc push 19 jmp _DualProcessCommandWrap ?fv19@FakeDispatcherBase@@EAGJXZ endp ?fv20@FakeDispatcherBase@@EAGJXZ proc push 20 jmp _DualProcessCommandWrap ?fv20@FakeDispatcherBase@@EAGJXZ endp ?fv21@FakeDispatcherBase@@EAGJXZ proc push 21 jmp _DualProcessCommandWrap ?fv21@FakeDispatcherBase@@EAGJXZ endp ?fv22@FakeDispatcherBase@@EAGJXZ proc push 22 jmp _DualProcessCommandWrap ?fv22@FakeDispatcherBase@@EAGJXZ endp ?fv23@FakeDispatcherBase@@EAGJXZ proc push 23 jmp _DualProcessCommandWrap ?fv23@FakeDispatcherBase@@EAGJXZ endp ?fv24@FakeDispatcherBase@@EAGJXZ proc push 24 jmp _DualProcessCommandWrap ?fv24@FakeDispatcherBase@@EAGJXZ endp ?fv25@FakeDispatcherBase@@EAGJXZ proc push 25 jmp _DualProcessCommandWrap ?fv25@FakeDispatcherBase@@EAGJXZ endp ?fv26@FakeDispatcherBase@@EAGJXZ proc push 26 jmp _DualProcessCommandWrap ?fv26@FakeDispatcherBase@@EAGJXZ endp ?fv27@FakeDispatcherBase@@EAGJXZ proc push 27 jmp _DualProcessCommandWrap ?fv27@FakeDispatcherBase@@EAGJXZ endp ?fv28@FakeDispatcherBase@@EAGJXZ proc push 28 jmp _DualProcessCommandWrap ?fv28@FakeDispatcherBase@@EAGJXZ endp ?fv29@FakeDispatcherBase@@EAGJXZ proc push 29 jmp _DualProcessCommandWrap ?fv29@FakeDispatcherBase@@EAGJXZ endp ?fv30@FakeDispatcherBase@@EAGJXZ proc push 30 jmp _DualProcessCommandWrap ?fv30@FakeDispatcherBase@@EAGJXZ endp ?fv31@FakeDispatcherBase@@EAGJXZ proc push 31 jmp _DualProcessCommandWrap ?fv31@FakeDispatcherBase@@EAGJXZ endp ?fv32@FakeDispatcherBase@@EAGJXZ proc push 32 jmp _DualProcessCommandWrap ?fv32@FakeDispatcherBase@@EAGJXZ endp ?fv33@FakeDispatcherBase@@EAGJXZ proc push 33 jmp _DualProcessCommandWrap ?fv33@FakeDispatcherBase@@EAGJXZ endp ?fv34@FakeDispatcherBase@@EAGJXZ proc push 34 jmp _DualProcessCommandWrap ?fv34@FakeDispatcherBase@@EAGJXZ endp ?fv35@FakeDispatcherBase@@EAGJXZ proc push 35 jmp _DualProcessCommandWrap ?fv35@FakeDispatcherBase@@EAGJXZ endp ?fv36@FakeDispatcherBase@@EAGJXZ proc push 36 jmp _DualProcessCommandWrap ?fv36@FakeDispatcherBase@@EAGJXZ endp ?fv37@FakeDispatcherBase@@EAGJXZ proc push 37 jmp _DualProcessCommandWrap ?fv37@FakeDispatcherBase@@EAGJXZ endp ?fv38@FakeDispatcherBase@@EAGJXZ proc push 38 jmp _DualProcessCommandWrap ?fv38@FakeDispatcherBase@@EAGJXZ endp ?fv39@FakeDispatcherBase@@EAGJXZ proc push 39 jmp _DualProcessCommandWrap ?fv39@FakeDispatcherBase@@EAGJXZ endp ?fv40@FakeDispatcherBase@@EAGJXZ proc push 40 jmp _DualProcessCommandWrap ?fv40@FakeDispatcherBase@@EAGJXZ endp ?fv41@FakeDispatcherBase@@EAGJXZ proc push 41 jmp _DualProcessCommandWrap ?fv41@FakeDispatcherBase@@EAGJXZ endp ?fv42@FakeDispatcherBase@@EAGJXZ proc push 42 jmp _DualProcessCommandWrap ?fv42@FakeDispatcherBase@@EAGJXZ endp ?fv43@FakeDispatcherBase@@EAGJXZ proc push 43 jmp _DualProcessCommandWrap ?fv43@FakeDispatcherBase@@EAGJXZ endp ?fv44@FakeDispatcherBase@@EAGJXZ proc push 44 jmp _DualProcessCommandWrap ?fv44@FakeDispatcherBase@@EAGJXZ endp ?fv45@FakeDispatcherBase@@EAGJXZ proc push 45 jmp _DualProcessCommandWrap ?fv45@FakeDispatcherBase@@EAGJXZ endp ?fv46@FakeDispatcherBase@@EAGJXZ proc push 46 jmp _DualProcessCommandWrap ?fv46@FakeDispatcherBase@@EAGJXZ endp ?fv47@FakeDispatcherBase@@EAGJXZ proc push 47 jmp _DualProcessCommandWrap ?fv47@FakeDispatcherBase@@EAGJXZ endp ?fv48@FakeDispatcherBase@@EAGJXZ proc push 48 jmp _DualProcessCommandWrap ?fv48@FakeDispatcherBase@@EAGJXZ endp ?fv49@FakeDispatcherBase@@EAGJXZ proc push 49 jmp _DualProcessCommandWrap ?fv49@FakeDispatcherBase@@EAGJXZ endp ?fv50@FakeDispatcherBase@@EAGJXZ proc push 50 jmp _DualProcessCommandWrap ?fv50@FakeDispatcherBase@@EAGJXZ endp ?fv51@FakeDispatcherBase@@EAGJXZ proc push 51 jmp _DualProcessCommandWrap ?fv51@FakeDispatcherBase@@EAGJXZ endp ?fv52@FakeDispatcherBase@@EAGJXZ proc push 52 jmp _DualProcessCommandWrap ?fv52@FakeDispatcherBase@@EAGJXZ endp ?fv53@FakeDispatcherBase@@EAGJXZ proc push 53 jmp _DualProcessCommandWrap ?fv53@FakeDispatcherBase@@EAGJXZ endp ?fv54@FakeDispatcherBase@@EAGJXZ proc push 54 jmp _DualProcessCommandWrap ?fv54@FakeDispatcherBase@@EAGJXZ endp ?fv55@FakeDispatcherBase@@EAGJXZ proc push 55 jmp _DualProcessCommandWrap ?fv55@FakeDispatcherBase@@EAGJXZ endp ?fv56@FakeDispatcherBase@@EAGJXZ proc push 56 jmp _DualProcessCommandWrap ?fv56@FakeDispatcherBase@@EAGJXZ endp ?fv57@FakeDispatcherBase@@EAGJXZ proc push 57 jmp _DualProcessCommandWrap ?fv57@FakeDispatcherBase@@EAGJXZ endp ?fv58@FakeDispatcherBase@@EAGJXZ proc push 58 jmp _DualProcessCommandWrap ?fv58@FakeDispatcherBase@@EAGJXZ endp ?fv59@FakeDispatcherBase@@EAGJXZ proc push 59 jmp _DualProcessCommandWrap ?fv59@FakeDispatcherBase@@EAGJXZ endp ?fv60@FakeDispatcherBase@@EAGJXZ proc push 60 jmp _DualProcessCommandWrap ?fv60@FakeDispatcherBase@@EAGJXZ endp ?fv61@FakeDispatcherBase@@EAGJXZ proc push 61 jmp _DualProcessCommandWrap ?fv61@FakeDispatcherBase@@EAGJXZ endp ?fv62@FakeDispatcherBase@@EAGJXZ proc push 62 jmp _DualProcessCommandWrap ?fv62@FakeDispatcherBase@@EAGJXZ endp ?fv63@FakeDispatcherBase@@EAGJXZ proc push 63 jmp _DualProcessCommandWrap ?fv63@FakeDispatcherBase@@EAGJXZ endp ?fv64@FakeDispatcherBase@@EAGJXZ proc push 64 jmp _DualProcessCommandWrap ?fv64@FakeDispatcherBase@@EAGJXZ endp ?fv65@FakeDispatcherBase@@EAGJXZ proc push 65 jmp _DualProcessCommandWrap ?fv65@FakeDispatcherBase@@EAGJXZ endp ?fv66@FakeDispatcherBase@@EAGJXZ proc push 66 jmp _DualProcessCommandWrap ?fv66@FakeDispatcherBase@@EAGJXZ endp ?fv67@FakeDispatcherBase@@EAGJXZ proc push 67 jmp _DualProcessCommandWrap ?fv67@FakeDispatcherBase@@EAGJXZ endp ?fv68@FakeDispatcherBase@@EAGJXZ proc push 68 jmp _DualProcessCommandWrap ?fv68@FakeDispatcherBase@@EAGJXZ endp ?fv69@FakeDispatcherBase@@EAGJXZ proc push 69 jmp _DualProcessCommandWrap ?fv69@FakeDispatcherBase@@EAGJXZ endp ?fv70@FakeDispatcherBase@@EAGJXZ proc push 70 jmp _DualProcessCommandWrap ?fv70@FakeDispatcherBase@@EAGJXZ endp ?fv71@FakeDispatcherBase@@EAGJXZ proc push 71 jmp _DualProcessCommandWrap ?fv71@FakeDispatcherBase@@EAGJXZ endp ?fv72@FakeDispatcherBase@@EAGJXZ proc push 72 jmp _DualProcessCommandWrap ?fv72@FakeDispatcherBase@@EAGJXZ endp ?fv73@FakeDispatcherBase@@EAGJXZ proc push 73 jmp _DualProcessCommandWrap ?fv73@FakeDispatcherBase@@EAGJXZ endp ?fv74@FakeDispatcherBase@@EAGJXZ proc push 74 jmp _DualProcessCommandWrap ?fv74@FakeDispatcherBase@@EAGJXZ endp ?fv75@FakeDispatcherBase@@EAGJXZ proc push 75 jmp _DualProcessCommandWrap ?fv75@FakeDispatcherBase@@EAGJXZ endp ?fv76@FakeDispatcherBase@@EAGJXZ proc push 76 jmp _DualProcessCommandWrap ?fv76@FakeDispatcherBase@@EAGJXZ endp ?fv77@FakeDispatcherBase@@EAGJXZ proc push 77 jmp _DualProcessCommandWrap ?fv77@FakeDispatcherBase@@EAGJXZ endp ?fv78@FakeDispatcherBase@@EAGJXZ proc push 78 jmp _DualProcessCommandWrap ?fv78@FakeDispatcherBase@@EAGJXZ endp ?fv79@FakeDispatcherBase@@EAGJXZ proc push 79 jmp _DualProcessCommandWrap ?fv79@FakeDispatcherBase@@EAGJXZ endp ?fv80@FakeDispatcherBase@@EAGJXZ proc push 80 jmp _DualProcessCommandWrap ?fv80@FakeDispatcherBase@@EAGJXZ endp ?fv81@FakeDispatcherBase@@EAGJXZ proc push 81 jmp _DualProcessCommandWrap ?fv81@FakeDispatcherBase@@EAGJXZ endp ?fv82@FakeDispatcherBase@@EAGJXZ proc push 82 jmp _DualProcessCommandWrap ?fv82@FakeDispatcherBase@@EAGJXZ endp ?fv83@FakeDispatcherBase@@EAGJXZ proc push 83 jmp _DualProcessCommandWrap ?fv83@FakeDispatcherBase@@EAGJXZ endp ?fv84@FakeDispatcherBase@@EAGJXZ proc push 84 jmp _DualProcessCommandWrap ?fv84@FakeDispatcherBase@@EAGJXZ endp ?fv85@FakeDispatcherBase@@EAGJXZ proc push 85 jmp _DualProcessCommandWrap ?fv85@FakeDispatcherBase@@EAGJXZ endp ?fv86@FakeDispatcherBase@@EAGJXZ proc push 86 jmp _DualProcessCommandWrap ?fv86@FakeDispatcherBase@@EAGJXZ endp ?fv87@FakeDispatcherBase@@EAGJXZ proc push 87 jmp _DualProcessCommandWrap ?fv87@FakeDispatcherBase@@EAGJXZ endp ?fv88@FakeDispatcherBase@@EAGJXZ proc push 88 jmp _DualProcessCommandWrap ?fv88@FakeDispatcherBase@@EAGJXZ endp ?fv89@FakeDispatcherBase@@EAGJXZ proc push 89 jmp _DualProcessCommandWrap ?fv89@FakeDispatcherBase@@EAGJXZ endp ?fv90@FakeDispatcherBase@@EAGJXZ proc push 90 jmp _DualProcessCommandWrap ?fv90@FakeDispatcherBase@@EAGJXZ endp ?fv91@FakeDispatcherBase@@EAGJXZ proc push 91 jmp _DualProcessCommandWrap ?fv91@FakeDispatcherBase@@EAGJXZ endp ?fv92@FakeDispatcherBase@@EAGJXZ proc push 92 jmp _DualProcessCommandWrap ?fv92@FakeDispatcherBase@@EAGJXZ endp ?fv93@FakeDispatcherBase@@EAGJXZ proc push 93 jmp _DualProcessCommandWrap ?fv93@FakeDispatcherBase@@EAGJXZ endp ?fv94@FakeDispatcherBase@@EAGJXZ proc push 94 jmp _DualProcessCommandWrap ?fv94@FakeDispatcherBase@@EAGJXZ endp ?fv95@FakeDispatcherBase@@EAGJXZ proc push 95 jmp _DualProcessCommandWrap ?fv95@FakeDispatcherBase@@EAGJXZ endp ?fv96@FakeDispatcherBase@@EAGJXZ proc push 96 jmp _DualProcessCommandWrap ?fv96@FakeDispatcherBase@@EAGJXZ endp ?fv97@FakeDispatcherBase@@EAGJXZ proc push 97 jmp _DualProcessCommandWrap ?fv97@FakeDispatcherBase@@EAGJXZ endp ?fv98@FakeDispatcherBase@@EAGJXZ proc push 98 jmp _DualProcessCommandWrap ?fv98@FakeDispatcherBase@@EAGJXZ endp ?fv99@FakeDispatcherBase@@EAGJXZ proc push 99 jmp _DualProcessCommandWrap ?fv99@FakeDispatcherBase@@EAGJXZ endp ?fv100@FakeDispatcherBase@@EAGJXZ proc push 100 jmp _DualProcessCommandWrap ?fv100@FakeDispatcherBase@@EAGJXZ endp ?fv101@FakeDispatcherBase@@EAGJXZ proc push 101 jmp _DualProcessCommandWrap ?fv101@FakeDispatcherBase@@EAGJXZ endp ?fv102@FakeDispatcherBase@@EAGJXZ proc push 102 jmp _DualProcessCommandWrap ?fv102@FakeDispatcherBase@@EAGJXZ endp ?fv103@FakeDispatcherBase@@EAGJXZ proc push 103 jmp _DualProcessCommandWrap ?fv103@FakeDispatcherBase@@EAGJXZ endp ?fv104@FakeDispatcherBase@@EAGJXZ proc push 104 jmp _DualProcessCommandWrap ?fv104@FakeDispatcherBase@@EAGJXZ endp ?fv105@FakeDispatcherBase@@EAGJXZ proc push 105 jmp _DualProcessCommandWrap ?fv105@FakeDispatcherBase@@EAGJXZ endp ?fv106@FakeDispatcherBase@@EAGJXZ proc push 106 jmp _DualProcessCommandWrap ?fv106@FakeDispatcherBase@@EAGJXZ endp ?fv107@FakeDispatcherBase@@EAGJXZ proc push 107 jmp _DualProcessCommandWrap ?fv107@FakeDispatcherBase@@EAGJXZ endp ?fv108@FakeDispatcherBase@@EAGJXZ proc push 108 jmp _DualProcessCommandWrap ?fv108@FakeDispatcherBase@@EAGJXZ endp ?fv109@FakeDispatcherBase@@EAGJXZ proc push 109 jmp _DualProcessCommandWrap ?fv109@FakeDispatcherBase@@EAGJXZ endp ?fv110@FakeDispatcherBase@@EAGJXZ proc push 110 jmp _DualProcessCommandWrap ?fv110@FakeDispatcherBase@@EAGJXZ endp ?fv111@FakeDispatcherBase@@EAGJXZ proc push 111 jmp _DualProcessCommandWrap ?fv111@FakeDispatcherBase@@EAGJXZ endp ?fv112@FakeDispatcherBase@@EAGJXZ proc push 112 jmp _DualProcessCommandWrap ?fv112@FakeDispatcherBase@@EAGJXZ endp ?fv113@FakeDispatcherBase@@EAGJXZ proc push 113 jmp _DualProcessCommandWrap ?fv113@FakeDispatcherBase@@EAGJXZ endp ?fv114@FakeDispatcherBase@@EAGJXZ proc push 114 jmp _DualProcessCommandWrap ?fv114@FakeDispatcherBase@@EAGJXZ endp ?fv115@FakeDispatcherBase@@EAGJXZ proc push 115 jmp _DualProcessCommandWrap ?fv115@FakeDispatcherBase@@EAGJXZ endp ?fv116@FakeDispatcherBase@@EAGJXZ proc push 116 jmp _DualProcessCommandWrap ?fv116@FakeDispatcherBase@@EAGJXZ endp ?fv117@FakeDispatcherBase@@EAGJXZ proc push 117 jmp _DualProcessCommandWrap ?fv117@FakeDispatcherBase@@EAGJXZ endp ?fv118@FakeDispatcherBase@@EAGJXZ proc push 118 jmp _DualProcessCommandWrap ?fv118@FakeDispatcherBase@@EAGJXZ endp ?fv119@FakeDispatcherBase@@EAGJXZ proc push 119 jmp _DualProcessCommandWrap ?fv119@FakeDispatcherBase@@EAGJXZ endp ?fv120@FakeDispatcherBase@@EAGJXZ proc push 120 jmp _DualProcessCommandWrap ?fv120@FakeDispatcherBase@@EAGJXZ endp ?fv121@FakeDispatcherBase@@EAGJXZ proc push 121 jmp _DualProcessCommandWrap ?fv121@FakeDispatcherBase@@EAGJXZ endp ?fv122@FakeDispatcherBase@@EAGJXZ proc push 122 jmp _DualProcessCommandWrap ?fv122@FakeDispatcherBase@@EAGJXZ endp ?fv123@FakeDispatcherBase@@EAGJXZ proc push 123 jmp _DualProcessCommandWrap ?fv123@FakeDispatcherBase@@EAGJXZ endp ?fv124@FakeDispatcherBase@@EAGJXZ proc push 124 jmp _DualProcessCommandWrap ?fv124@FakeDispatcherBase@@EAGJXZ endp ?fv125@FakeDispatcherBase@@EAGJXZ proc push 125 jmp _DualProcessCommandWrap ?fv125@FakeDispatcherBase@@EAGJXZ endp ?fv126@FakeDispatcherBase@@EAGJXZ proc push 126 jmp _DualProcessCommandWrap ?fv126@FakeDispatcherBase@@EAGJXZ endp ?fv127@FakeDispatcherBase@@EAGJXZ proc push 127 jmp _DualProcessCommandWrap ?fv127@FakeDispatcherBase@@EAGJXZ endp ?fv128@FakeDispatcherBase@@EAGJXZ proc push 128 jmp _DualProcessCommandWrap ?fv128@FakeDispatcherBase@@EAGJXZ endp ?fv129@FakeDispatcherBase@@EAGJXZ proc push 129 jmp _DualProcessCommandWrap ?fv129@FakeDispatcherBase@@EAGJXZ endp ?fv130@FakeDispatcherBase@@EAGJXZ proc push 130 jmp _DualProcessCommandWrap ?fv130@FakeDispatcherBase@@EAGJXZ endp ?fv131@FakeDispatcherBase@@EAGJXZ proc push 131 jmp _DualProcessCommandWrap ?fv131@FakeDispatcherBase@@EAGJXZ endp ?fv132@FakeDispatcherBase@@EAGJXZ proc push 132 jmp _DualProcessCommandWrap ?fv132@FakeDispatcherBase@@EAGJXZ endp ?fv133@FakeDispatcherBase@@EAGJXZ proc push 133 jmp _DualProcessCommandWrap ?fv133@FakeDispatcherBase@@EAGJXZ endp ?fv134@FakeDispatcherBase@@EAGJXZ proc push 134 jmp _DualProcessCommandWrap ?fv134@FakeDispatcherBase@@EAGJXZ endp ?fv135@FakeDispatcherBase@@EAGJXZ proc push 135 jmp _DualProcessCommandWrap ?fv135@FakeDispatcherBase@@EAGJXZ endp ?fv136@FakeDispatcherBase@@EAGJXZ proc push 136 jmp _DualProcessCommandWrap ?fv136@FakeDispatcherBase@@EAGJXZ endp ?fv137@FakeDispatcherBase@@EAGJXZ proc push 137 jmp _DualProcessCommandWrap ?fv137@FakeDispatcherBase@@EAGJXZ endp ?fv138@FakeDispatcherBase@@EAGJXZ proc push 138 jmp _DualProcessCommandWrap ?fv138@FakeDispatcherBase@@EAGJXZ endp ?fv139@FakeDispatcherBase@@EAGJXZ proc push 139 jmp _DualProcessCommandWrap ?fv139@FakeDispatcherBase@@EAGJXZ endp ?fv140@FakeDispatcherBase@@EAGJXZ proc push 140 jmp _DualProcessCommandWrap ?fv140@FakeDispatcherBase@@EAGJXZ endp ?fv141@FakeDispatcherBase@@EAGJXZ proc push 141 jmp _DualProcessCommandWrap ?fv141@FakeDispatcherBase@@EAGJXZ endp ?fv142@FakeDispatcherBase@@EAGJXZ proc push 142 jmp _DualProcessCommandWrap ?fv142@FakeDispatcherBase@@EAGJXZ endp ?fv143@FakeDispatcherBase@@EAGJXZ proc push 143 jmp _DualProcessCommandWrap ?fv143@FakeDispatcherBase@@EAGJXZ endp ?fv144@FakeDispatcherBase@@EAGJXZ proc push 144 jmp _DualProcessCommandWrap ?fv144@FakeDispatcherBase@@EAGJXZ endp ?fv145@FakeDispatcherBase@@EAGJXZ proc push 145 jmp _DualProcessCommandWrap ?fv145@FakeDispatcherBase@@EAGJXZ endp ?fv146@FakeDispatcherBase@@EAGJXZ proc push 146 jmp _DualProcessCommandWrap ?fv146@FakeDispatcherBase@@EAGJXZ endp ?fv147@FakeDispatcherBase@@EAGJXZ proc push 147 jmp _DualProcessCommandWrap ?fv147@FakeDispatcherBase@@EAGJXZ endp ?fv148@FakeDispatcherBase@@EAGJXZ proc push 148 jmp _DualProcessCommandWrap ?fv148@FakeDispatcherBase@@EAGJXZ endp ?fv149@FakeDispatcherBase@@EAGJXZ proc push 149 jmp _DualProcessCommandWrap ?fv149@FakeDispatcherBase@@EAGJXZ endp ?fv150@FakeDispatcherBase@@EAGJXZ proc push 150 jmp _DualProcessCommandWrap ?fv150@FakeDispatcherBase@@EAGJXZ endp ?fv151@FakeDispatcherBase@@EAGJXZ proc push 151 jmp _DualProcessCommandWrap ?fv151@FakeDispatcherBase@@EAGJXZ endp ?fv152@FakeDispatcherBase@@EAGJXZ proc push 152 jmp _DualProcessCommandWrap ?fv152@FakeDispatcherBase@@EAGJXZ endp ?fv153@FakeDispatcherBase@@EAGJXZ proc push 153 jmp _DualProcessCommandWrap ?fv153@FakeDispatcherBase@@EAGJXZ endp ?fv154@FakeDispatcherBase@@EAGJXZ proc push 154 jmp _DualProcessCommandWrap ?fv154@FakeDispatcherBase@@EAGJXZ endp ?fv155@FakeDispatcherBase@@EAGJXZ proc push 155 jmp _DualProcessCommandWrap ?fv155@FakeDispatcherBase@@EAGJXZ endp ?fv156@FakeDispatcherBase@@EAGJXZ proc push 156 jmp _DualProcessCommandWrap ?fv156@FakeDispatcherBase@@EAGJXZ endp ?fv157@FakeDispatcherBase@@EAGJXZ proc push 157 jmp _DualProcessCommandWrap ?fv157@FakeDispatcherBase@@EAGJXZ endp ?fv158@FakeDispatcherBase@@EAGJXZ proc push 158 jmp _DualProcessCommandWrap ?fv158@FakeDispatcherBase@@EAGJXZ endp ?fv159@FakeDispatcherBase@@EAGJXZ proc push 159 jmp _DualProcessCommandWrap ?fv159@FakeDispatcherBase@@EAGJXZ endp ?fv160@FakeDispatcherBase@@EAGJXZ proc push 160 jmp _DualProcessCommandWrap ?fv160@FakeDispatcherBase@@EAGJXZ endp ?fv161@FakeDispatcherBase@@EAGJXZ proc push 161 jmp _DualProcessCommandWrap ?fv161@FakeDispatcherBase@@EAGJXZ endp ?fv162@FakeDispatcherBase@@EAGJXZ proc push 162 jmp _DualProcessCommandWrap ?fv162@FakeDispatcherBase@@EAGJXZ endp ?fv163@FakeDispatcherBase@@EAGJXZ proc push 163 jmp _DualProcessCommandWrap ?fv163@FakeDispatcherBase@@EAGJXZ endp ?fv164@FakeDispatcherBase@@EAGJXZ proc push 164 jmp _DualProcessCommandWrap ?fv164@FakeDispatcherBase@@EAGJXZ endp ?fv165@FakeDispatcherBase@@EAGJXZ proc push 165 jmp _DualProcessCommandWrap ?fv165@FakeDispatcherBase@@EAGJXZ endp ?fv166@FakeDispatcherBase@@EAGJXZ proc push 166 jmp _DualProcessCommandWrap ?fv166@FakeDispatcherBase@@EAGJXZ endp ?fv167@FakeDispatcherBase@@EAGJXZ proc push 167 jmp _DualProcessCommandWrap ?fv167@FakeDispatcherBase@@EAGJXZ endp ?fv168@FakeDispatcherBase@@EAGJXZ proc push 168 jmp _DualProcessCommandWrap ?fv168@FakeDispatcherBase@@EAGJXZ endp ?fv169@FakeDispatcherBase@@EAGJXZ proc push 169 jmp _DualProcessCommandWrap ?fv169@FakeDispatcherBase@@EAGJXZ endp ?fv170@FakeDispatcherBase@@EAGJXZ proc push 170 jmp _DualProcessCommandWrap ?fv170@FakeDispatcherBase@@EAGJXZ endp ?fv171@FakeDispatcherBase@@EAGJXZ proc push 171 jmp _DualProcessCommandWrap ?fv171@FakeDispatcherBase@@EAGJXZ endp ?fv172@FakeDispatcherBase@@EAGJXZ proc push 172 jmp _DualProcessCommandWrap ?fv172@FakeDispatcherBase@@EAGJXZ endp ?fv173@FakeDispatcherBase@@EAGJXZ proc push 173 jmp _DualProcessCommandWrap ?fv173@FakeDispatcherBase@@EAGJXZ endp ?fv174@FakeDispatcherBase@@EAGJXZ proc push 174 jmp _DualProcessCommandWrap ?fv174@FakeDispatcherBase@@EAGJXZ endp ?fv175@FakeDispatcherBase@@EAGJXZ proc push 175 jmp _DualProcessCommandWrap ?fv175@FakeDispatcherBase@@EAGJXZ endp ?fv176@FakeDispatcherBase@@EAGJXZ proc push 176 jmp _DualProcessCommandWrap ?fv176@FakeDispatcherBase@@EAGJXZ endp ?fv177@FakeDispatcherBase@@EAGJXZ proc push 177 jmp _DualProcessCommandWrap ?fv177@FakeDispatcherBase@@EAGJXZ endp ?fv178@FakeDispatcherBase@@EAGJXZ proc push 178 jmp _DualProcessCommandWrap ?fv178@FakeDispatcherBase@@EAGJXZ endp ?fv179@FakeDispatcherBase@@EAGJXZ proc push 179 jmp _DualProcessCommandWrap ?fv179@FakeDispatcherBase@@EAGJXZ endp ?fv180@FakeDispatcherBase@@EAGJXZ proc push 180 jmp _DualProcessCommandWrap ?fv180@FakeDispatcherBase@@EAGJXZ endp ?fv181@FakeDispatcherBase@@EAGJXZ proc push 181 jmp _DualProcessCommandWrap ?fv181@FakeDispatcherBase@@EAGJXZ endp ?fv182@FakeDispatcherBase@@EAGJXZ proc push 182 jmp _DualProcessCommandWrap ?fv182@FakeDispatcherBase@@EAGJXZ endp ?fv183@FakeDispatcherBase@@EAGJXZ proc push 183 jmp _DualProcessCommandWrap ?fv183@FakeDispatcherBase@@EAGJXZ endp ?fv184@FakeDispatcherBase@@EAGJXZ proc push 184 jmp _DualProcessCommandWrap ?fv184@FakeDispatcherBase@@EAGJXZ endp ?fv185@FakeDispatcherBase@@EAGJXZ proc push 185 jmp _DualProcessCommandWrap ?fv185@FakeDispatcherBase@@EAGJXZ endp ?fv186@FakeDispatcherBase@@EAGJXZ proc push 186 jmp _DualProcessCommandWrap ?fv186@FakeDispatcherBase@@EAGJXZ endp ?fv187@FakeDispatcherBase@@EAGJXZ proc push 187 jmp _DualProcessCommandWrap ?fv187@FakeDispatcherBase@@EAGJXZ endp ?fv188@FakeDispatcherBase@@EAGJXZ proc push 188 jmp _DualProcessCommandWrap ?fv188@FakeDispatcherBase@@EAGJXZ endp ?fv189@FakeDispatcherBase@@EAGJXZ proc push 189 jmp _DualProcessCommandWrap ?fv189@FakeDispatcherBase@@EAGJXZ endp ?fv190@FakeDispatcherBase@@EAGJXZ proc push 190 jmp _DualProcessCommandWrap ?fv190@FakeDispatcherBase@@EAGJXZ endp ?fv191@FakeDispatcherBase@@EAGJXZ proc push 191 jmp _DualProcessCommandWrap ?fv191@FakeDispatcherBase@@EAGJXZ endp ?fv192@FakeDispatcherBase@@EAGJXZ proc push 192 jmp _DualProcessCommandWrap ?fv192@FakeDispatcherBase@@EAGJXZ endp ?fv193@FakeDispatcherBase@@EAGJXZ proc push 193 jmp _DualProcessCommandWrap ?fv193@FakeDispatcherBase@@EAGJXZ endp ?fv194@FakeDispatcherBase@@EAGJXZ proc push 194 jmp _DualProcessCommandWrap ?fv194@FakeDispatcherBase@@EAGJXZ endp ?fv195@FakeDispatcherBase@@EAGJXZ proc push 195 jmp _DualProcessCommandWrap ?fv195@FakeDispatcherBase@@EAGJXZ endp ?fv196@FakeDispatcherBase@@EAGJXZ proc push 196 jmp _DualProcessCommandWrap ?fv196@FakeDispatcherBase@@EAGJXZ endp ?fv197@FakeDispatcherBase@@EAGJXZ proc push 197 jmp _DualProcessCommandWrap ?fv197@FakeDispatcherBase@@EAGJXZ endp ?fv198@FakeDispatcherBase@@EAGJXZ proc push 198 jmp _DualProcessCommandWrap ?fv198@FakeDispatcherBase@@EAGJXZ endp ?fv199@FakeDispatcherBase@@EAGJXZ proc push 199 jmp _DualProcessCommandWrap ?fv199@FakeDispatcherBase@@EAGJXZ endp end
007slmg-np-activex
ffactivex/FakeDispatcherBase.asm
Assembly
mpl11
32,722
// stdafx.cpp : source file that includes just the standard includes // npactivex.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "npactivex.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
007slmg-np-activex
ffactivex/stdafx.cpp
C++
mpl11
299
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <Windows.h> #define ATL_THUNK_APIHOOK EXCEPTION_DISPOSITION __cdecl _except_handler( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ); typedef EXCEPTION_DISPOSITION (__cdecl *_except_handler_type)( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ); typedef struct tagATL_THUNK_PATTERN { LPBYTE pattern; int pattern_size; (void)(*enumerator)(struct _CONTEXT *); }ATL_THUNK_PATTERN; void InstallAtlThunkEnumeration(); void UninstallAtlThunkEnumeration();
007slmg-np-activex
ffactivex/atlthunk.h
C
mpl11
2,219
#include "ScriptFunc.h" NPClass ScriptFunc::npClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ ScriptFunc::_Allocate, /* deallocate */ ScriptFunc::_Deallocate, /* invalidate */ NULL, /* hasMethod */ NULL, //Scriptable::_HasMethod, /* invoke */ NULL, //Scriptable::_Invoke, /* invokeDefault */ ScriptFunc::_InvokeDefault, /* hasProperty */ NULL, /* getProperty */ NULL, /* setProperty */ NULL, /* removeProperty */ NULL, /* enumerate */ NULL, /* construct */ NULL }; map<pair<Scriptable*, MEMBERID>, ScriptFunc*> ScriptFunc::M; ScriptFunc::ScriptFunc(NPP inst) { } ScriptFunc::~ScriptFunc(void) { if (script) { pair<Scriptable*, MEMBERID> index(script, dispid); NPNFuncs.releaseobject(script); M.erase(index); } } ScriptFunc* ScriptFunc::GetFunctionObject(NPP npp, Scriptable *script, MEMBERID dispid) { pair<Scriptable*, MEMBERID> index(script, dispid); if (M[index] == NULL) { ScriptFunc *new_obj = (ScriptFunc*)NPNFuncs.createobject(npp, &npClass); NPNFuncs.retainobject(script); new_obj->setControl(script, dispid); M[index] = new_obj; } else { NPNFuncs.retainobject(M[index]); } return M[index]; } bool ScriptFunc::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) { if (!script) return false; bool ret = script->InvokeID(dispid, args, argCount, result); if (!ret) { np_log(script->instance, 0, "Invoke failed, DISPID 0x%08x", dispid); } return ret; }
007slmg-np-activex
ffactivex/ScriptFunc.cpp
C++
mpl11
1,507
// Copyright qiuc12@gmail.com // This file is generated autmatically by python. DONT MODIFY IT! #pragma once #include <OleAuto.h> class FakeDispatcher; HRESULT DualProcessCommand(int commandId, FakeDispatcher *disp, ...); extern "C" void DualProcessCommandWrap(); class FakeDispatcherBase : public IDispatch { private: virtual HRESULT __stdcall fv0(); virtual HRESULT __stdcall fv1(); virtual HRESULT __stdcall fv2(); virtual HRESULT __stdcall fv3(); virtual HRESULT __stdcall fv4(); virtual HRESULT __stdcall fv5(); virtual HRESULT __stdcall fv6(); virtual HRESULT __stdcall fv7(); virtual HRESULT __stdcall fv8(); virtual HRESULT __stdcall fv9(); virtual HRESULT __stdcall fv10(); virtual HRESULT __stdcall fv11(); virtual HRESULT __stdcall fv12(); virtual HRESULT __stdcall fv13(); virtual HRESULT __stdcall fv14(); virtual HRESULT __stdcall fv15(); virtual HRESULT __stdcall fv16(); virtual HRESULT __stdcall fv17(); virtual HRESULT __stdcall fv18(); virtual HRESULT __stdcall fv19(); virtual HRESULT __stdcall fv20(); virtual HRESULT __stdcall fv21(); virtual HRESULT __stdcall fv22(); virtual HRESULT __stdcall fv23(); virtual HRESULT __stdcall fv24(); virtual HRESULT __stdcall fv25(); virtual HRESULT __stdcall fv26(); virtual HRESULT __stdcall fv27(); virtual HRESULT __stdcall fv28(); virtual HRESULT __stdcall fv29(); virtual HRESULT __stdcall fv30(); virtual HRESULT __stdcall fv31(); virtual HRESULT __stdcall fv32(); virtual HRESULT __stdcall fv33(); virtual HRESULT __stdcall fv34(); virtual HRESULT __stdcall fv35(); virtual HRESULT __stdcall fv36(); virtual HRESULT __stdcall fv37(); virtual HRESULT __stdcall fv38(); virtual HRESULT __stdcall fv39(); virtual HRESULT __stdcall fv40(); virtual HRESULT __stdcall fv41(); virtual HRESULT __stdcall fv42(); virtual HRESULT __stdcall fv43(); virtual HRESULT __stdcall fv44(); virtual HRESULT __stdcall fv45(); virtual HRESULT __stdcall fv46(); virtual HRESULT __stdcall fv47(); virtual HRESULT __stdcall fv48(); virtual HRESULT __stdcall fv49(); virtual HRESULT __stdcall fv50(); virtual HRESULT __stdcall fv51(); virtual HRESULT __stdcall fv52(); virtual HRESULT __stdcall fv53(); virtual HRESULT __stdcall fv54(); virtual HRESULT __stdcall fv55(); virtual HRESULT __stdcall fv56(); virtual HRESULT __stdcall fv57(); virtual HRESULT __stdcall fv58(); virtual HRESULT __stdcall fv59(); virtual HRESULT __stdcall fv60(); virtual HRESULT __stdcall fv61(); virtual HRESULT __stdcall fv62(); virtual HRESULT __stdcall fv63(); virtual HRESULT __stdcall fv64(); virtual HRESULT __stdcall fv65(); virtual HRESULT __stdcall fv66(); virtual HRESULT __stdcall fv67(); virtual HRESULT __stdcall fv68(); virtual HRESULT __stdcall fv69(); virtual HRESULT __stdcall fv70(); virtual HRESULT __stdcall fv71(); virtual HRESULT __stdcall fv72(); virtual HRESULT __stdcall fv73(); virtual HRESULT __stdcall fv74(); virtual HRESULT __stdcall fv75(); virtual HRESULT __stdcall fv76(); virtual HRESULT __stdcall fv77(); virtual HRESULT __stdcall fv78(); virtual HRESULT __stdcall fv79(); virtual HRESULT __stdcall fv80(); virtual HRESULT __stdcall fv81(); virtual HRESULT __stdcall fv82(); virtual HRESULT __stdcall fv83(); virtual HRESULT __stdcall fv84(); virtual HRESULT __stdcall fv85(); virtual HRESULT __stdcall fv86(); virtual HRESULT __stdcall fv87(); virtual HRESULT __stdcall fv88(); virtual HRESULT __stdcall fv89(); virtual HRESULT __stdcall fv90(); virtual HRESULT __stdcall fv91(); virtual HRESULT __stdcall fv92(); virtual HRESULT __stdcall fv93(); virtual HRESULT __stdcall fv94(); virtual HRESULT __stdcall fv95(); virtual HRESULT __stdcall fv96(); virtual HRESULT __stdcall fv97(); virtual HRESULT __stdcall fv98(); virtual HRESULT __stdcall fv99(); virtual HRESULT __stdcall fv100(); virtual HRESULT __stdcall fv101(); virtual HRESULT __stdcall fv102(); virtual HRESULT __stdcall fv103(); virtual HRESULT __stdcall fv104(); virtual HRESULT __stdcall fv105(); virtual HRESULT __stdcall fv106(); virtual HRESULT __stdcall fv107(); virtual HRESULT __stdcall fv108(); virtual HRESULT __stdcall fv109(); virtual HRESULT __stdcall fv110(); virtual HRESULT __stdcall fv111(); virtual HRESULT __stdcall fv112(); virtual HRESULT __stdcall fv113(); virtual HRESULT __stdcall fv114(); virtual HRESULT __stdcall fv115(); virtual HRESULT __stdcall fv116(); virtual HRESULT __stdcall fv117(); virtual HRESULT __stdcall fv118(); virtual HRESULT __stdcall fv119(); virtual HRESULT __stdcall fv120(); virtual HRESULT __stdcall fv121(); virtual HRESULT __stdcall fv122(); virtual HRESULT __stdcall fv123(); virtual HRESULT __stdcall fv124(); virtual HRESULT __stdcall fv125(); virtual HRESULT __stdcall fv126(); virtual HRESULT __stdcall fv127(); virtual HRESULT __stdcall fv128(); virtual HRESULT __stdcall fv129(); virtual HRESULT __stdcall fv130(); virtual HRESULT __stdcall fv131(); virtual HRESULT __stdcall fv132(); virtual HRESULT __stdcall fv133(); virtual HRESULT __stdcall fv134(); virtual HRESULT __stdcall fv135(); virtual HRESULT __stdcall fv136(); virtual HRESULT __stdcall fv137(); virtual HRESULT __stdcall fv138(); virtual HRESULT __stdcall fv139(); virtual HRESULT __stdcall fv140(); virtual HRESULT __stdcall fv141(); virtual HRESULT __stdcall fv142(); virtual HRESULT __stdcall fv143(); virtual HRESULT __stdcall fv144(); virtual HRESULT __stdcall fv145(); virtual HRESULT __stdcall fv146(); virtual HRESULT __stdcall fv147(); virtual HRESULT __stdcall fv148(); virtual HRESULT __stdcall fv149(); virtual HRESULT __stdcall fv150(); virtual HRESULT __stdcall fv151(); virtual HRESULT __stdcall fv152(); virtual HRESULT __stdcall fv153(); virtual HRESULT __stdcall fv154(); virtual HRESULT __stdcall fv155(); virtual HRESULT __stdcall fv156(); virtual HRESULT __stdcall fv157(); virtual HRESULT __stdcall fv158(); virtual HRESULT __stdcall fv159(); virtual HRESULT __stdcall fv160(); virtual HRESULT __stdcall fv161(); virtual HRESULT __stdcall fv162(); virtual HRESULT __stdcall fv163(); virtual HRESULT __stdcall fv164(); virtual HRESULT __stdcall fv165(); virtual HRESULT __stdcall fv166(); virtual HRESULT __stdcall fv167(); virtual HRESULT __stdcall fv168(); virtual HRESULT __stdcall fv169(); virtual HRESULT __stdcall fv170(); virtual HRESULT __stdcall fv171(); virtual HRESULT __stdcall fv172(); virtual HRESULT __stdcall fv173(); virtual HRESULT __stdcall fv174(); virtual HRESULT __stdcall fv175(); virtual HRESULT __stdcall fv176(); virtual HRESULT __stdcall fv177(); virtual HRESULT __stdcall fv178(); virtual HRESULT __stdcall fv179(); virtual HRESULT __stdcall fv180(); virtual HRESULT __stdcall fv181(); virtual HRESULT __stdcall fv182(); virtual HRESULT __stdcall fv183(); virtual HRESULT __stdcall fv184(); virtual HRESULT __stdcall fv185(); virtual HRESULT __stdcall fv186(); virtual HRESULT __stdcall fv187(); virtual HRESULT __stdcall fv188(); virtual HRESULT __stdcall fv189(); virtual HRESULT __stdcall fv190(); virtual HRESULT __stdcall fv191(); virtual HRESULT __stdcall fv192(); virtual HRESULT __stdcall fv193(); virtual HRESULT __stdcall fv194(); virtual HRESULT __stdcall fv195(); virtual HRESULT __stdcall fv196(); virtual HRESULT __stdcall fv197(); virtual HRESULT __stdcall fv198(); virtual HRESULT __stdcall fv199(); protected: const static int kMaxVf = 200; };
007slmg-np-activex
ffactivex/FakeDispatcherBase.h
C++
mpl11
7,671
comment ? /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ .386 .model flat __except_handler proto .safeseh __except_handler ? .386 .model flat PUBLIC __KiUserExceptionDispatcher_hook .data public __KiUserExceptionDispatcher_origin __KiUserExceptionDispatcher_origin dd 0 public __KiUserExceptionDispatcher_ATL_p __KiUserExceptionDispatcher_ATL_p dd 0 .code __KiUserExceptionDispatcher_hook proc ; The arguments are already on the stack call __KiUserExceptionDispatcher_ATL_p push __KiUserExceptionDispatcher_origin ret __KiUserExceptionDispatcher_hook endp end
007slmg-np-activex
ffactivex/atlthunk_asm.asm
Assembly
mpl11
2,081
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include "npapi.h" #include <npfunctions.h> #include <prtypes.h> #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #include <atlbase.h> #include <atlstr.h> #include <atlcom.h> #include <atlctl.h> #include <varargs.h> #include "variants.h" extern NPNetscapeFuncs NPNFuncs; //#define NO_REGISTRY_AUTHORIZE #define np_log(instance, level, message, ...) log_activex_logging(instance, level, __FILE__, __LINE__, message, ##__VA_ARGS__) // For catch breakpoints. HRESULT NotImpl(); #define LogNotImplemented(instance) (np_log(instance, 0, "Not Implemented operation!!"), NotImpl()) void log_activex_logging(NPP instance, unsigned int level, const char* file, int line, char *message, ...); NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved); NPError NPP_Destroy(NPP instance, NPSavedData **save); NPError NPP_SetWindow(NPP instance, NPWindow *window); #define REGISTER_MANAGER
007slmg-np-activex
ffactivex/npactivex.h
C
mpl11
2,994
#pragma once // The following macros define the minimum required platform. The minimum required platform // is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run // your application. The macros work by enabling all features available on platform versions up to and // including the version specified. // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Specifies that the minimum required platform is Windows Vista. #define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. #define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif #ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0. #define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE. #endif
007slmg-np-activex
ffactivex/targetver.h
C
mpl11
1,428
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <npapi.h> #include <npruntime.h> #include <map> #include <vector> #include "Host.h" class CAxHost; class ObjectManager : public CHost { public: ObjectManager(NPP npp2); ~ObjectManager(void); static NPClass npClass; CHost* GetPreviousObject(NPP npp); static ObjectManager* GetManager(NPP npp); virtual ScriptBase *CreateScriptableObject(); void RetainOwnership(CAxHost *obj); bool RequestObjectOwnership(NPP newNpp, CAxHost* obj); private: struct ScriptManager : public ScriptBase { ScriptManager(NPP npp) : ScriptBase(npp) { } }; std::vector<CHost*> hosts; std::vector<CHost*> dynamic_hosts; static NPObject* _Allocate(NPP npp, NPClass *aClass) { ScriptManager *obj = new ScriptManager(npp); return obj; } static bool Invoke(NPObject *obj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool HasMethod(NPObject *obj, NPIdentifier name); static bool HasProperty(NPObject *obj, NPIdentifier name); static bool GetProperty(NPObject *obj, NPIdentifier name, NPVariant *value); static bool SetProperty(NPObject *obj, NPIdentifier name, const NPVariant *value); static void Deallocate(NPObject *obj); };
007slmg-np-activex
ffactivex/ObjectManager.h
C++
mpl11
2,783
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include "oleidl.h" #include <npapi.h> #include <npruntime.h> #include "npactivex.h" #include "objectProxy.h" #include "FakeDispatcher.h" class HTMLDocumentContainer : public CComObjectRoot, public IOleContainer, public IServiceProviderImpl<HTMLDocumentContainer>, public IWebBrowser2 { public: HTMLDocumentContainer(); void Init(NPP instance, ITypeLib *htmlLib); ~HTMLDocumentContainer(void); // IOleContainer virtual HRESULT STDMETHODCALLTYPE EnumObjects( /* [in] */ DWORD grfFlags, /* [out] */ __RPC__deref_out_opt IEnumUnknown **ppenum) { return LogNotImplemented(npp); } virtual HRESULT STDMETHODCALLTYPE ParseDisplayName( /* [unique][in] */ __RPC__in_opt IBindCtx *pbc, /* [in] */ __RPC__in LPOLESTR pszDisplayName, /* [out] */ __RPC__out ULONG *pchEaten, /* [out] */ __RPC__deref_out_opt IMoniker **ppmkOut) { return LogNotImplemented(npp); } virtual HRESULT STDMETHODCALLTYPE LockContainer( /* [in] */ BOOL fLock) { return LogNotImplemented(npp); } // IWebBrowser2 virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Navigate2( /* [in] */ __RPC__in VARIANT *URL, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Flags, /* [unique][optional][in] */ __RPC__in_opt VARIANT *TargetFrameName, /* [unique][optional][in] */ __RPC__in_opt VARIANT *PostData, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Headers) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE QueryStatusWB( /* [in] */ OLECMDID cmdID, /* [retval][out] */ __RPC__out OLECMDF *pcmdf) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ExecWB( /* [in] */ OLECMDID cmdID, /* [in] */ OLECMDEXECOPT cmdexecopt, /* [unique][optional][in] */ __RPC__in_opt VARIANT *pvaIn, /* [unique][optional][out][in] */ __RPC__inout_opt VARIANT *pvaOut) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ShowBrowserBar( /* [in] */ __RPC__in VARIANT *pvaClsid, /* [unique][optional][in] */ __RPC__in_opt VARIANT *pvarShow, /* [unique][optional][in] */ __RPC__in_opt VARIANT *pvarSize) {return LogNotImplemented(npp);}; virtual /* [bindable][propget][id] */ HRESULT STDMETHODCALLTYPE get_ReadyState( /* [out][retval] */ __RPC__out READYSTATE *plReadyState) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Offline( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbOffline) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Offline( /* [in] */ VARIANT_BOOL bOffline) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Silent( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbSilent) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Silent( /* [in] */ VARIANT_BOOL bSilent) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_RegisterAsBrowser( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_RegisterAsBrowser( /* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_RegisterAsDropTarget( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_RegisterAsDropTarget( /* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_TheaterMode( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_TheaterMode( /* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_AddressBar( /* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {*Value = True;return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_AddressBar( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Resizable( /* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Resizable( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Quit( void) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ClientToWindow( /* [out][in] */ __RPC__inout int *pcx, /* [out][in] */ __RPC__inout int *pcy) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE PutProperty( /* [in] */ __RPC__in BSTR Property, /* [in] */ VARIANT vtValue) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GetProperty( /* [in] */ __RPC__in BSTR Property, /* [retval][out] */ __RPC__out VARIANT *pvtValue) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Name( /* [retval][out] */ __RPC__deref_out_opt BSTR *Name) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_HWND( /* [retval][out] */ __RPC__out SHANDLE_PTR *pHWND) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_FullName( /* [retval][out] */ __RPC__deref_out_opt BSTR *FullName) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Path( /* [retval][out] */ __RPC__deref_out_opt BSTR *Path) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Visible( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Visible( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_StatusBar( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_StatusBar( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_StatusText( /* [retval][out] */ __RPC__deref_out_opt BSTR *StatusText) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_StatusText( /* [in] */ __RPC__in BSTR StatusText) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_ToolBar( /* [retval][out] */ __RPC__out int *Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_ToolBar( /* [in] */ int Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_MenuBar( /* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_MenuBar( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_FullScreen( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbFullScreen) {*pbFullScreen = FALSE; return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_FullScreen( /* [in] */ VARIANT_BOOL bFullScreen) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoBack( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoForward( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoHome( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoSearch( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Navigate( /* [in] */ __RPC__in BSTR URL, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Flags, /* [unique][optional][in] */ __RPC__in_opt VARIANT *TargetFrameName, /* [unique][optional][in] */ __RPC__in_opt VARIANT *PostData, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Headers) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Refresh( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Refresh2( /* [unique][optional][in] */ __RPC__in_opt VARIANT *Level) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Stop( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Application( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Parent( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Container( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Document( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp); virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_TopLevelContainer( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Type( /* [retval][out] */ __RPC__deref_out_opt BSTR *Type) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Left( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Left( /* [in] */ long Left) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Top( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Top( /* [in] */ long Top) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Width( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Width( /* [in] */ long Width) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Height( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Height( /* [in] */ long Height) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_LocationName( /* [retval][out] */ __RPC__deref_out_opt BSTR *LocationName) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_LocationURL( /* [retval][out] */ __RPC__deref_out_opt BSTR *LocationURL); virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Busy( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);} virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount( /* [out] */ __RPC__out UINT *pctinfo) {return LogNotImplemented(npp);} virtual HRESULT STDMETHODCALLTYPE GetTypeInfo( /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo) {return LogNotImplemented(npp);} virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames( /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId) {return LogNotImplemented(npp);} virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke( /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr) {return LogNotImplemented(npp);} BEGIN_COM_MAP(HTMLDocumentContainer) COM_INTERFACE_ENTRY(IOleContainer) COM_INTERFACE_ENTRY(IServiceProvider) COM_INTERFACE_ENTRY(IWebBrowser2) COM_INTERFACE_ENTRY_IID(IID_IWebBrowserApp, IWebBrowser2) COM_INTERFACE_ENTRY_IID(IID_IWebBrowser, IWebBrowser2) COM_INTERFACE_ENTRY_AGGREGATE_BLIND(dispatcher) END_COM_MAP() static const GUID IID_TopLevelBrowser; BEGIN_SERVICE_MAP(HTMLDocumentContainer) SERVICE_ENTRY(IID_IWebBrowserApp) SERVICE_ENTRY(IID_IWebBrowser2) SERVICE_ENTRY(IID_IWebBrowser) SERVICE_ENTRY(SID_SContainerDispatch); SERVICE_ENTRY(IID_TopLevelBrowser) END_SERVICE_MAP() private: FakeDispatcher *dispatcher; NPObjectProxy document_; NPP npp; };
007slmg-np-activex
ffactivex/HTMLDocumentContainer.h
C++
mpl11
17,424
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <atlbase.h> #include <comdef.h> #include <npapi.h> #include <npfunctions.h> #include <npruntime.h> #include "variants.h" #include "FakeDispatcher.h" #include "Host.h" extern NPNetscapeFuncs NPNFuncs; class CAxHost; struct Scriptable: public ScriptBase { private: Scriptable(const Scriptable &); // This method iterates all members of the current interface, looking for the member with the // id of member_id. If not found within this interface, it will iterate all base interfaces // recursively, until a match is found, or all the hierarchy was searched. bool find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind); DISPID ResolveName(NPIdentifier name, unsigned int invKind); //bool InvokeControl(DISPID id, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult); CComQIPtr<IDispatch> disp; bool invalid; DISPID dispid; void setControl(IUnknown *unk) { disp = unk; } bool IsProperty(DISPID member_id); public: Scriptable(NPP npp): ScriptBase(npp), invalid(false) { dispid = -1; } ~Scriptable() { } static NPClass npClass; static Scriptable* FromIUnknown(NPP npp, IUnknown *unk) { Scriptable *new_obj = (Scriptable*)NPNFuncs.createobject(npp, &npClass); new_obj->setControl(unk); return new_obj; } static Scriptable* FromAxHost(NPP npp, CAxHost* host); HRESULT getControl(IUnknown **obj) { if (disp) { *obj = disp.p; (*obj)->AddRef(); return S_OK; } return E_NOT_SET; } void Invalidate() {invalid = true;} bool HasMethod(NPIdentifier name); bool Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); bool InvokeID(DISPID id, const NPVariant *args, uint32_t argCount, NPVariant *result); bool HasProperty(NPIdentifier name); bool GetProperty(NPIdentifier name, NPVariant *result); bool SetProperty(NPIdentifier name, const NPVariant *value); bool Enumerate(NPIdentifier **value, uint32_t *count); private: // Some wrappers to adapt NPAPI's interface. static NPObject* _Allocate(NPP npp, NPClass *aClass); static void _Deallocate(NPObject *obj); static void _Invalidate(NPObject *obj) { if (obj) { ((Scriptable *)obj)->Invalidate(); } } static bool _HasMethod(NPObject *npobj, NPIdentifier name) { return ((Scriptable *)npobj)->HasMethod(name); } static bool _Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((Scriptable *)npobj)->Invoke(name, args, argCount, result); } static bool _HasProperty(NPObject *npobj, NPIdentifier name) { return ((Scriptable *)npobj)->HasProperty(name); } static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((Scriptable *)npobj)->GetProperty(name, result); } static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((Scriptable *)npobj)->SetProperty(name, value); } static bool _Enumerate(NPObject *npobj, NPIdentifier **value, uint32_t *count) { return ((Scriptable *)npobj)->Enumerate(value, count); } };
007slmg-np-activex
ffactivex/scriptable.h
C++
mpl11
4,934
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <Windows.h> #include <OleAuto.h> #include <npapi.h> #include <npruntime.h> #include "FakeDispatcherBase.h" #include "objectProxy.h" extern ITypeLib *pHtmlLib; class CAxHost; EXTERN_C const IID IID_IFakeDispatcher; class FakeDispatcher : public FakeDispatcherBase { private: class FakeDispatcherEx: IDispatchEx { private: FakeDispatcher *target; public: FakeDispatcherEx(FakeDispatcher *target) : target(target) { } virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID riid, __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject) { return target->QueryInterface(riid, ppvObject); } virtual ULONG STDMETHODCALLTYPE AddRef( void) { return target->AddRef(); } virtual ULONG STDMETHODCALLTYPE Release( void) { return target->Release(); } virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount( __RPC__out UINT *pctinfo) { return target->GetTypeInfoCount(pctinfo); } virtual HRESULT STDMETHODCALLTYPE GetTypeInfo( UINT iTInfo, LCID lcid, __RPC__deref_out_opt ITypeInfo **ppTInfo) { return target->GetTypeInfo(iTInfo, lcid, ppTInfo); } virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames( __RPC__in REFIID riid, __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, __RPC__in_range(0,16384) UINT cNames, LCID lcid, __RPC__out_ecount_full(cNames) DISPID *rgDispId) { return target->GetIDsOfNames(riid, rgszNames, cNames, lcid, rgDispId); } virtual HRESULT STDMETHODCALLTYPE Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { return target->Invoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } virtual HRESULT STDMETHODCALLTYPE GetDispID( __RPC__in BSTR bstrName, DWORD grfdex, __RPC__out DISPID *pid); virtual HRESULT STDMETHODCALLTYPE InvokeEx( __in DISPID id, __in LCID lcid, __in WORD wFlags, __in DISPPARAMS *pdp, __out_opt VARIANT *pvarRes, __out_opt EXCEPINFO *pei, __in_opt IServiceProvider *pspCaller); virtual HRESULT STDMETHODCALLTYPE DeleteMemberByName( __RPC__in BSTR bstrName, DWORD grfdex); virtual HRESULT STDMETHODCALLTYPE DeleteMemberByDispID(DISPID id); virtual HRESULT STDMETHODCALLTYPE GetMemberProperties( DISPID id, DWORD grfdexFetch, __RPC__out DWORD *pgrfdex); virtual HRESULT STDMETHODCALLTYPE GetMemberName( DISPID id, __RPC__deref_out_opt BSTR *pbstrName); virtual HRESULT STDMETHODCALLTYPE GetNextDispID( DWORD grfdex, DISPID id, __RPC__out DISPID *pid); virtual HRESULT STDMETHODCALLTYPE GetNameSpaceParent( __RPC__deref_out_opt IUnknown **ppunk); }; public: virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID riid, __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject); virtual ULONG STDMETHODCALLTYPE AddRef( void) { ++ref; return ref; } virtual ULONG STDMETHODCALLTYPE Release( void) { --ref; if (ref == 0) delete this; return ref; } virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount( __RPC__out UINT *pctinfo) { *pctinfo = 1; return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetTypeInfo( UINT iTInfo, LCID lcid, __RPC__deref_out_opt ITypeInfo **ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames( __RPC__in REFIID riid, __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, __RPC__in_range(0,16384) UINT cNames, LCID lcid, __RPC__out_ecount_full(cNames) DISPID *rgDispId); virtual HRESULT STDMETHODCALLTYPE Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); NPObject *getObject() { return npObject; } FakeDispatcher(NPP npInstance, ITypeLib *typeLib, NPObject *object); ~FakeDispatcher(void); HRESULT ProcessCommand(int ID, int *parlength,va_list &list); //friend HRESULT __cdecl DualProcessCommand(int parlength, int commandId, FakeDispatcher *disp, ...); private: static ITypeInfo* npTypeInfo; const static int DISPATCH_VTABLE = 7; FakeDispatcherEx *extended; NPP npInstance; NPObject *npObject; ITypeLib *typeLib; ITypeInfo *typeInfo; CAxHost *internalObj; bool HasValidTypeInfo(); int ref; DWORD dualType; #ifdef DEBUG char name[50]; char tag[100]; GUID interfaceid; #endif UINT FindFuncByVirtualId(int vtbId); };
007slmg-np-activex
ffactivex/FakeDispatcher.h
C++
mpl11
6,240
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <atlstr.h> #include "npactivex.h" #include "scriptable.h" #include "axhost.h" #include "ObjectManager.h" #include "FakeDispatcher.h" // {1DDBD54F-2F8A-4186-972B-2A84FE1135FE} static const GUID IID_IFakeDispatcher = { 0x1ddbd54f, 0x2f8a, 0x4186, { 0x97, 0x2b, 0x2a, 0x84, 0xfe, 0x11, 0x35, 0xfe } }; ITypeInfo* FakeDispatcher::npTypeInfo = (ITypeInfo*)-1; #define DispatchLog(level, message, ...) np_log(this->npInstance, level, "Disp 0x%08x " message, this, ##__VA_ARGS__) FakeDispatcher::FakeDispatcher(NPP npInstance, ITypeLib *typeLib, NPObject *object) : npInstance(npInstance), typeLib(typeLib), npObject(object), typeInfo(NULL), internalObj(NULL), extended(NULL) { ref = 1; typeLib->AddRef(); NPNFuncs.retainobject(object); ScriptBase *base = ObjectManager::GetInternalObject(npInstance, object); if (base) internalObj = dynamic_cast<CAxHost*>(base->host); #ifdef DEBUG name[0] = 0; tag[0] = 0; interfaceid = GUID_NULL; #endif NPVariantProxy npName, npTag; ATL::CStringA sname, stag; NPNFuncs.getproperty(npInstance, object, NPNFuncs.getstringidentifier("id"), &npName); if (npName.type != NPVariantType_String || npName.value.stringValue.UTF8Length == 0) NPNFuncs.getproperty(npInstance, object, NPNFuncs.getstringidentifier("name"), &npName); if (npName.type == NPVariantType_String) { sname = CStringA(npName.value.stringValue.UTF8Characters, npName.value.stringValue.UTF8Length); #ifdef DEBUG strncpy(name, npName.value.stringValue.UTF8Characters, npName.value.stringValue.UTF8Length); name[npName.value.stringValue.UTF8Length] = 0; #endif } if (NPNFuncs.hasmethod(npInstance, object, NPNFuncs.getstringidentifier("toString"))) { NPNFuncs.invoke(npInstance, object, NPNFuncs.getstringidentifier("toString"), &npTag, 0, &npTag); if (npTag.type == NPVariantType_String) { stag = CStringA(npTag.value.stringValue.UTF8Characters, npTag.value.stringValue.UTF8Length); #ifdef DEBUG strncpy(tag, npTag.value.stringValue.UTF8Characters, npTag.value.stringValue.UTF8Length); tag[npTag.value.stringValue.UTF8Length] = 0; #endif } } DispatchLog(1, "Type: %s, Name: %s", stag.GetString(), sname.GetString()); } /* [local] */ HRESULT STDMETHODCALLTYPE FakeDispatcher::Invoke( /* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS *pDispParams, /* [out] */ VARIANT *pVarResult, /* [out] */ EXCEPINFO *pExcepInfo, /* [out] */ UINT *puArgErr) { USES_CONVERSION; // Convert variants int nArgs = pDispParams->cArgs; NPVariantProxy *npvars = new NPVariantProxy[nArgs]; for (int i = 0; i < nArgs; ++i) { Variant2NPVar(&pDispParams->rgvarg[nArgs - 1 - i], &npvars[i], npInstance); } // Determine method to call. HRESULT hr = E_FAIL; BSTR pBstrName; NPVariantProxy result; NPIdentifier identifier = NULL; NPIdentifier itemIdentifier = NULL; if (HasValidTypeInfo() && SUCCEEDED(typeInfo->GetDocumentation(dispIdMember, &pBstrName, NULL, NULL, NULL))) { LPSTR str = OLE2A(pBstrName); SysFreeString(pBstrName); DispatchLog(2, "Invoke 0x%08x %d %s", dispIdMember, wFlags, str); if (dispIdMember == 0x401 && strcmp(str, "url") == 0) { str = "baseURI"; } else if (dispIdMember == 0x40A && strcmp(str, "parentWindow") == 0) { str = "defaultView"; } identifier = NPNFuncs.getstringidentifier(str); if (dispIdMember == 0 && (wFlags & DISPATCH_METHOD) && strcmp(str, "item") == 0) { // Item can be evaluated as the default property. if (NPVARIANT_IS_INT32(npvars[0])) itemIdentifier = NPNFuncs.getintidentifier(npvars[0].value.intValue); else if (NPVARIANT_IS_STRING(npvars[0])) itemIdentifier = NPNFuncs.getstringidentifier(npvars[0].value.stringValue.UTF8Characters); } else if (dispIdMember == 0x3E9 && (wFlags & DISPATCH_PROPERTYGET) && strcmp(str, "Script") == 0) { identifier = NPNFuncs.getstringidentifier("defaultView"); } } else if (typeInfo == npTypeInfo && dispIdMember != NULL && dispIdMember != -1) { identifier = (NPIdentifier) dispIdMember; } if (FAILED(hr) && itemIdentifier != NULL) { if (NPNFuncs.hasproperty(npInstance, npObject, itemIdentifier)) { if (NPNFuncs.getproperty(npInstance, npObject, itemIdentifier, &result)) { hr = S_OK; } } } if (FAILED(hr) && (wFlags & DISPATCH_METHOD)) { if (NPNFuncs.invoke(npInstance, npObject, identifier, npvars, nArgs, &result)) { hr = S_OK; } } if (FAILED(hr) && (wFlags & DISPATCH_PROPERTYGET)) { if (NPNFuncs.hasproperty(npInstance, npObject, identifier)) { if (NPNFuncs.getproperty(npInstance, npObject, identifier, &result)) { hr = S_OK; } } } if (FAILED(hr) && (wFlags & DISPATCH_PROPERTYPUT)) { if (nArgs == 1 && NPNFuncs.setproperty(npInstance, npObject, identifier, npvars)) hr = S_OK; } if (FAILED(hr) && dispIdMember == 0 && (wFlags & DISPATCH_METHOD)) { // Call default method. if (NPNFuncs.invokeDefault(npInstance, npObject, npvars, nArgs, &result)) { hr = S_OK; } } if (FAILED(hr) && dispIdMember == 0 && (wFlags & DISPATCH_PROPERTYGET) && pDispParams->cArgs == 0) { // Return toString() static NPIdentifier strIdentify = NPNFuncs.getstringidentifier("toString"); if (NPNFuncs.invoke(npInstance, npObject, strIdentify, NULL, 0, &result)) hr = S_OK; } if (SUCCEEDED(hr)) { NPVar2Variant(&result, pVarResult, npInstance); } else { DispatchLog(2, "Invoke failed 0x%08x %d", dispIdMember, wFlags); } delete [] npvars; return hr; } HRESULT STDMETHODCALLTYPE FakeDispatcher::QueryInterface( /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject) { HRESULT hr = E_FAIL; if (riid == IID_IDispatch || riid == IID_IUnknown) { *ppvObject = this; AddRef(); hr = S_OK; } else if (riid == IID_IDispatchEx) { if (extended == NULL) extended = new FakeDispatcherEx(this); *ppvObject = extended; AddRef(); hr = S_OK; } else if (riid == IID_IFakeDispatcher) { *ppvObject = this; AddRef(); hr = S_OK; } else if (!typeInfo) { hr = typeLib->GetTypeInfoOfGuid(riid, &typeInfo); if (SUCCEEDED(hr)) { TYPEATTR *attr; typeInfo->GetTypeAttr(&attr); dualType = attr->wTypeFlags; *ppvObject = static_cast<FakeDispatcher*>(this); AddRef(); typeInfo->ReleaseTypeAttr(attr); } } else { FakeDispatcher *another_obj = new FakeDispatcher(npInstance, typeLib, npObject); hr = another_obj->QueryInterface(riid, ppvObject); another_obj->Release(); } if (FAILED(hr) && internalObj) { IUnknown *unk; internalObj->GetControlUnknown(&unk); hr = unk->QueryInterface(riid, ppvObject); unk->Release(); /* // Try to find the internal object NPIdentifier object_id = NPNFuncs.getstringidentifier(object_property); NPVariant npVar; if (NPNFuncs.getproperty(npInstance, npObject, object_id, &npVar) && npVar.type == NPVariantType_Int32) { IUnknown *internalObject = (IUnknown*)NPVARIANT_TO_INT32(npVar); hr = internalObject->QueryInterface(riid, ppvObject); }*/ } #ifdef DEBUG if (hr == S_OK) { interfaceid = riid; } else { // Unsupported Interface! } #endif USES_CONVERSION; LPOLESTR clsid; StringFromCLSID(riid, &clsid); if (FAILED(hr)) { DispatchLog(0, "Unsupported Interface %s", OLE2A(clsid)); } else { DispatchLog(0, "QueryInterface %s", OLE2A(clsid)); } return hr; } FakeDispatcher::~FakeDispatcher(void) { if (HasValidTypeInfo()) { typeInfo->Release(); } if (extended) { delete extended; } DispatchLog(3, "Release"); NPNFuncs.releaseobject(npObject); typeLib->Release(); } // This function is used because the symbol of FakeDispatcher::ProcessCommand is not determined in asm file. extern "C" HRESULT __cdecl DualProcessCommand(int parlength, int commandId, int returnAddr, FakeDispatcher *disp, ...){ // returnAddr is a placeholder for the calling proc. va_list va; va_start(va, disp); // The parlength is on the stack, the modification will be reflect. HRESULT ret = disp->ProcessCommand(commandId, &parlength, va); va_end(va); return ret; } HRESULT FakeDispatcher::GetTypeInfo( /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo) { if (iTInfo == 0 && HasValidTypeInfo()) { *ppTInfo = typeInfo; typeInfo->AddRef(); return S_OK; } return E_INVALIDARG; } HRESULT FakeDispatcher::GetIDsOfNames( /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId){ if (HasValidTypeInfo()) { return typeInfo->GetIDsOfNames(rgszNames, cNames, rgDispId); } else { USES_CONVERSION; typeInfo = npTypeInfo; for (UINT i = 0; i < cNames; ++i) { DispatchLog(2, "GetIDsOfNames %s", OLE2A(rgszNames[i])); rgDispId[i] = (DISPID) NPNFuncs.getstringidentifier(OLE2A(rgszNames[i])); } return S_OK; } } HRESULT FakeDispatcher::ProcessCommand(int vfid, int *parlength, va_list &args) { // This exception is critical if we can't find the size of parameters. if (!HasValidTypeInfo()) { DispatchLog(0, "VT interface %d called without type info", vfid); __asm int 3; } UINT index = FindFuncByVirtualId(vfid); if (index == (UINT)-1) { DispatchLog(0, "Unknown VT interface id"); __asm int 3; } FUNCDESC *func; // We should count pointer of "this" first. *parlength = sizeof(LPVOID); if (FAILED(typeInfo->GetFuncDesc(index, &func))) __asm int 3; DISPPARAMS varlist; // We don't need to clear them. VARIANT *list = new VARIANT[func->cParams]; varlist.cArgs = func->cParams; varlist.cNamedArgs = 0; varlist.rgdispidNamedArgs = NULL; varlist.rgvarg = list; // Thanks that there won't be any out variants in HTML. for (int i = 0; i < func->cParams; ++i) { int listPos = func->cParams - 1 - i; ELEMDESC *desc = &func->lprgelemdescParam[listPos]; memset(&list[listPos], 0, sizeof(list[listPos])); RawTypeToVariant(desc->tdesc, args, &list[listPos]); size_t varsize = VariantSize(desc->tdesc.vt); size_t intvarsz = (varsize + sizeof(int) - 1) & (~(sizeof(int) - 1)); args += intvarsz; *parlength += intvarsz; } // We needn't clear it. Caller takes ownership. VARIANT result; HRESULT ret = Invoke(func->memid, IID_NULL, NULL, func->invkind, &varlist, &result, NULL, NULL); if (SUCCEEDED(ret)) ret = ConvertVariantToGivenType(typeInfo, func->elemdescFunc.tdesc, result, args); size_t varsize = VariantSize(func->elemdescFunc.tdesc.vt); // It should always be a pointer. It always should be counted. size_t intvarsz = varsize ? sizeof(LPVOID) : 0; *parlength += intvarsz; delete[] list; return ret; } UINT FakeDispatcher::FindFuncByVirtualId(int vtbId) { if (dualType & TYPEFLAG_FDUAL) return vtbId + DISPATCH_VTABLE; else return vtbId; } bool FakeDispatcher::HasValidTypeInfo() { return typeInfo && typeInfo != npTypeInfo; } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetDispID( __RPC__in BSTR bstrName, DWORD grfdex, __RPC__out DISPID *pid) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::InvokeEx( __in DISPID id, __in LCID lcid, __in WORD wFlags, __in DISPPARAMS *pdp, __out_opt VARIANT *pvarRes, __out_opt EXCEPINFO *pei, __in_opt IServiceProvider *pspCaller) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::DeleteMemberByName( __RPC__in BSTR bstrName, DWORD grfdex) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::DeleteMemberByDispID(DISPID id) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetMemberProperties( DISPID id, DWORD grfdexFetch, __RPC__out DWORD *pgrfdex) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetMemberName( DISPID id, __RPC__deref_out_opt BSTR *pbstrName) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetNextDispID( DWORD grfdex, DISPID id, __RPC__out DISPID *pid) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetNameSpaceParent( __RPC__deref_out_opt IUnknown **ppunk) { return LogNotImplemented(target->npInstance); }
007slmg-np-activex
ffactivex/FakeDispatcher.cpp
C++
mpl11
14,416
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // dllmain.cpp : Defines the entry point for the DLL application. #include "npactivex.h" #include "axhost.h" #include "atlthunk.h" #include "FakeDispatcher.h" CComModule _Module; NPNetscapeFuncs NPNFuncs; BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } // ============================== // ! Scriptability related code ! // ============================== // // here the plugin is asked by Mozilla to tell if it is scriptable // we should return a valid interface id and a pointer to // nsScriptablePeer interface which we should have implemented // and which should be defined in the corressponding *.xpt file // in the bin/components folder NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; if(instance == NULL) return NPERR_GENERIC_ERROR; CAxHost *host = (CAxHost *)instance->pdata; if(host == NULL) return NPERR_GENERIC_ERROR; switch (variable) { case NPPVpluginNameString: *((char **)value) = "ITSTActiveX"; break; case NPPVpluginDescriptionString: *((char **)value) = "IT Structures ActiveX for Firefox"; break; case NPPVpluginScriptableNPObject: *(NPObject **)value = host->GetScriptableObject(); break; default: rv = NPERR_GENERIC_ERROR; } return rv; } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } int32_t NPP_WriteReady (NPP instance, NPStream *stream) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; int32 rv = 0x0fffffff; return rv; } int32_t NPP_Write (NPP instance, NPStream *stream, int32_t offset, int32_t len, void *buffer) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; int32 rv = len; return rv; } NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname) { if(instance == NULL) return; } void NPP_Print (NPP instance, NPPrint* printInfo) { if(instance == NULL) return; } void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData) { if(instance == NULL) return; } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } int16 NPP_HandleEvent(NPP instance, void* event) { if(instance == NULL) return 0; int16 rv = 0; CAxHost *host = dynamic_cast<CAxHost*>((CHost *)instance->pdata); if (host) rv = host->HandleEvent(event); return rv; } NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) { if(pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; if(pFuncs->size < sizeof(NPPluginFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; pFuncs->newp = NPP_New; pFuncs->destroy = NPP_Destroy; pFuncs->setwindow = NPP_SetWindow; pFuncs->newstream = NPP_NewStream; pFuncs->destroystream = NPP_DestroyStream; pFuncs->asfile = NPP_StreamAsFile; pFuncs->writeready = NPP_WriteReady; pFuncs->write = NPP_Write; pFuncs->print = NPP_Print; pFuncs->event = NPP_HandleEvent; pFuncs->urlnotify = NPP_URLNotify; pFuncs->getvalue = NPP_GetValue; pFuncs->setvalue = NPP_SetValue; pFuncs->javaClass = NULL; return NPERR_NO_ERROR; } #define MIN(x, y) ((x) < (y)) ? (x) : (y) /* * Initialize the plugin. Called the first time the browser comes across a * MIME Type this plugin is registered to handle. */ NPError OSCALL NP_Initialize(NPNetscapeFuncs* pFuncs) { #ifdef DEBUG CString text; text.Format(_T("NPActiveX Pid %d"), GetCurrentProcessId()); MessageBox(NULL, text, _T(""), MB_OK); #endif CoInitialize(NULL); InstallAtlThunkEnumeration(); if (pHtmlLib == NULL) { OLECHAR path[MAX_PATH]; GetEnvironmentVariableW(OLESTR("SYSTEMROOT"), path, MAX_PATH - 30); StrCatW(path, L"\\system32\\mshtml.tlb"); HRESULT hr = LoadTypeLib(path, &pHtmlLib); } if(pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; #ifdef NDEF // The following statements prevented usage of newer Mozilla sources than installed browser at runtime if(HIBYTE(pFuncs->version) > NP_VERSION_MAJOR) return NPERR_INCOMPATIBLE_VERSION_ERROR; if(pFuncs->size < sizeof(NPNetscapeFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; #endif if (!AtlAxWinInit()) { return NPERR_GENERIC_ERROR; } _pAtlModule = &_Module; memset(&NPNFuncs, 0, sizeof(NPNetscapeFuncs)); memcpy(&NPNFuncs, pFuncs, MIN(pFuncs->size, sizeof(NPNetscapeFuncs))); return NPERR_NO_ERROR; } /* * Shutdown the plugin. Called when no more instanced of this plugin exist and * the browser wants to unload it. */ NPError OSCALL NP_Shutdown(void) { AtlAxWinTerm(); UninstallAtlThunkEnumeration(); return NPERR_NO_ERROR; }
007slmg-np-activex
ffactivex/dllmain.cpp
C++
mpl11
7,451
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once struct ITypeInfo; void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance); void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance); size_t VariantSize(VARTYPE vt); HRESULT ConvertVariantToGivenType(ITypeInfo *baseType, const TYPEDESC &vt, const VARIANT &var, LPVOID dest); void RawTypeToVariant(const TYPEDESC &desc, LPVOID source, VARIANT* var);
007slmg-np-activex
ffactivex/variants.h
C
mpl11
2,086
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "scriptable.h" #include "axhost.h" #include "ScriptFunc.h" #include "npactivex.h" NPClass Scriptable::npClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ Scriptable::_Allocate, /* deallocate */ Scriptable::_Deallocate, /* invalidate */ Scriptable::_Invalidate, /* hasMethod */ NULL, //Scriptable::_HasMethod, /* invoke */ NULL, //Scriptable::_Invoke, /* invokeDefault */ NULL, /* hasProperty */ Scriptable::_HasProperty, /* getProperty */ Scriptable::_GetProperty, /* setProperty */ Scriptable::_SetProperty, /* removeProperty */ NULL, /* enumerate */ Scriptable::_Enumerate, /* construct */ NULL }; bool Scriptable::find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind) { bool found = false; unsigned int i = 0; FUNCDESC *fDesc; for (i = 0; (i < attr->cFuncs) && !found; ++i) { HRESULT hr = info->GetFuncDesc(i, &fDesc); if (SUCCEEDED(hr) && fDesc && (fDesc->memid == member_id)) { if (invKind & fDesc->invkind) found = true; } info->ReleaseFuncDesc(fDesc); } #if 0 if (!found && (invKind & ~INVOKE_FUNC)) { VARDESC *vDesc; for (i = 0; (i < attr->cVars) && !found; ++i) { HRESULT hr = info->GetVarDesc(i, &vDesc); if ( SUCCEEDED(hr) && vDesc && (vDesc->memid == member_id)) { found = true; } info->ReleaseVarDesc(vDesc); } } if (!found) { // iterate inherited interfaces HREFTYPE refType = NULL; for (i = 0; (i < attr->cImplTypes) && !found; ++i) { ITypeInfoPtr baseInfo; TYPEATTR *baseAttr; if (FAILED(info->GetRefTypeOfImplType(0, &refType))) { continue; } if (FAILED(info->GetRefTypeInfo(refType, &baseInfo))) { continue; } baseInfo->AddRef(); if (FAILED(baseInfo->GetTypeAttr(&baseAttr))) { continue; } found = find_member(baseInfo, baseAttr, member_id, invKind); baseInfo->ReleaseTypeAttr(baseAttr); } } #endif return found; } bool Scriptable::IsProperty(DISPID member_id) { ITypeInfo *typeinfo; if (FAILED(disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &typeinfo))) { return false; } TYPEATTR *typeAttr; typeinfo->GetTypeAttr(&typeAttr); bool ret = find_member(typeinfo, typeAttr, member_id, DISPATCH_METHOD); typeinfo->ReleaseTypeAttr(typeAttr); typeinfo->Release(); return !ret; } DISPID Scriptable::ResolveName(NPIdentifier name, unsigned int invKind) { bool found = false; DISPID dID = -1; USES_CONVERSION; if (!name || !invKind) { return -1; } if (!disp) { return -1; } if (!NPNFuncs.identifierisstring(name)) { return -1; } NPUTF8 *npname = NPNFuncs.utf8fromidentifier(name); LPOLESTR oleName = A2W(npname); disp->GetIDsOfNames(IID_NULL, &oleName, 1, 0, &dID); return dID; #if 0 int funcInv; if (FindElementInvKind(disp, dID, &funcInv)) { if (funcInv & invKind) return dID; else return -1; } else { if ((dID != -1) && (invKind & INVOKE_PROPERTYGET)) { // Try to get property to check. // Use two parameters. It will definitely fail in property get/set, but it will return other orrer if it's not property. CComVariant var[2]; DISPPARAMS par = {var, NULL, 2, 0}; CComVariant result; HRESULT hr = disp->Invoke(dID, IID_NULL, 1, invKind, &par, &result, NULL, NULL); if (hr == DISP_E_MEMBERNOTFOUND || hr == DISP_E_TYPEMISMATCH) return -1; } } return dID; #endif if (dID != -1) { ITypeInfoPtr info; disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &info); if (!info) { return -1; } TYPEATTR *attr; if (FAILED(info->GetTypeAttr(&attr))) { return -1; } found = find_member(info, attr, dID, invKind); info->ReleaseTypeAttr(attr); } return found ? dID : -1; } bool Scriptable::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; np_log(instance, 2, "Invoke %s", NPNFuncs.utf8fromidentifier(name)); DISPID id = ResolveName(name, INVOKE_FUNC); bool ret = InvokeID(id, args, argCount, result); if (!ret) { np_log(instance, 0, "Invoke failed: %s", NPNFuncs.utf8fromidentifier(name)); } return ret; } bool Scriptable::InvokeID(DISPID id, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (-1 == id) { return false; } CComVariant *vArgs = NULL; if (argCount) { vArgs = new CComVariant[argCount]; if (!vArgs) { return false; } for (unsigned int i = 0; i < argCount; ++i) { // copy the arguments in reverse order NPVar2Variant(&args[i], &vArgs[argCount - i - 1], instance); } } DISPPARAMS params = {NULL, NULL, 0, 0}; params.cArgs = argCount; params.cNamedArgs = 0; params.rgdispidNamedArgs = NULL; params.rgvarg = vArgs; CComVariant vResult; HRESULT rc = disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &params, &vResult, NULL, NULL); if (vArgs) { delete []vArgs; } if (FAILED(rc)) { return false; } Variant2NPVar(&vResult, result, instance); return true; } bool Scriptable::HasMethod(NPIdentifier name) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_FUNC); return (id != -1) ? true : false; } bool Scriptable::HasProperty(NPIdentifier name) { static NPIdentifier classid = NPNFuncs.getstringidentifier("classid"); if (name == classid) { return true; } if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYGET | INVOKE_PROPERTYPUT); return (id != -1) ? true : false; } bool Scriptable::GetProperty(NPIdentifier name, NPVariant *result) { if (invalid) return false; static NPIdentifier classid = NPNFuncs.getstringidentifier("classid"); if (name == classid) { CAxHost *host = (CAxHost*)this->host; if (this->disp == NULL) { char* cstr = (char*)NPNFuncs.memalloc(1); cstr[0] = 0; STRINGZ_TO_NPVARIANT(cstr, *result); return true; } else { USES_CONVERSION; char* cstr = (char*)NPNFuncs.memalloc(50); strcpy(cstr, "CLSID:"); LPOLESTR clsidstr; StringFromCLSID(host->getClsID(), &clsidstr); // Remove braces. clsidstr[lstrlenW(clsidstr) - 1] = '\0'; strcat(cstr, OLE2A(clsidstr + 1)); CoTaskMemFree(clsidstr); STRINGZ_TO_NPVARIANT(cstr, *result); return true; } } DISPID id = ResolveName(name, INVOKE_PROPERTYGET); if (-1 == id) { np_log(instance, 0, "Cannot find property: %s", NPNFuncs.utf8fromidentifier(name)); return false; } DISPPARAMS params; params.cArgs = 0; params.cNamedArgs = 0; params.rgdispidNamedArgs = NULL; params.rgvarg = NULL; CComVariant vResult; if (IsProperty(id)) { HRESULT hr = disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &params, &vResult, NULL, NULL); if (SUCCEEDED(hr)) { Variant2NPVar(&vResult, result, instance); np_log(instance, 2, "GetProperty %s", NPNFuncs.utf8fromidentifier(name)); return true; } } np_log(instance, 2, "GetMethodObject %s", NPNFuncs.utf8fromidentifier(name)); OBJECT_TO_NPVARIANT(ScriptFunc::GetFunctionObject(instance, this, id), *result); return true; } bool Scriptable::SetProperty(NPIdentifier name, const NPVariant *value) { static NPIdentifier classid = NPNFuncs.getstringidentifier("classid"); if (name == classid) { np_log(instance, 1, "Set classid property: %s", value->value.stringValue); CAxHost* axhost = (CAxHost*)host; CLSID newCLSID = CAxHost::ParseCLSIDFromSetting(value->value.stringValue.UTF8Characters, value->value.stringValue.UTF8Length); if (newCLSID != GUID_NULL && (!axhost->hasValidClsID() || newCLSID != axhost->getClsID())) { axhost->Clear(); if (axhost->setClsID(newCLSID)) { axhost->CreateControl(false); IUnknown *unk; if (SUCCEEDED(axhost->GetControlUnknown(&unk))) { this->setControl(unk); unk->Release(); } axhost->ResetWindow(); } } return true; } if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYPUT); if (-1 == id) { return false; } CComVariant val; NPVar2Variant(value, &val, instance); DISPPARAMS params; // Special initialization needed when using propery put. DISPID dispidNamed = DISPID_PROPERTYPUT; params.cNamedArgs = 1; params.rgdispidNamedArgs = &dispidNamed; params.cArgs = 1; params.rgvarg = &val; CComVariant vResult; WORD wFlags = DISPATCH_PROPERTYPUT; if (val.vt == VT_DISPATCH) { wFlags |= DISPATCH_PROPERTYPUTREF; } const char* pname = NPNFuncs.utf8fromidentifier(name); if (FAILED(disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, wFlags, &params, &vResult, NULL, NULL))) { np_log(instance, 0, "SetProperty failed %s", pname); return false; } np_log(instance, 0, "SetProperty %s", pname); return true; } Scriptable* Scriptable::FromAxHost(NPP npp, CAxHost* host) { Scriptable *new_obj = (Scriptable*)NPNFuncs.createobject(npp, &npClass); IUnknown *unk; if (SUCCEEDED(host->GetControlUnknown(&unk))) { new_obj->setControl(unk); new_obj->host = host; unk->Release(); } return new_obj; } NPObject* Scriptable::_Allocate(NPP npp, NPClass *aClass) { return new Scriptable(npp); } void Scriptable::_Deallocate(NPObject *obj) { if (obj) { Scriptable *a = static_cast<Scriptable*>(obj); //np_log(a->instance, 3, "Dealocate obj"); delete a; } } bool Scriptable::Enumerate(NPIdentifier **value, uint32_t *count) { UINT cnt; if (!disp || FAILED(disp->GetTypeInfoCount(&cnt))) return false; *count = 0; for (UINT i = 0; i < cnt; ++i) { CComPtr<ITypeInfo> info; disp->GetTypeInfo(i, LOCALE_SYSTEM_DEFAULT, &info); TYPEATTR *attr; info->GetTypeAttr(&attr); *count += attr->cFuncs; info->ReleaseTypeAttr(attr); } uint32_t pos = 0; NPIdentifier *v = (NPIdentifier*) NPNFuncs.memalloc(sizeof(NPIdentifier) * *count); USES_CONVERSION; for (UINT i = 0; i < cnt; ++i) { CComPtr<ITypeInfo> info; disp->GetTypeInfo(i, LOCALE_SYSTEM_DEFAULT, &info); TYPEATTR *attr; info->GetTypeAttr(&attr); BSTR name; for (uint j = 0; j < attr->cFuncs; ++j) { FUNCDESC *desc; info->GetFuncDesc(j, &desc); if (SUCCEEDED(info->GetDocumentation(desc->memid, &name, NULL, NULL, NULL))) { LPCSTR str = OLE2A(name); v[pos++] = NPNFuncs.getstringidentifier(str); SysFreeString(name); } info->ReleaseFuncDesc(desc); } info->ReleaseTypeAttr(attr); } *count = pos; *value = v; return true; }
007slmg-np-activex
ffactivex/scriptable.cpp
C++
mpl11
12,450
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <map> #include <vector> #include <atlbase.h> #include <comdef.h> #include <npapi.h> #include <npfunctions.h> #include <npruntime.h> #include "variants.h" extern NPNetscapeFuncs NPNFuncs; extern NPClass GenericNPObjectClass; typedef bool (*DefaultInvoker)(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); struct ltnum { bool operator()(long n1, long n2) const { return n1 < n2; } }; struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); class GenericNPObject: public NPObject { private: GenericNPObject(const GenericNPObject &); bool invalid; DefaultInvoker defInvoker; void *defInvokerObject; std::vector<NPVariant> numeric_mapper; // the members of alpha mapper can be reassigned to anything the user wishes std::map<const char *, NPVariant, ltstr> alpha_mapper; // these cannot accept other types than they are initially defined with std::map<const char *, NPVariant, ltstr> immutables; public: friend bool toString(void *, const NPVariant *, uint32_t, NPVariant *); GenericNPObject(NPP instance); GenericNPObject(NPP instance, bool isMethodObj); ~GenericNPObject(); void Invalidate() {invalid = true;} void SetDefaultInvoker(DefaultInvoker di, void *context) { defInvoker = di; defInvokerObject = context; } static bool _HasMethod(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasMethod(name); } static bool _Invoke(NPObject *npobj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((GenericNPObject *)npobj)->Invoke(methodName, args, argCount, result); } static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (((GenericNPObject *)npobj)->defInvoker) { return (((GenericNPObject *)npobj)->InvokeDefault)(args, argCount, result); } else { return false; } } static bool _HasProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasProperty(name); } static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((GenericNPObject *)npobj)->GetProperty(name, result); } static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((GenericNPObject *)npobj)->SetProperty(name, value); } static bool _RemoveProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->RemoveProperty(name); } static bool _Enumerate(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount) { return ((GenericNPObject *)npobj)->Enumerate(identifiers, identifierCount); } bool HasMethod(NPIdentifier name); bool Invoke(NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result); bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result); bool HasProperty(NPIdentifier name); bool GetProperty(NPIdentifier name, NPVariant *result); bool SetProperty(NPIdentifier name, const NPVariant *value); bool RemoveProperty(NPIdentifier name); bool Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount); };
007slmg-np-activex
ffactivex/GenericNPObject.h
C++
mpl11
5,100
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "atlthunk.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <stdio.h> #include "ApiHook\Hook.h" typedef struct tagEXCEPTION_REGISTER { tagEXCEPTION_REGISTER *prev; _except_handler_type handler; }EXCEPTION_REGISTER, *LPEXCEPTION_REGISTER; /* Supported patterns: C7 44 24 04 XX XX XX XX mov [esp+4], imm32 E9 YY YY YY YY jmp imm32 B9 XX XX XX XX mov ecx, imm32 E9 YY YY YY YY jmp imm32 BA XX XX XX XX mov edx, imm32 B9 YY YY YY YY mov ecx, imm32 FF E1 jmp ecx B9 XX XX XX XX mov ecx, imm32 B8 YY YY YY YY mov eax, imm32 FF E0 jmp eax 59 pop ecx 58 pop eax 51 push ecx FF 60 04 jmp [eax+4] */ /* Pattern 1: C7 44 24 04 XX XX XX XX mov [esp+4], imm32 E9 YY YY YY YY jmp imm32 */ BYTE pattern1[] = {0xC7, 0x44, 0x24, 0x04, 0, 0, 0, 0, 0xE9, 0, 0, 0, 0}; void _process_pattern1(struct _CONTEXT *ContextRecord) { LPDWORD esp = (LPDWORD)(ContextRecord->Esp); DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 4); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 9); esp[1] = imm1; ContextRecord->Eip += imm2 + 13; } /* Pattern 2: B9 XX XX XX XX mov ecx, imm32 E9 YY YY YY YY jmp imm32 */ BYTE pattern2[] = {0xB9, 0, 0, 0, 0, 0xE9, 0, 0, 0, 0}; void _process_pattern2(struct _CONTEXT *ContextRecord) { DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6); ContextRecord->Ecx = imm1; ContextRecord->Eip += imm2 + 10; } /* Pattern 3: BA XX XX XX XX mov edx, imm32 B9 YY YY YY YY mov ecx, imm32 FF E1 jmp ecx */ BYTE pattern3[] = {0xBA, 0, 0, 0, 0, 0xB9, 0, 0, 0, 0, 0xFF, 0xE1}; void _process_pattern3(struct _CONTEXT *ContextRecord) { DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6); ContextRecord->Edx = imm1; ContextRecord->Ecx = imm2; ContextRecord->Eip += imm2; } /* B9 XX XX XX XX mov ecx, imm32 B8 YY YY YY YY mov eax, imm32 FF E0 jmp eax */ BYTE pattern4[] = {0xB9, 0, 0, 0, 0, 0xB8, 0, 0, 0, 0, 0xFF, 0xE0}; void _process_pattern4(struct _CONTEXT *ContextRecord) { DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6); ContextRecord->Ecx = imm1; ContextRecord->Eax = imm2; ContextRecord->Eip += imm2; } /* 59 pop ecx 58 pop eax 51 push ecx FF 60 04 jmp [eax+4] */ BYTE pattern5[] = {0x59, 0x58, 0x51, 0xFF, 0x60, 0x04}; void _process_pattern5(struct _CONTEXT *ContextRecord) { LPDWORD stack = (LPDWORD)(ContextRecord->Esp); ContextRecord->Ecx = stack[0]; ContextRecord->Eax = stack[1]; stack[1] = stack[0]; ContextRecord->Esp += 4; ContextRecord->Eip = *(LPDWORD)(ContextRecord->Eax + 4); } ATL_THUNK_PATTERN patterns[] = { {pattern1, sizeof(pattern1), _process_pattern1}, {pattern2, sizeof(pattern2), _process_pattern2}, {pattern3, sizeof(pattern3), _process_pattern3}, {pattern4, sizeof(pattern4), _process_pattern4}, {pattern5, sizeof(pattern5), _process_pattern5} }; ATL_THUNK_PATTERN *match_patterns(LPVOID eip) { LPBYTE codes = (LPBYTE)eip; for (int i = 0; i < sizeof(patterns) / sizeof(patterns[0]); ++i) { BOOL match = TRUE; for (int j = 0; j < patterns[i].pattern_size && match; ++j) { if (patterns[i].pattern[j] != 0 && patterns[i].pattern[j] != codes[j]) match = FALSE; } if (match) { return &patterns[i]; } } return NULL; } EXCEPTION_DISPOSITION __cdecl _except_handler_atl_thunk( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) { if ((ExceptionRecord->ExceptionFlags) || ExceptionRecord->ExceptionCode != STATUS_ACCESS_VIOLATION || ExceptionRecord->ExceptionAddress != (LPVOID)ContextRecord->Eip) { // Not expected Access violation exception return ExceptionContinueSearch; } // Try to match patterns ATL_THUNK_PATTERN *pattern = match_patterns((LPVOID)ContextRecord->Eip); if (pattern) { //DWORD old; // We can't always protect the ATL by except_handler, so we mark it executable. //BOOL ret = VirtualProtect((LPVOID)ContextRecord->Eip, pattern->pattern_size, PAGE_EXECUTE_READWRITE, &old); pattern->enumerator(ContextRecord); return ExceptionContinueExecution; } else { return ExceptionContinueSearch; } } #ifndef ATL_THUNK_APIHOOK _except_handler_type original_handler4; #else HOOKINFO hook_handler; #endif #if 0 EXCEPTION_DISPOSITION __cdecl my_except_handler4( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) { //assert(original_handler); EXCEPTION_DISPOSITION step1 = _except_handler_atl_thunk(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); if (step1 == ExceptionContinueExecution) return step1; #ifndef ATL_THUNK_APIHOOK _except_handler_type original_handler = original_handler4; #else _except_handler_type original_handler = (_except_handler_type)hook_handler4.Stub; #endif return original_handler(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); } EXCEPTION_DISPOSITION __cdecl my_except_handler3( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) { //assert(original_handler); EXCEPTION_DISPOSITION step1 = _except_handler_atl_thunk(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); if (step1 == ExceptionContinueExecution) return step1; #ifndef ATL_THUNK_APIHOOK // We won't wrap handler3, this shouldn't be used.. _except_handler_type original_handler = original_handler3; #else _except_handler_type original_handler = (_except_handler_type)hook_handler4.Stub; #endif return original_handler(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); } #endif BOOL CheckDEPEnabled() { // In case of running in a XP SP2. HMODULE hInst = LoadLibrary(TEXT("Kernel32.dll")); typedef BOOL (WINAPI *SetProcessDEPPolicyType)( __in DWORD dwFlags ); typedef BOOL (WINAPI *GetProcessDEPPolicyType)( __in HANDLE hProcess, __out LPDWORD lpFlags, __out PBOOL lpPermanent ); SetProcessDEPPolicyType setProc = (SetProcessDEPPolicyType)GetProcAddress(hInst, "SetProcessDEPPolicy"); GetProcessDEPPolicyType getProc = (GetProcessDEPPolicyType)GetProcAddress(hInst, "GetProcessDEPPolicy"); if (setProc) { // This is likely to fail, but we set it first. setProc(PROCESS_DEP_ENABLE); } BOOL enabled = FALSE; DWORD lpFlags; BOOL lpPermanent; if (getProc && getProc(GetCurrentProcess(), &lpFlags, &lpPermanent)) { enabled = (lpFlags == (PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION | PROCESS_DEP_ENABLE)); } return enabled; } extern "C" void _KiUserExceptionDispatcher_hook(); extern "C" DWORD _KiUserExceptionDispatcher_origin; extern "C" DWORD _KiUserExceptionDispatcher_ATL_p; typedef void (__stdcall *ZwContinueType)(struct _CONTEXT *, int); ZwContinueType ZwContinue; int __cdecl _KiUserExceptionDispatcher_ATL( struct _EXCEPTION_RECORD *ExceptionRecord, struct _CONTEXT *ContextRecord) { if (_except_handler_atl_thunk(ExceptionRecord, NULL, ContextRecord, NULL) == ExceptionContinueExecution) { ZwContinue(ContextRecord, 0); } return 0; } bool atlThunkInstalled = false; void InstallAtlThunkEnumeration() { if (atlThunkInstalled) return; if (CheckDEPEnabled()) { #ifndef ATL_THUNK_APIHOOK // Chrome is protected by DEP. EXCEPTION_REGISTER *reg; __asm { mov eax, fs:[0] mov reg, eax } while ((DWORD)reg->prev != 0xFFFFFFFF) reg = reg->prev; // replace the old handler original_handler = reg->handler; reg->handler = _except_handler; #else _KiUserExceptionDispatcher_ATL_p = (DWORD)_KiUserExceptionDispatcher_ATL; ZwContinue = (ZwContinueType) GetProcAddress(GetModuleHandle(TEXT("ntdll")), "ZwContinue"); HEInitHook(&hook_handler, GetProcAddress(GetModuleHandle(TEXT("ntdll")), "KiUserExceptionDispatcher") , _KiUserExceptionDispatcher_hook); HEStartHook(&hook_handler); _KiUserExceptionDispatcher_origin = (DWORD)hook_handler.Stub; atlThunkInstalled = true; #endif } } void UninstallAtlThunkEnumeration() { #ifdef ATL_THUNK_APIHOOK if (!atlThunkInstalled) return; HEStopHook(&hook_handler); atlThunkInstalled = false; #endif }
007slmg-np-activex
ffactivex/AtlThunk.cpp
C++
mpl11
10,401
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "HTMLDocumentContainer.h" #include "npactivex.h" #include <MsHTML.h> const GUID HTMLDocumentContainer::IID_TopLevelBrowser = {0x4C96BE40, 0x915C, 0x11CF, {0x99, 0xD3, 0x00, 0xAA, 0x00, 0x4A, 0xE8, 0x37}}; HTMLDocumentContainer::HTMLDocumentContainer() : dispatcher(NULL) { } void HTMLDocumentContainer::Init(NPP instance, ITypeLib *htmlLib) { NPObjectProxy npWindow; NPNFuncs.getvalue(instance, NPNVWindowNPObject, &npWindow); NPVariantProxy documentVariant; if (NPNFuncs.getproperty(instance, npWindow, NPNFuncs.getstringidentifier("document"), &documentVariant) && NPVARIANT_IS_OBJECT(documentVariant)) { NPObject *npDocument = NPVARIANT_TO_OBJECT(documentVariant); dispatcher = new FakeDispatcher(instance, htmlLib, npDocument); } npp = instance; } HRESULT HTMLDocumentContainer::get_LocationURL(BSTR *str) { NPObjectProxy npWindow; NPNFuncs.getvalue(npp, NPNVWindowNPObject, &npWindow); NPVariantProxy LocationVariant; if (!NPNFuncs.getproperty(npp, npWindow, NPNFuncs.getstringidentifier("location"), &LocationVariant) || !NPVARIANT_IS_OBJECT(LocationVariant)) { return E_FAIL; } NPObject *npLocation = NPVARIANT_TO_OBJECT(LocationVariant); NPVariantProxy npStr; if (!NPNFuncs.getproperty(npp, npLocation, NPNFuncs.getstringidentifier("href"), &npStr)) return E_FAIL; CComBSTR bstr(npStr.value.stringValue.UTF8Length, npStr.value.stringValue.UTF8Characters); *str = bstr.Detach(); return S_OK; } HRESULT STDMETHODCALLTYPE HTMLDocumentContainer::get_Document( __RPC__deref_out_opt IDispatch **ppDisp) { if (dispatcher) return dispatcher->QueryInterface(DIID_DispHTMLDocument, (LPVOID*)ppDisp); return E_FAIL; } HTMLDocumentContainer::~HTMLDocumentContainer(void) { }
007slmg-np-activex
ffactivex/HTMLDocumentContainer.cpp
C++
mpl11
3,293
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #include <atlbase.h> #include <atlstr.h> // TODO: reference additional headers your program requires here
007slmg-np-activex
ffactivex/stdafx.h
C
mpl11
2,250