Can we make use of syntax highlighting feature to remove all comments from a source file in SublimeText? - language-agnostic

I have a bunch of source files written in different languages, and I would like to strip all comments from the source files.
While writing regex is certainly an option, depending on the input files, I may have to handle cases where the character to denote comment appears inside string literals. There is also the need to maintain a list of regex for different languages.
The syntax highlighting seems to do quite a good job at highlighting the comments, but there doesn't seem to be any command to remove all comments in the Command Palette.
Is there any way to leverage the syntax highlighting feature in SublimeText to remove all comments from source files in different languages?

Based on nhahtdh's answer, the following plugin should work for both Sublime Text 2 and 3
import sublime_plugin
class RemoveCommentsCommand(sublime_plugin.TextCommand):
def run(self, edit):
comments = self.view.find_by_selector('comment')
for region in reversed(comments):
self.view.erase(edit, region)
Create a new file with Python syntax, and paste the code above into it. Save the file in your Packages/User directory (accessible via Preferences -> Browse Packages...) as remove_comments.py. You can now either run the plugin via the console, or bind a key combination to it. To run via the console, just type
view.run_command('remove_comments')
in the console, and all the comments in the current view will be deleted.
To bind a key combination, open Preferences -> Key Bindings-User and add the following (surround it with square brackets [] if the file is empty):
{ "keys": ["ctrl+alt+shift+r"], "command": "remove_comments" }
Save the file, and you can now hit CtrlAltShiftR (or whatever key combination you choose) and all comments in the current file will be deleted.

Assumption
We will make use of the syntax highlighting rules in Sublime Text to remove all comments, so the method below works only if the syntax highlighting works correctly for the language of your source file.
For most languages, the syntax highlighting rules do quite a good job at recognizing the comments. However, it would be best if you take another look at your files to see if there is any anomaly in syntax highlighting.
The current method only works for Sublime Text 2.
Solution
Open the Console via View > Show Console or the key combination Ctrl+`
Copy and paste the following commands line by line:
e = view.begin_edit()
len([view.erase(e, r) for r in reversed(view.find_by_selector('comment'))])
view.end_edit(e)
After the last command, the edit will be applied and all comments will be removed.

Related

How to convince VS code to accept # as comment in JSON files?

We have special files that contain JSON data mixed with # comments.
I figured I need to enhance Code's json.settings file with:
"files.associations": {
"*.ourextension": "jsonc"
}
but then I discovered that jsconc is about JSON data with // comments.
Is there a convenient way to get VS code to accept # comments in JSON data?
Edit: VS code recognizes the jsconc language, it gives me this error message:
And it also accepts // comments:
adding the // got me a green first line, and now the second line gets the first error (because starting with #).
If you use the Change Language mode command (or click on the language indicator on the status bar) you can select "jsonc JSON with Comments".
I think this is only auto-detected when the extension is .jsonc.
NB. JSON with comments uses JavaScript style single line comments: from a \\, outside a string literal, to the end of line.
To support some different comment indicator would require a new language mode (and an extension to add it).
A distinct non-answer: it might be possible to add a such a new language definition, but it would require quite a bit of work. I also had a quick look if I could simply change the corresponding config json file for jsonc that ships with VS code, but that file is rather complex, and would probably be overridden with the next VS code update.
Thus a straight forward workaround. Two scripts to replace one command style with the other:
#!/bin/sh
# a helper script that turns all # into //
# with the syntax that works for sed on MAC OS
for file in "$#"
do
sed -i '' -e 's,#,//,g' $file
done
Not exactly convenient, but fast and robust, given our specific requirements.

Set syntax for a specific file name in Sublime Text 2/3

I have a program that uses a file called user.cfg to get its user defined configuration settings. The odd thing is that they chose the syntax for this file to be Tcl (it's not odd that it is Tcl, it's odd they chose the .cfg extension instead of .tcl). So, when I open this file in Sublime Text, it doesn't know what syntax highlighting scheme to choose.
What I would like to do is set the syntax highlighting for user.cfg to Tcl, but not all .cfg files to Tcl.
I have seen this question which is very similar to mine, except in that case the special file name had no extension so Sublime Text knew to assign Ruby highlighting to only that one file. Unfortunately, I have an extension so the solution given there will not work for me.
Is there any known way to get Sublime Text base a highlighting scheme on the full filename?
Take a look at the ApplySyntax plugin.
The previous answer is completely true; however, I thought it would be better to have it here all in one place rather than going on another webpage to find the list of procedure to apply it
Sublime text 3
This is found here
Ensure Package Control is installed. Instructions are found here.
In Sublime Text, press Ctrl+Shift+P (Win, Linux) or Cmd+Shift+P (macOS) to bring up the quick panel and start typing Package Control: Install Package.
Select the command and it will show a list of installable plugins.
Start typing ApplySyntax; when you see it, select it.
Restart to be sure everything is loaded proper.
Enjoy!

Snippet with Custom Variables

I'd like to create a package containing a series of snippets that incorporate user-definable variables. For example, I'd like the user to be able to provide a value for a variable called HOSTNAME and have the snippets include that user's value.
The Sublime Text Unofficial Documentation explains:
Snippets have access to contextual information in the form of environment variables. Sublime Text automatically sets the values of the variables listed below.
You can also add your own variables to provide extra information. These custom variables are defined in .sublime-options files.
I've had no luck finding any information on the syntax for a .sublime-options file, however, and Sublime does not seem to try to read a file with that extension when I save it anywhere under the Packages directory. Is this a typo?
Using a .tmPreferences file seems to do what I'm looking for. Is this the only method of getting user-defined values into a snippet? Is it possible to use a .sublime-settings file?
The .sublime-options, actually, is the .sublime-settings. .sublime-options were the ST1 files and the docs got outdated, BUT you use the wrong link, you should always check and switch in the sidebar on the left to your version - ST2, ST3.
And to answer your question, you need to put the variables in .tmPreferences as may be seen here

Sublime to change Tcl syntax highlighting

In notepad++, the tcl command arguments get highlighted. Like this:
puts [my_tcl_command -arg1 foo -arg2 bar]
How can I change the syntax highlighting definition in Sublime Text 2. I guess it's somewhere in this file "Sublime Text 2\Packages\TCL\Tcl.tmLanguage".
Syntax highlighting in Sublime Text is controlled by two files - the .tmLanguage file, which you mentioned, and your theme's .tmTheme file. Scopes are assigned to your code by interpreting regular expressions contained in the .tmLanguage file. For example, puts is assigned the scopes source.tcl keyword.other.tcl You can determine this by putting your cursor in a certain spot, then hitting CtrlAltShift-P - the scope(s) will appear in the bottom bar. Alternatively, I highly recommend using the ScopeHunter plugin.
So, now that we have the scope, it's up to the tmTheme file to assign the syntax highlighting. Unless you've installed a plugin theme, these files live in the Packages/Color Schemes - Default directory. It's in XML format, and you can search for the scope that's assigned to your -arg1 and -arg2 arguments and change the colors - they're in hex RGB web format.
EDIT
I just re-read your question, and realized that you want to assign a new scope to highlight the arguments. For that, you'll need to edit the .tmLanguage file and add a new regex to highlight them, assign a scope, then either alter your .tmTheme to add the new scope, or just assign one that's already highlighted. I don't know that much about how Notepad++ assigns its syntax highlighting rules, so you may be able to find one already written. Taking a look at other .tmLanguage files can be very instructive, as well. I recommend the Python one, even though it's not terribly well organized, because there are a large number of scopes, and it's fairly easy to see what's being done.

Set default syntax to different filetype in Sublime Text 2

How do I set a default filetype for a certain file extension in Sublime Text 2? Specifically I want to have *.cfg files default to having Ini syntax highlighting but I cannot seem to figure out how I could create this custom setting.
In the current version of Sublime Text 2 (Build: 2139), you can set the syntax for all files of a certain file extension using an option in the menu bar. Open a file with the extension you want to set a default for and navigate through the following menus: View -> Syntax -> Open all with current extension as... ->[your syntax choice].
Updated 2012-06-28: Recent builds of Sublime Text 2 (at least since Build 2181) have allowed the syntax to be set by clicking the current syntax type in the lower right corner of the window. This will open the syntax selection menu with the option to Open all with current extension as... at the top of the menu.
Updated 2016-04-19: As of now, this also works for Sublime Text 3.
Go to a Packages/User, create (or edit) a .sublime-settings file named after the Syntax where you want to add the extensions, Ini.sublime-settings in your case, then write there something like this:
{
"extensions":["cfg"]
}
And then restart Sublime Text
In ST2 there's a package you can install called Default FileType which does just that.
More info here.
You can turn on syntax highlighting based on the contents of the file.
For example, my Makefiles regardless of their extension the first line as follows:
#-*-Makefile-*- vim:syntax=make
This is typical practice for other editors such as vim.
However, for this to work you need to modify the
Makefile.tmLanguage file.
Find the file (for Sublime Text 3 in Ubuntu) at:
/opt/sublime_text/Packages/Makefile.sublime-package
Note, that is really a zip file. Copy it, rename with .zip at the end, and extract the Makefile.tmLanguage file from it.
Edit the new Makefile.tmLanguage by adding the "firstLineMatch" key and string after the "fileTypes" section. In the example below, the last two lines are new (should be added by you). The <string> section holds the regular expression, that will enable syntax highlighting for the files that match the first line. This expression recognizes two patterns: "-*-Makefile-*-" and "vim:syntax=make".
...
<key>fileTypes</key>
<array>
<string>GNUmakefile</string>
<string>makefile</string>
<string>Makefile</string>
<string>OCamlMakefile</string>
<string>make</string>
</array>
<key>firstLineMatch</key>
<string>^#\s*-\*-Makefile-\*-|^#.*\s*vim:syntax=make</string>
Place the modified Makefile.tmLanguage in the User settings directory:
~/.config/sublime-text-3/Packages/User/Makefile.tmLanguage
All the files matching the first line rule should turn the syntax highlighting on when opened.
The best solution for me turned out to be to used the ApplySyntax package.
The steps are as follows:
Install the package via Package Control
CTRL + SHIFT + P and enter ApplySyntax: Browse Syntaxes. Find your desired syntax here and note the exact line shown, e.g. I was looking to set it to Markdown from the Markdown Editing package, so for me the line was MarkdownEditing/syntaxes/Markdown.
CTRL + SHIFT + P and enter ApplySyntax: Settings.
On line "new_file_syntax": "XYZ", enter the line from Step 2.
See here for further documentation.
I found this to work better than the DefaultFileType package, because it isn't limited to just new files created by pressing CTRL + N and captured new tabs opened by clicking the empty space to the right of an open tab.
I hope is useful to someone 11 years after the original question was asked. 😅