]> git.lyx.org Git - lyx.git/blob - src/insets/InsetHyperlink.cpp
Do not percent-encode & in urls
[lyx.git] / src / insets / InsetHyperlink.cpp
1 /**
2  * \file InsetHyperlink.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  * \author Uwe Stöhr
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetHyperlink.h"
15
16 #include "Buffer.h"
17 #include "DispatchResult.h"
18 #include "Encoding.h"
19 #include "Format.h"
20 #include "FuncRequest.h"
21 #include "FuncStatus.h"
22 #include "LaTeXFeatures.h"
23 #include "OutputParams.h"
24 #include "output_xhtml.h"
25 #include "sgml.h"
26 #include "texstream.h"
27
28 #include "support/docstream.h"
29 #include "support/FileName.h"
30 #include "support/filetools.h"
31 #include "support/gettext.h"
32 #include "support/lstrings.h"
33
34 #include "frontends/alert.h"
35
36 using namespace std;
37 using namespace lyx::support;
38
39 namespace lyx {
40
41
42 InsetHyperlink::InsetHyperlink(Buffer * buf, InsetCommandParams const & p)
43         : InsetCommand(buf, p)
44 {}
45
46
47 ParamInfo const & InsetHyperlink::findInfo(string const & /* cmdName */)
48 {
49         static ParamInfo param_info_;
50         if (param_info_.empty()) {
51                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL,
52                                 ParamInfo::HANDLING_LATEXIFY);
53                 param_info_.add("target", ParamInfo::LATEX_REQUIRED);
54                 param_info_.add("type", ParamInfo::LATEX_REQUIRED);
55                 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
56         }
57         return param_info_;
58 }
59
60
61 docstring InsetHyperlink::screenLabel() const
62 {
63         docstring const temp = _("Hyperlink: ");
64
65         docstring url;
66
67         url += getParam("name");
68         if (url.empty())
69                 url += getParam("target");
70
71         // elide if long
72         if (url.length() > 30) {
73                 docstring end = url.substr(url.length() - 17, url.length());
74                 support::truncateWithEllipsis(url, 13);
75                 url += end;
76         }
77         return temp + url;
78 }
79
80
81 void InsetHyperlink::doDispatch(Cursor & cur, FuncRequest & cmd)
82 {
83         switch (cmd.action()) {
84
85         case LFUN_INSET_EDIT:
86                 viewTarget();
87                 break;
88
89         default:
90                 InsetCommand::doDispatch(cur, cmd);
91                 break;
92         }
93 }
94
95
96 bool InsetHyperlink::getStatus(Cursor & cur, FuncRequest const & cmd,
97                 FuncStatus & flag) const
98 {
99         switch (cmd.action()) {
100         case LFUN_INSET_EDIT:
101                 flag.setEnabled(getParam("type").empty() || getParam("type") == "file:");
102                 return true;
103
104         default:
105                 return InsetCommand::getStatus(cur, cmd, flag);
106         }
107 }
108
109
110 void InsetHyperlink::viewTarget() const
111 {
112         if (getParam("type") == "file:") {
113                 FileName url = makeAbsPath(to_utf8(getParam("target")), buffer().filePath());
114                 string const format = theFormats().getFormatFromFile(url);
115                 theFormats().view(buffer(), url, format);
116         }
117 }
118
119
120 void InsetHyperlink::latex(otexstream & os,
121                            OutputParams const & runparams) const
122 {
123         docstring url = getParam("target");
124         docstring name = getParam("name");
125         static char_type const chars_url[2] = {'%', '#'};
126
127         // For the case there is no name given, the target is set as name.
128         // Do this before !url.empty() and !name.empty() to handle characters
129         // such as % correctly.
130         if (name.empty())
131                 name = url;
132
133         if (!url.empty()) {
134                 // Use URI/URL-style percent-encoded string (hexadecimal).
135                 // We exclude some characters that must not be transformed
136                 // in hrefs (% # / : ? = &) or that we need to treat manually (\).
137                 url = to_percent_encoding(url, from_ascii("%#\\/:?=&"));
138                 // We handle \ manually since \\ is valid
139                 for (size_t i = 0, pos;
140                         (pos = url.find('\\', i)) != string::npos;
141                         i = pos + 2) {
142                         if (url[pos + 1] != '\\')
143                                 url.replace(pos, 1, from_ascii("%5C"));
144                 }
145
146                 // The characters in chars_url[] need to be escaped in the url
147                 // field because otherwise LaTeX will fail when the hyperlink is
148                 // within an argument of another command, e.g. in a \footnote. It
149                 // is important that they are escaped as "\#" and not as "\#{}".
150                 // FIXME this is not necessary in outside of commands.
151                 for (int k = 0; k < 2; k++)
152                         for (size_t i = 0, pos;
153                                 (pos = url.find(chars_url[k], i)) != string::npos;
154                                 i = pos + 2)
155                                 url.replace(pos, 1, from_ascii("\\") + chars_url[k]);
156
157                 // add "http://" when the type is web (type = empty)
158                 // and no "://" or "run:" is given
159                 docstring type = getParam("type");
160                 if (url.find(from_ascii("://")) == string::npos
161                         && url.find(from_ascii("run:")) == string::npos
162                         && type.empty())
163                         url = from_ascii("http://") + url;
164
165         } // end if (!url.empty())
166
167         if (!name.empty()) {
168                 name = params().prepareCommand(runparams, name,
169                                         ParamInfo::HANDLING_LATEXIFY);
170                 // replace the tilde by the \sim character as suggested in the
171                 // LaTeX FAQ for URLs
172                 if (getParam("literal") != from_ascii("true")) {
173                         docstring const sim = from_ascii("$\\sim$");
174                         for (size_t i = 0, pos;
175                                 (pos = name.find('~', i)) != string::npos;
176                                 i = pos + 1)
177                                 name.replace(pos, 1, sim);
178                 }
179         }
180
181         if (runparams.moving_arg)
182                 os << "\\protect";
183
184         // output the ready \href command
185         os << "\\href{" << getParam("type") << url << "}{" << name << '}';
186 }
187
188
189 int InsetHyperlink::plaintext(odocstringstream & os,
190         OutputParams const &, size_t) const
191 {
192         odocstringstream oss;
193
194         oss << '[' << getParam("target");
195         if (getParam("name").empty())
196                 oss << ']';
197         else
198                 oss << "||" << getParam("name") << ']';
199
200         docstring const str = oss.str();
201         os << str;
202         return str.size();
203 }
204
205
206 int InsetHyperlink::docbook(odocstream & os, OutputParams const &) const
207 {
208         os << "<ulink url=\""
209            << subst(getParam("target"), from_ascii("&"), from_ascii("&amp;"))
210            << "\">"
211            << sgml::escapeString(getParam("name"))
212            << "</ulink>";
213         return 0;
214 }
215
216
217 docstring InsetHyperlink::xhtml(XHTMLStream & xs, OutputParams const &) const
218 {
219         docstring const & target =
220                 html::htmlize(getParam("target"), XHTMLStream::ESCAPE_AND);
221         docstring const & name   = getParam("name");
222         xs << html::StartTag("a", to_utf8("href=\"" + target + "\""));
223         xs << (name.empty() ? target : name);
224         xs << html::EndTag("a");
225         return docstring();
226 }
227
228
229 void InsetHyperlink::toString(odocstream & os) const
230 {
231         odocstringstream ods;
232         plaintext(ods, OutputParams(0), INT_MAX);
233         os << ods.str();
234 }
235
236
237 void InsetHyperlink::forOutliner(docstring & os, size_t const, bool const) const
238 {
239         docstring const & n = getParam("name");
240         if (!n.empty()) {
241                 os += n;
242                 return;
243         }
244         os += getParam("target");
245 }
246
247
248 docstring InsetHyperlink::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
249 {
250         docstring url = getParam("target");
251         docstring type = getParam("type");
252         docstring guitype = _("www");
253         if (type == "mailto:")
254                 guitype = _("email");
255         else if (type == "file:")
256                 guitype = _("file");
257         return bformat(_("Hyperlink (%1$s) to %2$s"), guitype, url);
258 }
259
260
261 void InsetHyperlink::validate(LaTeXFeatures & features) const
262 {
263         features.require("hyperref");
264         InsetCommand::validate(features);
265 }
266
267
268 string InsetHyperlink::contextMenuName() const
269 {
270         return "context-hyperlink";
271 }
272
273
274 } // namespace lyx