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