Dismiss errors/warnings given a line or regex - visual-studio-code

I have a templating language on top of html,js,css. I want to be able to disable errors if it comes from lines of code that match a given regex.
For example, given this templated HTML, vscode will throw some errors suggesting invalid css syntax:
<!-- custom css -->
<style id="custom-css">
{{User.customCSS}}
</style>
If what I'm asking (suppressing errors with regex) is impossible, what are my options to hide these errors?
There are extensions that come for these templating languages, but beyond syntax highlighting, they do not accomplish anything else.
I also cannot disable the entire errors/language features because that's extremely helpful.
The edit below was made by jD3V in response to a comment made by the OP's author
The Core Issue that I Want a Solution for:
VS Code Language Features are not working, however, this behavior is totally expected — after all VS Code tries to interpret the code — that you the author — write in a given document. VS Code wants to provide hints and warnings, but it is impossible for VS Code to do so when an arbitrary syntax has been injected into a well defined syntax, consequently; It's impossible for VS Code to provide language features for a syntax it doesn't know how to read — but I had hoped, to somehow, get a limited version of language features???

The rule below...
// #file ".../.vscode/settings.json"
{
"css.validate": true
}
...causes an error when ever a foreign syntax is written into a CSS document.
This is not a Rule that is Defined by a Linter or Formatter
This rule is unique in the sense that it checks whether your CSS document is in compliance with the current CSS Specifications Snapshot (which currently is the 2021 snapshot).
The rule was likely inspired by encouraged into existence due to the W3 Consortium's implementation of the same tool, that can be used through the W3C website.
CORE W3 Validator (official)
I can't say for certain, but because the standard puts out an official validation tool (which I have never known another standard to do, but I am sure CSS isn't alone) its likely that the official tool some how defines the VS Code tool. Either way, the setting "css.validate": true/false is not going to use the CSS Languages grammar to decide if the CSS is valid, it will probably use another grammar the meets the requirements of the W3 Consortium.
I am going to continue to find out if there is anyway around having to deactivate the tool. It maybe that you need to define a custom file-type, or turn the rule of though.
It is important to note that the validator is a tool that checks, whether or not, a CSS document — any document w/ the extension .css — meets the guidelines set by the current "W3 CSS Specification (which AtToW, the 2021 Spec Snapshot is the current spec used)". That means that the tool cannot be configured, because it simply does, or does not, meet the spec's guidelines.
https://jigsaw.w3.org/css-validator/
Note from Author:
Okay so, I keep seeing this bounty, and I know the answer, but I am teaching myself the same general subject area that the answer below is part of, so I didn't want to answer it, but since no one else has, I know I can point you in the generally-correct direction.
I know that there are two ways of doing this. The first means is the harder way, but if you ever plan on using this language in a different editor than VS Code, it might be one to consider.
Create a 'TextMate Grammar', if you have access to MacOS, this is a much simpler endeavor, as 'TextMate' has the best support for writing the grammar-type that was invented for it, or at least IMO. If you plan on using your {{}} brackets in CSS, you can write a CSS grammar, and just add support for your {{DoubleCurlySyntax}}.
The other option you have is, what I consider, the best option for embedded languages, and it was designed to be able to implement a custom syntax like yours far more easily. This is what I have been learning, and I have had to teach myself everything up to this point, because no one seems to know the answers to the questions I ask about it. Fortunately, much of what I have learned has been documented in a tutorial that is now part of the Official VS Code Documentation. You can find it here.
This is a broad topic, and there is no quick snippet someone could show you for creating a syntax quickly. This question touches on some of the fundamentals that computer science is built on, such as the "Grammar".
Speak of grammars, if you want to go that route there is a new tool currently in beta, that has been made available to the public. It can, if anything else, be used as a way to understand and learn how to author, define & implement a "TextMate Syntax PList" and "TextMate List of Scopes", which, when combined, makes up a TextMate Grammar.
The Tool is here. And no I am not bamboozling you into getting hacked the don't have an SSL license for what ever dumb reason. The tool is legit though.
IRO Tool
Update
In response to #Tori's Comment.
In response to Tosi's comment I personally think anytime someone creates a Language for VS Code for the first time, they will have to jump the same hurdles you are, especially this one.
I probably already stated this at some point, but this is a broad subject, there are many different factors to consider when implementing your language.
Here are my thoughts about your comment
At some point you're going to have to snippet generate CSS for your syntax to work.
What many frameworks & custom syntaxes like your own do, is they create a custom file extension, and write there language with in that type of file, then they use a parser, and regex to replace the syntax with CSS. The replacement of the values is what makes the language useful because it acts as a pre-processor and offers the ability to write dynamic CSS or HTML. A trait that usually only true programming languages have. Because the custom-syntax has to be parsed out, and a language that can be read by the Runtime Environment (which is the browser for your use-case), we can easily use another file ext. than .css to help VS Code out. Using a custom file ext would let vscode know, hey this is not standard SS. Your grammar will tell VS Code that it is very close to CSS, with minor syntactic changes.
This is the same means that I think several templating engines (like Pug, Mustache or Handlebars) use.
I think at this point you might want to consider how you are going to generate the raw CSS from your custom CSS-syntax.
Using alternate file extensions is a very common solution for this problem. A good example is JSON w/ Comments or .jsonc.
This is a good place to make use of the editor.action.inspectTMScopes tool
Using the inspector tool, we can view what the tokens for a "JSON w/ Comments" file looks like (aka .jsonc).
I assume you have used the tool, if not you can access it via the command palette, by typing in the phrase "Developer: Inspect Editor Tokens and Scopes", and then select the command when you see it.
The default keybinding for the tool is CTRL + ALT + SHIFT + i
Open a JSONC or *.jsonc Document
Many of the Configuration files end with .json but are configured using "files.associations: { ... }" to use the JSONC grammar. For example I used the inspector tool in my current projects "./.vscode/setting.json" file.
When you open the document, make sure there is valid JSON in it, then create a comment (which should be valid as we are working in JSONC). Then use the tool to inspect the comment.
The TextMate Token Inspector Tool should show you something that looks like the image &/or snippet below
.________________________________________________________________________.
| ·Hello·World 12 chars |
|________________________________________________________________________|
| language jsonc |
| standard token type Comment |
| foreground #99999999 |
| background #11101E |
| contrast ratio 3.10 |
| _______________________________________________________________________|
| textmate scopes comment.line.double-slash.js |
| meta.structure.dictionary.value.json.comments |
| meta.structure.dictionary.json.comments |
| source.json.comments |
| foreground comment.line |
| { "foreground": "#99999999", "fontStyle": "" } |
|________________________________________________________________________|
This is a GREAT example, because it shows you how VS Code's support for JSON w/ Comments uses the JSON TextMate grammar, and the comments property is tacked on to it. The comments at the end of source.json.comments denotes that this is a JSON grammar with the JSONC syntax added to it.
Now it gets even cooler! Well, it gets cooler if your a nerd like me. :-)
The first property shown in the tool when viewing the comments is comment.line.double-slash.js. In-other-words, the tools output should be interpreted as...
The JSONC Grammar extends the Standard JSON Grammar, by adding support for the JS Comment property from the JS Grammar!!!!!!
To me, that is cool!
As a bonus, here is how I extend a language, and assign it to a custom file type:
As I mentioned, I teaching myself the same topic. My language is called L3, and is a templating engine for ANSI Escape Sequences and Control Codes. This is part of my extension-manifest (or package.json).
/** #file "package.json" (My Extension Manifest) */
"contributes": {
"languages": [
{
"id": "l3",
"aliases": [
"L3",
"L3"
],
"extensions": [
".l3",
".lll",
".l3Lang
]
}
],
"grammars": [
{
"language": "l3",
"scopeName": "source.html.l3",
"path": "./syntaxes/l3.tmLanguage"
}
]
},
The "extensions":[".l3"] property is defining my language to be used in ".l3" documents as the language, and grammar for that document
The way that JSONC accomplishes injecting syntax into another grammar to define its-self is through the the "injectTo" property that getts added to the grammar contribution in the package.json extention manifest.
See the guide here to read more about injecting grammars into grammars.

Related

Possibility of a multilanguage 'source' name with Twincat Eventlogger

Roald has written an excellent guide for the Twincat Eventlogger.
https://roald87.github.io/twincat/2020/11/03/twincat-eventlogger-plc-part.html
https://roald87.github.io/twincat/2021/01/20/twincat-eventlogger-hmi-part.html
For us this is exactly what we want, there is however 1 thing I haven't figured out. How to get the sourcename of the alarm in multiple languages in the HMI. params::sourceName gives the path in the software (example: MAIN.fbConveyor1.Cylinder1) This path can be customized when initializing the alarm (as Roald has shown). This doesn't work in my case, since I would like to define a generic alarm (example: "Cilinder not retracted within maximum time") that is instantiated multiple times.
I was thinking of using the source as a way to show the operator where the alarm occurs. We use this way (path) already for saving machine settings among other things. The machines we build are installed all over the world, so multilanguage is a must.
Beckhoff does support multilanguage alarm names (when defined), but the source is not defined, but dynamically generated.
Anyone have an idea how this problem can be solved?
If I understand your question correctly, then being able to parameterize the event text with information of the source of the problem should help you out.
If you define the event text as Cylinder {0} has not retracted in time. then you can add the arguments of that text during runtime.
IF bRaiseAlarm THEN
bRaiseAlarm := FALSE;
fbAlarm.ipArguments.Clear().AddString('Alice');
fbAlarm.Raise(0);
END_IF
However, since this also stated in the articles you mentioned, I am unsure if this would solve your problem.
'Alice' in this example, can be hard to localize. The following options come to my mind.
The string can be based on an ENUM. Enums can have textlist support, so if you add your translations there, that should allow multilingual output. However... this does require a lot of setup, placing translations inside your code, and making sure the PLC application is aware of the language that the parameter should use.
Use tags to mark the source device, as tags can be language invariant. It is not the most user-friendly method, but it could work for you. It would become something like: "Cylinder 'AA.1123' did not retract in time.". 'AA.1123' as a tag would have to be stored inside your PLC code as a string. You will have to trust that your operator can relate the tag back to the actual source.
Hopefully, this helped, or else please help me understand the problem better.

VS Code Conditional Snippets

I am looking to have some snippets listed conditionally in the VS Code IntelliSense for a particular language. I am considering creating an extension, intercepting the list of CompletionItems, and removing any snippets that do not satisfy my conditions based on languageId and settings/configuration I will contribute with the extension. I am looking for the simplest solution to accomplish this, but if I need a Language Server then so be it. If I can dynamically load a snippets file for a particular languageId then that would be even better. I just need a starting point from someone more familiar with the API. I haven't even found how to retrieve CompletionList to start the intercept -- I searched the API doc but found nothing but its object definition.
As of VSCode 1.14, you cannot have conditional user snippets but an extension can contribute snippets conditionally. Try looking into creating a CompletionItemProvider that returns completion items with their kind set to CompletionItemKind.Snippet.
The JsDocCompletionProvider in the VSCode codebase is one example of this pattern. It only returns jsdoc snippets when the area around the cursor matches a regular expression

Removing annotations from a Modelica model

I'm developing a Modelica library and need to produce a document with source code listings. I'd like to be able to include the source of the Modelica models without annotations.
I could manually edit them out, but I'm looking for a more automated strategy. I'm guessing the most convenient and straightforward approach is to use some tool to save .mo files with no annotations and include those in my document (I'm using \lstinputlisting in LaTeX).
Is it possible to do this? I have access to Dymola, OpenModelica and JModelica. Dymola is obviously capable of producing such a listing, as it's able to include it in the automatically generated documentation (File > Export > HTML...). I've been looking into scripting with Dymola and OpenModelica, but haven't found a way to do this either.
JModelica seems like it could be a good option, but I don't have experience working with Python. If this is possible and someone gives me some pointers, I'm willing to look into it myself. I found a mention to a prettyprint function that might do the job, but I'm not sure where to start. I can't even find reference to that function in the latest documentation.
It would also be more convenient for me to find a way of doing it with Dymola/OpenModelica (whether through the UI or by using a script). Have I missed something?
I think you could use saveTotalModel("total.mo", MyModelName) in OpenModelica. This will strip most annotations (not ones used for code generation if I remember correctly) and pretty-print the source code including all dependencies. Then you just copy-paste the models/packages that you want to include in the listing. Or if you prefer, you can do something like the following to only include code for a particular model:
loadModel(Modelica);
loadFile("MyModel.mo");
saveTotalModel("total.mo", MyModel.A.B);
clear();
loadFile(MyModel);
str := list(MyModel.A.B);
writeFile("MyModel.A.B.listing", str);

Automatic documentation of an OO MATLAB project with mtoc++/Doxygen

I have an OO project in MATLAB and would like to automatically produce some documentation.
After some research I have found a convenient tool called mtoc++ which apparently produces a documentation using Doxygen (I have no experience with).
My only question is whether in order to use the tool I need to write comments in MATLAB using a specific format (language?) so that mtoc++/Doxygen could understand and document my comments?
If so, then what this format/ language is and where I can find its description?
After correctly installing and configuring mtoc++/Doxygen, the documentation is created automatically.
If you want to define personalized comments for specific custom parameters, you can follow the instructions on this page:
http://www.ians.uni-stuttgart.de/MoRePaS/software/mtocpp/docs/tools.html
Look under the heading Configuration options for the mtoc++ filter.
What you have to do is to edit the mtocpp.conf file, located in tools/config folder, and the format you'll be using is this:
add(params) = <parameter1_name> => """Your parameter1 description text in triple quotes""";
An example would be:
add(params) = myVariable => """This variable is defined by me""";
So you can define personalized comments for your Parameters, Fields, Extra Documentation and Global Settings.
I am sure there must be other workarounds to add comments and documentation.
I hope this helps. Happy coding.

How to internationalize java source code?

EDIT: I completely re-wrote the question since it seems like I was not clear enough in my first two versions. Thanks for the suggestions so far.
I would like to internationalize the source code for a tutorial project (please notice, not the runtime application). Here is an example (in Java):
/** A comment */
public String doSomething() {
System.out.println("Something was done successfully");
}
in English , and then have the French version be something like:
/** Un commentaire */
public String faitQuelqueChose() {
System.out.println("Quelque chose a été fait avec succès.");
}
and so on. And then have something like a properties file somewhere to edit these translations with usual tools, such as:
com.foo.class.comment1=A comment
com.foo.class.method1=doSomething
com.foo.class.string1=Something was done successfully
and for other languages:
com.foo.class.comment1=Un commentaire
com.foo.class.method1=faitQuelqueChose
com.foo.class.string1=Quelque chose a été fait avec succès.
I am trying to find the easiest, most efficient and unobtrusive way to do this with the least amount of manual grunt work (other than obviously translating the actual text). Preferably working under Eclipse. For example, the original code would be written in English, then externalized (to properties, preferably leaving the original source untouched), translated (humanly) and then re-generated (as a separate source file / project).
Some trails I have found (other than what AlexS suggested):
AntLR, a language parser / generator. There seems to be a supporting Eclipse plugin
Using Eclipse's AST (Abstract Syntax Tree) and I guess building some kind of plugin.
I am just surprised there isn't a tool out there that does this already.
I'd use unique strings as methodnames (or anything you want to be replaced by localized versions.
public String m37hod_1() {
System.out.println(m355a6e_1);
}
then I'd define a propertyfile for each language like this:
m37hod_1=doSomething
m355a6e_1="Something was done successfully"
And then I'd write a small program parsing the sourcefiles and replacing the strings. So everything just outside eclipse.
Or I'd use the ant task Replace and propertyfiles as well, instead of a standalone translation program.
Something like that:
<replace
file="${src}/*.*"
value="defaultvalue"
propertyFile="${language}.properties">
<replacefilter
token="m37hod_1"
property="m37hod_1"/>
<replacefilter
token="m355a6e_1"
property="m355a6e_1"/>
</replace>
Using one of these methods you won't have to explain anything about localization in your tutorials (except you want to), but can concentrate on your real topic.
What you want is a massive code change engine.
ANTLR won't do the trick; ASTs are necessary but not sufficient. See my essay on Life After Parsing. Eclipse's "AST" may be better, if the Eclipse package provides some support for name and type resolution; otherwise you'll never be able to figure out how to replace each "doSomething" (might be overloaded or local), unless you are willing to replace them all identically (and you likely can't do that, because some symbols refer to Java library elements).
Our DMS Software Reengineering Toolkit could be used to accomplish your task. DMS can parse Java to ASTs (including comment capture), traverse the ASTs in arbitrary ways, analyze/change ASTs, and the export modified ASTs as valid source code (including the comments).
Basically you want to enumerate all comments, strings, and declarations of identifiers, export them to an external "database" to be mapped (manually? by Google Translate?) to an equivalent. In each case you want to note not only the item of interest, but its precise location (source file, line, even column) because items that are spelled identically in the original text may need different spellings in the modified text.
Enumeration of strings is pretty easy if you have the AST; simply crawl the tree and look for tree nodes containing string literals. (ANTLR and Eclipse can surely do this, too).
Enumeration of comments is also straightforward if the parser you have captures comments. DMS does. I'm not quite sure if ANTLR's Java grammar does, or the Eclipse AST engine; I suspect they are both capable.
Enumeration of declarations (classes, methods, fields, locals) is relatively straightforward; there's rather more cases to worry about (e.g., anonymous classes containing extensions to base classes). You can code a procedure to walk the AST and match the tree structures, but here's the place that DMS starts to make a difference: you can write surface-syntax patterns that look like the source code you want to match. For instance:
pattern local_for_loop_index(i: IDENTIFIER, t: type, e: expression, e2: expression, e3:expression): for_loop_header
= "for (\t \i = \e,\e2,\e3)"
will match declarations of local for loop variables, and return subtrees for the IDENTIFIER, the type, and the various expressions; you'd want to capture just the identifier (and its location, easily done by taking if from the source position information that DMS stamps on every tree node). You'd probably need 10-20 such patterns to cover the cases of all the different kinds of identifiers.
Capture step completed, something needs to translate all the captured entities to your target language. I'll leave that to you; what's left is to put the translated entities back.
The key to this is the precise source location. A line number isn't good enough in practice; you may have several translated entities in the same line, in the worst case, some with different scopes (imagine nested for loops for example). The replacement process for comments, strings and the declarations are straightforward; rescan the tree for nodes that match any of the identified locations, and replace the entity found there with its translation. (You can do this with DMS and ANTLR. I think Eclipse ADT requires you generate a "patch" but I guess that would work.).
The fun part comes in replacing the identifier uses. For this, you need to know two things:
for any use of an identifier, what is the declaration is uses; if you know this, you can replace it with the new name for the declaration; DMS provides full name and type resolution as well as a usage list, making this pretty easy, and
Do renamed identifiers shadow one another in scopes differently than the originals? This is harder to do in general. However, for the Java language, we have a "shadowing" check, so you can at least decide after renaming that you have an issues. (There's even a renaming procedure that can be used to resolve such shadowing conflicts
After patching the trees, you simply rewrite the patched tree back out as a source file using DMS's built-in prettyprinter. I think Eclipse AST can write out its tree plus patches. I'm not sure ANTLR provides any facilities for regenerating source code from ASTs, although somebody may have coded one for the Java grammar. This is harder to do than it sounds, because of all the picky detail. YMMV.
Given your goal, I'm a little surprised that you don't want a sourcefile "foo.java" containing "class foo { ... }" to get renamed to .java. This would require not only writing the transformed tree to the translated file name (pretty easy) but perhaps even reconstructing the directory tree (DMS provides facilities for doing directory construction and file copies, too).
If you want to do this for many languages, you'd need to run the process once per language. If you wanted to do this just for strings (the classic internationalization case), you'd replace each string (that needs changing, not all of them do) by a call on a resource access with a unique resource id; a runtime table would hold the various strings.
One approach would be to finish the code in one language, then translate to others.
You could use Eclipse to help you.
Copy the finished code to language-specific projects.
Then:
Identifiers: In the Outline view (Window>Show View>Outline), select each item and Refactor>Rename (Alt+Shift+R). This takes care of renaming the identifier wherever it's used.
Comments: Use Search>File to find all instances of "/*" or "//". Click on each and modify.
Strings:
Use Source>Externalize strings to find all of the literal strings.
Search>File for "Messages.getString()".
Click on each result and modify.
On each file, ''Edit>Find/Replace'', replacing "//\$NON-NLS-.*\$" with empty string.
for the printed/logged string, java possess some internatization functionnalities, aka ResourceBundle. There is a tutorial about this on oracle site
Eclipse also possess a funtionnality for this ("Externalize String", as i recall).
for the function name, i don't think there anything out, since this will require you to maintain the code source on many version...
regards
Use .properties file, like:
Locale locale = new Locale(language, country);
ResourceBundle captions= ResourceBundle.getBundle("Messages",locale);
This way, Java picks the Messages.properties file according to the current local (which is acquired from the operating system or Java locale settings)
The file should be on the classpath, called Messages.properties (the default one), or Messages_de.properties for German, etc.
See this for a complete tutorial:
http://docs.oracle.com/javase/tutorial/i18n/intro/steps.html
As far as the source code goes, I'd strongly recommend staying with English. Method names like getUnternehmen() are worse to the average developer then plain English ones.
If you need to familiarize foreign developers to your code, write a proper developer documentation in their language.
If you'd like to have Javadoc in both English and other languages, see this SO thread.
You could write your code using freemarker templates (or another templating language such as velocity).
doSomething.tml
/** ${lang['doSomething.comment']} */
public String ${lang['doSomething.methodName']}() {
System.out.println("${lang['doSomething.message']}");
}
lang_en.prop
doSomething.comment=A comment
doSomething.methodName=doSomething
doSomething.message=Something was done successfully
And then merge the template with each language prop file during your build (using Ant / Gradle / Maven etc.)