Just getting started with Vim and am writing a basic HTML file. In SublimeText you could just right click and open in browser, but i'm having trouble finding how to do the same with Vim. I have Ubuntu and I want to preview the code in Chrome.
Thanks!
You can use :! to execute external commands within vim (see :help :!). The % sign in an :ex command expands to the current file name (see :help :_%). That being said, you can use the following to first save the file and then open it in the browser of your choice
:w|!google-chrome %
If you'd rather use firefox or chromium, use firefox or chromium, respectively, in place of google-chrome. If you're on mac or linux you could also use the open or xdg-open commands, respectively, to open the file in its default application. Don't want to type that out every time? Make your own command or mapping in your .vimrc.
command! ViewInBrowser :w|!google-chrome %
nnoremap <leader>b :ViewInBrowser<cr>
Related
I have started using Vim since last month and I am halfway through Vimscript.Ijust want to know how to run my html file and open it in my browser (Edge).
Update: whenever i am writing this-
nnoremap e :exe ':silent !chromium-browser %'
it is showing that chromium-browser is not an internal or external command
I'm just trying out Atom for the first time and I find it bothersome that Atom keeps opening a new window for each file I click on - I'd prefer that it defaulted to opening each file in the same window.
I'm hoping for something along the lines of "open_files_in_new_window" : false, in Sublime. Unfortunately, all the google results I'm seeing just lament that this toggle is not immediately obvious.
In your terminal you can type atom -a <filename||folder> and the file(s) will open within the same atom window.
Go to Settings > Packages, look for the tabs package. In the settings for this package, choose "use preview Tabs".
Per the atom -h command, one should open files with -n=false or --new-window=false argument passed so that they are opened in an existing window, e.g.
atom -n=false ~/Desktop/test.py
One could make atom -n=false an alias of atom in the ~/.bashrc or ~/.zshrc file, or one could edit the corresponding file in /home/<your username>/.local/share/applications so that the command it invokes is, for instance, /usr/lib/atom/atom -n=false %F.
Just in the editor window, drag the open tab by mouse onto the window you need.
I want a solution that does what's described in the vim wiki here, but that works on Chrome.
That is, I'm trying to avoid this:
Edit your HTML/CSS file.
Hit save in Vim.
CMD/CNTRL/ALT + TAB over to Firefox.
Press Ctrl-R in Firefox to refresh.
CMD/CNTRL/ALT + TAB back to Vim.
Do it again and again, wincing a little bit each time.
The vim wiki solution is for firefox, and other scripts and solutions I've found on the web are Mac only. But I'm on windows, and will often have vim open on the left half of the screen (editing html) and chrome open on the right half of the screen (displaying the file I'm editing).
A really "dumb" solution would work fine for me. That is, there wouldn't even need to be communication of the filename between vim and the browser. If I could just turn on a mode in vim, call it "auto-refresh", and now anytime I do a :w the currently active tab in chrome refreshes itself, without taking focus off the vim window. That would be perfect. Is it possible?
I don't know how to reload a give chrome page from shell, however, I agree with Chiel92 that if you need to see your changes when file changes, you can do that from browser.
See LiveReload, works with Windows & Mac (not for me then) and supports Safari & Chrome.
LiveReload will check your main page as well all css and javscript that it depends from, if any of those changes, it will reload it.
They seems to have launched a second version, however official site of version 2 it's offline and doesn't seem version 2 it's on github either. (Version 1 it's it's on github)
a solution that might work for you is in your html coding include the line in the head tag
<meta http-equiv="refresh" content="30" />
this will reload the page every 30 seconds directly taking from
w3schools.com
now when you want to deploy it just remove that line
If you are working on mac, then a bit of apple script does the job.
putting this function in your vim configuration will let you automate the process of switching between windows and refreshing you described.
function! ReloadBrowser()
silent exe "!osascript -e 'tell app \"Firefox\" to activate\<cr>
\tell app \"System events\"\<cr> keystroke \"r\" using command down\<cr>
\end tell'"
silent exe "!osascript -e 'tell app \"Iterm2\" to activate'"
endfunction
Calling that function will change system focus to Firefox, hit CMD-R to refresh the page, then change focus back to Iterm2.
Change 'Firefox' and 'Iterm2' to fit your workflow.
You can type the function into the vim command prompt like :call ReloadBrowser() or trigger the call with a mapping like this:
nnoremap <leader>rl call ReloadBrowser()<cr>
To trigger the call any time you write the file you could use an autocommand.
augroup AutoReload
au!
autocmd BufWritePost *.filetype call ReloadBrowser()
augroup END
That could get a bit annoying though so if you really want that behavior I think it would be best to make it toggle-able like this:
let s:auto_reload = v:false
function! ToggleAutoReload()
if s:auto_reload
augroup AutoReload
au!
autocmd BufWritePost *.filetype call ReloadBrowser()
augroup END
else
augroup AutoReload
au!
augroup END
endif
let s:auto_reload = !s:auto_reload
endfunction
with that in place you can either manually trigger the reload with <leader>rl or use :call ToggleAutoReload() to enable automatic reloading when you save the file, and a second :call ToggleAutoReload() will disable it when you're done.
I've tried LiveReload in the past but it wasn't a very dependable solution: it was very buggy and unstable and the installation process was too involved for too little effect.
Since then, (more than a year) I've been using a small Chrome extension that automatically reloads the webpage every x seconds. It's not "smart" at all but it works well both for local files and hosted files. I've used it countless times without any side effects whatsoever.
That Solution on the Vim Wiki is possible because of MozREPL which allows an external process to interact with Firefox. From there it's quite trivial to write an autocmd that triggers a refresh on :w or on CursorHold. But AFAIK there's no such tool for Chrome/Chromium and they don't offer an external API. LiveReload is a brilliant but failed hack and I believe that you'll have to settle with the dumb solution if you must work with Chrome.
edit
I just remembered a script that works very well on this Linux box but is a little bit limited on Mac OS X and doesn't seem to work on Windows. Essentially you register a window/tab with a part of it's name:
$ webrf setup-by-search test.html
then you simply do:
$ webrf refresh
to refresh the page.
I use WSL and two screens so for me this works. (as with every :write is a bit too much)
nmap <leader>t :silent !powershell.exe -command "Add-Type -AssemblyName System.Windows.Forms; [Windows.Forms.Cursor]::Position = \"-1290,50\"; Add-Type -MemberDefinition '[DllImport(\"user32.dll\")] public static extern void mouse_event(int flags, int dx, int dy, int cButtons, int info);' -Name U32 -Namespace W; [W.U32]::mouse_event(6,0,0,0,0); [Windows.Forms.Cursor]::Position = \"40,40\"; [W.U32]::mouse_event(6,0,0,0,0);"<CR><CR>
It basicly tells vim through a powershell command to have the mouse cursor go to:
position -1290, 50 ( which is where the refresh button of chrome is)
left mouse click
position 40,40 (which is where my vim is in full screen)
left mouse click
Step 3 and 4 is needed to refocus vim I tried to sent ALT-TAB but my vimrc disliked the % symbol.
On Windows OS you can utilize an AutoHotKey script that will automate that for a key press.
For example, the following script will bind Left Alt + r to switch to the browser window, send a Control + r(Refresh) and then get back to your previous window.
Replace Title_of_your_webpage with your browser's window title string after your page has loaded in it.
!r::
WinGet, winid, , Title_of_your_webpage
WinActivate, ahk_id %winid%
Send ^r
Send !{Tab}
Return
Is there a keyboard shortcut to format code in Notepad++ ?
I'm mainly working with HTML, CSS and Python code.
For example:
<title>{% block title %} {% endblock %}</title>
<link rel="stylesheet" href="/media/style.css" type="text/css" media="screen" />
</head>
To:
<head>
<title>
{% block title %}
{% endblock %}
</title>
<link rel="stylesheet" href="/media/style.css" type="text/css" media="screen" />
</head>
I remember Visual Studio doing it with Ctrl+K+D and NetBeans having the feature too but can't find it within Notepad++, if it can even do it.
TextFX -> HTML Tidy -> Tidy: Reindent XML
Remember to have the HTML code selected before you do this.
there is such a plugin as UniversalIndentGUI, it can be installed right from the plugin manager and has possibilities to reindent the most used programming languages.
If you go to TextFX menu and go to TextFX Edit, you will see a menu item Reindent C++ Code.
That will also format C# code.
ANSWER AS OF June 2019
Install the XML Tools plugin from the Plugin Admin (in Notepad++ 7.7 at least)
Then click Plugins -> XML Tools -> Pretty Print (XML Only with Line breaks)
That did it for me.
Here is a list of the available shortcuts in Notepad++.
In case your desired functionality is not available, you are able to define own macros and assign them to a custom shortcut (i am not used to use macros).
UPDATE: I will post the shortcuts here in case the link gets invalid:
Shortcut Command
Ctrl-C Copy
Ctrl-X Cut
Ctrl-V Paste
Ctrl-Z Undo
Ctrl-Y Redo
Ctrl-A Select All
Ctrl-F Launch Find Dialog
Ctrl-H Launch Find / Replace Dialog
Ctrl-D Duplicate Current Line
Ctrl-L Delete Current Line
Ctrl-T Switch the current line position with the previous line position
F3 Find Next
Shft-F3 Find Previous
Ctrl-Shft-F Find in Files
Ctrl-F3 Find (volatil) Next
Ctrl-Shft-F3 Find (volatil) Previous
Ctrl-Shft-I Incremental Search
Ctrl-S Save File
Ctrl-Alt-S Save As
Ctrl-Shft-S Save All
Ctrl-O Open File
Ctrl-N New File
Ctrl-F2 Toggle Bookmark
F2 Go To Next Bookmark
Shft-F2 Go To Previous Bookmark
Ctrl-G Launch GoToLine Dialog
Ctrl-W Close Current Document
Alt-Shft-Arrow keys or Alt + Left mouse click Column Mode Select
F5 Launch Run Dialog
Ctrl-Space Launch CallTip ListBox
Alt-Space Launch Word Completion ListBox
Tab (selection of several lines) Insert Tabulation or Space (Indent)
Shft-Tab (selection of several lines) Remove Tabulation or Space (outdent)
Ctrl-(Keypad-/Keypad+) or Ctrl + mouse wheel butto Zoom in (+ or up) and Zoom out (- or down)
Ctrl-Keypad/ Restore the original size from zoom
F11 Toggle Full Screen Mode
Ctrl-Tab Next Document
Ctrl-Shft-Tab Previous Document
Ctrl-Shft-Up Move Current Line Up
Ctrl-Shft-Down Move Current Line Down
Ctrl-Alt-F Collapse the Current Level
Ctrl-Alt-Shft-F Uncollapse the Current Level
Alt-0 Fold All
Alt-(1~8) Collapse the Level (1~8)
Alt-Shft-0 Unfold All
Alt-Shft-(1~8) Uncollapse the Level (1~8)
Ctrl-BackSpace Delete to start of word
Ctrl-Delete Delete to end of word
Ctrl-Shft-BackSpace Delete to start of line
Ctrl-Shft-Delete Delete to end of line
Ctrl-U Convert to lower case
Ctrl-Shft-U Convert to UPPER CASE
Ctrl-B Go to matching brace
Ctrl-Shft-R Start to record /Stop recording the macro
Ctrl-Shft-P Play recorded macro
Ctrl-Q Block comment/uncomment
Ctrl-Shft-Q Stream comment
Ctrl-Shft-T Copy current line to clipboard
Ctrl-P Print
Alt-F4 Exit
Ctrl-I Split Lines
Ctrl-J Join Lines
Ctrl-Alt-R Text Direction RTL
Ctrl-Alt-L Text Direction LT
F1 About
The latest plugin is tidy2, which can be installed through Plugins>Plugin Manager>Show Plugin Manager.
I suggest editing config 1 and setting quote-marks: no, especially if you have script that makes use of quotes.
Also, tidying more than once can result in inserting ampersands the first time and then replacing the ampersands the second time. You may want to play with the config to get it to where you need it.
For JavaScript Formatting I use Notepad ++ JSMin Plugin.Quite Handy
This isn't quite the answer you were looking for, but it's the solution I came to when I had the same question.
[update - I'm using vscode now for everything. I think it works better in a lot of cases.]
I'm a pretty serious Notepad++ user, so don't take this the wrong way. I have started using NetBeans 8 to develop websites in addition to Notepad++ because you can set it to autoformat on save for all your languages, and there are a ton of configuration options for how the formatting looks, down to the most minute detail. You might look into it and find it is a worthy tool to use in conjunction with notepad++. It's also open source, completely free, and has a bunch of plugins and other useful things like automatically compiling Sass if you use that too. It's definitely not as quick as NP++ so it's not great for small edits, but it can be nice for a long coding session.
In my notepad++, it seems TextFX needs a perl environment to format HTML files. Tidy2 demands nothing so I think it's more handy.
If all you need is alignment, try the plugin called Code Alignment.
You can get it from the built-in plugin manager in Notepad++.
We can use the following shortcut in the latest version of notepad++ for formatting the code
Alt + Ctrl + Shift + B
In Plugins > Plugin Admin > Search 'XML Tools' > Install.
The window will restart and install XML Tools under plugins.
Open your file and click Ctrl + Alt + Shift + B
No. Notepad++ can't format by itself. Formatting can easily be accomplished in many IDEs like Eclipse, NetBeans, Visual Studio [Code].
Another Potential Solution
Okay, so it's been 12 years since this question was asked. I think that I've found a another acceptable solution, that is perhaps better for formatting files, using Prettier.
What is Prettier?
Prettier is described as: "an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary."
Prettier Supports the Following Languages
HTML
CSS, Less, and SCSS
JavaScript
TypeScript
JSX, Angular, Vue
JSON, Markdown, YAML
And a few others.
If You Want to Use Other Languages, You Can Either Use:
Plugins made by the community to Prettier, which allow support for other formats such: Java, Rust, PHP, SQL, and others.
Non-Prettier formatters supporting other languages such as clang-format (npm version) (C / C++ / Java / JavaScript / JSON / Objective-C / Protobuf / C#), or Black (Python).
How To Install
You're going to need to install Node.js for this tutorial.
Note: There may be other work arounds for using the subsequent
mentioned software without using Node.js. But to keep this tutorial
simple and the fact that Node.js already carries widespread
familiarity among developers, I'm going to be using this software
without explaining how to install it.
After installing Node.js, install prettier globally to your system, allowing yourself to run prettier anywhere from the command line.
# NPM is the package manager used by Node.js
# And --global allows you to use prettier anywhere on your local computer.
npm install --global prettier
# To install other plugins (example):
npm install --g prettier-plugin-rust prettier-plugin-java
# To Install clang-format using NPM
npm install -g clang-format
# Usage Examples
prettier --write jquery-min.js # Formatting a JavaScript file
clang-format -i Test.cpp # Formatting C++ file
On Notepad++, install a plugin called NppExec from Menu> Plugins Admin...> Available> NppExec.
You can now run NppExec by either pressing F6 or by clicking Menu > Plugins > NppExec > Execute NppExec Script...
Now you should have a window pop up, giving you the option of executing a command.
You can either use prettier on a (1) specific file or (2) all files in a folder or (3) all files in a directory recursively.
You can always reload a file after it's better overwritten by Prettier using Ctrl+R, and enabling the following setting: Menu > MISC. > Update silently.
Commands and Screenshots of NppExec + Prettier.
REM Using Prettier on Current File (use cmd or powershell /c)
cmd /c prettier --write "$(FULL_CURRENT_PATH)"
REM Using Prettier on Current Folder (a single asterisk)
pwsh /c prettier --write "$(CURRENT_DIRECTORY)\*"
REM Using Prettier on Current Directory Recursively (double asterisk)
pwsh /c prettier --write "$(CURRENT_DIRECTORY)\**"
Install NppExec Plugin
Running NppExec Plugin
Executing Commands on NppExec
NPP+ v7.9.1 with the latest version of XMLTools can't format exported VBA code from Office 2016/2019 Word. It puts all the code on the same line since it strips the CRLF out. Moreover, when you enable "auto validation" it errors out on the first VBA line that is, Attribute VB_Name = "The VBA module name". So any of the xml tool validations apparently can't be used for VBA validation.
Im in the situation that I often send small codesnippets and xml-snippets to coworkers and partners via my outlook.
Has anyone got a good idea or tool that I can use to have my pastes syntaxhighlighted before I paste them into an email.
I was thinking of an intermediate paste to "$fancytool" and then I would have something to copy that will htmlified so I can copy paste it into the "compose email" window.
Edit-More-info:
Im pasting from windows within a VMWare virtual Machine, it might be eclipse, xmlspy, logfiles and other programs
Even-more-info:
I've seen this link how to do it from Vim. Unfortunately it seldom from vim im copying Code, and my email machine hasnt got any vim. The vmware machines has gvim, but I was hoping for an easier way that pasting to vim, saving to file, opening in internetexplorer and then copy/paste
Late but I can give an answer that works.
You need 2 things
putty
access to some Unix server (With vim)
In putty options, Under window → selection , turn the check box on for
Paste in to clipboard in RTF as well as plain text.
Log on to the server using putty.
start vim by typing vim
Paste your text (for example XML ) in to vim.
enter command mode (of vim by pressing ESC) and type
:set syn=xml.
Syntax highlighting kicks in.
Copy the text using mouse and paste it into your email.
5 years too late, sorry, but I've a much simpler solution than the accepted answer.
Use this online tool: http://tohtml.com/
copy the preview from your browser window and just paste into Word or Outlook.
Vim (or GVim) will output your code as formatted HTML. Then as long as your email is using an HTML format you can copy and paste it in.
Just an update on this matter, if you're on Windows, you can install Notepad++ (which is one of the best windows editors anyway), it comes out of the box with a plugin for this: "Copy text with Syntax Highlighting", when you select some text and right click on it.
If you just want the Add-In here it is.
If you want to know how it is done, here is an article on how to write the Add-In.
Comment: svrist mentioned a code paste site with syntax highlighting. Try http://codepad.org/
(don't have enough mojo to comment yet)
This link led me to SciTE.
Looks like SciTE has a Copy to RTF feature:
Edit(vmware upgrade):
But it looks like I am pretty much lost when I use vmware because I cant transfer rtf clipboard items to the vmware host. And I cant install software on the vmware host.
Maybe a paste-site with syntax highlighting?
If you're on Windows, Visual Studio does this automatically. At least it does for me, using Visual Studio 2005 on XP and copy/pasting to both MS Word and Lotus Notes
HeidiSQL does this for sql queries, and the syntax highlighting choices they made are quite readable. However, this will only work for sql queries, not other code. I like Notepad++ for Windows-based systems, and here are some instructions for Notepad++. Several people mentioned VIM for unix/shell environment.
For gVim (Windows), I defined this function and a convenience mapping:
function! HlCopy() range
exec a:firstline.','.a:lastline.'TOhtml'
normal yG
q!
!start /min powershell "Get-Clipboard | Set-Clipboard -AsHtml"
redraw
endfun
vmap Y :call HlCopy()<CR>
How to use?
Enter visual mode with v or by selecting text with left mouse. Then copy the current selection as raw text with y or highlighted text with Y.
Pass range directly (without visual mode): :1,3call HlCopy().
If you are lazy like me, you can set additional options for TOhtml in that function. I have this in my vimrc:
function! HlCopy() range
let g:html_font = "Consolas"
let g:html_number_lines = 0
exec a:firstline.','.a:lastline.'TOhtml'
normal yG
q!
!start /min powershell "Get-Clipboard | Set-Clipboard -AsHtml"
redraw
endfun
vmap Y :call HlCopy()<CR>