]> git.lyx.org Git - lyx.git/blob - src/insets/InsetRef.cpp
73ee8cbbcb8c4cadd3ad3f0d04fc5cd4d1c76990
[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         static docstring const prtcmd = from_ascii("\\prettyref");
81         
82         docstring prefix;
83         label = split(ref, prefix, ':');
84
85         // we have to have xxx:xxxxx...
86         if (prefix.empty()) {
87                 LYXERR0("Label `" << label << "' contains no prefix.");
88                 label = ref;
89                 return defcmd;
90         }
91         
92         if (!buffer().params().use_refstyle) {
93                 // \prettyref uses the whole label
94                 label = ref;
95                 return prtcmd;
96         }
97
98         // make sure the prefix is legal for a latex command
99         int const len = prefix.size();
100         for (int i = 0; i < len; i++) {
101                 if (!isalpha(prefix[i])) {
102                         LYXERR0("Prefix `" << prefix << "' contains non-letters.");
103                         // restore the label
104                         label = ref;
105                         return defcmd;
106                 }
107         }
108         return from_ascii("\\") + prefix + from_ascii("ref");
109 }
110
111
112 docstring InsetRef::getEscapedLabel(OutputParams const & rp) const
113 {
114         InsetCommandParams const & p = params();
115         ParamInfo const & pi = p.info();
116         ParamInfo::ParamData const & pd = pi["reference"];
117         return p.prepareCommand(rp, getParam("reference"), pd.handling());              
118 }
119
120
121 int InsetRef::latex(odocstream & os, OutputParams const & rp) const
122 {
123         string const cmd = getCmdName();
124         if (cmd != "formatted") {
125                 // We don't want to output p_["name"], since that is only used 
126                 // in docbook. So we construct new params, without it, and use that.
127                 InsetCommandParams p(REF_CODE, cmd);
128                 docstring const ref = getParam("reference");
129                 p["reference"] = ref;
130                 os << p.getCommand(rp);
131                 return 0;
132         } 
133         
134         // so we're doing a formatted reference.
135         docstring const data = getEscapedLabel(rp);
136         docstring label;
137         docstring const fcmd = getFormattedCmd(data, label);
138         os << fcmd << '{' << label << '}';
139         return 0;
140 }
141
142
143 int InsetRef::plaintext(odocstream & os, OutputParams const &) const
144 {
145         docstring const str = getParam("reference");
146         os << '[' << str << ']';
147         return 2 + str.size();
148 }
149
150
151 int InsetRef::docbook(odocstream & os, OutputParams const & runparams) const
152 {
153         docstring const & name = getParam("name");
154         if (name.empty()) {
155                 if (runparams.flavor == OutputParams::XML) {
156                         os << "<xref linkend=\""
157                            << sgml::cleanID(buffer(), runparams, getParam("reference"))
158                            << "\" />";
159                 } else {
160                         os << "<xref linkend=\""
161                            << sgml::cleanID(buffer(), runparams, getParam("reference"))
162                            << "\">";
163                 }
164         } else {
165                 os << "<link linkend=\""
166                    << sgml::cleanID(buffer(), runparams, getParam("reference"))
167                    << "\">"
168                    << getParam("name")
169                    << "</link>";
170         }
171
172         return 0;
173 }
174
175
176 docstring InsetRef::xhtml(XHTMLStream & xs, OutputParams const &) const
177 {
178         docstring const & ref = getParam("reference");
179         InsetLabel const * il = buffer().insetLabel(ref);
180         string const & cmd = params().getCmdName();
181         docstring display_string;
182
183         if (il && !il->counterValue().empty()) {
184                 // Try to construct a label from the InsetLabel we reference.
185                 docstring const & value = il->counterValue();
186                 if (cmd == "ref")
187                         display_string = value;
188                 else if (cmd == "vref")
189                         // normally, would be "ref on page #", but we have no pages
190                         display_string = value;
191                 else if (cmd == "pageref" || cmd == "vpageref")
192                         // normally would be "on page #", but we have no pages
193                         display_string = _("elsewhere");
194                 else if (cmd == "eqref")
195                         display_string = bformat(from_ascii("equation (%1$s)"), value);
196                 else if (cmd == "prettyref" 
197                          // we don't really have the ability to handle these 
198                          // properly in XHTML output
199                          || cmd == "nameref")
200                         display_string = il->prettyCounter();
201         } else 
202                         display_string = ref;
203
204         // FIXME What we'd really like to do is to be able to output some
205         // appropriate sort of text here. But to do that, we need to associate
206         // some sort of counter with the label, and we don't have that yet.
207         string const attr = "href=\"#" + html::cleanAttr(to_utf8(ref)) + "\"";
208         xs << html::StartTag("a", attr);
209         xs << display_string;
210         xs << html::EndTag("a");
211         return docstring();
212 }
213
214
215 void InsetRef::tocString(odocstream & os) const
216 {
217         plaintext(os, OutputParams(0));
218 }
219
220
221 void InsetRef::updateBuffer(ParIterator const & it, UpdateType)
222 {
223         docstring const & ref = getParam("reference");
224         // register this inset into the buffer reference cache.
225         buffer().references(ref).push_back(make_pair(this, it));
226
227         docstring label;
228         for (int i = 0; !types[i].latex_name.empty(); ++i) {
229                 if (getCmdName() == types[i].latex_name) {
230                         label = _(types[i].short_gui_name);
231                         break;
232                 }
233         }
234         label += ref;
235         
236         if (!buffer().isLatex() && !getParam("name").empty()) {
237                 label += "||";
238                 label += getParam("name");
239         }
240         
241         screen_label_ = label;
242         bool shortened = false;
243         unsigned int const maxLabelChars = 24;
244         if (screen_label_.size() > maxLabelChars) {
245                 screen_label_.erase(maxLabelChars - 3);
246                 screen_label_ += "...";
247                 shortened = true;
248         }
249         if (shortened)
250                 tooltip_ = label;
251         else 
252                 tooltip_ = from_ascii("");
253 }
254
255
256 void InsetRef::addToToc(DocIterator const & cpit)
257 {
258         docstring const & label = getParam("reference");
259         if (buffer().insetLabel(label))
260                 // This InsetRef has already been taken care of in InsetLabel::addToToc().
261                 return;
262
263         // It seems that this reference does not point to any valid label.
264         screen_label_ = _("BROKEN: ") + screen_label_;
265         Toc & toc = buffer().tocBackend().toc("label");
266         toc.push_back(TocItem(cpit, 0, screen_label_));
267 }
268
269
270 void InsetRef::validate(LaTeXFeatures & features) const
271 {
272         string const cmd = getCmdName();
273         if (cmd == "vref" || cmd == "vpageref")
274                 features.require("varioref");
275         else if (getCmdName() == "formatted") {
276                 if (buffer().params().use_refstyle) {
277                         features.require("refstyle");
278                         docstring const data = getEscapedLabel(features.runparams());
279                         docstring label;
280                         string const fcmd = to_utf8(getFormattedCmd(data, label));
281                         if (fcmd != "\\ref") {
282                                 string lcmd = "\\AtBeginDocument{\\providecommand" + fcmd + "[1]{\\ref{#1}}}";
283                                 features.addPreambleSnippet(lcmd);
284                         }
285                 } else
286                         features.require("prettyref");
287         } else if (getCmdName() == "eqref" && !buffer().params().use_refstyle)
288                 // refstyle defines its own version
289                 features.require("amsmath");
290         else if (cmd == "nameref")
291                 features.require("nameref");
292 }
293
294
295 InsetRef::type_info InsetRef::types[] = {
296         { "ref",       N_("Standard"),              N_("Ref: ")},
297         { "eqref",     N_("Equation"),              N_("EqRef: ")},
298         { "pageref",   N_("Page Number"),           N_("Page: ")},
299         { "vpageref",  N_("Textual Page Number"),   N_("TextPage: ")},
300         { "vref",      N_("Standard+Textual Page"), N_("Ref+Text: ")},
301         { "formatted", N_("Formatted"),             N_("Format: ")},
302         { "nameref",   N_("Reference to Name"),     N_("NameRef:")},
303         { "", "", "" }
304 };
305
306
307 int InsetRef::getType(string const & name)
308 {
309         for (int i = 0; !types[i].latex_name.empty(); ++i)
310                 if (name == types[i].latex_name)
311                         return i;
312         return 0;
313 }
314
315
316 string const & InsetRef::getName(int type)
317 {
318         return types[type].latex_name;
319 }
320
321
322 } // namespace lyx