]> git.lyx.org Git - lyx.git/blob - src/insets/InsetLabel.cpp
bcb72904bb465b9527c5deae24e46869edf89bb9
[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 "CutAndPaste.h"
22 #include "DispatchResult.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "InsetIterator.h"
26 #include "Language.h"
27 #include "LyX.h"
28 #include "output_xhtml.h"
29 #include "ParIterator.h"
30 #include "sgml.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().params().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;
126         for (auto const & p: buffer().references(old_label)) {
127                 ugh.resetBuffer(p.second.buffer());
128                 CursorData(p.second).recordUndo();
129                 if (p.first->lyxCode() == MATH_REF_CODE) {
130                         InsetMathRef * mi = p.first->asInsetMath()->asRefInset();
131                         mi->changeTarget(new_label);
132                 } else {
133                         InsetCommand * ref = p.first->asInsetCommand();
134                         ref->setParam("reference", new_label);
135                 }
136         }
137 }
138
139
140 ParamInfo const & InsetLabel::findInfo(string const & /* cmdName */)
141 {
142         static ParamInfo param_info_;
143         if (param_info_.empty())
144                 param_info_.add("name", ParamInfo::LATEX_REQUIRED,
145                                 ParamInfo::HANDLING_ESCAPE);
146         return param_info_;
147 }
148
149
150 docstring InsetLabel::screenLabel() const
151 {
152         return screen_label_;
153 }
154
155
156 void InsetLabel::updateBuffer(ParIterator const & par, UpdateType utype)
157 {
158         docstring const & label = getParam("name");
159
160         // Check if this one is active (i.e., neither deleted with change-tracking
161         // nor in an inset that does not produce output, such as notes or inactive branches)
162         Paragraph const & para = par.paragraph();
163         bool active = !para.isDeleted(par.pos()) && para.inInset().producesOutput();
164         // If not, check whether we are in a deleted/non-outputting inset
165         if (active) {
166                 for (size_type sl = 0 ; sl < par.depth() ; ++sl) {
167                         Paragraph const & outer_par = par[sl].paragraph();
168                         if (outer_par.isDeleted(par[sl].pos())
169                             || !outer_par.inInset().producesOutput()) {
170                                 active = false;
171                                 break;
172                         }
173                 }
174         }
175
176         if (buffer().activeLabel(label) && active) {
177                 // Problem: We already have an active InsetLabel with the same name!
178                 screen_label_ = _("DUPLICATE: ") + label;
179                 return;
180         }
181         buffer().setInsetLabel(label, this, active);
182         screen_label_ = label;
183
184         if (utype == OutputUpdate) {
185                 // save info on the active counter
186                 Counters const & cnts =
187                         buffer().masterBuffer()->params().documentClass().counters();
188                 active_counter_ = cnts.currentCounter();
189                 Language const * lang = par->getParLanguage(buffer().params());
190                 if (lang && !active_counter_.empty()) {
191                         counter_value_ = cnts.theCounter(active_counter_, lang->code());
192                         pretty_counter_ = cnts.prettyCounter(active_counter_, lang->code());
193                 } else {
194                         counter_value_ = from_ascii("#");
195                         pretty_counter_ = from_ascii("#");
196                 }
197         }
198 }
199
200
201 void InsetLabel::addToToc(DocIterator const & cpit, bool output_active,
202                           UpdateType, TocBackend & backend) const
203 {
204         docstring const & label = getParam("name");
205
206         // inactive labels get a cross mark
207         if (buffer().insetLabel(label, true) != this)
208                 output_active = false;
209
210         // We put both  active and inactive labels to the outliner
211         shared_ptr<Toc> toc = backend.toc("label");
212         toc->push_back(TocItem(cpit, 0, screen_label_, output_active));
213         // The refs get assigned only to the active label. If no active one exists,
214         // assign the (BROKEN) refs to the first inactive one.
215         if (buffer().insetLabel(label, true) == this || !buffer().activeLabel(label)) {
216                 for (auto const & p : buffer().references(label)) {
217                         DocIterator const ref_pit(p.second);
218                         if (p.first->lyxCode() == MATH_REF_CODE)
219                                 toc->push_back(TocItem(ref_pit, 1,
220                                                 p.first->asInsetMath()->asRefInset()->screenLabel(),
221                                                 output_active));
222                         else
223                                 toc->push_back(TocItem(ref_pit, 1,
224                                                 static_cast<InsetRef *>(p.first)->getTOCString(),
225                                                 output_active));
226                 }
227         }
228 }
229
230
231 bool InsetLabel::getStatus(Cursor & cur, FuncRequest const & cmd,
232                            FuncStatus & status) const
233 {
234         bool enabled;
235         switch (cmd.action()) {
236         case LFUN_LABEL_INSERT_AS_REFERENCE:
237         case LFUN_LABEL_COPY_AS_REFERENCE:
238                 enabled = true;
239                 break;
240         case LFUN_INSET_MODIFY:
241                 if (cmd.getArg(0) == "changetype") {
242                         // this is handled by InsetCommand,
243                         // but not by InsetLabel.
244                         enabled = false;
245                         break;
246                 }
247                 // no "changetype":
248                 // fall through
249         default:
250                 return InsetCommand::getStatus(cur, cmd, status);
251         }
252
253         status.setEnabled(enabled);
254         return true;
255 }
256
257
258 void InsetLabel::doDispatch(Cursor & cur, FuncRequest & cmd)
259 {
260         switch (cmd.action()) {
261
262         case LFUN_INSET_MODIFY: {
263                 // the only other option here is "changetype", and we
264                 // do not have different types.
265                 if (cmd.getArg(0) != "label") {
266                         cur.undispatched();
267                         return;
268                 }
269                 InsetCommandParams p(LABEL_CODE);
270                 // FIXME UNICODE
271                 InsetCommand::string2params(to_utf8(cmd.argument()), p);
272                 if (p.getCmdName().empty()) {
273                         cur.noScreenUpdate();
274                         break;
275                 }
276                 if (p["name"] != params()["name"]) {
277                         // undo is handled in updateLabelAndRefs
278                         updateLabelAndRefs(p["name"], &cur);
279                 }
280                 cur.forceBufferUpdate();
281                 break;
282         }
283
284         case LFUN_LABEL_COPY_AS_REFERENCE: {
285                 InsetCommandParams p(REF_CODE, "ref");
286                 p["reference"] = getParam("name");
287                 cap::clearSelection();
288                 cap::copyInset(cur, new InsetRef(buffer_, p), getParam("name"));
289                 break;
290         }
291
292         case LFUN_LABEL_INSERT_AS_REFERENCE: {
293                 InsetCommandParams p(REF_CODE, "ref");
294                 p["reference"] = getParam("name");
295                 string const data = InsetCommand::params2string(p);
296                 lyx::dispatch(FuncRequest(LFUN_INSET_INSERT, data));
297                 break;
298         }
299
300         default:
301                 InsetCommand::doDispatch(cur, cmd);
302                 break;
303         }
304 }
305
306
307 void InsetLabel::latex(otexstream & os, OutputParams const & runparams_in) const
308 {
309         OutputParams runparams = runparams_in;
310         docstring command = getCommand(runparams);
311         // In macros with moving arguments, such as \section,
312         // we store the label and output it after the macro (#2154)
313         if (runparams_in.postpone_fragile_stuff)
314                 runparams_in.post_macro += command;
315         else {
316                 if (runparams.moving_arg)
317                         os << "\\protect";
318                 os << command;
319         }
320 }
321
322
323 int InsetLabel::plaintext(odocstringstream & os,
324         OutputParams const &, size_t) const
325 {
326         docstring const str = getParam("name");
327         os << '<' << str << '>';
328         return 2 + str.size();
329 }
330
331
332 int InsetLabel::docbook(odocstream & os, OutputParams const & runparams) const
333 {
334         os << "<!-- anchor id=\""
335            << sgml::cleanID(buffer(), runparams, getParam("name"))
336            << "\" -->";
337         return 0;
338 }
339
340
341 docstring InsetLabel::xhtml(XHTMLStream & xs, OutputParams const &) const
342 {
343         // FIXME XHTML
344         // Unfortunately, the name attribute has been deprecated, so we have to use
345         // id here to get the document to validate as XHTML 1.1. This will cause a
346         // problem with some browsers, though, I'm sure. (Guess which!) So we will
347         // have to figure out what to do about this later.
348         docstring const attr = "id=\"" + html::cleanAttr(getParam("name")) + '"';
349         xs << html::CompTag("a", to_utf8(attr));
350         return docstring();
351 }
352
353
354 } // namespace lyx