]> git.lyx.org Git - features.git/blob - src/insets/InsetLabel.cpp
e325f1ea94c5431b6c019d9c9719b39e4ad0494f
[features.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 "Text.h"
32 #include "TextClass.h"
33 #include "TocBackend.h"
34
35 #include "mathed/InsetMathHull.h"
36 #include "mathed/InsetMathRef.h"
37
38 #include "frontends/alert.h"
39
40 #include "support/convert.h"
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43 #include "support/lyxalgo.h"
44
45 using namespace std;
46 using namespace lyx::support;
47
48 namespace lyx {
49
50
51 InsetLabel::InsetLabel(Buffer * buf, InsetCommandParams const & p)
52         : InsetCommand(buf, p)
53 {}
54
55
56 void InsetLabel::initView()
57 {
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
61         // (#8141).
62         updateLabel(getParam("name"));
63 }
64
65
66 void InsetLabel::uniqueLabel(docstring & label) const
67 {
68         docstring const new_label = label;
69         int i = 1;
70         bool ambiguous = false;
71         while (buffer().activeLabel(label)) {
72                 label = new_label + '-' + convert<docstring>(i);
73                 ++i;
74                 ambiguous = true;
75         }
76         if (ambiguous) {
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));
81         }
82 }
83
84
85 void InsetLabel::updateLabel(docstring const & new_label, bool const active)
86 {
87         docstring label = new_label;
88         if (active)
89                 uniqueLabel(label);
90         setParam("name", label);
91 }
92
93
94 void InsetLabel::updateLabelAndRefs(docstring const & new_label,
95                 Cursor * cursor)
96 {
97         docstring const old_label = getParam("name");
98         docstring label = new_label;
99         uniqueLabel(label);
100         if (label == old_label)
101                 return;
102
103         // This handles undo groups automagically
104         UndoGroupHelper ugh(&buffer());
105         if (cursor)
106                 cursor->recordUndo();
107         setParam("name", label);
108         updateReferences(old_label, label);
109 }
110
111
112 void InsetLabel::updateReferences(docstring const & old_label,
113                 docstring const & new_label)
114 {
115         UndoGroupHelper ugh;
116         for (auto const & p: buffer().references(old_label)) {
117                 ugh.resetBuffer(p.second.buffer());
118                 CursorData(p.second).recordUndo();
119                 if (p.first->lyxCode() == MATH_REF_CODE) {
120                         InsetMathRef * mi = p.first->asInsetMath()->asRefInset();
121                         mi->changeTarget(new_label);
122                 } else {
123                         InsetCommand * ref = p.first->asInsetCommand();
124                         ref->setParam("reference", new_label);
125                 }
126         }
127 }
128
129
130 ParamInfo const & InsetLabel::findInfo(string const & /* cmdName */)
131 {
132         static ParamInfo param_info_;
133         if (param_info_.empty())
134                 param_info_.add("name", ParamInfo::LATEX_REQUIRED,
135                                 ParamInfo::HANDLING_ESCAPE);
136         return param_info_;
137 }
138
139
140 docstring InsetLabel::screenLabel() const
141 {
142         return screen_label_;
143 }
144
145
146 void InsetLabel::updateBuffer(ParIterator const & par, UpdateType utype)
147 {
148         docstring const & label = getParam("name");
149
150         // Check if this one is active (i.e., neither deleted with change-tracking
151         // nor in an inset that does not produce output, such as notes or inactive branches)
152         Paragraph const & para = par.paragraph();
153         bool active = !para.isDeleted(par.pos()) && para.inInset().producesOutput();
154         // If not, check whether we are in a deleted/non-outputting inset
155         if (active) {
156                 for (size_type sl = 0 ; sl < par.depth() ; ++sl) {
157                         Paragraph const & outer_par = par[sl].paragraph();
158                         if (outer_par.isDeleted(par[sl].pos())
159                             || !outer_par.inInset().producesOutput()) {
160                                 active = false;
161                                 break;
162                         }
163                 }
164         }
165
166         if (buffer().activeLabel(label) && active) {
167                 // Problem: We already have an active InsetLabel with the same name!
168                 screen_label_ = _("DUPLICATE: ") + label;
169                 return;
170         }
171         buffer().setInsetLabel(label, this, active);
172         screen_label_ = label;
173
174         if (utype == OutputUpdate) {
175                 // save info on the active counter
176                 Counters const & cnts =
177                         buffer().masterBuffer()->params().documentClass().counters();
178                 active_counter_ = cnts.currentCounter();
179                 Language const * lang = par->getParLanguage(buffer().params());
180                 if (lang && !active_counter_.empty()) {
181                         counter_value_ = cnts.theCounter(active_counter_, lang->code());
182                         pretty_counter_ = cnts.prettyCounter(active_counter_, lang->code());
183                 } else {
184                         counter_value_ = from_ascii("#");
185                         pretty_counter_ = from_ascii("#");
186                 }
187         }
188 }
189
190
191 void InsetLabel::addToToc(DocIterator const & cpit, bool output_active,
192                           UpdateType, TocBackend & backend) const
193 {
194         docstring const & label = getParam("name");
195
196         // inactive labels get a cross mark
197         if (buffer().insetLabel(label, true) != this)
198                 output_active = false;
199
200         // We put both  active and inactive labels to the outliner
201         shared_ptr<Toc> toc = backend.toc("label");
202         toc->push_back(TocItem(cpit, 0, screen_label_, output_active));
203         // The refs get assigned only to the active label. If no active one exists,
204         // assign the (BROKEN) refs to the first inactive one.
205         if (buffer().insetLabel(label, true) == this || !buffer().activeLabel(label)) {
206                 for (auto const & p : buffer().references(label)) {
207                         DocIterator const ref_pit(p.second);
208                         if (p.first->lyxCode() == MATH_REF_CODE)
209                                 toc->push_back(TocItem(ref_pit, 1,
210                                                 p.first->asInsetMath()->asRefInset()->screenLabel(),
211                                                 output_active));
212                         else
213                                 toc->push_back(TocItem(ref_pit, 1,
214                                                 static_cast<InsetRef *>(p.first)->getTOCString(),
215                                                 output_active));
216                 }
217         }
218 }
219
220
221 bool InsetLabel::getStatus(Cursor & cur, FuncRequest const & cmd,
222                            FuncStatus & status) const
223 {
224         bool enabled;
225         switch (cmd.action()) {
226         case LFUN_LABEL_INSERT_AS_REFERENCE:
227         case LFUN_LABEL_COPY_AS_REFERENCE:
228                 enabled = true;
229                 break;
230         case LFUN_INSET_MODIFY:
231                 if (cmd.getArg(0) == "changetype") {
232                         // this is handled by InsetCommand,
233                         // but not by InsetLabel.
234                         enabled = false;
235                         break;
236                 }
237                 // no "changetype":
238                 // fall through
239         default:
240                 return InsetCommand::getStatus(cur, cmd, status);
241         }
242
243         status.setEnabled(enabled);
244         return true;
245 }
246
247
248 void InsetLabel::doDispatch(Cursor & cur, FuncRequest & cmd)
249 {
250         switch (cmd.action()) {
251
252         case LFUN_INSET_MODIFY: {
253                 // the only other option here is "changetype", and we
254                 // do not have different types.
255                 if (cmd.getArg(0) != "label") {
256                         cur.undispatched();
257                         return;
258                 }
259                 InsetCommandParams p(LABEL_CODE);
260                 // FIXME UNICODE
261                 InsetCommand::string2params(to_utf8(cmd.argument()), p);
262                 if (p.getCmdName().empty()) {
263                         cur.noScreenUpdate();
264                         break;
265                 }
266                 if (p["name"] != params()["name"]) {
267                         // undo is handled in updateLabelAndRefs
268                         updateLabelAndRefs(p["name"], &cur);
269                 }
270                 cur.forceBufferUpdate();
271                 break;
272         }
273
274         case LFUN_LABEL_COPY_AS_REFERENCE: {
275                 InsetCommandParams p(REF_CODE, "ref");
276                 p["reference"] = getParam("name");
277                 cap::clearSelection();
278                 cap::copyInset(cur, new InsetRef(buffer_, p), getParam("name"));
279                 break;
280         }
281
282         case LFUN_LABEL_INSERT_AS_REFERENCE: {
283                 InsetCommandParams p(REF_CODE, "ref");
284                 p["reference"] = getParam("name");
285                 string const data = InsetCommand::params2string(p);
286                 lyx::dispatch(FuncRequest(LFUN_INSET_INSERT, data));
287                 break;
288         }
289
290         default:
291                 InsetCommand::doDispatch(cur, cmd);
292                 break;
293         }
294 }
295
296
297 int InsetLabel::plaintext(odocstringstream & os,
298         OutputParams const &, size_t) const
299 {
300         docstring const str = getParam("name");
301         os << '<' << str << '>';
302         return 2 + str.size();
303 }
304
305
306 int InsetLabel::docbook(odocstream & os, OutputParams const & runparams) const
307 {
308         os << "<!-- anchor id=\""
309            << sgml::cleanID(buffer(), runparams, getParam("name"))
310            << "\" -->";
311         return 0;
312 }
313
314
315 docstring InsetLabel::xhtml(XHTMLStream & xs, OutputParams const &) const
316 {
317         // FIXME XHTML
318         // Unfortunately, the name attribute has been deprecated, so we have to use
319         // id here to get the document to validate as XHTML 1.1. This will cause a
320         // problem with some browsers, though, I'm sure. (Guess which!) So we will
321         // have to figure out what to do about this later.
322         docstring const attr = "id=\"" + html::cleanAttr(getParam("name")) + '"';
323         xs << html::CompTag("a", to_utf8(attr));
324         return docstring();
325 }
326
327
328 } // namespace lyx