Intellij indentation format - method definition with/without braces (in scala) - scala

I am having a minor annoyance with intellij indentation which I hope someone can help me with.
If I write a method declaration with braces, indenting works properly:
def function(a:A): B = { // When I hit return on this line...
// the cursor goes here (4 spaces in)
}
However, if I don't include braces, I don't get any indentation:
def function(a:A): B = // When I hit return on this line...
// the cursor goes here (0 spaces in)
To make matters stranger, if I already have some code on the first line before hitting return, I do get the correct spacing
Before:
def function(a:A): B = some.code.here //cursor is immediately after the = sign
After:
def function(a:A): B =
some.code.here // Correct indentation behavior.
So what I want to know is this: is there a setting which will result in an auto-indent if I hit return at the end of a method declaration without any code behind the cursor?
Thanks!

Related

vscode API: get Position of last character of line

Following up on this still unanswered question regarding VS Code Extensions with the VS Code API. I didn't answer it because it specifically asked for a solution using the with method of the Position object. I couldn't make that work, nor was I able to loop through the object to get the last character. Trying to manipulate the selection with vscode.commands.executeCommand didn't work either, because vscode.window.activeTextEditor doesn't appear to reflect the actual selection in the window as soon as the Execution Development Host starts running. The only solution I could find was the hoop-jumping exercise below, which gets the first character of one line and the first character of the next line, sets a Range, gets the text of that Range, then reduces the length of that text string by 1 to get the last character of the previous line.
function getCursorPosition() {
const position = editor.selection.active;
curPos = selection.start;
return curPos;
}
curPos = getCursorPosition();
var curLineStart = new vscode.Position(curPos.line, 0);
var nextLineStart = new vscode.Position(curPos.line + 1, 0);
var rangeWithFirstCharOfNextLine = new vscode.Range( curLineStart, nextLineStart);
var contentWithFirstCharOfNextLine = editor.document.getText(rangeWithFirstCharOfNextLine);
var firstLineLength = contentWithFirstCharOfNextLine.length - 1;
var curLinePos = new vscode.Position(curPos.line, firstLineLength);
var curLineEndPos = curLinePos.character;
console.log('curLineEndPos :>> ' + curLineEndPos);
I'm obviously missing something - it can't be impossible to get the last character of a line using the VSCode API without mickey-mousing the thing like this. So the question is simply, what is the right way to do this?
Once you have the cursor Position the TextDocument.lineAt() function returns a TextLine. From which you can get its range and that range.end.character will give you the character number of the last character. - not including the linebreak which if you want to include that see TextLine.rangeIncludingLineBreak().
const editor = vscode.window.activeTextEditor;
const document = editor.document;
const cursorPos = editor.selection.active;
document.lineAt(cursorPos).range.end.character;
Note (from [TextDocument.lineAt documentation][1] ):
Returns a text line denoted by the position. Note that the returned
object is not live and changes to the document are not reflected.

Scala replace one text for another text with special chars included

i need a function to replace one text per another one, currently this is the code i am using, but it's not really working, or at least instead of replacing, removing the text and leave it empty, this is the code:
Thanks for your time, appreciated
def replaceIcons(message: String) = {
message.replaceAll("[|TInterfaceiconsInv_Misc_Tournaments_banner_Human.png:13,8:14:0,9:-2,8|t]:", "[https://cdn.discordapp.com/emojis/511683443231424532.png?v=1]:")
}
This is the message i want to replace i.postimg.cc/zDHwfXHX/ser.png
The expected output is this one: i.postimg.cc/k4mCt5X3/serr.png
Example message to replace:
[global] [Zerobalas]: [|TInterfaceiconsInv_Misc_Tournaments_banner_Human.png:13,8:14:0,9:-2,8|t]: asd
Example output expected:
[global] [Zerobalas]: [https://cdn.discordapp.com/emojis/511683443231424532.png?v=1]: asd
Try this:
def replaceIcons(message: String) = {
message.replace("[|TInterfaceiconsInv_Misc_Tournaments_banner_Human.png:13,8:14:0,9:-2,8|t]:", "[https://cdn.discordapp.com/emojis/511683443231424532.png?v=1]:")
}
println(replaceIcons("[global] [Zerobalas]: [|TInterfaceiconsInv_Misc_Tournaments_banner_Human.png:13,8:14:0,9:-2,8|t]: asd"))

VS Code, Prettier and Flow not working nicely together - what am I missing?

I'm using the prettier-vscode extension to format my js code, but flow annotations are formatted in a weird way with lots of extra space:
const handleResponse = async function < T > ( // <-- should be function<T>(
response,
url: string,
options: responseOptions = {}
): Promise < T | null > { // <-- should be Promise<T|null> {
or Promise<T | null> {
I've looked around in all the places I could think of to see what config I need to change to get this working, but I can't find anywhere that seems to affect the spacing in te above case.
There's also some weirdness going on with multi-line ternary statements, but I don't think that's related to flow:
const WORKORDERS_BASE_URL =
WORKORDERS_PORT === '80' ? // <-- I'd prefer if ? and : were on the next line
`http://${WORKORDERS_HOST}` : // <-- on same indentation level as above - I want one more
`http://${WORKORDERS_HOST}:${WORKORDERS_PORT}` // <-- same here, I want more indentation
The worst case of them all is this change, which happens when I format the document:
Promise<?T>
// becomes
Promise<<?T>
i.e. it actually breaks my code!
Where should I look for config that controls these things?

How to stop the execution or throw an error in scala play framework

I'm developing a scala application with play framework, but i got something strange.
i can't stop the execution nor throwing an error in order to send a response for the client, it always continue the code and it always returning okay, however i made a dummy function that it should return a bad request but unfortunately it is returning OK here is what i wrote. any help will be appreciated
def foo(locale: String, orderId: Int) = Action { implicit request => {
val x=4+7;
if(x==11){
BadRequest(JsonHelper.convertToJson("Bad bad it is really bad "))
}
OK(JsonHelper.convertToJson("Well Done"))
}
}
the above code returning OK Well done.
To make your code return a BadRequest, add an else:
def foo(locale: String, orderId: Int) = Action { implicit request => {
val x = 4 + 7;
if (x == 11)
BadRequest(JsonHelper.convertToJson("Bad bad it is really bad "))
else // <---
OK(JsonHelper.convertToJson("Well Done"))
}}
Your problem is your if without curly braces.
refered to this link :https://docs.scala-lang.org/style/control-structures.html#curly-braces
if - Omit braces if you have an else clause. Otherwise, surround the
contents with curly braces even if the contents are only a single
line.
so you can just suuround the BadRequest with curly braces or add an else statement between your Bad and OK instruction. Be careful, don't forget the indentation !
edit 20/12/2017 >> un scala the last instruction is implicitly returned. Your last instruction is OK, so it returns OK.
Add explicit return statement in your if block or add an else statement.

Procedural macro parsing weirdness in Rust

I'm trying to parse a macro similar to this one:
annoying!({
hello({
// some stuff
});
})
Trying to do this with a procedural macro definition similar to the following, but I'm getting a behaviour I didn't expect and I'm not sure I'm doing something I'm not supposed to or I found a bug. In the following example, I'm trying to find the line where each block is,
for the first block (the one just inside annoying!) it reports the correct line, but for the inner block, when I try to print them it's always 1, no matter where the code is etc.
#![crate_type="dylib"]
#![feature(macro_rules, plugin_registrar)]
extern crate syntax;
extern crate rustc;
use macro_result::MacroResult;
use rustc::plugin::Registry;
use syntax::ext::base::{ExtCtxt, MacResult};
use syntax::ext::quote::rt::ToTokens;
use syntax::codemap::Span;
use syntax::ast;
use syntax::parse::tts_to_parser;
mod macro_result;
#[plugin_registrar]
pub fn plugin_registrar(registry: &mut Registry) {
registry.register_macro("annoying", macro_annoying);
}
pub fn macro_annoying(cx: &mut ExtCtxt, _: Span, tts: &[ast::TokenTree]) -> Box<MacResult> {
let mut parser = cx.new_parser_from_tts(tts);
let lo = cx.codemap().lookup_char_pos(parser.span.lo);
let hi = cx.codemap().lookup_char_pos(parser.span.hi);
println!("FIRST LO {}", lo.line); // real line for annoying! all cool
println!("FIRST HI {}", hi.line); // real line for annoying! all cool
let block_tokens = parser.parse_block().to_tokens(cx);
let mut block_parser = tts_to_parser(cx.parse_sess(), block_tokens, cx.cfg());
block_parser.bump(); // skip {
block_parser.parse_ident(); // hello
block_parser.bump(); // skip (
// block lines
let lo = cx.codemap().lookup_char_pos(block_parser.span.lo);
let hi = cx.codemap().lookup_char_pos(block_parser.span.hi);
println!("INNER LO {}", lo.line); // line 1? wtf?
println!("INNER HI {}", hi.line); // line 1? wtf?
MacroResult::new(vec![])
}
I think the problem might be the fact that I'm creating a second parser to parse the inner block, and that might be making the Span types inside it go crazy, but I'm not sure that's the problem or how to keep going from here. The reason I'm creating this second parser is so I can recursively parse what's inside each of the blocks, I might be doing something I'm not supposed to, in which case a better suggestion would be very welcome.
I believe this is #15962 (and #16472), to_tokens has a generally horrible implementation. Specifically, anything non-trivial uses ToSource, which just turns the code to a string, and then retokenises that (yes, it's not great at all!).
Until those issues are fixed, you should just handle the original tts directly as much as possible. You could approximate the right span using the .span of the parsed block (i.e. return value of parse_block), which will at least focus the user's attention on the right area.