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"
17 #include "buffer_funcs.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "CutAndPaste.h"
22 #include "DispatchResult.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "InsetIterator.h"
28 #include "ParIterator.h"
30 #include "texstream.h"
32 #include "TextClass.h"
33 #include "TocBackend.h"
35 #include "mathed/InsetMathHull.h"
36 #include "mathed/InsetMathRef.h"
38 #include "frontends/alert.h"
40 #include "support/convert.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43 #include "support/lyxalgo.h"
46 using namespace lyx::support;
51 InsetLabel::InsetLabel(Buffer * buf, InsetCommandParams const & p)
52 : InsetCommand(buf, p)
56 void InsetLabel::initView()
58 // This seems to be used only for inset creation.
59 // Therefore we do not update refs here, since this would
60 // erroneously change refs from existing duplicate labels
62 updateLabel(getParam("name"));
66 void InsetLabel::uniqueLabel(docstring & label) const
68 docstring const new_label = label;
70 bool ambiguous = false;
71 while (buffer().activeLabel(label)) {
72 label = new_label + '-' + convert<docstring>(i);
77 // Warn the user that the label has been changed to something else.
78 frontend::Alert::warning(_("Label names must be unique!"),
79 bformat(_("The label %1$s already exists,\n"
80 "it will be changed to %2$s."), new_label, label));
85 void InsetLabel::updateLabel(docstring const & new_label, bool const active)
87 docstring label = new_label;
90 setParam("name", label);
94 void InsetLabel::updateLabelAndRefs(docstring const & new_label,
97 docstring const old_label = getParam("name");
98 docstring label = new_label;
100 if (label == old_label)
103 // This handles undo groups automagically
104 UndoGroupHelper ugh(&buffer());
106 cursor->recordUndo();
107 if (buffer().masterParams().track_changes) {
108 // With change tracking, we insert a new label and
109 // delete the old one
110 InsetCommandParams p(LABEL_CODE, "label");
112 string const data = InsetCommand::params2string(p);
113 lyx::dispatch(FuncRequest(LFUN_INSET_INSERT, data));
114 lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_FORWARD));
116 setParam("name", label);
117 updateReferences(old_label, label);
121 void InsetLabel::updateReferences(docstring const & old_label,
122 docstring const & new_label)
125 if (buffer().masterParams().track_changes) {
126 // With change tracking, we insert a new ref and
127 // delete the old one
128 lyx::dispatch(FuncRequest(LFUN_MASTER_BUFFER_FORALL,
129 "inset-forall Ref inset-modify ref changetarget "
130 + old_label + " " + new_label));
132 for (auto const & p: buffer().references(old_label)) {
133 ugh.resetBuffer(p.second.buffer());
134 CursorData(p.second).recordUndo();
135 if (p.first->lyxCode() == MATH_REF_CODE) {
136 InsetMathRef * mi = p.first->asInsetMath()->asRefInset();
137 mi->changeTarget(new_label);
139 InsetCommand * ref = p.first->asInsetCommand();
140 ref->setParam("reference", new_label);
147 ParamInfo const & InsetLabel::findInfo(string const & /* cmdName */)
149 static ParamInfo param_info_;
150 if (param_info_.empty())
151 param_info_.add("name", ParamInfo::LATEX_REQUIRED,
152 ParamInfo::HANDLING_ESCAPE);
157 docstring InsetLabel::screenLabel() const
159 return screen_label_;
163 void InsetLabel::updateBuffer(ParIterator const & par, UpdateType utype, bool const /*deleted*/)
165 docstring const & label = getParam("name");
167 // Check if this one is active (i.e., neither deleted with change-tracking
168 // nor in an inset that does not produce output, such as notes or inactive branches)
169 Paragraph const & para = par.paragraph();
170 bool active = !para.isDeleted(par.pos()) && para.inInset().producesOutput();
171 // If not, check whether we are in a deleted/non-outputting inset
173 for (size_type sl = 0 ; sl < par.depth() ; ++sl) {
174 Paragraph const & outer_par = par[sl].paragraph();
175 if (outer_par.isDeleted(par[sl].pos())
176 || !outer_par.inInset().producesOutput()) {
183 if (buffer().activeLabel(label) && active) {
184 // Problem: We already have an active InsetLabel with the same name!
185 screen_label_ = _("DUPLICATE: ") + label;
188 buffer().setInsetLabel(label, this, active);
189 screen_label_ = label;
191 if (utype == OutputUpdate) {
192 // save info on the active counter
193 Counters const & cnts =
194 buffer().masterBuffer()->params().documentClass().counters();
195 active_counter_ = cnts.currentCounter();
196 Language const * lang = par->getParLanguage(buffer().params());
197 if (lang && !active_counter_.empty()) {
198 counter_value_ = cnts.theCounter(active_counter_, lang->code());
199 pretty_counter_ = cnts.prettyCounter(active_counter_, lang->code());
201 counter_value_ = from_ascii("#");
202 pretty_counter_ = from_ascii("#");
208 void InsetLabel::addToToc(DocIterator const & cpit, bool output_active,
209 UpdateType, TocBackend & backend) const
211 docstring const & label = getParam("name");
213 // inactive labels get a cross mark
214 if (buffer().insetLabel(label, true) != this)
215 output_active = false;
217 // We put both active and inactive labels to the outliner
218 shared_ptr<Toc> toc = backend.toc("label");
219 toc->push_back(TocItem(cpit, 0, screen_label_, output_active));
220 // The refs get assigned only to the active label. If no active one exists,
221 // assign the (BROKEN) refs to the first inactive one.
222 if (buffer().insetLabel(label, true) == this || !buffer().activeLabel(label)) {
223 for (auto const & p : buffer().references(label)) {
224 DocIterator const ref_pit(p.second);
225 if (p.first->lyxCode() == MATH_REF_CODE)
226 toc->push_back(TocItem(ref_pit, 1,
227 p.first->asInsetMath()->asRefInset()->screenLabel(),
230 toc->push_back(TocItem(ref_pit, 1,
231 static_cast<InsetRef *>(p.first)->getTOCString(),
232 static_cast<InsetRef *>(p.first)->outputActive()));
238 bool InsetLabel::getStatus(Cursor & cur, FuncRequest const & cmd,
239 FuncStatus & status) const
242 switch (cmd.action()) {
243 case LFUN_LABEL_INSERT_AS_REFERENCE:
244 case LFUN_LABEL_COPY_AS_REFERENCE:
247 case LFUN_INSET_MODIFY:
248 if (cmd.getArg(0) == "changetype") {
249 // this is handled by InsetCommand,
250 // but not by InsetLabel.
257 return InsetCommand::getStatus(cur, cmd, status);
260 status.setEnabled(enabled);
265 void InsetLabel::doDispatch(Cursor & cur, FuncRequest & cmd)
267 switch (cmd.action()) {
269 case LFUN_INSET_MODIFY: {
270 // the only other option here is "changetype", and we
271 // do not have different types.
272 if (cmd.getArg(0) != "label") {
276 InsetCommandParams p(LABEL_CODE);
278 InsetCommand::string2params(to_utf8(cmd.argument()), p);
279 if (p.getCmdName().empty()) {
280 cur.noScreenUpdate();
283 if (p["name"] != params()["name"]) {
284 // undo is handled in updateLabelAndRefs
285 updateLabelAndRefs(p["name"], &cur);
287 cur.forceBufferUpdate();
291 case LFUN_LABEL_COPY_AS_REFERENCE: {
292 InsetCommandParams p(REF_CODE, "ref");
293 p["reference"] = getParam("name");
294 cap::clearSelection();
295 cap::copyInset(cur, new InsetRef(buffer_, p), getParam("name"));
299 case LFUN_LABEL_INSERT_AS_REFERENCE: {
300 InsetCommandParams p(REF_CODE, "ref");
301 p["reference"] = getParam("name");
302 string const data = InsetCommand::params2string(p);
303 lyx::dispatch(FuncRequest(LFUN_INSET_INSERT, data));
308 InsetCommand::doDispatch(cur, cmd);
314 void InsetLabel::latex(otexstream & os, OutputParams const & runparams_in) const
316 OutputParams runparams = runparams_in;
317 docstring command = getCommand(runparams);
318 docstring const label = getParam("name");
319 if (buffer().params().output_changes
320 && buffer().activeLabel(label)
321 && buffer().insetLabel(label, true) != this) {
322 // this is a deleted label and we have a non-deleted with the same id
323 // rename it for output to prevent wrong references
324 docstring newlabel = label;
326 while (buffer().insetLabel(newlabel)) {
327 newlabel = label + "-DELETED-" + convert<docstring>(i);
330 command = subst(command, label, newlabel);
332 // In macros with moving arguments, such as \section,
333 // we store the label and output it after the macro (#2154)
334 if (runparams_in.postpone_fragile_stuff)
335 runparams_in.post_macro += command;
337 if (runparams.moving_arg)
344 int InsetLabel::plaintext(odocstringstream & os,
345 OutputParams const &, size_t) const
347 docstring const str = getParam("name");
348 os << '<' << str << '>';
349 return 2 + str.size();
353 void InsetLabel::docbook(XMLStream & xs, OutputParams const & runparams) const
355 // Output an anchor only if it has not been processed before.
356 if (runparams.docbook_anchors_to_ignore.find(getParam("name")) == runparams.docbook_anchors_to_ignore.end()) {
357 docstring attr = from_utf8("xml:id=\"") + xml::cleanID(getParam("name")) + from_utf8("\"");
358 xs << xml::CompTag("anchor", to_utf8(attr));
363 docstring InsetLabel::xhtml(XMLStream & xs, OutputParams const &) const
366 // Unfortunately, the name attribute has been deprecated, so we have to use
367 // id here to get the document to validate as XHTML 1.1. This will cause a
368 // problem with some browsers, though, I'm sure. (Guess which!) So we will
369 // have to figure out what to do about this later.
370 docstring const attr = "id=\"" + xml::cleanAttr(getParam("name")) + '"';
371 xs << xml::CompTag("a", to_utf8(attr));