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