Writing a vim function to insert a block of static text - function

I'd like to be able to do something like this in vim (you can assume v7+ if it helps).
Type in a command like this (or something close)
:inshtml
and have vim dump the following into the current file at the current cursor location
<!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>
<title></title>
</head>
<body>
</body>
</html>
Can I write a vim function do this is? Is there a better way?

Late to the party, just for future reference, but another way of doing it is to create a command, e.g.
:command Inshtml :normal i your text here^V<ESC>
The you can call it as
:Inshtml
Explanation: the command runs in command mode, and you switch to normal mode with :normal, then to insert mode with 'i', what follows the 'i' is your text and you finish with escape, which is entered as character by entering ^V
It is also possible to add arguments, e.g.
:command -nargs=1 Inshtml :normal i You entered <args>^V<ESC>
where <args> (entered literally as is) will be replaced with the actual arguments, and you call it with
:Inshtml blah

I do that by keeping under my vim folder a set of files which then I insert using the r command (which inserts the contents of a file, at the current location if no line number is passed) from some function:
function! Class()
" ~/vim/cpp/new-class.txt is the path to the template file
r~/vim/cpp/new-class.txt
endfunction
This is very practical - in my opinion - when you want to insert multi-line text. Then you can, for example, map a keyboard shortcut to call your function:
nmap ^N :call Class()<CR>

i have created a new file generate_html.vim in ~/.vim/plugins/
with the following code
"
" <This plugin generates html tags to new html files>
"
autocmd BufNewFile *.html call Generate_html()
function! Generate_html()
call append(0, "<!DOCTYPE HTML>")
call append(1, "<html><head>")
call append(2, " <title></title>")
call append(3, ' <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />')
call append(4, ' <style type="text/css">')
call append(5, ' </style>')
call append(6, '</head>')
call append(7, '<body>')
call append(8, '</body>')
call append(9, '</html>')
endfunction
this way, everytime I open a new .html file in vim, it prints that text to the new file

Can you define an abbreviation. e.g.
:ab insh 'your html here'
as nothing in the above appears to be parameterised ?
In fact, looking at my VIM configs, I detect a new .html file being loaded thus:
autocmd BufNewFile *.html call GenerateHeader()
and define a function GenerateHeader() to insert my required template (I do the same for Java/Perl etc.).
It's worth getting the Vim Cookbook for this sort of stuff. It's a sound investment.

snippetsEmu
I like to use the snippetsEmu vim plugin to insert code snippets like your.
The advantage of snippetsEmu is that you can specify place holders and jump directly to them in order to insert a value. In your case you could for example add a place holder between the title tags so you can easily add a title to the document when inserting this snippet.
snippetsEmu comes with various snippets (also for HTML) and new snippets can be esaily added.
EDIT
snipMate
Today I revisited my VIM confiugration + installed plugins and found the snipMate plugin, which is IMHO even better than snippetsEmu. snipMate updates just like TextMate all placeholders on the fly.

This should be possible. I use auto-replacement. In my .vimrc I have this line:
iab _perls #!/usr/bin/perl<CR><BS><CR>use strict;<CR>use warnings;<CR>
And whenever I start a Perl script, I just type _perls and hit Enter.

You can use Python (or any other program) if like me you haven't quite grasped vimScript
This guy talks about the vim expression register. Essentially you put something like this in your .vimrc file
:imap <C-j> <C-r>=system('/home/BennyHill/htmlScript.py')<CR>
So that every time in insert mode you press Ctrlj it calls the script htmlScript.py which has something like this in it (NOTE I haven't actually tested this)
#!/usr/bin/env python
import sys
snippet="""<!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>
<title></title>
</head>
<body>
</body>
</html>"""
sys.stdout.write(snippet)
Then just remember to make the file executable (chmod 0755 /home/BennyHill/htmlScript.py). It might be overkill, but I am far more comfortable with Python than I am with vim's syntax.

You can once copy this text to some ( for example 'a' ) register. And paste it every time you need unless you overwrite register 'a'.
To copy to register a in visual mode: "ay
To paste from register a in normal mode: "ap
To paste from register a in insert mode: a
Or if you have this template already copied you can use
let #a = #*
To put this template to register a.

There are many template expander plugins for vim.
NB: I'm maintaining the fork of muTemplate. Just dump your code into
{rtp}/template/html.template or into $VIMTEMPLATES/html.template. And that's all. If you don't want the snippet to be implicitly loaded when opening a new HTML file, then name the template-file html/whatever.template (instead of html.template), and load it with :MuTemplate html/whatever of with whatever^r<tab> in INSERT mode (in an HTML buffer).
All the path issues, portability issues, etc are already taken care of. And unlike snippetEmu that supports (and somehow expects) several (hard to maintain, IMO) snippets in a same snippets definition file, Mu-template requires one template-file per snippet.

Put your text in a file (e.g.,html).
Then put the following in your .vimrc.
command Inshtml r html
I use Inshtml instead of inshtml because vim doesn't support user defined command starting with small letter.
Then if can type Inshtml in command mode (i.e., :Inshtml).

Related

Is there a way to render an HTML page from Ruby?

I am developing an application that takes in the address of a web page and generates an HTML file with the source of that page. I have successfully generated the file. I can't figure out how to launch that file in a new tab. Here
This is running in Repl.it, a web-based code editor. Here's what I have:
def run
require 'open-uri'
puts "enter a URL and view the source"
puts "don't include the https:// at the beginning"
url = gets.chomp
fh = open("https://"+url)
html = fh.read
puts html
out_file = File.new("out.html", "w")
out_file.puts(html)
out_file.close
run
end
Then I'm running that code.
As I understand you just want to save html of site and open new file in your browser.
You can do it this way (I use Firefox).
require 'net/http'
require 'uri'
uri = URI.parse('https://bla-bla-bla.netlify.com/')
response = Net::HTTP.get_response(uri)
file_name = 'out.html'
File.write(file_name, response.body)
system("firefox #{file_name}")
Note: Keep in mind that site owners often block parsers, so you may have to use torify.
Now check the file
$ cat out.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bla-bla-bla</title>
</head>
<body>
<p>Bla-bla</p>
</body>
</html>
Everything worked out.
Hope it helps you.
If all you need is to open this file locally in your computer, I would perform a system call.
For example on my macOS the following would open the HTML page on my default browser:
system("open #{out_file.path}")
If you want to supply the rendered HTML to other users in your network then you will need a HTTP server, I suggest Sinatra to start with.

Delete lines (or tag) from HTML-Files using batch (.bat) script

Lets say I have a few HTML-Files starting with similar lines like this:
<HTML>
<HEAD>
<TITLE>Some HTML Page</TITLE>
<H1>something</H1>
<A>something else</A>
<A>something else fsomething else></A>
<A>End of something</A>
<H2>Beginning of something else
text text text....</H2>
</HEAD>
What I need is to delete some of the code from all those files using the Windows Shell (cmd).
I would prefer a solution which deletes the tag I don't need in this case the <H2> Tag which would be unique in all files.
But because as mentioned the files beginnings are similar a (probably easier) solution which allows me to remove a range of lines would also be o.k.
In this case lines 9 to 11.
What I tried so far for one file and the remove lines method:
#Echo OFF
Set /A "BL=9"
Set /A "EL=11"
Set /A "Z=%EL%-%BL%"
(Type "inputFile.html" | MORE +%BL%)>"inputFile.html"
I would probably need the Opposite function call of MORE so i could first write everything before line 9 into the file and in a second step append everything after line 11 with the MORE command and >>.
I tried to extend this answer: https://stackoverflow.com/a/12737334/4543887
to my needs, but well my Command line skills are pretty basic.
I know it would be easy using for example sed, but Im restricted to cmd.
If you don't care about some of the tag indents being changed, you could use DOM methods in JScript. It's generally better to objectify and parse structured markup data such as HTML, XML, JSON, etc, than to hack and scrape as flat text anyway. Save this with a .bat extension and salt to taste.
#if (#CodeSection == #Batch) #then
#echo off & setlocal
set "in=test.html"
rem // run JScript hybrid code, passing the HTML content via stdin
<"%in%" cscript /nologo /e:JScript "%~f0"
rem // Exit script. You're done. w00p w00p!
goto :EOF
#end // end Batch / begin JScript hybrid code
var DOM = WSH.CreateObject('htmlfile'),
stdin = WSH.CreateObject('Scripting.FileSystemObject').GetStandardStream(0).ReadAll(),
trash = {};
// force loading IE11 engine then clear
DOM.write('<meta http-equiv="x-ua-compatible" content="IE=11" />');
DOM.close();
// load HTML into the IE11 engine and manipulate
DOM.write(stdin);
trash = DOM.getElementsByTagName('h2')[0];
trash.parentNode.removeChild(trash);
// output modified HTML
WSH.Echo(DOM.documentElement.outerHTML);
DOM.close();
The htmlfile COM object isn't very well documented on Microsoft's website. But you can see all its properties and methods by doing
powershell "new-object -COM htmlfile | gm | more"

Selenium sendKeys with Chrome- Hebrew

I try to use:
action.sendKeys("some phrase with a dot, for example: www.google.co.il ");
but when i run the program what the action writes is:
www*google*co*il
the * represent hebrew character.
I can disable this only by disabling the hebrew language in my computer.
I tried to bypass the problem by using JS: set.attribute but it makes a lot of problems and i need something better.
Is there a function similar to sendkeys or a way to fix it?
You can try JavascriptExecuter using below code:
WebElement text= driver.findElement(By.name("q"));
JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
jsExecutor.executeScript("arguments[0].value='test input';", text);
Webelement is the textbox where your need to write the value.
Or you can try some copy paste action after clicking into text box.
actions.click();
Refer to this URL for help:
http://www.helloselenium.com/2015/03/how-to-set-string-to-clipboard-data.html
I found out a way to change language during the tests while I solved another problem related to Upload a picture. there is this freeware called AuTOIT that you can use to help you with dialogs on Windows. I wrote a script to push the alt and click shift and my language is changed.
To change the language, I use the line:
Runtime.getRuntime().exec("path_of_script_here/name_of_script_here.exe");
The script was made the following way:
Open a text file.
Inside the file write:
Send ("{ALTDOWN}") ;Hold down Alt
Sleep(100) ;Wait 100 milliseconds
Send("{LSHIFT}{ALTUP}") ;Press Left-Shift and release Alt
Save as .au3 file.
Download and install AUTOIT.
Compile the script and then exe file will be created.
Run the test.
Hope this will help everyone else who encounters this problem. If something is not clear, ask me and I will gladly help.

How can I call a Perl script inside HTML page?

I have a single HTML file, how I use a Perl script(date/hour) in the HTML code?
My goal: show a date/hour in HTML
Obs.: alone both script are ok.
Example:
HTML File:
<html>
<body>
code or foo.pl script
</body>
</html>
Perl script(foo.pl):
#!/usr/local/bin/perl
use CGI qw/:push -nph/;
$| = 1;
print multipart_init(-boundary=>'----here we go!');
for (0 .. 4) {
print multipart_start(-type=>'text/plain'),
"The current time is ",scalar(localtime),"\n";
if ($_ < 4) {
print multipart_end;
} else {
print multipart_final;
}
sleep 1;
}
Perl is a server-side language, so it must be run on the server. The HTML code is displayed in the browser, and it is generated by the server. So you would have to run the perl script on the server to generate the date / hour, and embed that into the HTML code that you serve to the browser.
Here is a tutorial on how to do this.
It sounds like you want Ajax. Your HTML page uses JavaScript to call your Perl program. Your JavaScript gets the response and replaces the part of the page where you want the data to go. Alternatively, you can just skip the Perl bit altogether and just do it all in JavaScript.
You can either generate the entire HTML page via a CGI script (as per Chetan's answer) - or as an alternative you can use one of the templating modules (EmbPerl, Mason, HTML::Template, or many others).
The templating solution is better for real software development, where separation of HTML and the Perl logic is more important. E.g. for EmbPerl, your code would look like:
<html>
<body>
[- my $date_hour= my_sub_printing_date_and_hour(); # Logic to generate -]
[+ $date_hour # print into HTML - could be combined with last statement +]
</body>
</html>

make my file readable as either Perl or HTML

In the spirit of the "Perl Preamble" where a script works properly whether executed by a shell script interpreter or the Perl interpreter...
I have a Perl script which contains an embedded HTML document (as a "heredoc"), i.e.:
#!/usr/bin/perl
... some Perl code ...
my $html = <<'END' ;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
... more HTML ...
</HTML>
END
... Perl code that processes $html ...
I would like to be able to work on the HTML that's inside the Perl script and check it out using a web browser, and only run the script when the HTML is the way I want. To accomplish this, I need the file to be openable both as an HTML file and as a Perl script.
I have tried various tricks with Perl comments and HTML comments but can't get it quite perfect. The file as a whole doesn't have to be "strictly legal" HTML (although the embedded document should be)... just displayable in a browser with no (or minimal) Perl garbage visible.
EDIT: Solved! See my own answer
Read it and weep Mr. #Axeman... I now present to you the empty set:
</dev/fd/0 eval 'exec perl -x -S $0 ${1+"$#"}' #> <!--
#!perl
... some Perl code ...
my $html = << '<!-- END' ; # -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
... more HTML ...
</HTML>
<!-- END
... Perl code that processes $html ...
# -->
This sounds like a path to pain. Consider storing the HTML in a separate file and reading it in within the script.
Maybe this is a job for Markup::Perl:
# don't write this...
print "Content-type: text/html;\n\n";
print "<html>\n<body>\n";
print "<p>\nYour \"lucky number\" is\n";
print "<i>", int rand 10, "</i>\n</p>\n";
print "</body>\n</html>\n";
# write this instead...
use Markup::Perl;
<html><body><p>
Your "lucky number" is
<i><perl> print int rand 10 </perl></i>
</p></body></html>
You could also drop the use Markup::Perl line and run your script like
perl -MMarkup::Perl my_page_with_embedded_perl.html
Then the page should render pretty well.
Sounds to me like you want a templating solution, such as Template::Toolkit or HTML::Template. Embedding HTML in your code or embedding code in your HTML is a recipe for pain.
Have you considered putting Perl inside of HTML?
Like ASP4 does?
It's a lot easier that way - trust me ;-)