Making a command only run in certain cases in Vim - vim

I'm trying to figure out how to get this command to only run in certain cases:
au BufNewFile,BufRead *.js imap <buffer> {<cr> {<cr>}<c-o>O<Tab><Down>;<Up>
Examples:
// No!
if () {
}
// YES!
foo.x = function () {
};
// YES!
var x = {
// NO!
y: function () {
}
};
// YES!
foo(function () {
});
So the pattern would be, NO semi IF it starts with for|switch|if|else|if else (and whatever else) OR if there is a : on the same line.
I really don't even know where to look.

you could try mapping with <expr>.
I wrote a function, which returns the mapping you need with or without the semi. :
fun! Mapping()
return "{\<cr>}\<c-o>O\<Tab>\<Down>".(getline('.') =~# '^\s*for\s\|if\s\|else\s'||getline('.') =~# ':'? '' : ';')."\<up>"
endfunction
then you could add this mapping into your au
inoremap <buffer> <expr> {<cr> Mapping()
note that I didn't put all the keywords in the line, I just added if else for as example. you could add other keywords and test.

Related

How can I code a keybindings sequence in Awesome WM?

My problem is that the basic option to make keybindings in Awesome WM (Window Manager), awful.key(), doesn't work for keybindings like [super+d, e] or [super+d, super+r].
I found a way to do it, but is impractical. Maybe some parameter of "awful.keygrabber" works, but I can't find much information about its behavior.
This is how:
awful.keygrabber {
start_callback = function() --[[do something]] end,
stop_callback = function() --[[do something]] end,
-- You might want to avoid `export_keybindings` if you want
-- a single point of entry. If so, they use a normal `awful.key`
-- to start the keygrabber.
export_keybindings = true,
-- This is the important part, it releases the keygrabber
-- when `Super` is released. If you don't want this and
-- release when an unrelated key is pressed, do it
-- with `keypressed_callback` instead.
stop_event = "release",
stop_key = {"Escape", "Super_L", "Super_R"},
keybindings = {
{{ modkey } , "d" , function()
--[[do something]]
end},
{{ modkey } , "e" , function()
--[[do something]]
end},
}
}

P5.js - Translate keycode presses to actual keyboard letters (in system)

function keyPressed() {
if (keyCode === "e") {
control *"system keyboard"* to output "e"
I want to type letters with poses via the [Teachable Machine.] (https://teachablemachine.withgoogle.com/train/pose)
The simplest solution would be to use the p5.js key property, which for normal printable keys will be the string for the letter inserted by the key being pressed (taking the state of the shift key into account). Just be sure you take the non-printable keys (Shift, Alt, Meta, Backspace, Tab, Enter, Escape, etc.) into account.
If you don't want to use the built in p5.js capabilities, then this question is a duplicate of Get Character value from KeyCode in JavaScript... then trim
I kinda wrote everything within comments...
// copied this line of of the mozilla docs also this is for window rather than canvas
window.addEventListener("keydown", function(event){//you should just create a html canvas
// console.log(event.code) // and just select('#id')||('.class')||('canvas').
// console.log(event.code.replace("Key","")) // ya can also get rid of these console.log()-s
if(typeof getCharString === "function"){ // this checks if function exists
getCharString(event.code) // this'll give you the text
}
}) // idk if you can do this with p5.js or not tbh...
function getCharString(P_EN_GUI_N_AGHHHH){
console.log(`${P_EN_GUI_N_AGHHHH} !!!`)
console.log( P_EN_GUI_N_AGHHHH+"!!!")
}
// |
// here's just for copy |
// V
window.addEventListener("keydown", function(event){
if(typeof getCharString === "function"){
getCharString(event.code)
}
})
function getCharString(str){
console.log(str)
} // str == string

Selecting (and deleting) entire function with definition (INCLUDING whitespace) in Vim

I recently switched to using Vim (with VSCode) as my editor.
I'm trying to delete a function with it's definition in JavaScript. I looked on google and here on StackOverflow and found this question. Unfortunately the answers for this question only work for functions without white space.
Here is how my function looks:
const useBattery = () => {
const [battery, setBattery] = useState({ level: 0, charging: false });
const handleChange = ({ target: { level, charging } }) => setBattery({ level, charging });
useEffect(() => {
let battery;
navigator.getBattery().then(bat => {
battery = bat;
battery.addEventListener("levelchange", handleChange);
battery.addEventListener("chargingchange", handleChange);
handleChange({ target: battery });
});
return () => {
battery.removeEventListener("levelchange", handleChange);
battery.removeEventListener("chargingchange", handleChange);
};
}, []);
return battery;
};
I tried several approaches, the best one was da{ when my cursor is within the function. This motion will delete the function body, but not the definition.
Is there any way to delete the function and the definition in one motion using Vim, if there is white space in the function?
From inside the function, as you say da{ deletes only the braces and its content, without the preceding declaration or the following semicolon. However... if we switch to linewise...?
There is a semi-hidden section a bit under :help exclusive-linewise with bold heading but no tag to jump to: "FORCING A MOTION TO BE LINEWISE, CHARACTERWISE OR BLOCKWISE", saying that we can switch to a non-default selection by using v (characterwise), V (linewise) or Ctrl-V (blockwise) immediately after the operator. So...
dVa{
As mentioned in the post you linked to, d]] when the cursor is placed at the beginning of the function definition will delete the whole function.

vim - I'm looking for plugin what adds tabulation inside block

This feature is available in Intelij, and works like this:
I have for example some code (| is a cursor in this example):
|
doSomething();
variable = "foo";
And I'm adding it inside block, for example if:
if (true)
{
doSomething();
variable = "foo";
|
Now after type closing bracket, plugin should add tabulation for code inside block:
if (true)
{
doSomething();
variable = "foo";
}|
I hope I explained how it should work. Is there plugin for this?
In-order to indent a block of code inside {}, you can use =%.
It's just a matter of an insert mode mapping for } to insert }, and run the command =%
It can be done with
:inoremap } }<esc>k :normal =%<cr>

Drupal 7 sort search results by relevancy

In my module I have this implementation where I have a hook_search_execute() function which can be used for rewriting/extending default Drupal search. This function calls for executeFirstPass() method and adds to the query the following $first->addExpression('SUM(i.score * t.count)', 'calculated_score');
When I'm trying to add my sorting as following $query->orderBy('calculated_score', 'ASC');, I have an error.
However if I add $query->orderBy('n.title', 'ASC'); or $query->orderBy('n.created', 'ASC'); everything is fine and is sorting as it should be.
Does anyone have any ideas why this is happens?
After all my research I came only to this crappy solution.
In modules/search/search.extender.inc file we have the following code in line 437 (depends on Drupal version).
....
// Convert scores to an expression.
$this->addExpression('SUM(' . implode(' + ', $this->scores) . ')', 'calculated_score', $this->scoresArguments);
if (count($this->getOrderBy()) == 0) {
// Add default order after adding the expression.
$this->orderBy('calculated_score', 'DESC');
}
....
I turned this code into:
....
// Convert scores to an expression.
$this->addExpression('SUM(' . implode(' + ', $this->scores) . ')', 'calculated_score', $this->scoresArguments);
if (count($this->getOrderBy()) == 0) {
if ($_GET['orderby'] == 'relevance' && $_GET['orderdir'] == 'ASC') {
$dir = 'ASC';
}
else {
$dir = 'DESC';
}
// Add default order after adding the expression.
$this->orderBy('calculated_score', $dir);
}
....
Please feel free to propose clean solution.

Resources