I have strings in a namelist, that correspond to variables as well as field names in the application.
The function should read strings from namelist, add an 'f' to get field_names, and then put variable values in corresponding fields.
I tried following code, that does not give any error, but also does not work:
namelist: ["var1" "var2"]
var1: 5
var2: 10
process: [
repeat i length? namelist [
(to-set-path compose rejoin [namelist/:i "f/text"] (to-word namelist/:i))
]
]
lay: layout [
text "Values to appear here: "
var1f: field "a"
var2f: field "b"
button "Click" [do process]
]
view lay
As a general point: it is easy to turn strings into WORD!s (e.g. to-word "foo"). However, it can be tough to magically make that WORD! reference be bound to "the variable you meant". The wily reasons for this have to do with the fact that there is no scope. See:
Is there a overall explanation about definitional scoping in Rebol and Red
So what you are trying to do is going to be a little dodgy regardless. There are better ways. But to try to avoid un-asking the question, I'll explain what's happening here and how to fix it in the style you were attempting.
corrected version is for instructional purposes only. please do this another way.
compose rejoin [namelist/:i "f/text"]
REJOIN is applied to blocks, and merges the contents, with a result type loosely based on the first element. (It's a questionable operation, but historically popular in Rebol code.)
Since namelist/:i is a string, your REJOIN will produce a string...and this string will wind up being passed to COMPOSE. But COMPOSE is meant to be applied to BLOCK!s...and searches for parenthesized groups inside of it, evaluating them while leaving the rest of the code alone. It's a kind of templating system for blocks, with no effect on other kinds of input...so you'll get the same string out.
TO-SET-PATH is thus being fed a STRING! (e.g. "var1f/text"). I didn't even know that path conversion accepted strings. I find the behavior of this operation to be puzzling, because it apparently LOADs the string and then makes it the singular element of a length 1 SET-PATH!.
>> p: to-set-path "foo/bar"
== foo/bar: ;-- huh? really, did that work?
>> type? p
== set-path! ;-- ok, good, I guess.
>> length? p
== 1 ;-- wait, what?
>> type? first p
== path! ;-- a PATH! inside a SET-PATH!...?
>> length? first p
== 2
>> type? first first p
== word!
>> foo: 10
>> get first first p
== 10 ;-- well, at least it's bound
That's not making the kind of SET-PATH! you want; you want a SET-PATH! with 2 WORD! elements. Converting a BLOCK! to a SET-PATH! would be a way of doing this.
to-set-path compose [(load rejoin [namelist/:i "f"]) text]
Now we see COMPOSE being used correctly, where it will run the evaluation inside the parentheses and leave the text word alone. This produces a block with 2 elements in it, which is easily converted to a SET-PATH!. I'm using LOAD instead of TO-WORD to take care of some of the "magic" of connecting to an actual variable that plain word conversion would not do. But it's just a workaround--not a sure thing, and won't always be the answer to the problem.
But producing a SET-PATH! doesn't mean it runs. If I say:
s: to-set-word "x"
probe type? s
No SET-WORD! is executed, it's merely generated. And in this case, stored in the variable s. But if I hadn't stored it in a variable, the evaluation product would have just been thrown out...the way 2 is simply thrown out if I write 1 + 1 print "hi". To execute the SET-PATH!, you need to put it in a context where it will be composed into source and evaluated.
(Note: Ren-C has a primitive called EVAL which can do this on the fly, e.g. eval (quote x:) 10 will assign 10 to x.)
But in Red you'll need to do something like this:
namelist: ["var1" "var2"]
var1: 5
var2: 10
process: [
repeat i length? namelist [
do probe compose [
(to-set-path compose [(load rejoin [namelist/:i "f"]) text])
to-string
(load namelist/:i)
]
]
]
lay: layout [
text "Values to appear here: "
var1f: field "a"
var2f: field "b"
button "Click" [do process]
]
view lay
Now your outer COMPOSE is building an 3-element block, where the first element will be a SET-PATH!, the second a WORD! that was literally left alone to convert your integer to a string, and the third a WORD! that will be evaluated to the relevant integer. The DO of that block will have the assignment effect.
I changed your to-word namelist/:i to load namelist/:i. Again, for the reason I mentioned...TO-WORD alone doesn't put on a "binding".
I left a PROBE in there so you could see what is built and executed:
[var1f/text: to-string var1]
[var2f/text: to-string var2]
PROBE is a very helpful tool, which outputs its argument but also passes it through. You can insert it at various points in your code to get a better understanding of what's going on.
(Note: If you're wondering why I don't suggest writing a narrow EVAL-2 helper operation that only works for SET-PATH!, it's because such a thing exists with a better name. It's called SET. Try set (quote x:) 10 then print x. In fact, variants of this is how you'd actually want to do things... obj: make object! [a: 10] then set (in obj 'a) 20 then print obj/a. As I said, there's a lot better ways to go about what you're doing, but I tried to stay focused on doing it the-way-you-were-trying.)
This doesn't directly answer your question, though seems to address the problem you're facing. It uses the face/extra field to associate the fields to your value list:
namelist: [var1 var2]
var1: 5
var2: 10
process: function [][
foreach face lay/pane [
if find namelist face/extra [
face/text: form get to word! face/extra
]
]
]
lay: layout [
text "Values to appear here: "
field "a" extra 'var1
field "b" extra 'var2
button "Click" [process]
]
view lay
The only wrinkles are: it applies get to the words as they are set in the View spec—they need to be within the same context as the values you're working on, and—you can't get a lit-word! so have to change it to word! before getting.
Another approach if you want to contain your values in a map:
values: #(foo: 5 bar: 10)
process: function [container [object!]][
foreach face container/pane [
if find values face/extra [
face/text: form select values face/extra
]
]
]
view [
text "Values to appear here: "
field "a" extra 'foo
field "b" extra 'bar
button "Click" [process face/parent]
]
Step 1: refactor
Here is your code reformatted and print (1) statements added:
namelist: ["var1" "var2"]
var1: 5
var2: 10
process: [
print "process: start" ; (1)
repeat i length? namelist [
(to-set-path compose rejoin [namelist/:i "f/text"] (to-word namelist/:i))
]
print "process: end" ; (1)
]
lay: layout [
text "Values to appear here: "
var1f: field "a"
var2f: field "b"
button "Click" [do process]
]
view lay
When I run this in the console and press "Click", it gives the following:
process: start
process: end
So I know at least the button works
Step 2: debug with print
Now I can focus, moving print inside the code block:
process: [
repeat i length? namelist [
print (
to-set-path compose rejoin [
namelist/:i "f/text"
] (to-word namelist/:i)
)
]
]
Almost immediately I can see what's wrong here :
var1 ; expecting `var1f` here
var2 ;
Step 3: we need to go deeper with probe
Aside
Now, before I proceed further, notice that this code doesn't access
anything inside the view block (because it doesn't work!).
But the nice thing here is you could ignore this and come back to it later.
What you need is a way to access var1f/text programmatically
Keeping that in mind, here is a better way to phrase this question:
Step 3a: how to dynamically create objects with different names and set values to them?
var1f/text: 5
(given the code in step 2)
Now, I reach a conundrum here. This would probably be best asked as a different, simpler question.
I decided to continue assuming you accomplished this (there's another answer too)
Note
The important thing to take home in this step is the datatype Red view uses and what you're working with is the same thing: red objects.
There is no difference (all are instances of a simple face object)
Step 4: you're done! Or are you?
So you're able to create the gui you want for your work and you're done!
Right?
But then you ask yourself, is this the best way to do it?
What if you want to add some more of this, or something else entirely?
You have read the official gui docs especially the part about view engine
You've looked at examples of vid and adding view face objects manually
You've looked at the repo on github for sample code and small apps
You've even tried the old, but stable rebol2
But you still don't get it? Don't despair, this is normal.
A lot of stuff have names that are conceptually similar to what you are familiar in other languages but are different in subtle ways which tends to make them really different.
In the end tho, a lot is simpler than you'd think but stranger(having deeper implications)
tl;dr
Separate your view code from the rest so it's easier to debug
Use print, probe and dump-face to debug
Related
I would like to know if there is a message I can override in Pharo so that my custom classes display more descriptive information in the inspector/debuger much like simple variable types do, like Integers or Strings. For instance:
Instead of that, I would like it to show a more custom and informative description consisting of its internal variales so as to have a tighter/tidier view of the variables instead of having to click on it and open another chart (therefore losing sight of the information on the previous chart). I know you can increase the amount of charts shown below, but that is not the point of the question. I would like to achieve something like this:
I have browsed the pharo forums and found nothing, I have also tried overriding over 30 methods hoping that one of them changed the output. Only the class message seemed to change the output, but I could only return an instance of Metaclass and besides messing with this message would break a lot of stuff. Finally I tried to reverse engineer the debugger and then the inspector to see at which point is the table constructed and what values are used or which messages are sent to build said values, but it was just too much for me, the callstack kept growing and I couldn't even scratch the surface.
Luckily, doing this in any Smalltalk is very easy. Types inherited from Object are expected to answer to the message printString, and ultimately printOn: aStream. Those messages are expected to give a description of the object. So, you should just override printOn: in your class (printString uses printOn:) and all the browsers and inspectors will automatically use it. There other possibilities in Pharo, if you want to provide more complex information in different tabs, but I think printOn: will suffice for you.
An example would be:
MyPoint>>printOn: aStream
aStream nextPut: ${.
x printOn: aStream.
aStream nextPutAll: ', '
y printOn: aStream.
aStream nextPut: $}
In Smalltalk, every time you observe something you don't like or understand, you ask the question: Which message is doing this?
In your case, the question would be: Which message creates the string a MyPoint that I see everywhere?
Next, to answer your question you need to find a good place for inserting a halt and then debug from there until you find the culprit. To do this just find the simplest expression that would reproduce the issue and debug it. In your case the right-click command in the Playground will do. So,
Write and select (MyPoint on: 14 and: -5) halt in a Playground.
Right-click and issue the Print it command (I'm assuming you already checked that this command produces the string 'a MyPoint').
Debug
Go over the evaluation of #DoIt, which answers the result
Continue this way alternating between Into and Over to make sure you follow the result to where it's being taken
Eventually you will reach the implementation of Object >> #printString. Bingo!
Now you can open a System Browser and take a look at this method, study how it's been implemented in different classes, etc. Your investigation should show you that the most basic message for printing is #printOn:. You may also want to take a look at other implementors so to better understand what people usually do. (Bear in mind that writing good #printOn:s is a minimalist art)
Overriding printOn: will work for simple cases where you want to just change description.
Pharo allows a lot more than that!
Due the extensible (moldable) nature of our inspector, you do not need to override a method to get your own visualisation of the object.
For example, look this array visualisation:
This is obtained adding this method to Collection:
gtInspectorItemsIn: composite
<gtInspectorPresentationOrder: 0>
^ composite fastList
title: 'Items';
display: [ self asOrderedCollection ];
beMultiple;
format: [ :each | GTObjectPrinter asTruncatedTextFrom: each ];
send: [ :result |
result
ifNil: [ nil ]
ifNotNil: [ result size = 1
ifTrue: [ result anyOne ]
ifFalse: [ self species withAll: result ]
]
]
if you browse for senders of gtInspectorPresentationOrder: you will see there are already a lot of special visualisations in the image.
You can take those as an example on how to create your own, adapted exactly to what you need :)
I frequently run into problems that could be solved with automating code writing, but aren't long enough to justify it as tediously entering each piece is faster.
Here is an example:
Putting lists into dictionaries and things like this. Converting A into B.
A
hotdog HD
hamburger HB
hat H
B
def symbolizeType
case self.type
when "hotdog"
return "HD"
when "hamburger"
return "HB"
when "hat"
return "H"
end
Sure I could come up with something to do this automatically, but it would only make sense if the list was 100+ items long. For a list of 10-20 items, is there a better solution than tediously typing? This is a Ruby example, but I typically run into cases like this all the time. Instead of a case statement, maybe it's a dictionary, maybe it's a list, etc.
My current solution is a python template with the streaming input and output already in place, and I just have to write the parsing and output code. This is pretty good, but is there better? I feel like this would be something VIM macro would excel at, but I'm that experienced with VIM. Can VIM do this easily?
For vim, it'd be a macro running over a list of space separated pairs of words, inserting the first 'when "' bit, the long form word 'hotdog', the ending quote, a newline and 'return "', and then the abbreviation and then final quote, then going back to the list and repeating.
Starting with a register w of:
when "
register r of:
return "
an initial list of:
hotdog HD
hamburger HB
hat H
and a starting file of:
def symbolizeType
case self.type
"newline here"
you can use the following macro at the start of the initial list:
^"ayeeeb"byeo"wp"apa"^Mrb"j
where ^M is a newline.
I do this frequently, and I use a single register and a macro, so I'll share.
Simply pick a register, record your keystrokes, and then replay your keystrokes from the register.
This is a long explanation, but the process is extremely simple and intuitive.
Here are the steps that I would take:
A. The starting text
hotdog HD
hamburger HB
hat H
B. Insert the initial, non-repetitive lines preceding the text to transform
def symbolizeType
case self.type
hotdog HD
hamburger HB
hat H
C. Transform the first line, while recording your keystrokes in a macro
This step I'll write out in detailed sub-steps.
Place the cursor on the first line to transform ("hotdog") and type qa to begin recording your keystrokes as a macro into register a.
Type ^ to move the cursor to the start of the line
Type like you normally would to transform the line to what you want, which for me comes out looking like the following macro
^i^Iwhen "^[ea"^[ldwi^M^Ireturn "^[ea"^[j
Where ^I is Tab, ^[ is Esc, and ^M is Enter.
After the line is transformed to your liking, move your cursor to the next line that you want to transform. You can see this in the macro above with the final j at the end.
This will allow you to automatically repeat the macro while it cycles through each repetitive line.
Stop recording the macro by typing q again.
You can then replay the macro from register a as many times as you like using a standard vim count prefix, in this case two consecutive times starting from the next line to transform.
2#a
This gives the following text
def symbolizeType
case self.type
when "hotdog"
return "HD"
when "hamburger"
return "HB"
when "hat"
return "H"
D. Finally, insert the ending non-repetitive text
def symbolizeType
case self.type
when "hotdog"
return "HD"
when "hamburger"
return "HB"
when "hat"
return "H"
end
Final Comments
This works very quick for any random, repetitive text, and I find it very fluent.
Simply pick a register, record your keystrokes, and then replay your keystrokes from the register.
For things like this I have a few ways of making it easier. One is to use an editor like Sublime Text that allows you to multi-edit a number of things at once, so you can throw in markup with a few keystrokes and convert that into a Hash like:
NAME_TO_CODE = {
hotdog: 'HD',
hamburger: 'HB',
hat: 'H'
}
Not really a whole lot changed there. Your function looks like:
def symbolize_type(type)
NAME_TO_CODE[type.to_sym]
end
Defining this as a data structure has the bonus of being able to manipulate it:
CODE_TO_NAME = NAME_TO_CODE.invert
Now you can do this:
def unsymbolize_type(symbol)
CODE_TO_NAME[symbol.to_s]
end
You can also get super lazy and just parse it on the fly:
NAME_TO_CODE = Hash[%w[
hotdog HD
hamburger HB
hat H
].each_slice(2).to_a]
snippets are like the built-in :abbreviate on steroids, usually with parameter insertions, mirroring, and multiple stops inside them. One of the first, very famous (and still widely used) Vim plugins is snipMate (inspired by the TextMate editor); unfortunately, it's not maintained any more; though there is a fork. A modern alternative (that requires Python though) is UltiSnips. There are more, see this list on the Vim Tips Wiki.
There are three things to evaluate: First, the features of the snippet engine itself, second, the quality and breadth of snippets provided by the author or others; third, how easy it is to add new snippets.
I am having trouble understanding an error emerging from two consecutive while loops in a net logo project.
;;;;;;;;;;;;;;;;;;;;;;;;
;;; Global variables ;;;
;;;;;;;;;;;;;;;;;;;;;;;;
globals [it]
;;;;;;;;;;;;;;;;;;;;;;
;;; Breedin agents ;;;
;;;;;;;;;;;;;;;;;;;;;;
breed [houses house]
breed [firms firm]
;;;;;;;;;;;;;
;;; Setup ;;;
;;;;;;;;;;;;;
to setup
clear-all
reset-ticks
create-firms F
create-houses H
;; sets position of the firms in the space for better visualisation
set it 0
while [it < F ]
[ask firm it [
set color yellow
set heading it * 360 / F
fd 5
]
set it it + 1
]
;; sets position of the households in the space for better visualisation
set it 0
while [it < H ]
[ask house it [
set color yellow
set heading it * 360 / H
fd 15
]
set it it + 1
]
When I run the above code I get an error message
firm 0 is not a HOUSE
error while observer running HOUSE
called by procedure SETUP
called by Button 'Setup'
pointing at house it in the code.
Notice that when I only run the first while loop, everything works fine.
I guess there is something I do not understand in the use of while loops in net logo.
Why does the second while loop seem to consider that I am calling firms although I asked to call houses?
Is there a better way to implement while loops in net logo?
Many thanks in advance for you help
What's happening?
who numbers in NetLogo are assigned from the same sequence for all turtles, independently of their breeds. If you do:
create-firms 1
create-houses 1
Then you will have firm 0 and house 1, which you could also address as turtles. For example, in the command center:
observer> show turtle 0
observer: (firm 0)
observer> show turtle 1
observer: (house 1)
It makes sense to have unique identifiers like that, because the breed of a turtle is a very transient thing. It can be changed:
observer> ask firm 0 [ set breed houses ]
observer> show turtle 0
observer: (house 0)
The turtle has kept its who number despite the change of breed.
Why does the second while loop seem to consider that I am calling firms although I asked to call houses?
What you are doing is the equivalent of taking turtle 0 (which is a firm) and trying to cast it to a house. This is why NetLogo complains that firm 0 is not a house.
A better way to do it
Is there a better way to implement while loops in net logo?
Yes: don't use while! More seriously: using while is most often unnecessary. There is usually a better way to do things.
Also, in general, don't use who numbers for anything. If you want to deal with many turtles at once, use a turtle set. If you want to keep track of a turtle, store the reference to it directly (e.g., set my-firm one-of firms). If you find yourself wanting to use the who number, take a step back and rethink about your problem: there is almost certainly another way.
You want to do something with all your houses? Just ask them!
ask houses [
set color yellow
fd 15
]
There is one thing that the snippet above does not address, however: your requirement for evenly spaced turtles. But you can achieve this by using the create-ordered-<breeds> to create your turtles. With it, your entire setup becomes:
clear-all
create-ordered-firms F [
set color yellow
fd 15
]
create-ordered-houses H [
set color yellow
fd 15
]
But what if you really need an index?
But what if create-ordered-<breeds> did not exist, or if you wanted to do something similar that required some sort of index? You still don't need while: a combination of foreach and n-values will get you there:
create-houses H
(foreach sort houses n-values H [ ? * 360 / H ] [
ask ?1 [
set color yellow
set heading ?2
fd 15
]
])
(We use sort to turn the houses turtle set into a list, but [self] of houses works as well if you want them shuffled.)
That code may look weird at first, but it's actually a pretty common and useful pattern in NetLogo. It "zips" the thing you want to act on with the index that you want to assign to it. It also has a few nice advantages over a while loop: no "off by one" errors, no extra variable and no risk of forgetting to increment the counter or to accidentally mutate it.
The Ruby diff-lcs library does a great job of generating the changeset you need to get from one sequence to another but the format of the output is somewhat confusing to me. I would expect a list of changes but instead the output is always a list containing one or two lists of changes. What is the meaning/intent of having multiple lists of changes?
Consider the following simple example:
> Diff::LCS.diff('abc', 'a-c')
# => [[#<Diff::LCS::Change:0x01 #action="-", #position=1, #element="b">,
# #<Diff::LCS::Change:0x02 #action="+", #position=1, #element="-">],
# [#<Diff::LCS::Change:0x03 #action="-", #position=3, #element="">]]
Ignoring the fact that the last change is blank, why are there two lists of changes instead of just one?
You might have better luck with a better example. If you do this:
Diff::LCS.diff('ab cd', 'a- c_')
Then the output looks like this (with the noise removed):
[
[
<#action="-", #position=1, #element="b">,
<#action="+", #position=1, #element="-">
], [
<#action="-", #position=4, #element="d">,
<#action="+", #position=4, #element="_">
]
]
If we look at Diff::LCS.diff('ab cd ef', 'a- c_ e+'), then we'd get three inner arrays instead of two.
What possible reason could there be for this? There are three operations in a diff:
Add a string.
Remove string.
Change a string.
A change is really just a combination of removes and adds so we're left with just remove and add as the fundamental operations; these line up with the #action values quite nicely. However, when humans look at diffs, we want to see a change as a distinct operation, we want to see that b has become -, the "remove b, add -" version is an implementation detail.
If all we had was this:
[
<#action="-", #position=1, #element="b">,
<#action="+", #position=1, #element="-">,
<#action="-", #position=4, #element="d">,
<#action="+", #position=4, #element="_">
]
then you'd have to figure out which +/- pairs were really changes and which were separate additions and removals.
So the inner arrays map the two fundamental operations (add, remove) to the three operations (add, remove, change) that humans want to see.
You might want to examine the structure of the outputs from these as well:
Diff::LCS.diff('ab cd', 'a- x c_')
Diff::LCS.diff('ab', 'abx')
Diff::LCS.diff('ab', 'xbx')
I think an explicit change #action for Diff::LCS::Change would be better but at least the inner arrays let you group the individual additions and removals into higher level edits.
If you take a look at the Combinatorica package in Mathematica8 in (mathematicapath)/AddOns/LegacyPackages/DiscreteMath/Combinatorica.m you will find the definitions of functions. What I'm interested to know is how Mathematica knows how to format the usage messages. Something tells me that I'm not looking at the right file. In any case, lets try the following:
Cofactor::usage = "Cofactor[m, {i, j}] calculates the (i, j)th cofactor of matrix m."
This line is the 682 line in the file mentioned above. Now if we run it in a mathematica notebook and we use ?Cofactor we will see the exact same message. But if we get the package then the message is formatted. Here is a screenshot:
Notice how the m, i and j inside the function changed and a double arrow was added to the message. I think the arrow was added to the message because there exists documentation for it. Can someone explain this behavior?
EDIT:
This is a screenshot of my notebook file that autosaves to an m file.
As you can see, the L and M are in italic times new roman. Now I will load the package and see the usage.
So far so good. Now lets look at the Documentation center. I will look for the function LineDistance.
As you can see, it shows a weird message. In this case we only want to display the message without any styles. I still can't figure out how the Combinatorica package does this.
I followed this to make the index so that the doc center can display the summary. The summary is essentially the usage display. Let me know if I need to be more specific.
OK, here's the explanation.
Digging in the Combinatorica source reveals this:
(* get formatted Combinatorica messages, except for special cases *)
If[FileType[ToFileName[{System`Private`$MessagesDir,$Language},"Usage.m"]]===File,
Select[FindList[ToFileName[{System`Private`$MessagesDir,$Language},"Usage.m"],"Combinatorica`"],
StringMatchQ[#,StartOfString~~"Combinatorica`*"]&&
!StringMatchQ[#,"Combinatorica`"~~("EdgeColor"|"Path"|"Thin"|"Thick"|"Star"|"RandomInteger")~~__]&]//ToExpression;
]
It is loading messages from ToFileName[{System`Private`$MessagesDir,$Language},"Usage.m"], which on my machine is SystemFiles\Kernel\TextResources\English\Usage.m. This is why all usage messages are created conditionally in Combinatorica.m (only if they don't exist yet). If you look in Usage.m you'll see it has all the ugly boxes stuff that #ragfield mentioned.
I guess the simplest way to have formatted messages is to edit them in the front end in a notebook, and create an auto-save package. This way you can use all the front end's formatting tools, and won't need to deal with boxes.
I will answer on how the link in the Message is generated. Tracing Message printing shows a call to undocumented Documentation`CreateMessageLink function which returns the URL to the corresponding Documentation page if this page exists:
Trace[Information[Sin], Documentation`CreateMessageLink]
In[32]:= Documentation`CreateMessageLink["System", "Sin", "argx", "English"]
Out[32]= "paclet:ref/message/General/argx"
In some cases we can also see calls to Internal`MessageButtonHandler which further calls Documentation`CreateMessageLink:
Trace[Message[Sin::argx, 1, 1],
Internal`MessageButtonHandler | Documentation`CreateMessageLink,
TraceInternal -> True]
The way to embed style information in a String expression is to use linear syntax. For a box expression such as:
StyleBox["foo", FontSlant->Italic]
You can embed this inside of a String by adding \* to the front of it and escaping any special characters such as quotes:
"blah \*StyleBox[\"foo\", FontSlant->Italic] blah"
This should work for any box expression, no matter how complicated:
"blah \*RowBox[{SubsuperscriptBox[\"\[Integral]\",\"0\",\"1\"],RowBox[{FractionBox[\"1\",RowBox[{\"x\",\"+\",\"1\"}]],RowBox[{\"\[DifferentialD]\",\"x\"}]}]}] blah"
I am currently working on rewriting your ApplicationMaker for newer Mathematica-Versions with added functionalities and came to the exact same question here.
My answer is simple: Mathematica dont allowes you to use formated summaries for your symbols (or even build in symbols), so we have to unformate the usage-strings for the summaries. The usagestring itself can still have formatting, but one needs to have a function that removes all the formatingboxes from a string.
i have a solution that uses the UndocumentedTestFEParserPacket as described by John Fultz! in this question.
This funny named Tool parses a String Input into the real unchanged Mathematica BoxForm.
This is my example code:
str0 = Sum::usage
str1=StringJoin[ToString[StringReplace[#, "\\\"" -> "\""]]& /#
(Riffle[MathLink`CallFrontEnd[
FrontEnd`UndocumentedTestFEParserPacket[str0, True]]〚1〛
//. RowBox[{seq___}] :> seq /. BoxData -> List, " "]
/. SubscriptBox[a_, b_] :> a<>"_"<>b
/. Except[List, _Symbol][args__] :> Sequence##Riffle[{args}, " "])];
str2 = Fold[StringReplace, str1,
{((WhitespaceCharacter...)~~br:("["|"("|"=") ~~ (WhitespaceCharacter ...)) :> br,
((WhitespaceCharacter ...) ~~ br:("]"|"}"|","|".")) :> br,
(br:("{") ~~ (WhitespaceCharacter ...)) :> br,
". " ~~ Except[EndOfString] -> ". \n"}]
and this is how the Output looks like (first Output formatted fancy str0, second simple flat str2)
Code Explanation:
str0 is the formatted usagestring with all the StyleBoxes and other formatting boxes.
str1:
UndocumentedTestFEParserPacket[str0, True] gives Boxes and strips off all StyleBoxes, thats because the second argument is True.
First Replacement removes all RowBoxes. The outer BoxForm changed to a List of strings. Whitespaces are inserted between these strings the by Riffle. SubscriptBox gets a special treatment. The last line replaces every remaining FormatBox such as UnderoverscriptBox and it does that by adding Whitespaces between the arguments, and returning the arguments as a flat Sequence.
ToString[StringReplace[#, "\\\"" -> "\""]]& /#
was added to include more cases such as StringReplace::usage. This cases include string representations "" with Styles inside of a the usage-string, when "args" has to be given as strings.
str2:
In this block of code i only remove unwanted WhitespaceCharacter from the string str1 and i add linebreaks "/n" after the ".", because they got lost during the Parsing. There are 3 different cases where WhitespaceCharacter can be removed.
1 removing left-and right sided WithespaceCharacter from a character like "[".
2. and 3. removing WithespaceCharacter from left(2) or right(3) side.
Summary
Istead of summary-> mySymbol::usage, use summary -> unformatString[mySymbol::usage] with unformatString being an appropriate function that performes the unformating like descriped above.
Alternatively you can define another usage message manually like
f::usage = "fancy string with formating";
f::usage2 = "flat string without formating";
than use summary -> mySymbol::usage2