Strange suggestions sublime text editor - autocomplete

when I write code I like the computer to give me suggestions. But with sublime text editor I get very weird unwanted suggestions like this:
even when I want to use a function or class it doesn't tell me which parameters are required.
does anyone know how I can solve this problem?
class student:
def __init__(self,name,age,grade):
self.name = name
self.age = age
self.grade = grade
def get_grade(self):
return self.grade
s1 = student()

Sublime's internal autocompletion system suggests symbols/words from the files that are available in your project (that is, the files that are available from the side bar). As such, the answer to your first question is that you're seeing those symbols because they appear in other files.
You can turn that off with this setting (shown here with the default value):
// Auto complete will used indexed data to provide completions from other
// files when this is enabled
"auto_complete_use_index": true,
For your second question, it's probably worth mentioning first that you might also notice that not only does Sublime not offer you help with parameters, it will also not show you methods on the classes you're using. For example using your code, if you tried to autocomplete s1. you might expect to see the method of that class only, but you'll see all completions.
If you want that kind of IDE-like completion, you need to install the LSP package along with a support package for your language (in your case one for Python).
The LSP server does deep introspection of the contents of your code to provide (among other services) an autocompletion experience closer to what you're looking for.

Related

Dismiss errors/warnings given a line or regex

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.

Documentation of OCaml code in Eclipse

I'm using Eclipse with the OcaIDE-Plugin to write my ocaml-project.
I have written several ocaml-functions that I want to document (comment, return values and params).
I've created my documentation in the .ml-files like described in this link: http://caml.inria.fr/pub/docs/manual-ocaml/ocamldoc.html
Here is an example of one function:
(** sorting tuples where first element is key *)
let my_comp x y = (*Some code*)
Unfortunately, my comments don't show up, when I press F2 at one of the functions, it only shows the name and the file it is contained.
When writing comments in an mli-file, it works as expected, but i also want to document "private" functions that are not accessible from the outside. Can I define functions in the mli, that are NOT accessible from the outside, just for the documentation?
How can I make Eclipse to show my documention?
Well, as you said, you would like to show the documentation but not export the function out of the module. That, sadly, won't work.
I guess OcaIDE can be considered as incomplete but it doesn't look like it's something people care about (I don't know a single person working on OcaIDE). If you like having autocompletion etc, maybe try to program with emacs and install merlin (look, I found the perfect post for you : here)
As for the suggestion of defining a function in the mli not accessible from the outside, it's completely opposed to why mli files are created, so don't expect that to be possible. ;-)
I hoped I've been able to help you.

what makes a variable be visible (intellij idea)

With intellij idea, how do I find out what makes a variable be visible?
An example of when it is hard:
Suppose you look at class A, and you see a variable something. If you jump to source you see that it's defined in trait X. But you don't extend trait X directly. What do you extend, then, that makes this variable visible? If you have a deeply nested hierarchy, tracking can be hard.
Any recommendations or solutions?
EDIT: Please vote for the feature if you're interested: http://youtrack.jetbrains.com/issue/IDEA-124369
I don't think that IntelliJ IDEA has any shortcut for "finding what makes a variable visible".
However you can determine it using the "Find Usages" option (Alt + F7). For example:
import java.nio._
object TempObj extends App {
def func = 2
val p = file.Paths.get("some-path")
func
}
So Find Usages on "file", tells you that its from the Package "file" (in heading of the new Tab it also shows the complete package name, ex: Find Usages of java.nio.file in Project Files).
Whereas Find Usages on func will tell you that its a Method (And the Tab heading now says: Find Usages of func() in Project and Libraries)
So now in way you can determine, what exactly makes the variable visible. This also works for imports since it shows the package from which it is imported and you can then look for import of that packages.
I know of two almost-solutions to this problem.
Go-to-declaration, as you mentioned, solves this problem in the case of local variables.
More generally, the "find usages" feature gives you a neat little breakdown by type and file of different uses of the variable. From this you can see if it's involved in a static import.
It's not perfect, but with a moment's thought these two are generally sufficient to figure out what you want.
Use ctrl+b or F4 to jump to source code. Alternatively you can use ctrl+shift+a to get option/action. You can find shortcuts at http://gaerfield.github.io/ide-shortcuts/ as well. Hope it will help.
From what I understood you want to see the code that creates an Object you use, for instance Mystery someMystery;.
That gives you two options to populate someMystery:
someMystery = ... where ... is your code to populate
someMystery and if that is the case you should follow
that code (with ctrl+B as far as you need to) to the point where it
actually creates the Mystery object.
Use CDI to populate that object instance for you, in which case you should look into the CDI mechanism in order to see in what way the object instance is populated.
In either way IMO there is no way to know for sure if the someMystery instance is of some more concrete class than Mystery, because it is decided in runtime, not in compile time, so your next bet would be to run the program in debug and see what object goes into someMystery, although you are not guaranteed to get the same type of object every time.
PS. My answer is based entirely on my java understanding of the topic, can't say if it is valid for scala also.
This might not be exactly the answer you were hoping to get.
However, quoting yourself,
If you have a deeply nested hierarchy, tracking can be hard.
Have you considered using composition over inheritance? Perhaps this would remove the need for the feature you are looking for.
Deeply nested hierarchy doesn't sound good. I understand your pain about that.
When you override vals or defs there is a little circle next to the line number that shows where it is from even when it is from nested hierarchy. Hovering over vals with the command key down also shows you a little tooltip where it is from.
Does this help?
https://youtu.be/r3D9axSlBo8
if you want class, field or method to be visible, you need to implement them as public. If it was your question.

Auto fix common typo in eclipse

Lets say for example I write many times priavte instead private.
Is there a way to let Eclipse automatically fix my common typo?
Something like construct a map of my common typo to its desire fix,
and then just let Eclipse fix it without asking me about that.
Are there any other IDE\editors that have such support?
There is no builtin support for automatically changing strings. The closest to your request are the templates of the Java editor, but even those must explicitly be activated using CtrlSpace.
To get around your problem, I suggest simply not to write that much yourself. If you want to declare a private field, type just "pr" and hit CtrlSpace to invoke code completion. Eclipse can do code completion quite well, often even without any trigger characters (try it with an empty class file).

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.)