Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

help on formatting my notebook back as it was. From 'code' style to Input style

I did something silly I think.

I changed my cell style to 'code' and starting changing indentation and moving code around the way I like to, (since it is easier to do that in 'code' cell style, as the notebook interface does not get in the way). But after trying it for a while, I find other issues with this with this style.

Now I changed the style back to 'input'. But now all the code has all these extra spaces in them, and code does not look good any more as it was in the original 'input' style.

I made too many edits and manual formatting to the code.

Is there a way to tell Mathematica to 'auto-format' the code back to the default input style? i.e. remove all the extra space where needed, realign things the way they were, etc...

If I have to do this by hand, will take me forever. I could not find such as option. I tried many options there on the menues, and nothing helps.

ps. in Matlab, this is trivial to do, just select all code, then select 'smart-ident' from a menu, and it will do that.

ps. I tried emacs Mathematica mode, and they have no prety-print either.

EDIT

I tried these: Select cell, then Cell->Convert To, and selected 'InputForm' and also selected 'input Form Display'.

This seems to have removed all the extra white spaces. Which is good. Now I only need to go and just hit returns in all the right places to get it back to the original form.

At least this is much better than having to delete spaces by hand. So, disaster seems to be contained for now.

EDIT

screen shot after converting 'code' style back to 'standard form'. very hard to read.

enter image description here thanks,

EDIT

To make sure what the question is, given some Mathematica code, which is 'mangled' up, and formatted by hand with manual space inserting and manual inserting of returns all over, and now if I just put it in a notebook with default style, I want it to smart-indent back to the default setting, and have all the line-wrapping, etc... as if it was originally written in the default style. i.e. pretty-print to what it would be if it was written using the 'input' code style.

here is a small function as an example that I formatted by hand. It will look not well formatted even more when I paste it here. If you copy this code to your notebook, default style, then how to auto-format it back to the default settings without doing it by hand?

If[Abs@omega <= $MachineEpsilon,
    (
      data = {{0, 0}};
      p    = ListPlot[data, Sequence@plotOptions]
     ),
    (
      driverPeriod            = 2. Pi/Abs@omega;
      valuesOfDriverAmplitude = 
    Range[aStart, aStart + aLen, aLen/aIntervals];
      timeValues              = 
    Range[initialDriverPeriod*driverPeriod, 
     finalDriverPeriod*driverPeriod, driverPeriod ];

      data  = 
    Table[0, {Length[valuesOfDriverAmplitude]}, {Length[timeValues ]}];
      total = Length[timeValues]*Length[valuesOfDriverAmplitude];
      bifurcationProgress = 0.;
      count = 0.;

      Do[
         (
           {x1, x2, x3} = 
      solve[q, valuesOfDriverAmplitude [[i]], omega, phase, 
       initialDriverPeriod*driverPeriod,
                                (finalDriverPeriod)*driverPeriod, x10,
        x20, isDamped, 4, 4];
           currentTorqueAmplitude = valuesOfDriverAmplitude[[i]];
           Do[
              (

       data[[i, j]] = {currentTorqueAmplitude, x2[timeValues[[j]]  ]};
                count      += 1;
                bifurcationProgress = count/total;
               ),
                {j, 1, Length[timeValues]}
              ]
          ),
         {i, 1, Length[valuesOfDriverAmplitude]}
         ];

     p = ListPlot[Flatten[data, 1], Sequence@plotOptions]
     )
  ];

EDIT 6 PM

1) Saved the notebook as m file (mathematica package) called aclFix.m 2) then I did the following

str=Import["aclFix.m")

also tried

str=Get["aclFix.m"];

but in both cases, all what I get is the actual Manipulate on the screen showing up. And the command shown below (StringReplace etc....) does not work on it as it is not a string. I get lots of errors, such as

    StringReplace::strse: String or list of strings expected at position 1 in 
StringReplace[Manipulate[<<1>>,
{{aStart,0.9,},0,2,0.01,ImageSize->Tiny,ImagePadding->0,ControlPlacement->1},
{{aLen,0.2,},0.01,2,0.01,ImageSize->Tiny,ImagePadding->0,ControlPlacement->2},
<<45>>,SynchronousUpdating->False,ContinuousAction->False,<<6>>],
{(x_/;x==FromCharacterCode[32])..->,(x_/;x==<<17>>[9])..->}]. >>

may be I misunderstood the solution..

EDIT 1 AM

I exported the notebook as "m" file, Imported it back as

str = Import["aclFix.m", "Text"];

then

code=StringReplace[str, {(x_ /; x == FromCharacterCode[32]) .. -> 
   "", (x_ /; x == FromCharacterCode[9]) .. -> ""}]

then

Export["fix.m", code]

But it is still a string. When I import it back, it is still a string. I tried ToExpression[code] but it did nothing. How do convert it to actual code? This is an example looking at the .m using text editor. I used the above code to test it on. May be we are getting close here?

Will look more at it.

(* Created by Wolfram Mathematica 8.0 for Students - Personal Use Only : www.wolfram.com *)

"If[Abs@omega<=$MachineEpsilon,\n(\ndata={{0,0}};\np=ListPlot[data,Sequence@p\

lotOptions]\n),\n(\ndriverPeriod=2.Pi/Abs@omega;\nvaluesOfDriverAmplitude=\nR\

ange[aStart,aStart+aLen,aLen/aIntervals];\ntimeValues=\nRange[initialDriverPe\

riod*driverPeriod,\nfinalDriverPeriod*driverPeriod,driverPeriod];\n\ndata=\nT\

able[0,{Length[valuesOfDriverAmplitude]},{Length[timeValues]}];\ntotal=Length\

[timeValues]*Length[valuesOfDriverAmplitude];\nbifurcationProgress=0.;\ncount\

=0.;\n\nDo[\n(\n{x1,x2,x3}=\nsolve[q,valuesOfDriverAmplitude[[i]],omega,phase\

,\ninitialDriverPeriod*driverPeriod,\n(finalDriverPeriod)*driverPeriod,x10,\n\

x20,isDamped,4,4];\ncurrentTorqueAmplitude=valuesOfDriverAmplitude[[i]];\nDo[\

\n(\n\ndata[[i,j]]={currentTorqueAmplitude,x2[timeValues[[j]]]};\ncount+=1;\n\

bifurcationProgress=count/total;\n),\n{j,1,Length[timeValues]}\n]\n),\n{i,1,L\

ength[valuesOfDriverAmplitude]}\n];\n\np=ListPlot[Flatten[data,1],Sequence@pl\

otOptions]\n)\n];"
like image 463
Nasser Avatar asked Sep 10 '11 02:09

Nasser


2 Answers

It would be useful to have a sample of the code (not just visual). In the meantime, maybe this will work:

Save your code in an m-file. Then import it into the variable str, then run this

StringReplace[str,
 {
  (x_ /; x == FromCharacterCode[32]) .. -> "",
  (x_ /; x == FromCharacterCode[9]) .. -> ""
  }
 ]

and save the result into another m-file. What this does is to remove all series of one or more spaces or tabs. Thus, if for instance

str =
 "f[
    g[
        u   ]]"

(which contains both spaces and tabs) then running the code I gave gives

f[
g[
u]]

and you can save this back into an m-file.

If this doesn't do what you want then maybe if you provide a piece of code that is formatted the wrong way would help.

(or you could try with the interactive regexp-builder in emacs: m-x re-builder, but if you're not familiar with regexps it's probably not worth it)

like image 69
acl Avatar answered Oct 25 '22 07:10

acl


How about something like

nb = EvaluationNotebook[];
NotebookFind[nb, "Code", All, CellStyle]
FrontEndExecute[{FrontEndToken[nb, "Style", "Input"]}]
FrontEndExecute[{FrontEndToken[nb, "SelectionConvert", "StandardForm"]}]

This will convert all "Code" cells to "Input" cells and convert their contents to "StandardForm".

For a list of all FrontEndTokens see belisarius' answer here.


Another option that follows from the recent comment of Rolf Mertig and Alt-Click (or Ctrl-Alt-Click in linux) on a "Code" cell to select all "Code" cells. Then use the Format menu to convert to "Input" style cells and then the Cell menu to Convert To StandardForm. (Alternatively that is Alt-Click on a "Code cell" followed by Alt-9 and then Ctrl-Shift-N)

like image 30
Simon Avatar answered Oct 25 '22 08:10

Simon