# texstudio macro for next or previous label

In texstudio there exist two menus by which one can add the \ref{} with reference previous or next label. However, the usage of such a command is more encountered when referencing to equations, where the \eqref{} should be applied instead. Therefore, it would be more appropriate if it inserts the key of the next or previous label.

Ex. consider the case:

$$\label{ZEqnNum448683} \begin{array}{l} {\mathop{\min }\limits_{x} \mathop{\sum }\limits_{k}^{} |y_{k}^{+} -y_{k}^{-} |+|z_{k}^{+} -z_{k}^{-} |} \end{array}$$


I need a shortcut to insert just the key, i.e. ZEqnNum448683 into my text when writing above or bellow this equation.

• \mathop{\min } should be \min and \mathop{\sum } should be \sum (they are mathop already) you only need \limits here as array is being used instead of a multi-line math display environment such as align – David Carlisle Dec 24 '17 at 15:15
• Thank you. they were generated by MathType I really don't follow what it does! – Hamid Dec 24 '17 at 16:16

Here's one way:

## Insert Key of Next Label:

%SCRIPT
var LineNo = cursor.lineNumber(), ColNo = cursor.columnNumber();
cursor.movePosition(1,cursorEnums.End, cursorEnums.KeepAnchor);
var myText = cursor.selectedText();
var regEx = /\\label{(.*)}/
var match = regEx.exec(myText);

cursor.moveTo(LineNo, ColNo);
if (match && match[1]){
editor.insertText(match[1])
}


## Insert Key of Previous Label:

%SCRIPT
var LineNo = cursor.lineNumber(), ColNo = cursor.columnNumber();
cursor.movePosition(1,cursorEnums.Start, cursorEnums.KeepAnchor);
var myText = cursor.selectedText();
var regEx = /\\label{(.*)}/
var match = regEx.exec(myText);

cursor.moveTo(LineNo, ColNo);
if (match && match[1]){
editor.insertText(match[1])
}


Assign these to their own respective keyboard shortcuts. In the gif below, I show briefly how to implement these two macros. (Under Macros -> Edit Macros -> Add)

## Test MWE

\documentclass[]{article}

\begin{document}
$$\label{BeforeLabel} x = y$$

% Test here:
\eqref{} % Next key
\eqref{} % Previous key

$$\label{AfterLabel} a = b$$
\end{document}