]> git.lyx.org Git - lyx.git/blob - src/insets/InsetLabel.cpp
Move Cursor.h from Clipboard.h
[lyx.git] / src / insets / InsetLabel.cpp
1 /**
2  * \file InsetLabel.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetLabel.h"
14
15 #include "InsetRef.h"
16
17 #include "buffer_funcs.h"
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "Cursor.h"
22 #include "CutAndPaste.h"
23 #include "DispatchResult.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "InsetIterator.h"
27 #include "Language.h"
28 #include "LyX.h"
29 #include "ParIterator.h"
30 #include "xml.h"
31 #include "texstream.h"
32 #include "Text.h"
33 #include "TextClass.h"
34 #include "TocBackend.h"
35
36 #include "mathed/InsetMathHull.h"
37 #include "mathed/InsetMathRef.h"
38
39 #include "frontends/alert.h"
40
41 #include "support/convert.h"
42 #include "support/gettext.h"
43 #include "support/lstrings.h"
44 #include "support/lyxalgo.h"
45
46 using namespace std;
47 using namespace lyx::support;
48
49 namespace lyx {
50
51
52 InsetLabel::InsetLabel(Buffer * buf, InsetCommandParams const & p)
53         : InsetCommand(buf, p)
54 {}
55
56
57 void InsetLabel::initView()
58 {
59         // This seems to be used only for inset creation.
60         // Therefore we do not update refs here, since this would
61         // erroneously change refs from existing duplicate labels
62         // (#8141).
63         updateLabel(getParam("name"));
64 }
65
66
67 void InsetLabel::uniqueLabel(docstring & label) const
68 {
69         docstring const new_label = label;
70         int i = 1;
71         bool ambiguous = false;
72         while (buffer().activeLabel(label)) {
73                 label = new_label + '-' + convert<docstring>(i);
74                 ++i;
75                 ambiguous = true;
76         }
77         if (ambiguous) {
78                 // Warn the user that the label has been changed to something else.
79                 frontend::Alert::warning(_("Label names must be unique!"),
80                         bformat(_("The label %1$s already exists,\n"
81                         "it will be changed to %2$s."), new_label, label));
82         }
83 }
84
85
86 void InsetLabel::updateLabel(docstring const & new_label, bool const active)
87 {
88         docstring label = new_label;
89         if (active)
90                 uniqueLabel(label);
91         setParam("name", label);
92 }
93
94
95 void InsetLabel::updateLabelAndRefs(docstring const & new_label,
96                 Cursor * cursor)
97 {
98         docstring const old_label = getParam("name");
99         docstring label = new_label;
100         uniqueLabel(label);
101         if (label == old_label)
102                 return;
103
104         // This handles undo groups automagically
105         UndoGroupHelper ugh(&buffer());
106         if (cursor)
107                 cursor->recordUndo();
108         if (buffer().masterParams().track_changes) {
109                 // With change tracking, we insert a new label and
110                 // delete the old one
111                 InsetCommandParams p(LABEL_CODE, "label");
112                 p["name"] = label;
113                 string const data = InsetCommand::params2string(p);
114                 lyx::dispatch(FuncRequest(LFUN_INSET_INSERT, data));
115                 lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_FORWARD));
116         } else
117                 setParam("name", label);
118         updateReferences(old_label, label);
119 }
120
121
122 void InsetLabel::updateReferences(docstring const & old_label,
123                 docstring const & new_label)
124 {
125         UndoGroupHelper ugh(nullptr);
126         if (buffer().masterParams().track_changes) {
127                 // With change tracking, we insert a new ref and
128                 // delete the old one
129                 lyx::dispatch(FuncRequest(LFUN_MASTER_BUFFER_FORALL,
130                                           "inset-forall Ref inset-modify ref changetarget "
131                                           + old_label + " " + new_label));
132         } else {
133                 for (auto const & p: buffer().references(old_label)) {
134                         ugh.resetBuffer(p.second.buffer());
135                         CursorData(p.second).recordUndo();
136                         if (p.first->lyxCode() == MATH_REF_CODE) {
137                                 InsetMathRef * mi = p.first->asInsetMath()->asRefInset();
138                                 mi->changeTarget(new_label);
139                         } else {
140                                 InsetCommand * ref = p.first->asInsetCommand();
141                                 ref->setParam("reference", new_label);
142                         }
143                 }
144         }
145 }
146
147
148 ParamInfo const & InsetLabel::findInfo(string const & /* cmdName */)
149 {
150         static ParamInfo param_info_;
151         if (param_info_.empty())
152                 param_info_.add("name", ParamInfo::LATEX_REQUIRED,
153                                 ParamInfo::HANDLING_ESCAPE);
154         return param_info_;
155 }
156
157
158 docstring InsetLabel::screenLabel() const
159 {
160         return screen_label_;
161 }
162
163
164 void InsetLabel::updateBuffer(ParIterator const & par, UpdateType utype, bool const /*deleted*/)
165 {
166         docstring const & label = getParam("name");
167
168         // Check if this one is active (i.e., neither deleted with change-tracking
169         // nor in an inset that does not produce output, such as notes or inactive branches)
170         Paragraph const & para = par.paragraph();
171         bool active = !para.isDeleted(par.pos()) && para.inInset().producesOutput();
172         // If not, check whether we are in a deleted/non-outputting inset
173         if (active) {
174                 for (size_type sl = 0 ; sl < par.depth() ; ++sl) {
175                         Paragraph const & outer_par = par[sl].paragraph();
176                         if (outer_par.isDeleted(par[sl].pos())
177                             || !outer_par.inInset().producesOutput()) {
178                                 active = false;
179                                 break;
180                         }
181                 }
182         }
183
184         if (buffer().activeLabel(label) && active) {
185                 // Problem: We already have an active InsetLabel with the same name!
186                 screen_label_ = _("DUPLICATE: ") + label;
187                 return;
188         }
189         buffer().setInsetLabel(label, this, active);
190         screen_label_ = label;
191
192         if (utype == OutputUpdate) {
193                 // save info on the active counter
194                 Counters const & cnts =
195                         buffer().masterBuffer()->params().documentClass().counters();
196                 active_counter_ = cnts.currentCounter();
197                 Language const * lang = par->getParLanguage(buffer().params());
198                 if (lang && !active_counter_.empty()) {
199                         counter_value_ = cnts.theCounter(active_counter_, lang->code());
200                         pretty_counter_ = cnts.prettyCounter(active_counter_, lang->code());
201                 } else {
202                         counter_value_ = from_ascii("#");
203                         pretty_counter_ = from_ascii("#");
204                 }
205         }
206 }
207
208
209 void InsetLabel::addToToc(DocIterator const & cpit, bool output_active,
210                           UpdateType, TocBackend & backend) const
211 {
212         docstring const & label = getParam("name");
213
214         // inactive labels get a cross mark
215         if (buffer().insetLabel(label, true) != this)
216                 output_active = false;
217
218         // We put both  active and inactive labels to the outliner
219         shared_ptr<Toc> toc = backend.toc("label");
220         toc->push_back(TocItem(cpit, 0, screen_label_, output_active));
221         // The refs get assigned only to the active label. If no active one exists,
222         // assign the (BROKEN) refs to the first inactive one.
223         if (buffer().insetLabel(label, true) == this || !buffer().activeLabel(label)) {
224                 for (auto const & p : buffer().references(label)) {
225                         DocIterator const ref_pit(p.second);
226                         if (p.first->lyxCode() == MATH_REF_CODE)
227                                 toc->push_back(TocItem(ref_pit, 1,
228                                                 p.first->asInsetMath()->asRefInset()->screenLabel(),
229                                                 output_active));
230                         else
231                                 toc->push_back(TocItem(ref_pit, 1,
232                                                 static_cast<InsetRef *>(p.first)->getTOCString(),
233                                                 static_cast<InsetRef *>(p.first)->outputActive()));
234                 }
235         }
236 }
237
238
239 bool InsetLabel::getStatus(Cursor & cur, FuncRequest const & cmd,
240                            FuncStatus & status) const
241 {
242         bool enabled;
243         switch (cmd.action()) {
244         case LFUN_LABEL_INSERT_AS_REFERENCE:
245         case LFUN_LABEL_COPY_AS_REFERENCE:
246                 enabled = true;
247                 break;
248         case LFUN_INSET_MODIFY:
249                 if (cmd.getArg(0) == "changetype") {
250                         // this is handled by InsetCommand,
251                         // but not by InsetLabel.
252                         enabled = false;
253                         break;
254                 }
255                 // no "changetype":
256                 // fall through
257         default:
258                 return InsetCommand::getStatus(cur, cmd, status);
259         }
260
261         status.setEnabled(enabled);
262         return true;
263 }
264
265
266 void InsetLabel::doDispatch(Cursor & cur, FuncRequest & cmd)
267 {
268         switch (cmd.action()) {
269
270         case LFUN_INSET_MODIFY: {
271                 // the only other option here is "changetype", and we
272                 // do not have different types.
273                 if (cmd.getArg(0) != "label") {
274                         cur.undispatched();
275                         return;
276                 }
277                 InsetCommandParams p(LABEL_CODE);
278                 // FIXME UNICODE
279                 InsetCommand::string2params(to_utf8(cmd.argument()), p);
280                 if (p.getCmdName().empty()) {
281                         cur.noScreenUpdate();
282                         break;
283                 }
284                 if (p["name"] != params()["name"]) {
285                         // undo is handled in updateLabelAndRefs
286                         updateLabelAndRefs(p["name"], &cur);
287                 }
288                 cur.forceBufferUpdate();
289                 break;
290         }
291
292         case LFUN_LABEL_COPY_AS_REFERENCE: {
293                 InsetCommandParams p(REF_CODE, "ref");
294                 p["reference"] = getParam("name");
295                 cap::clearSelection();
296                 cap::copyInset(cur, new InsetRef(buffer_, p), getParam("name"));
297                 break;
298         }
299
300         case LFUN_LABEL_INSERT_AS_REFERENCE: {
301                 InsetCommandParams p(REF_CODE, "ref");
302                 p["reference"] = getParam("name");
303                 string const data = InsetCommand::params2string(p);
304                 lyx::dispatch(FuncRequest(LFUN_INSET_INSERT, data));
305                 break;
306         }
307
308         default:
309                 InsetCommand::doDispatch(cur, cmd);
310                 break;
311         }
312 }
313
314
315 void InsetLabel::latex(otexstream & os, OutputParams const & runparams_in) const
316 {
317         OutputParams runparams = runparams_in;
318         docstring command = getCommand(runparams);
319         docstring const label = getParam("name");
320         if (buffer().params().output_changes
321             && buffer().activeLabel(label)
322             && buffer().insetLabel(label, true) != this) {
323                 // this is a deleted label and we have a non-deleted with the same id
324                 // rename it for output to prevent wrong references
325                 docstring newlabel = label;
326                 int i = 1;
327                 while (buffer().insetLabel(newlabel)) {
328                         newlabel = label + "-DELETED-" + convert<docstring>(i);
329                         ++i;
330                 }
331                 command = subst(command, label, newlabel);
332         }
333         // In macros with moving arguments, such as \section,
334         // we store the label and output it after the macro (#2154)
335         if (runparams_in.postpone_fragile_stuff)
336                 runparams_in.post_macro += command;
337         else {
338                 // protect label in moving argument (#9404),
339                 // but not in subfloat caption (#11950)
340                 if (runparams.moving_arg
341                     && runparams.inFloat != OutputParams::SUBFLOAT)
342                         os << "\\protect";
343                 os << command;
344         }
345 }
346
347
348 int InsetLabel::plaintext(odocstringstream & os,
349         OutputParams const &, size_t) const
350 {
351         docstring const str = getParam("name");
352         os << '<' << str << '>';
353         return 2 + str.size();
354 }
355
356
357 void InsetLabel::docbook(XMLStream & xs, OutputParams const & runparams) const
358 {
359         // Output an anchor only if it has not been processed before.
360         docstring id = getParam("name");
361         docstring cleaned_id = xml::cleanID(id);
362         if (runparams.docbook_anchors_to_ignore.find(id) == runparams.docbook_anchors_to_ignore.end() &&
363                 runparams.docbook_anchors_to_ignore.find(cleaned_id) == runparams.docbook_anchors_to_ignore.end()) {
364                 docstring attr = from_utf8("xml:id=\"") + cleaned_id + from_utf8("\"");
365                 xs << xml::CompTag("anchor", to_utf8(attr));
366         }
367 }
368
369
370 docstring InsetLabel::xhtml(XMLStream & xs, OutputParams const &) const
371 {
372         // FIXME XHTML
373         // Unfortunately, the name attribute has been deprecated, so we have to use
374         // id here to get the document to validate as XHTML 1.1. This will cause a
375         // problem with some browsers, though, I'm sure. (Guess which!) So we will
376         // have to figure out what to do about this later.
377         docstring const attr = "id=\"" + xml::cleanAttr(getParam("name")) + '"';
378         xs << xml::CompTag("a", to_utf8(attr));
379         return docstring();
380 }
381
382
383 } // namespace lyx