It turned out that Visual Studio fooled me with wrong syntax warnings! My setup was perfectly valid.
To avoid warnings right click anywhere inside the file and choose "Execution Settings - SQLCMD Mode".
There is also a toolbar button named SQLCMD Mode doing the same thing.
Here is the menu item in case you can't find the toolbar button: