What's the best way to override a default key binding in spacemacs? - spacemacs

I'm using spacemacs: https://github.com/syl20bnr/spacemacs
I've tried both user hook places for overriding cmd-k to be kill-buffer rather than delete-window. However, when I restart, neither works.
(defun dotspacemacs/user-init ()
"Initialization function for user code.
It is called immediately after `dotspacemacs/init'. You are free to put any
user code."
(defun dotspacemacs/user-init ()
(global-set-key (kbd "s-k") 'kill-buffer)
)
)
(defun dotspacemacs/user-config ()
"Configuration function for user code.
This function is called at the very end of Spacemacs initialization after
layers configuration. You are free to put any user code."
(global-set-key (kbd "s-k") 'kill-buffer)
)
What's the best way to debug this?

I just noticed that you have defined defun dotspacemacs/user-init inside defun dotspacemacs/user-init.
Rather than that, I test (global-set-key (kbd "s-k") 'kill-buffer) in dotspacemacs/user-init and dotspacemacs/user-config and works it both places.
Maybe the error it's something related to your config file.
Did you have enabled osx layer?

Related

(url-retrieve) Symbol's value as variable is void

I have a function to retrieve an IP from a github repo. I get the error "Symbol's value as variable is void: response" the first time I call the function, but any subsequent calls after the first are successful. I tried adding (require 'url) but to no avail.
(defun get-ip ()
(let ((url-request-method "GET")
(url-request-extra-headers
'(("Authorization" . "token xxxxxxxxx")
("Accept" . "application/vnd.github.v3.raw"))))
(progn (url-retrieve "https://api.github.com/repos/xxxxxxx"
(lambda (status)
(progn (setq response (buffer-substring (point-min) (point-max)))
(kill-buffer (current-buffer))))
nil
'silent)
(string-match "\\([0-9]*\\.[0-9]*\\.[0-9]*\\.[0-9]*\\)" response)
(match-string 0 response))))
You should not create a global response variable. Add it to your let form instead, so that it is local to the defun. See also https://www.gnu.org/software/emacs/manual/html_node/elisp/Local-Variables.html
More fundamentally, url-retrieve is an asynchronous function: the code which attempts to set response will not yet have a buffer to operate on when url-retrieve has finished evaluating (it will continue in the background, and eventually call its callback in the lambda, but there is no guarantee that this happens during the execution of your form). The simple but slightly clunky solution is to switch to url-retrieve-synchronously and live with the fact that it could take a while.
You also need to take care to avoid clobbering the user's buffer, their position within that buffer, or the regex match history.
With these fixes, it is also natural to factor out response entirely.
(defun get-ip ()
(let ((url-request-method "GET")
(url-request-extra-headers
'(("Authorization" . "token xxxxxxxxx")
("Accept" . "application/vnd.github.v3.raw"))))
(save-match-data
(save-current-buffer
(set-buffer
(url-retrieve-synchronously "http://www.google.com/" 'silent))
(goto-char (point-min))
(if (search-forward-regexp "\\([0-9]*\\.[0-9]*\\.[0-9]*\\.[0-9]*\\)" nil t)
(match-string 0) "")))))

Jest Mocking Out Implementation

I have a file with this function
export const doSomething = (arg1, arg2) => {
SomeClass.someFunction()
OtherClass.otherFunction()
}
I've looked at how people mock stuff online, but none of them solves my case. Basically in my jest test I want to call
test('sendText to send text with the proper number', () => {
doSomething()
expect(SomeClass.someFunction).toBeCalled();
})
I don't exactly know how to do that. All the stuff I have looked online has mocked a function on the top level of the test function and then passed into the actual function they want to test which is very different from what I want to do.
SomeClass is a third party thing I imported for tracking and I just want to verify that it is called. Same for the OtherClass. How do I do that?
You would do that by mocking SomeClass.
import doSomething from './../doSomething';
import SomeClass from 'module/with/SomeClass';
jest.mock('module/with/SomeClass');
test('sendText to send text with the proper number', () => {
doSomething()
expect(SomeClass.someFunction).toBeCalled();
})
Jest should be able to determine the third party module’s structure and automatically provide mocks.

A haskell "withSubprocess" construct around a do block

I'm working through the Haskell WebDriver selenium package for testing, here.
I have this example:
import Test.WebDriver
firefoxConfig :: WDConfig
firefoxConfig = defaultConfig
main :: IO ()
main = runSession firefoxConfig $ do
openPage "http://google.com"
searchInput <- findElem ( ByCSS "input[type='text']" )
sendKeys "Hello, World!" searchInput
submit searchInput
closeSession
The getting started section makes clear that the selenium client requires a selenium server to communicate with
java -jar selenium-server-standalone-*.jar
Without it running, you get this:
ghci λ> main
*** Exception: FailedConnectionException2 "127.0.0.1" 4444 False connect: does not exist (Connection refused)
I'd like to wrap my whole test script in a function that initializes the selenium-server, records its pid, and kill(pid) after I run the session. That is, for the duration of my existing main, I'd like to call the java selenium-server into existence, but I'd like it to stop existing as soon as the call finishes.
In python I'd do this by something like defining a __enter__() and an __exit__() with other tear-down stuff, subprocess.Popen, record the id, kill it, then calling
with Browser() as b:
do_stuff
I get the sense the runSession entity is the kind of thing I would need to replicate to wrap startup and teardown like this in the sense that it takes the firefoxConfig $ do block as an argument and I want to do that, too.
However, I can't quite understand the types from interrogating runSession, how to make this kind of thing:
ghci λ> :t runSession
runSession
:: Test.WebDriver.Config.WebDriverConfig conf =>
conf -> WD a -> IO a
I think I'd be looking for some kind of withMonad I could apply to this which is applied to the do. I think the syntax would be some kind of...
import Test.WebDriver
import System.Process
firefoxConfig :: WDConfig
firefoxConfig = defaultConfig
withBrowser :: Monad a -> Monad a -- maybe this type?
withBrowser = do
r <- createProcess (proc "java -jar selenium-server-standalone-*.jar" [])
-- other magic here?
main :: IO ()
main = withBrowser $ runSession firefoxConfig $ do
openPage "http://google.com"
searchInput <- findElem ( ByCSS "input[type='text']" )
sendKeys "Hello, World!" searchInput
submit searchInput
closeSession
How would I achieve this? Is monad right at all? Is there a more Haskell idiom or strategy for this?
You basically just want bracket from https://hackage.haskell.org/package/base-4.9.0.0/docs/Control-Exception.html#v:bracket .
It allows you to specify setup and teardown IO actions to to run around a third action. It automatically handles feeding the output of the setup action into both the main and teardown actions, do your setup action should just give the PID as it's result, so the teardown action will be told what PID to kill.
Something like:
withBrowser browserAction
= bracket startSelenium killSelenium (const browserAction)
(Where I've assumed you don't want the main action to have to take an argument for the pid, so I used const to ignore it)

How do I use a macro across module files?

I have two modules in separate files within the same crate, where the crate has macro_rules enabled. I want to use the macros defined in one module in another module.
// macros.rs
#[macro_export] // or not? is ineffectual for this, afaik
macro_rules! my_macro(...)
// something.rs
use macros;
// use macros::my_macro; <-- unresolved import (for obvious reasons)
my_macro!() // <-- how?
I currently hit the compiler error "macro undefined: 'my_macro'"... which makes sense; the macro system runs before the module system. How do I work around that?
Macros within the same crate
New method (since Rust 1.32, 2019-01-17)
foo::bar!(); // works
mod foo {
macro_rules! bar {
() => ()
}
pub(crate) use bar; // <-- the trick
}
foo::bar!(); // works
With the pub use, the macro can be used and imported like any other item. And unlike the older method, this does not rely on source code order, so you can use the macro before (source code order) it has been defined.
Old method
bar!(); // Does not work! Relies on source code order!
#[macro_use]
mod foo {
macro_rules! bar {
() => ()
}
}
bar!(); // works
If you want to use the macro in the same crate, the module your macro is defined in needs the attribute #[macro_use]. Note that macros can only be used after they have been defined!
Macros across crates
Crate util
#[macro_export]
macro_rules! foo {
() => ()
}
Crate user
use util::foo;
foo!();
Note that with this method, macros always live at the top-level of a crate! So even if foo would be inside a mod bar {}, the user crate would still have to write use util::foo; and not use util::bar::foo;. By using pub use, you can export a macro from a module of your crate (in addition to it being exported at the root).
Before Rust 2018, you had to import macro from other crates by adding the attribute #[macro_use] to the extern crate util; statement. That would import all macros from util. This syntax should not be necessary anymore.
Alternative approach as of 1.32.0 (2018 edition)
Note that while the instructions from #lukas-kalbertodt are still up to date and work well, the idea of having to remember special namespacing rules for macros can be annoying for some people.
EDIT: it turns out their answer has been updated to include my suggestion, with no credit mention whatsoever 😕
On the 2018 edition and onwards, since the version 1.32.0 of Rust, there is another approach which works as well, and which has the benefit, imho, of making it easier to teach (e.g., it renders #[macro_use] obsolete). The key idea is the following:
A re-exported macro behaves as any other item (function, type, constant, etc.): it is namespaced within the module where the re-export occurs.
It can then be referred to with a fully qualified path.
It can also be locally used / brought into scope so as to refer to it in an unqualified fashion.
Example
macro_rules! macro_name { ... }
pub(crate) use macro_name; // Now classic paths Just Work™
And that's it. Quite simple, huh?
Feel free to keep reading, but only if you are not scared of information overload ;) I'll try to detail why, how and when exactly does this work.
More detailed explanation
In order to re-export (pub(...) use ...) a macro, we need to refer to it! That's where the rules from the original answer are useful: a macro can always be named within the very module where the macro definition occurs, but only after that definition.
macro_rules! my_macro { ... }
my_macro!(...); // OK
// Not OK
my_macro!(...); /* Error, no `my_macro` in scope! */
macro_rules! my_macro { ... }
Based on that, we can re-export a macro after the definition; the re-exported name, then, in and of itself, is location agnostic, as all the other global items in Rust 🙂
In the same fashion that we can do:
struct Foo {}
fn main() {
let _: Foo;
}
We can also do:
fn main() {
let _: A;
}
struct Foo {}
use Foo as A;
The same applies to other items, such as functions, but also to macros!
fn main() {
a!();
}
macro_rules! foo { ... } // foo is only nameable *from now on*
use foo as a; // but `a` is now visible all around the module scope!
And it turns out that we can write use foo as foo;, or the common use foo; shorthand, and it still works.
The only question remaining is: pub(crate) or pub?
For #[macro_export]-ed macros, you can use whatever privacy you want; usually pub.
For the other macro_rules! macros, you cannot go above pub(crate).
Detailed examples
For a non-#[macro_export]ed macro
mod foo {
use super::example::my_macro;
my_macro!(...); // OK
}
mod example {
macro_rules! my_macro { ... }
pub(crate) use my_macro;
}
example::my_macro!(...); // OK
For a #[macro_export]-ed macro
Applying #[macro_export] on a macro definition makes it visible after the very module where it is defined (so as to be consistent with the behavior of non-#[macro_export]ed macros), but it also puts the macro at the root of the crate (where the macro is defined), in an absolute path fashion.
This means that a pub use macro_name; right after the macro definition, or a pub use crate::macro_name; in any module of that crate will work.
Note: in order for the re-export not to collide with the "exported at the root of the crate" mechanic, it cannot be done at the root of the crate itself.
pub mod example {
#[macro_export] // macro nameable at `crate::my_macro`
macro_rules! my_macro { ... }
pub use my_macro; // macro nameable at `crate::example::my_macro`
}
pub mod foo {
pub use crate::my_macro; // macro nameable at `crate::foo::my_macro`
}
When using the pub / pub(crate) use macro_name;, be aware that given how namespaces work in Rust, you may also be re-exporting constants / functions or types / modules. This also causes problems with globally available macros such as #[test], #[allow(...)], #[warn(...)], etc.
In order to solve these issues, remember you can rename an item when re-exporting it:
macro_rules! __test__ { ... }
pub(crate) use __test__ as test; // OK
macro_rules! __warn__ { ... }
pub(crate) use __warn__ as warn; // OK
Also, some false positive lints may fire:
from the trigger-happy clippy tool, when this trick is done in any fashion;
from rustc itself, when this is done on a macro_rules! definition that happens inside a function's body: https://github.com/rust-lang/rust/issues/78894
This answer is outdated as of Rust 1.1.0-stable.
You need to add #![macro_escape] at the top of macros.rs and include it using mod macros; as mentioned in the Macros Guide.
$ cat macros.rs
#![macro_escape]
#[macro_export]
macro_rules! my_macro {
() => { println!("hi"); }
}
$ cat something.rs
#![feature(macro_rules)]
mod macros;
fn main() {
my_macro!();
}
$ rustc something.rs
$ ./something
hi
For future reference,
$ rustc -v
rustc 0.13.0-dev (2790505c1 2014-11-03 14:17:26 +0000)
Adding #![macro_use] to the top of your file containing macros will cause all macros to be pulled into main.rs.
For example, let's assume this file is called node.rs:
#![macro_use]
macro_rules! test {
() => { println!("Nuts"); }
}
macro_rules! best {
() => { println!("Run"); }
}
pub fn fun_times() {
println!("Is it really?");
}
Your main.rs would look sometime like the following:
mod node; //We're using node.rs
mod toad; //Also using toad.rs
fn main() {
test!();
best!();
toad::a_thing();
}
Finally let's say you have a file called toad.rs that also requires these macros:
use node; //Notice this is 'use' not 'mod'
pub fn a_thing() {
test!();
node::fun_times();
}
Notice that once files are pulled into main.rs with mod, the rest of your files have access to them through the use keyword.
I have came across the same problem in Rust 1.44.1, and this solution works for later versions (known working for Rust 1.7).
Say you have a new project as:
src/
main.rs
memory.rs
chunk.rs
In main.rs, you need to annotate that you are importing macros from the source, otherwise, it will not do for you.
#[macro_use]
mod memory;
mod chunk;
fn main() {
println!("Hello, world!");
}
So in memory.rs you can define the macros, and you don't need annotations:
macro_rules! grow_capacity {
( $x:expr ) => {
{
if $x < 8 { 8 } else { $x * 2 }
}
};
}
Finally you can use it in chunk.rs, and you don't need to include the macro here, because it's done in main.rs:
grow_capacity!(8);
The upvoted answer caused confusion for me, with this doc by example, it would be helpful too.
Note: This solution does work, but do note as #ineiti highlighted in the comments, the order u declare the mods in the main.rs/lib.rs matters, all mods declared after the macros mod declaration try to invoke the macro will fail.

How to not encapsulate Coffeescript

I don't know whether all coffeescript compilers wrap their scripts in anonymous functions, but that's what I see Rails doing. How can I disable this encapsulation?
I want to put several initializing functions in a single coffeescript file, then call one of them from an on-page <script> tag (so that each page calls a different initializer). This can't be if the initializing functions are encapsulated.
Coffeescript initializer functions:
initializerA = -> console.log 'foo'
initializerB = -> console.log 'bar'
On-page code:
<script>$(document).ready(initializerA)</script>
Sys: coffee-rails 3.2.1, Rails 3.2.3, Ruby 1.9.3
Coffeescript documentation says that all script will be wrapped in an anonymous function for the sake of encapsulation/safety. To make something accessible within the global scope do the following:
window.myvar = myvar
You can put several into a single file by doing something like this:
((Demo, $, undefined_) ->
Demo.utils = Demo.utils or {}
Demo.utils.bacon = (->
alert("bacon called")
)()
Demo.utils.eggs = (->
alert("eggs called")
)()
) window.Demo = window.Demo or {}, jQuery
Then in your page just call the appropriate method:
Demo.utils.bacon();
A good explanation of this pattern can be found here.