title: Inferring next code line to be executed in Matlab debug session
body: <p>I am writing an interface to help me debug Matlab code in a console session on linux (that is, without GUI). I am using tmux to split the screen, on the left pane I run Matlab and on the right pane the script is open in Vim. My custom mex function which I call <code>dbstep2</code> calls the regular <code>dbstep</code>, and also to a matlab script called <code>send_to_vim_via_tmux</code> where I infer the current line, and send to the right pane a command (via <code>tmux send-keys</code>) to highlight the next line of code that will be executed, mimicking a debug session with GUI. </p>
  
  <p>Since I cannot call <code>dbstep</code> from a Matlab <code>dbstep2.m</code> script (if I do, it just stops inside <code>dbstep2</code> as if a breakpoint was set there), I do it from a simple mex file containing only 2 lines (<code>dbstep2.c</code>):</p>
  
  <pre><code>mexCallMATLAB(0, NULL, 0, NULL, "send_to_vim_via_tmux");
  mexCallMATLAB(0, NULL, 0, NULL, "dbstep"); 
  </code></pre>
  
  <p>The problem is that the call to <code>dbstep</code> <strong>always happens last</strong>, no matter where the <code>mexCallMATLAB(0, NULL, 0, NULL, "dbstep");</code> line is placed in the C source code. I guess that's the way <code>dbstep</code> is implemented. This means in my <code>send_to_vim_via_tmux</code> script, I have to infer the <em>next</em> line to be executed. In order to infer the correct line to highlight, I use Matlab's <code>dbstack</code> to get to current line, and then I apply some logic (add 1 and optionally skip empty lines or comment lines etc.)</p>
  
  <p>My problem is with <code>while</code>/<code>for</code> loops, where at the <code>end</code> keyword I don't know if the loop is going to end or not. So for example:</p>
  
  <pre><code>[line 1] a = 1;     %'// debugger stops at this line, then I call dbstep2 
  [line 2] b = 2;     %'// My script can infer line #1, so I highlight line 1+1=2
  [line 3] for i = 1 : 10
  [line 4]    b = b + i;
  [line 5] end        %'// is next line 6 or 3 ???
  </code></pre>
  
  <p>Is there any way to infer the next line that will be executed, maybe some undocumented magic? The only other option is to parse the file being debugged and analyze the condition - which seems an overkill for what was meant to be a simple helper tool.</p>