]> git.lyx.org Git - lyx.git/blob - src/insets/InsetRef.cpp
InsetTabular.cpp: fix #7003 that I accidentally introduced when fixing #6958
[lyx.git] / src / insets / InsetRef.cpp
1 /**
2  * \file InsetRef.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author José Matos
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10 #include <config.h>
11
12 #include "InsetRef.h"
13
14 #include "Buffer.h"
15 #include "BufferParams.h"
16 #include "Cursor.h"
17 #include "DispatchResult.h"
18 #include "InsetLabel.h"
19 #include "LaTeXFeatures.h"
20 #include "LyX.h"
21 #include "OutputParams.h"
22 #include "output_xhtml.h"
23 #include "ParIterator.h"
24 #include "sgml.h"
25 #include "TocBackend.h"
26
27 #include "support/debug.h"
28 #include "support/docstream.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31
32 using namespace lyx::support;
33 using namespace std;
34
35 namespace lyx {
36
37
38 InsetRef::InsetRef(Buffer * buf, InsetCommandParams const & p)
39         : InsetCommand(buf, p)
40 {}
41
42
43 InsetRef::InsetRef(InsetRef const & ir)
44         : InsetCommand(ir)
45 {}
46
47
48 bool InsetRef::isCompatibleCommand(string const & s) {
49         //FIXME This is likely not the best way to handle this.
50         //But this stuff is hardcoded elsewhere already.
51         return s == "ref" 
52                 || s == "pageref"
53                 || s == "vref" 
54                 || s == "vpageref"
55                 || s == "formatted"
56                 || s == "eqref"
57                 || s == "nameref";
58 }
59
60
61 ParamInfo const & InsetRef::findInfo(string const & /* cmdName */)
62 {
63         static ParamInfo param_info_;
64         if (param_info_.empty()) {
65                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL);
66                 param_info_.add("reference", ParamInfo::LATEX_REQUIRED,
67                                 ParamInfo::HANDLING_ESCAPE);
68         }
69         return param_info_;
70 }
71
72
73 // for refstyle, given pfx:suffix, we want to return "\\pfxcmd"
74 // and put "suffix" into label.
75 // otherwise, we put the reference into label.
76 docstring InsetRef::getFormattedCmd(
77                 docstring const & ref, docstring & label) const
78 {
79         static docstring const defcmd = from_ascii("\\ref");
80         // default is that label is data
81         // we'll change it if need be
82         if (!buffer().params().use_refstyle) {
83                 label = ref;
84                 return from_ascii("\\prettyref");
85         }
86
87         docstring prefix;
88         label = split(ref, prefix, ':');
89         if (prefix.empty()) {
90                 LYXERR0("Label `" << label << "' contains no prefix.");
91                 label = ref;
92                 return defcmd;
93         }
94         
95         // make sure the prefix is legal for a latex command
96         int const len = prefix.size();
97         for (int i = 0; i < len; i++) {
98                 if (!isalpha(prefix[i])) {
99                         LYXERR0("Prefix `" << prefix << "' contains non-letters.");
100                         // restore the label
101                         label = ref;
102                         return defcmd;
103                 }
104         }
105         return from_ascii("\\") + prefix + from_ascii("ref");
106 }
107
108
109 docstring InsetRef::getEscapedLabel(OutputParams const & rp) const
110 {
111         InsetCommandParams const & p = params();
112         ParamInfo const & pi = p.info();
113         ParamInfo::ParamData const & pd = pi["reference"];
114         return p.prepareCommand(rp, getParam("reference"), pd.handling());              
115 }
116
117
118 int InsetRef::latex(odocstream & os, OutputParams const & rp) const
119 {
120         string const cmd = getCmdName();
121         if (cmd != "formatted") {
122                 // We don't want to output p_["name"], since that is only used 
123                 // in docbook. So we construct new params, without it, and use that.
124                 InsetCommandParams p(REF_CODE, cmd);
125                 docstring const ref = getParam("reference");
126                 p["reference"] = ref;
127                 os << p.getCommand(rp);
128                 return 0;
129         } 
130         
131         // so we're doing a formatted reference.
132         docstring const data = getEscapedLabel(rp);
133         docstring label;
134         docstring const fcmd = getFormattedCmd(data, label);
135         os << fcmd << '{' << label << '}';
136         return 0;
137 }
138
139
140 int InsetRef::plaintext(odocstream & os, OutputParams const &) const
141 {
142         docstring const str = getParam("reference");
143         os << '[' << str << ']';
144         return 2 + str.size();
145 }
146
147
148 int InsetRef::docbook(odocstream & os, OutputParams const & runparams) const
149 {
150         docstring const & name = getParam("name");
151         if (name.empty()) {
152                 if (runparams.flavor == OutputParams::XML) {
153                         os << "<xref linkend=\""
154                            << sgml::cleanID(buffer(), runparams, getParam("reference"))
155                            << "\" />";
156                 } else {
157                         os << "<xref linkend=\""
158                            << sgml::cleanID(buffer(), runparams, getParam("reference"))
159                            << "\">";
160                 }
161         } else {
162                 os << "<link linkend=\""
163                    << sgml::cleanID(buffer(), runparams, getParam("reference"))
164                    << "\">"
165                    << getParam("name")
166                    << "</link>";
167         }
168
169         return 0;
170 }
171
172
173 docstring InsetRef::xhtml(XHTMLStream & xs, OutputParams const &) const
174 {
175         docstring const & ref = getParam("reference");
176         InsetLabel const * il = buffer().insetLabel(ref);
177         string const & cmd = params().getCmdName();
178         docstring display_string;
179
180         if (il && !il->counterValue().empty()) {
181                 // Try to construct a label from the InsetLabel we reference.
182                 docstring const & value = il->counterValue();
183                 if (cmd == "ref")
184                         display_string = value;
185                 else if (cmd == "vref")
186                         // normally, would be "ref on page #", but we have no pages
187                         display_string = value;
188                 else if (cmd == "pageref" || cmd == "vpageref")
189                         // normally would be "on page #", but we have no pages
190                         display_string = _("elsewhere");
191                 else if (cmd == "eqref")
192                         display_string = bformat(from_ascii("equation (%1$s)"), value);
193                 else if (cmd == "prettyref" 
194                          // we don't really have the ability to handle these 
195                          // properly in XHTML output
196                          || cmd == "nameref")
197                         display_string = il->prettyCounter();
198         } else 
199                         display_string = ref;
200
201         // FIXME What we'd really like to do is to be able to output some
202         // appropriate sort of text here. But to do that, we need to associate
203         // some sort of counter with the label, and we don't have that yet.
204         string const attr = "href=\"#" + html::cleanAttr(to_utf8(ref)) + "\"";
205         xs << html::StartTag("a", attr);
206         xs << display_string;
207         xs << html::EndTag("a");
208         return docstring();
209 }
210
211
212 void InsetRef::tocString(odocstream & os) const
213 {
214         plaintext(os, OutputParams(0));
215 }
216
217
218 void InsetRef::updateBuffer(ParIterator const & it, UpdateType)
219 {
220         docstring const & ref = getParam("reference");
221         // register this inset into the buffer reference cache.
222         buffer().references(ref).push_back(make_pair(this, it));
223
224         docstring label;
225         for (int i = 0; !types[i].latex_name.empty(); ++i) {
226                 if (getCmdName() == types[i].latex_name) {
227                         label = _(types[i].short_gui_name);
228                         break;
229                 }
230         }
231         label += ref;
232         
233         if (!buffer().isLatex() && !getParam("name").empty()) {
234                 label += "||";
235                 label += getParam("name");
236         }
237         
238         screen_label_ = label;
239         bool shortened = false;
240         unsigned int const maxLabelChars = 24;
241         if (screen_label_.size() > maxLabelChars) {
242                 screen_label_.erase(maxLabelChars - 3);
243                 screen_label_ += "...";
244                 shortened = true;
245         }
246         if (shortened)
247                 tooltip_ = label;
248         else 
249                 tooltip_ = from_ascii("");
250 }
251
252
253 void InsetRef::addToToc(DocIterator const & cpit)
254 {
255         docstring const & label = getParam("reference");
256         if (buffer().insetLabel(label))
257                 // This InsetRef has already been taken care of in InsetLabel::addToToc().
258                 return;
259
260         // It seems that this reference does not point to any valid label.
261         screen_label_ = _("BROKEN: ") + screen_label_;
262         Toc & toc = buffer().tocBackend().toc("label");
263         toc.push_back(TocItem(cpit, 0, screen_label_));
264 }
265
266
267 void InsetRef::validate(LaTeXFeatures & features) const
268 {
269         string const cmd = getCmdName();
270         if (cmd == "vref" || cmd == "vpageref")
271                 features.require("varioref");
272         else if (getCmdName() == "formatted") {
273                 if (buffer().params().use_refstyle) {
274                         features.require("refstyle");
275                         docstring const data = getEscapedLabel(features.runparams());
276                         docstring label;
277                         string const fcmd = to_utf8(getFormattedCmd(data, label));
278                         if (fcmd != "\\ref") {
279                                 string lcmd = "\\AtBeginDocument{\\providecommand" + fcmd + "[1]{\\ref{#1}}}";
280                                 features.addPreambleSnippet(lcmd);
281                         }
282                 } else
283                         features.require("prettyref");
284         } else if (getCmdName() == "eqref" && !buffer().params().use_refstyle)
285                 // refstyle defines its own version
286                 features.require("amsmath");
287         else if (cmd == "nameref")
288                 features.require("nameref");
289 }
290
291
292 InsetRef::type_info InsetRef::types[] = {
293         { "ref",       N_("Standard"),              N_("Ref: ")},
294         { "eqref",     N_("Equation"),              N_("EqRef: ")},
295         { "pageref",   N_("Page Number"),           N_("Page: ")},
296         { "vpageref",  N_("Textual Page Number"),   N_("TextPage: ")},
297         { "vref",      N_("Standard+Textual Page"), N_("Ref+Text: ")},
298         { "formatted", N_("Formatted"),             N_("Format: ")},
299         { "nameref",   N_("Reference to Name"),     N_("NameRef:")},
300         { "", "", "" }
301 };
302
303
304 int InsetRef::getType(string const & name)
305 {
306         for (int i = 0; !types[i].latex_name.empty(); ++i)
307                 if (name == types[i].latex_name)
308                         return i;
309         return 0;
310 }
311
312
313 string const & InsetRef::getName(int type)
314 {
315         return types[type].latex_name;
316 }
317
318
319 } // namespace lyx