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