1
$\begingroup$

I have my own package (just a bunch of functions) in the *.m file, which I load using the Needs[] command. Everything works fine except for one detail: each time I want to edit the package and open it by double clicking in the file explorer, Mathematica opens the *.m file with all the formatting removed (no indentation whatsoever). Is there a way to avoid this?

$\endgroup$
  • $\begingroup$ How do you indent your code? Do you use the cells or text elements (spaces/tabs) within the cells? $\endgroup$ – rcollyer Oct 22 at 13:57
  • $\begingroup$ I'm not sure. When creating the package, I just opened a new Mathematica window, and then used Save As *.m file. I do not use spaces for indentation. $\endgroup$ – mavzolej Oct 22 at 14:10
  • $\begingroup$ The interface for the package editor is relatively simple compared to the regular notebooks. If you didn't add any formatting yourself, or changed the formatting of the cells, then that info is not saved. You can think of it as a text editor that just tries to make things look nice, but doesn't actually save that info. $\endgroup$ – rcollyer Oct 22 at 20:32
  • $\begingroup$ I don't see this. Is it a problem with a specific .m file? Or with all .m files? $\endgroup$ – mikado Oct 22 at 22:22
  • $\begingroup$ With all .m-files. $\endgroup$ – mavzolej Oct 23 at 8:45
1
$\begingroup$

When creating the package, I just opened a new Mathematica window, and then used Save As *.m file.

You can use another workflow: instead of saving your Notebook as an .m file, you should save it as a usual Notebook, but preliminarily you should make all your input cells to be initialization cells and set AutoGeneratedPackage -> True for your Notebook:

SetOptions[EvaluationNotebook[], AutoGeneratedPackage -> True]

Now each time you save your Notebook a package with the same name will be generated in the same folder. The package will contain the contents of your initialization cells.

There are two possible ways to make your input cells to be initialization cells:

  1. By setting the InitializationCell -> True flag (menu item Cell ► Cell Properties ► Initialization Cell)

  2. By setting the InitializationGroup -> True flag (menu item Cell ► Cell Properties ► Initialization Group). It may be more handy than the first method, because with this method it is sufficient to create a single initialization group at the top of the Notebook (for example, by creating a cell with style "Section" and applying this menu item to it).

Related:

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.