How can I properly wrap my Elisp docstrings that involve keybinds? - formatting

Emacs Lisp has a facility for adapting documentation to the user's current key bindings, by referencing the command name in the docstring and letting Emacs dynamically insert the current key binding for that command when the user requests the documention. However, when I use this in a docstring that mentions many key bindings, it completely messes up the line wrapping. Take this example from my package:
(substitute-command-keys
"Fix ido behavior when `require-match' is non-nil.
Standard ido will allow
\\<ido-common-completion-map>\\[ido-select-text] to exit with an
incomplete completion even when `require-match' is non-nil.
Ordinary completion does not allow this. In ordinary completion,
\\[ido-exit-minibuffer] on an incomplete match is equivalent to
\\[ido-complete], and \\[ido-select-text] selects the first
match. Since \\[ido-exit-minibuffer] in ido already selects the
first match, this advice sets up \\[ido-select-text] to be
equivalent to \\[ido-complete] in the same situation.
This advice only activates if the current ido completion was
called through ido-cr+.")
With the standard bindings, the docstring displayed to the user looks like this:
Fix ido behavior when ‘require-match’ is non-nil.
Standard ido will allow
C-j to exit with an
incomplete completion even when ‘require-match’ is non-nil.
Ordinary completion does not allow this. In ordinary completion,
RET on an incomplete match is equivalent to
TAB, and C-j selects the first
match. Since RET in ido already selects the
first match, this advice sets up C-j to be
equivalent to TAB in the same situation.
This advice only activates if the current ido completion was
called through ido-cr+.
which looks atrocious and borderline unreadable due to the random variations in line length in the middle paragraph. Here's what it should actually look like:
Fix ido behavior when ‘require-match’ is non-nil.
Standard ido will allow C-j to exit with an incomplete completion
even when ‘require-match’ is non-nil. Ordinary completion does
not allow this. In ordinary completion, RET on an incomplete
match is equivalent to TAB, and C-j selects the first match.
Since RET in ido already selects the first match, this advice
sets up C-j to be equivalent to TAB in the same situation.
This advice only activates if the current ido completion was
called through ido-cr+.
Obviously, the problem is that the special sequences recognized by substitute-command-keys are not the same length as the strings that replace them, which throws off the line wrapping in my source code. Is there some way to force emacs to re-compute the paragraph wrapping in my docstring after running substitute-command-keys and before displaying it to the user?

You could use visual-line-mode together with adaptive-wrap. This way you can continue logical lines and don't split them yourself.

Is there some way to force emacs to re-compute the paragraph wrapping in my docstring after running substitute-command-keys and before displaying it to the user?
I don't believe so (and in general it would undoubtedly be problematic), but if you expect the short keybindings to be displayed (rather than M-x name-of-command) then you can use longer lines and trust they will be rendered as shorter lines. If the assumption is wrong, then you'll render lines which are longer than you wanted (rather than the current situation of lines which are shorter than you wanted).
Note that you don't need to exceed your regular fill column in your source code to do this -- you can break lines in the docstring source with an "escaped newline" (backslash+newline), as the reader omits these sequences from the string (refer to C-hig (elisp)Syntax for Strings).
E.g.:
(substitute-command-keys
"Fix ido behavior when `require-match' is non-nil.
Standard ido will allow \\<ido-common-completion-map>\
\\[ido-select-text] to exit with an incomplete completion
even when `require-match' is non-nil. Ordinary completion does
not allow this. In ordinary completion, \\[ido-exit-minibuffer]\
on an incomplete match
is equivalent to \\[ido-complete], and \\[ido-select-text]\
selects the first match. Since \\[ido-exit-minibuffer]
in ido already selects the first match, this advice sets up\
\\[ido-select-text] to
be equivalent to \\[ido-complete] in the same situation.
This advice only activates if the current ido completion was
called through ido-cr+.")
renders:
"Fix ido behavior when `require-match' is non-nil.
Standard ido will allow C-j to exit with an incomplete completion
even when `require-match' is non-nil. Ordinary completion does
not allow this. In ordinary completion, RET on an incomplete match
is equivalent to TAB, and C-j selects the first match. Since RET
in ido already selects the first match, this advice sets up C-j to
be equivalent to TAB in the same situation.
This advice only activates if the current ido completion was
called through ido-cr+."

Related

VIM equivalent of IntelliJ's expand/shrink selection?

How would one achieve the same result. I believe the keybinding for macOS Intellij is op+up/down and on windows it is alt+w/d.
Essentially the function highlights the current word, then, with successive presses, expands out to the full string/line/area in-between parenthesis/further out to the next set of parenthesis. Very useful for developing in LISP.
The closest I've gotten is this: https://vi.stackexchange.com/a/19028
Try this plug in: https://github.com/terryma/vim-expand-region
It expands selections based on Vim’s text objects.
Well this may seem comfortable but does not correspondent with the internal logic of vim itself.
See, in vim everything you enter is like a sentence. va{ for example: there is a verb v -> visually select and an object (or movement) { -> paragraph. In this case there is also a modifier a around. You can exchange stuff in this sentence and it will still work vaw, dil, cB and so on. The power of vim is greatly based on that concept.
Of course you can write a function that does vaw first, then S-v and lastly va{ but that will only work with visual selection. It will not work with c or d or anything. So I will recommend to get used to use different keys for different actions.
The visual selection is mostly not needed anyway. Change a paragraph? directly use ca} and so on.
I have found that VI/VA + WOBO (as many times as you need to expand) works similarly. Not as fast but its the same concept and you can even expand/shrink asymmetrically based on your WO's and BO's (Or OW's and OB's depending on how you look at it)

Where is contains( Junction) defined?

This code works:
(3,6...66).contains( 9|21 ).say # OUTPUT: «any(True, True)␤»
And returns a Junction. It's also tested, but not documented.
The problem is I can't find its implementation anywhere. The Str code, which is also called from Cool, never returns a Junction (it does not take a Junction, either). There are no other methods contain in source.
Since it's autothreaded, it's probably specially defined somewhere. I have no idea where, though. Any help?
TL;DR Junction autothreading is handled by a single central mechanism. I have a go at explaining it below.
(The body of your question starts with you falling into a trap, one I think you documented a year or two back. It seems pretty irrelevant to what you're really asking but I cover that too.)
How junctions get handled
Where is contains( Junction) defined? ... The problem is I can't find [the Junctional] implementation anywhere. ... Since it's autothreaded, it's probably specially defined somewhere.
Yes. There's a generic mechanism that automatically applies autothreading to all P6 routines (methods, operators etc.) that don't have signatures that explicitly control what happens with Junction arguments.
Only a tiny handful of built in routines have these explicit Junction handling signatures -- print is perhaps the most notable. The same is true of user defined routines.
.contains does not have any special handling. So it is handled automatically by the generic mechanism.
Perhaps the section The magic of Junctions of my answer to an earlier SO Filtering elements matching two regexes will be helpful as a high level description of the low level details that follow below. Just substitute your 9|21 for the foo & bar in that SO, and your .contains for the grep, and it hopefully makes sense.
Spelunking the code
I'll focus on methods. Other routines are handled in a similar fashion.
method AUTOTHREAD does the work for full P6 methods.
This is setup in this code that sets up handling for both nqp and full P6 code.
The above linked P6 setup code in turn calls setup_junction_fallback.
When a method call occurs in a user's program, it involves calling find_method (modulo cache hits as explained in the comment above that code; note that the use of the word "fallback" in that comment is about a cache miss -- which is technically unrelated to the other fallback mechanisms evident in this code we're spelunking thru).
The bit of code near the end of this find_method handles (non-cache-miss) fallbacks.
Which arrives at find_method_fallback which starts off with the actual junction handling stuff.
A trap
This code works:
(3,6...66).contains( 9|21 ).say # OUTPUT: «any(True, True)␤»
It "works" to the degree this does too:
(3,6...66).contains( 2 | '9 1' ).say # OUTPUT: «any(True, True)␤»
See Lists become strings, so beware .contains() and/or discussion of the underlying issues such as pmichaud's comment.
Routines like print, put, infix ~, and .contains are string routines. That means they coerce their arguments to Str. By default the .Str coercion of a listy value is its elements separated by spaces:
put 3,6...18; # 3 6 9 12 15 18
put (3,6...18).contains: '9 1'; # True
It's also tested
Presumably you mean the two tests with a *.contains argument passed to classify:
my $m := #l.classify: *.contains: any 'a'..'f';
my $s := classify *.contains( any 'a'..'f'), #l;
Routines like classify are list routines. While some list routines do a single operation on their list argument/invocant, eg push, most of them, including classify, iterate over their list doing something with/to each element within the list.
Given a sequence invocant/argument, classify will iterate it and pass each element to the test, in this case a *.contains.
The latter will then coerce individual elements to Str. This is a fundamental difference compared to your example which coerces a sequence to Str in one go.

Pharo: customizing smart characters

The checkbox "Smart Characters" in "Code Completion" section of Settings Browser does (at least) two things:
1) It doubles some characters when typed: ', ", (, [, {
2) It enables that I can select a piece of code, press ( (i.e. Shift+9), and the selected code becomes surrounded by parentheses: (). I also can remove parentheses by pressing ( again. I also can do this with [] by pressing [ and with {} by pressing {, i.e. Shift+[.
I do not like the first of these things so I want to disable it, but I like the second thing and want to keep it. How can I achieve this? Turning off the checkbox will disable both.
P.S. I know that when the checkbox is off, adding/removing parentheses works by Cmd+Shift+9 (which is less convenient than Shift+9) and that Cmd+[ works for [], although I do not know any working shortcut for adding/removing {} when the checkbox is off.
The setting is called "Smart Characters", which should give you a clue as to where to look. Open a Finder, type in smartCharacters, and hit Enter. You should see some partial matches as well as an exact match for NECController and NECPreferences class (and the former just calls the latter). If you investigate the classes involved a bit, you'll see that smartCharacters stores a boolean, and that smartCharactersMapping returns a dictionary mapping some characters to their "counterparts", i.e. $[ to $] and so on. Now look at senders of smartCharactersMapping, and you'll see where it's being called from.
The caller you're most likely interested in would be NECController>>smartCharacterWithEvent. So put a breakpoint in that very ugly method to see what it does. You don't care about the first two cases (the editor having a selection and there not being a smart mapping), since you want to prevent the second matching character from being inserted. So the interesting bit for you is this bit:
self newSmartCharacterInsertionStringForLeft: char right: opposite
The method only has one implementor and that one sender, so it should be safe to comment out the original method and just return the "left" character, i.e.:
newSmartCharacterInsertionStringForLeft: left right: right
^String with: left
In other words, instead of creating a string with the left and right characters, and possibly spaces between them, just return a new string with the single character you typed. Might not be the most elegant way of solving this, but it should work, and should show you how to solve similar problems in the future.
(Ideally, you'll find a better solution, post it here as an alternate answer, and contribute it to the Pharo codebase - Pharo is open source, after all.)

naming a function that exhibits "set if not equal" behavior

This might be an odd question, but I'm looking for a word to use in a function name. I'm normally good at coming up with succinct, meaningful function names, but this one has me stumped so I thought I'd appeal for help.
The function will take some desired state as an argument and compare it to the current state. If no change is needed, the function will exit normally without doing anything. Otherwise, the function will take some action to achieve the desired state.
For example, if wanted to make sure the front door was closed, i might say:
my_house.<something>_front_door('closed')
What word or term should use in place of the something? I'd like it to be short, readable, and minimize the astonishment factor.
A couple clarifying points...
I would want someone calling the function to intuitively know they didn't need to wrap the function an 'if' that checks the current state. For example, this would be bad:
if my_house.front_door_is_open():
my_house.<something>_front_door('closed')
Also, they should know that the function won't throw an exception if the desired state matches the current state. So this should never happen:
try:
my_house.<something>_front_door('closed')
except DoorWasAlreadyClosedException:
pass
Here are some options I've considered:
my_house.set_front_door('closed')
my_house.setne_front_door('closed') # ne=not equal, from the setne x86 instruction
my_house.ensure_front_door('closed')
my_house.configure_front_door('closed')
my_house.update_front_door('closed')
my_house.make_front_door('closed')
my_house.remediate_front_door('closed')
And I'm open to other forms, but most I've thought of don't improve readability. Such as...
my_house.ensure_front_door_is('closed')
my_house.conditionally_update_front_door('closed')
my_house.change_front_door_if_needed('closed')
Thanks for any input!
I would use "ensure" as its succinct, descriptive and to the point:
EnsureCustomerExists(CustomerID)
EnsureDoorState(DoorStates.Closed)
EnsureUserInterface(GUIStates.Disabled)
Interesting question!
From the info that you have supplied, it seems to me that setstate (or simply set, if you are setting other things than states) would be fine, though ensure is good if you want to really emphasize the redundancy of an if.
To me it is however perfectly intuitive that setting a state does not throw an exception, or require an if. Think of setting the state of any other variable:
In C:
int i;
i = 5; // Would you expect this to throw an exception if i was already 5?
// Would you write
if (i != 5)
i = 5;
// ?
Also it only takes about one sentence to document this behaviour:
The function does nothing if the
current state equals the requested
state.
EDIT: Actually, thinking about it, if it is really important to you (for some reason) that the user is not confused about this, I would in fact pick ensure (or some other non-standard name). Why? Because as a user, a name like that would make me scratch my head a bit and look up the documentation ("This is more than just an ordinary set-function, apparently").
EDIT 2: Only you know how you design your programs, and which function name fits in best. From what you are saying, it seems like your setting functions sometimes throw exceptions, and you need to name a setting function that doesn't - e.g. set_missile_target. If that is the case, I think you should consider the set_if, set_when, set_cond or cond_set names. Which one would kind of depend on the rest of your code. I would also add that one line of documentation (or two, if you're generous), which clarifies the whole thing.
For example:
// Sets missile target if current target is not already the requested target,
// in which case it does nothing. No exceptions are thrown.
function cond_set_missile_target ()
or function cond_set_MissileTarget ()
or function condSet_MissileTarget ()
or function condSetMissileTarget ()
ensure is not so bad, but to me it implies only that there is additional logic required to set the state (e.g. multiple states tied together, or other complications). It helps to make the user avoid adding unnecessary ifs, but it does not help much with the exception issue. I would expect an ensure function to throw an exception sooner than a set function, since the ensure function clearly has more responsibilities for, well, ensuring that this setting operation is in fact done right.
I'd go for ensure for the function you describe. I'd also use camelCase, but I suppose you may be in a language that prefers underscores.
You could always document (shock!) your API so that others don't make the mistakes you describe.

Working with Seaside continuations

How do I get a BlockClosure in Squeak (I want to use BlockClosure>>callCC)?
When I write [#foo] that is a BlockContext, what's the deal?
Update: I have worked out that BlockClosure is a thing mainly of new compiler.
Instead how do I work with seaside Continuations? I'm having problems, and any examples would be appreciated.
Further update: The purpose of this is not to use seaside (at least not directly) but rather to write traversals and other such things in a way that is easier than rolling my own state-tracking iterators.
Normally, with Seaside, you never have to deal with Continuations yourself at all.
You just use #call: and #answer: from within your components.
If you're trying to do something else with Continuation other than writing a Seaside application, take a look at WAComponent>>call: for an example of usage.
Or try this. Open a Transcript window. Now, in a Workspace, select all of this code at once and Do-it:
continuation := nil.
result := Continuation currentDo: [:cc |
"store the continuation, cc, somewhere for later use"
continuation := cc.
1 ].
Transcript show: result.
You should see 1 displayed in the Transcript window. Now, in the workspace, do:
continuation value: 2
and then:
continuation value: 3
You should see each value you pass to continuation displayed in the Transcript because each value you pass to #value: causes the context of the continuation to be restored and the new value assigned to result.
Hopefully that helps...