3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
13 #include "InsetLabel.h"
18 #include "BufferParams.h"
20 #include "CutAndPaste.h"
21 #include "FuncRequest.h"
22 #include "FuncStatus.h"
25 #include "ParIterator.h"
27 #include "texstream.h"
29 #include "TextClass.h"
30 #include "TocBackend.h"
32 #include "mathed/InsetMathRef.h"
34 #include "frontends/alert.h"
36 #include "support/convert.h"
37 #include "support/gettext.h"
38 #include "support/lstrings.h"
41 using namespace lyx::support;
46 InsetLabel::InsetLabel(Buffer * buf, InsetCommandParams const & p)
47 : InsetCommand(buf, p)
51 void InsetLabel::initView()
53 // This seems to be used only for inset creation.
54 // Therefore we do not update refs here, since this would
55 // erroneously change refs from existing duplicate labels
57 updateLabel(getParam("name"));
61 void InsetLabel::uniqueLabel(docstring & label) const
63 docstring const new_label = label;
65 bool ambiguous = false;
66 while (buffer().activeLabel(label)) {
67 label = new_label + '-' + convert<docstring>(i);
72 // Warn the user that the label has been changed to something else.
73 frontend::Alert::warning(_("Label names must be unique!"),
74 bformat(_("The label %1$s already exists,\n"
75 "it will be changed to %2$s."), new_label, label));
80 void InsetLabel::updateLabel(docstring const & new_label, bool const active)
82 docstring label = new_label;
85 setParam("name", label);
89 void InsetLabel::updateLabelAndRefs(docstring const & new_label,
92 docstring const old_label = getParam("name");
93 docstring label = new_label;
95 if (label == old_label)
98 // This handles undo groups automagically
99 UndoGroupHelper ugh(&buffer());
101 cursor->recordUndo();
102 bool const changes = buffer().masterParams().track_changes;
104 // With change tracking, we insert a new label and
105 // delete the old one
106 InsetCommandParams p(LABEL_CODE, "label");
108 string const data = InsetCommand::params2string(p);
109 lyx::dispatch(FuncRequest(LFUN_INSET_INSERT, data));
110 lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_FORWARD));
112 setParam("name", label);
113 updateReferences(old_label, label, changes);
117 void InsetLabel::updateReferences(docstring const & old_label,
118 docstring const & new_label, bool const changes)
120 UndoGroupHelper ugh(nullptr);
122 // With change tracking, we insert a new ref and
123 // delete the old one
124 lyx::dispatch(FuncRequest(LFUN_MASTER_BUFFER_FORALL,
125 "inset-forall Ref inset-modify ref changetarget "
126 + old_label + " " + new_label));
128 for (auto const & p: buffer().references(old_label)) {
129 ugh.resetBuffer(p.second.buffer());
130 CursorData(p.second).recordUndo();
131 if (p.first->lyxCode() == MATH_REF_CODE) {
132 InsetMathRef * mi = p.first->asInsetMath()->asRefInset();
133 mi->changeTarget(new_label);
135 InsetCommand * ref = p.first->asInsetCommand();
136 ref->setParam("reference", new_label);
143 ParamInfo const & InsetLabel::findInfo(string const & /* cmdName */)
145 static ParamInfo param_info_;
146 if (param_info_.empty())
147 param_info_.add("name", ParamInfo::LATEX_REQUIRED,
148 ParamInfo::HANDLING_ESCAPE);
153 docstring InsetLabel::screenLabel() const
155 return screen_label_;
159 void InsetLabel::updateBuffer(ParIterator const & it, UpdateType, bool const /*deleted*/)
161 docstring const & label = getParam("name");
163 // Check if this one is active (i.e., neither deleted with change-tracking
164 // nor in an inset that does not produce output, such as notes or inactive branches)
165 Paragraph const & para = it.paragraph();
166 bool active = !para.isDeleted(it.pos()) && para.inInset().producesOutput();
167 // If not, check whether we are in a deleted/non-outputting inset
169 for (size_type sl = 0 ; sl < it.depth() ; ++sl) {
170 Paragraph const & outer_par = it[sl].paragraph();
171 if (outer_par.isDeleted(it[sl].pos())
172 || !outer_par.inInset().producesOutput()) {
179 if (buffer().activeLabel(label) && active) {
180 // Problem: We already have an active InsetLabel with the same name!
181 screen_label_ = _("DUPLICATE: ") + label;
184 buffer().setInsetLabel(label, this, active);
185 screen_label_ = label;
187 // save info on the active counter
189 buffer().masterBuffer()->params().documentClass().counters();
190 active_counter_ = cnts.currentCounter();
191 Language const * lang = it->getParLanguage(buffer().params());
192 if (lang && !active_counter_.empty()) {
193 if (active_counter_ != from_ascii("equation")) {
194 counter_value_ = cnts.theCounter(active_counter_, lang->code());
195 pretty_counter_ = cnts.prettyCounter(active_counter_, lang->code());
197 split(label, prex, ':');
200 formatted_counter_ = pretty_counter_;
202 formatted_counter_ = cnts.formattedCounter(active_counter_, prex, lang->code());
204 // For equations, the counter value and pretty counter
205 // value will be set by the parent InsetMathHull.
206 counter_value_ = from_ascii("#");
207 pretty_counter_ = from_ascii("");
208 formatted_counter_ = from_ascii("");
211 counter_value_ = from_ascii("#");
212 pretty_counter_ = from_ascii("#");
213 formatted_counter_ = from_ascii("#");
218 void InsetLabel::addToToc(DocIterator const & cpit, bool output_active,
219 UpdateType, TocBackend & backend) const
221 docstring const & label = getParam("name");
223 // inactive labels get a cross mark
224 if (buffer().insetLabel(label, true) != this)
225 output_active = false;
227 // We put both active and inactive labels to the outliner
228 shared_ptr<Toc> toc = backend.toc("label");
229 TocItem toc_item = TocItem(cpit, 0, screen_label_, output_active);
230 toc_item.prettyStr(formatted_counter_);
231 toc->push_back(toc_item);
232 // The refs get assigned only to the active label. If no active one exists,
233 // assign the (BROKEN) refs to the first inactive one.
234 if (buffer().insetLabel(label, true) == this || !buffer().activeLabel(label)) {
235 for (auto const & p : buffer().references(label)) {
236 DocIterator const ref_pit(p.second);
237 if (p.first->lyxCode() == MATH_REF_CODE)
238 toc->push_back(TocItem(ref_pit, 1,
239 p.first->asInsetMath()->asRefInset()->screenLabel(),
242 toc->push_back(TocItem(ref_pit, 1,
243 static_cast<InsetRef *>(p.first)->getTOCString(),
244 static_cast<InsetRef *>(p.first)->outputActive()));
250 bool InsetLabel::getStatus(Cursor & cur, FuncRequest const & cmd,
251 FuncStatus & status) const
254 switch (cmd.action()) {
255 case LFUN_LABEL_INSERT_AS_REFERENCE:
256 case LFUN_LABEL_COPY_AS_REFERENCE:
259 case LFUN_INSET_MODIFY:
260 if (cmd.getArg(0) == "changetype") {
261 // this is handled by InsetCommand,
262 // but not by InsetLabel.
269 return InsetCommand::getStatus(cur, cmd, status);
272 status.setEnabled(enabled);
277 void InsetLabel::doDispatch(Cursor & cur, FuncRequest & cmd)
279 switch (cmd.action()) {
281 case LFUN_INSET_MODIFY: {
282 // the only other option here is "changetype", and we
283 // do not have different types.
284 if (cmd.getArg(0) != "label") {
288 InsetCommandParams p(LABEL_CODE);
290 InsetCommand::string2params(to_utf8(cmd.argument()), p);
291 if (p.getCmdName().empty()) {
292 cur.noScreenUpdate();
295 if (p["name"] != params()["name"]) {
296 // undo is handled in updateLabelAndRefs
297 updateLabelAndRefs(p["name"], &cur);
299 cur.forceBufferUpdate();
303 case LFUN_LABEL_COPY_AS_REFERENCE: {
304 InsetCommandParams p(REF_CODE, "ref");
305 p["reference"] = getParam("name");
306 cap::clearSelection();
307 cap::copyInset(cur, new InsetRef(buffer_, p), getParam("name"));
311 case LFUN_LABEL_INSERT_AS_REFERENCE: {
312 InsetCommandParams p(REF_CODE, "ref");
313 p["reference"] = getParam("name");
314 string const data = InsetCommand::params2string(p);
315 lyx::dispatch(FuncRequest(LFUN_INSET_INSERT, data));
320 InsetCommand::doDispatch(cur, cmd);
326 void InsetLabel::latex(otexstream & os, OutputParams const & runparams_in) const
328 OutputParams runparams = runparams_in;
329 docstring command = getCommand(runparams);
330 docstring const label = getParam("name");
331 if (buffer().params().output_changes
332 && buffer().activeLabel(label)
333 && buffer().insetLabel(label, true) != this) {
334 // this is a deleted label and we have a non-deleted with the same id
335 // rename it for output to prevent wrong references
336 docstring newlabel = label;
338 while (buffer().insetLabel(newlabel)) {
339 newlabel = label + "-DELETED-" + convert<docstring>(i);
342 command = subst(command, label, newlabel);
344 // In macros with moving arguments, such as \section,
345 // we store the label and output it after the macro (#2154)
346 if (runparams_in.postpone_fragile_stuff)
347 runparams_in.post_macro += command;
349 // protect label in moving argument (#9404),
350 // but not in subfloat caption (#11950)
351 if (runparams.moving_arg
352 && runparams.inFloat != OutputParams::SUBFLOAT)
359 int InsetLabel::plaintext(odocstringstream & os,
360 OutputParams const &, size_t) const
362 docstring const str = getParam("name");
363 os << '<' << str << '>';
364 return 2 + str.size();
368 void InsetLabel::docbook(XMLStream & xs, OutputParams const & runparams) const
370 // Output an anchor only if it has not been processed before.
371 docstring id = getParam("name");
372 docstring cleaned_id = xml::cleanID(id);
373 if (runparams.docbook_anchors_to_ignore.find(id) == runparams.docbook_anchors_to_ignore.end() &&
374 runparams.docbook_anchors_to_ignore.find(cleaned_id) == runparams.docbook_anchors_to_ignore.end()) {
375 docstring attr = from_utf8("xml:id=\"") + cleaned_id + from_utf8("\"");
376 xs << xml::CompTag("anchor", to_utf8(attr));
381 docstring InsetLabel::xhtml(XMLStream & xs, OutputParams const &) const
383 // Print the label as an HTML anchor, so that an external link can point to this equation.
384 // (URL: FILE.html#EQ-ID.)
386 // Unfortunately, the name attribute has been deprecated, so we have to use
387 // id here to get the document to validate as XHTML 1.1. This will cause a
388 // problem with some browsers, though, I'm sure. (Guess which!) So we will
389 // have to figure out what to do about this later.
390 docstring const attr = "id=\"" + xml::cleanAttr(getParam("name")) + '"';
391 xs << xml::CompTag("a", to_utf8(attr));