In ST2 snippets, can $TM_CURRENT_WORD be overwritten? - sublimetext2

For context:
I'm writing up a snippet for Python to quickly cast a variable, like so: variable_foo to str(variable_foo).
If I use $SELECTION, it works fine. But if I use $TM_CURRENT_WORD, it inserts the replacement value into the middle of the variable text, like this: variastr(variable_foo)ble_foo.
I could just keep using $SELECTION, but I'd prefer the added ease of not having to select the variable first with Ctrl+D that $TM_CURRENT_WORD would provide. Is there something I'm overlooking which makes this possible, or is $SELECTION the only way to go?
For reference, the currently functional version of the snippet: ${1:type}($SELECTION)${0}
And an alternate version: ${1:type}${SELECTION/^.*/\($0\)/g}${0}

I believe that is the intended behavior. You can use a plugin to get the behavior you want though.
import sublime_plugin
class ExpandInsertSnippetCommand(sublime_plugin.TextCommand):
def run(self, edit, contents=None, name=None):
cursors = self.view.sel()
new_cursors = []
for cursor in cursors:
new_cursors.append(self.view.word(cursor))
cursors.clear()
for cursor in new_cursors:
cursors.add(cursor)
self.view.run_command("insert_snippet", {"contents": contents, "name": name})
Rather than using the command "insert_snippet" for whatever binding you have, use "expand_insert_snippet".

Related

In Jupyter Notebook, how to show output within function without using print

I want the code to show "123" without using built-in print function, but it does not. What should I do?
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
def myf():
"123"
myf()
If I got right, you just want to print the "123", right?
def myf():
print("123")
myf()
If you want to receive the "123" as a result of your def, would be something like this :
def myf():
x = "123"
return x
Z = myf()
print (Z)
"123"
You can use the display function:
Although, I don't think that's what you want. The settings you're enabling:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
Only apply to returned values; that's why you don't see it printed. If you return the value and call the function a few times, you'll see them:
I don't have a direct answer to this, but I have some pointers to the problem.
Normal output is written either in stdout or stderr by some Python provided method. However, when utilizing the IPython feature of checking a value by using either direct value ("123") or variable (first line a = "123", second line a). This output stream can not be captured with simple %%capture magic in Jupyter; the output vanishes in the scope of the function definition.
I do agree that this would be useful; in machine learning we sometimes use dependency inversion like structures, where we modify functions instead of line-by-line code, where debugging gets hard since we can not capture some of the outputs without injecting a print or display. However, not using display might have unwanted and hard to predict consequences as some of the models can be rather verbose in what they write. However, capturing some outputs without extra prints and displays from user defined cells might be nice feature.
Notice that sometimes print doesn't work, but display does. Print might not always understand how our utilities in pandas or matplotlib works.

Klaxon's JSON pretty printing outputs "["result"]"

val time = json.lookup<String?>("query.results.channel.title").toJsonString(true)
outputs
["Yahoo! Weather - Nome,AK,US"]
is there a way to get the output without the brackets and the quotation marks ?
I guess that
.replace("[\"","").replace("\"]","")
isn't the best way
The brackets are contained in the default implementation (see https://github.com/cbeust/klaxon/blob/master/src/main/kotlin/com/beust/klaxon/DSL.kt at the very bottom function appendJsonStringImpl)
So it is not possible, to remove them by configuration.
It might work if you write an extension function for this particular class, but i guess this is not what you want.
So this is currently not possible without writing your own extension(-function).

Why does a function name have to be specified in a use statement?

In perl, sometimes it is necessary to specify the function name in the use statement.
For example:
use Data::DPath ('dpath');
will work but
use Data::DPath;
won't.
Other modules don't need the function names specified, for example:
use WWW::Mechanize;
Why?
Each module chooses what functions it exports by default. Some choose to export no functions by default at all, you have to ask for them. There's a few good reasons to do this, and one bad one.
If you're a class like WWW::Mechanize, then you don't need to export any functions. Everything is a class or object method. my $mech = WWW::Mechanize->new.
If you're a pragma like strict then there are no functions nor methods, it does its work simply by being loaded.
Some modules export waaay too many functions by default. An example is Test::Deep which exports...
all any array array_each arrayelementsonly arraylength arraylengthonly bag blessed bool cmp_bag cmp_deeply cmp_methods cmp_set code eq_deeply hash
hash_each hashkeys hashkeysonly ignore Isa isa listmethods methods noclass
none noneof num obj_isa re reftype regexpmatches regexponly regexpref
regexprefonly scalarrefonly scalref set shallow str subbagof subhashof
subsetof superbagof superhashof supersetof useclass
The problem comes when another module tries to export the same functions, or if you write a function with the same name. Then they clash and you get mysterious warnings.
$ cat ~/tmp/test.plx
use Test::Deep;
use List::Util qw(all);
$ perl -w ~/tmp/test.plx
Subroutine main::all redefined at /Users/schwern/perl5/perlbrew/perls/perl-5.20.2/lib/5.20.2/Exporter.pm line 66.
at /Users/schwern/tmp/test.plx line 2.
Prototype mismatch: sub main::all: none vs (&#) at /Users/schwern/perl5/perlbrew/perls/perl-5.20.2/lib/5.20.2/Exporter.pm line 66.
at /Users/schwern/tmp/test.plx line 2.
For this reason, exporting lots of functions is discouraged. For example, the Exporter documentation advises...
Do not export method names!
Do not export anything else by default without a good reason!
Exports pollute the namespace of the module user. If you must export try to use #EXPORT_OK in preference to #EXPORT and avoid short or common symbol names to reduce the risk of name clashes.
Unfortunately, some modules take this too far. Data::DPath is a good example. It has a really clear main function, dpath(), which it should export by default. Otherwise it's basically useless.
You can always turn off exporting with use Some::Module ();.
The reason is that some modules simply contain functions in them and they may or may not have chosen to export them by default, and that means they may need to be explicitly imported by the script to access directly or use a fully qualified name to access them. For example:
# in some script
use SomeModule;
# ...
SomeModule::some_function(...);
or
use SomeModule ('some_function');
# ...
some_function(...);
This can be the case if the module was not intended to be used in an object-oriented way, i.e. where no classes have been defined and lines such as my $obj = SomeModule->new() wouldn't work.
If the module has defined content in the EXPORT_OK array, it means that the client code will only get access to it if it "asks for it", rather than "automatically" when it's actually present in the EXPORT array.
Some modules automatically export their content by means of the #EXPORT array. This question and the Exporter docs have more detail on this.
Without you actually posting an MCVE, it's difficult to know what you've done in your Funcs.pm module that may be allowing you to import everything without using EXPORT and EXPORT_OK arrays. Perhaps you did not include the package Funcs; line in your module, as #JonathanLeffler suggested in the comments. Perhaps you did something else. Perl is one of those languages where people pride themselves in the TMTOWTDI mantra, often to a detrimental/counter-productive level, IMHO.
The 2nd example you presented is very different and fairly straightforward. When you have something like:
use WWW::Mechanize;
my $mech = new WWW::Mechanize;
$mech->get("http://www.google.com");
you're simply instantiating an object of type WWW::Mechanize and calling an instance method, called get, on it. There's no need to import an object's methods because the methods are part of the object itself. Modules looking to have an OOP approach are not meant to export anything. They're different situations.

PhpStorm to support registry pattern

In my code I use Registry pattern like that:
$data = Registry::get('classA')->methodOfClassA($param1, param2);
Registry class stores instances of some classes in internal array, so in any place of my code I can call class methods for handy functions like in line above.
But, the problem is that PHP-storm does not autocomplete when I type:
Registry::get('classA')->
And, that is worse, it does not go to declaration of the method "methodOfClassA" when I hover mouse cursor holding mac-button (analogue of control-button on windows)
I suppose, that IDE AI is not so good to recognise cases like that, but maybe there is some tricks to do that in a hard way? hardcoding classes+method names in some file and so on...
At least, I want it to understand to go to method declaration when I click method name...
Any advices?
http://confluence.jetbrains.com/display/PhpStorm/PhpStorm+Advanced+Metadata
This link describes it all -- it is already used by multiple projects/frameworks/code-generation helpers, like Magento, for example (some other can be found mentioned in the comments of the actual ticket).
For other situations you may want to check out DynamicReturnTypePlugin plugin (Settings | Plugins | Browse repositories...) -- have not tried myself and therefore cannot comment how good/fast/laggy it is.
You can always indicate the variable type in two steps:
/** #var $foo MyClass */
$foo = $this->get('MyClass');
$foo->bar(); // autocomplete works

Equivalent of abbrev-mode but for functions?

I'm a big fan of abbrev-mode and I'd like something a bit similar: you start typing and as soon as you enter some punctation (or just a space would be enough) it invokes a function (if I type space after a special abbreviation, of course, just like abbrev-mode does).
I definitely do NOT want to execute some function every single time I hit space...
So instead of expanding the abbreviation using abbrev-mode, it would run a function of my choice.
Of course it needs to be compatible with abbrev-mode, which I use all the time.
How can I get this behavior?
One approach could be to use pre-abbrev-expand-hook. I don't use abbrev mode myself, but it rather sounds as if you could re-use the abbrev mode machinery this way, and simply define some 'abbreviations' which expand to themselves (or to nothing?), and then you catch them in that hook and take whatever action you wish to.
The expand library is apparently related, and that provides expand-expand-hook, which may be another alternative?
edit: Whoops; pre-abbrev-expand-hook is obsolete since 23.1
abbrev-expand-functions is the correct variable to use:
Wrapper hook around `expand-abbrev'.
The functions on this special hook are called with one argument:
a function that performs the abbrev expansion. It should return
the abbrev symbol if expansion took place.
See M-x find-function RET expand-abbrev RET for the code, and you'll also want to read C-h f with-wrapper-hook RET to understand how this hook is used.
EDIT:
Your revised question adds some key details that my answer didn't address. phils has provided one way to approach this issue. Another would be to use yasnippet . You can include arbitrary lisp code in your snippet templates, so you could do something like this:
# -*- mode: snippet -*-
# name: foobars
# key: fbf
# binding: direct-keybinding
# --
`(foo-bar-for-the-win)`
You'd need to ensure your function didn't return anything, or it would be inserted in the buffer. I don't use abbrev-mode, so I don't know if this would introduce conflicts. yas/snippet takes a bit of experimenting to get it running, but it's pretty handy once you get it set up.
Original answer:
You can bind space to any function you like. You could bind all of the punctuation keys to the same function, or to different functions.
(define-key your-mode-map " " 'your-choice-function)
You probably want to do this within a custom mode map, so you can return to normal behaviour when you switch modes. Globally setting space to anything but self-insert would be unhelpful.
Every abbrev is composed of several elements. Among the main elements are the name (e.g. "fbf"), the expansion (any string you like), and the hook (a function that gets called). In your case it sounds like you want the expansion to be the empty string and simply specify your foo-bar-for-the-win as the hook.