sisl / tufte_algorithms_book

A template for textbooks in the same style as Algorithms for Optimization
352 stars 66 forks source link

Share between console and block? #16

Closed sebastianpech closed 5 years ago

sebastianpech commented 5 years ago

Is it possible to define eg. a function in a jlblock and call that function in juliaconsole? There is a workaround proposed in gpoore/pythontex#55 can this be applied to the julia version?

tawheeler commented 5 years ago

I didn't know that this was not possible. Feel free to test out the workaround and see if you can get it to work.

sebastianpech commented 5 years ago

After a little bit of testing, pythontex doesn't work so well for me. However, just as an update in case someone comes here searching for a solution to the problem: I managed to get that working, but, it doesn't work out-of-the-box. The new defintion of juliacon in pythontex.tex is not using makepythontexfamily, so it doesn't create the inline version that's needed for the workaround. So one needs to add that and also adapt the new environments for placing the shared code. What I came up with is the following (Pretty sure there is a more latexy version for that, but I'm really no expert in latex code)

New env for inline macros that makes sure nothing get's printed:

This is used for including the generated function into the console session, without printing the results of the include command.

\newcommand{\pytx@MakeInlinecFVNoPrint}[1]{%
    \expandafter\newrobustcmd\expandafter{\csname #1c\endcsname}{%
        \Depythontex{cmd:#1c:ov:p}%
        \xdef\pytx@type{#1}%
        \edef\pytx@cmd{c}%
        \pytx@SetContext
        \pytx@SetGroup
        \let\pytx@InlineShow\@empty
        \let\pytx@InlineSave\pytx@InlineSaveCode
        \let\pytx@InlinePrint\@empty
        \pytx@Inline
    }%
}%

Add to the juliacon definition with

\pytx@MakeInlinecFVNoPrint{juliacon}

Define the new env. similar to the ones in the workaround

\newcommand{\expandjlconc}[1]{\expandafter\reallyexpandjlconc\expandafter{#1}}
\newcommand{\reallyexpandjlconc}[1]{\juliaconc{include("#1")}}
\newcounter{jlconcodeblckcounter}
\newenvironment{jlconcodeblck}%
{\expandafter\edef\csname snippetfile\endcsname{snippet-\thejlconcodeblckcounter.jl}%
 \expandafter\edef\csname osnippetfile\endcsname{\outputdir/snippet-\thejlconcodeblckcounter.jl}%
  \VerbatimEnvironment
  \begin{VerbatimOut}{\osnippetfile}}%
 {\end{VerbatimOut}%
 \expandjlconc{\osnippetfile}
 \inputpygments{julia}{\osnippetfile}
\stepcounter{jlconcodeblckcounter}}

Now the following works:

\begin{jlconcodeblck}
function bar(x)
    x^2
end
\end{jlconcodeblck}
\begin{juliaconsole}
bar(10)
\end{juliaconsole}
mykelk commented 4 years ago

I think something like this works in pythontex 0.17:

\begin{juliaconcode}
using InteractiveUtils
using LinearAlgebra
\end{juliaconcode}

It won't print, but it will be part of the console session.