]> git.lyx.org Git - lyx.git/blob - src/insets/InsetHyperlink.cpp
validate encodable characters in href inset (#8357)
[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
26 #include "support/docstream.h"
27 #include "support/FileName.h"
28 #include "support/filetools.h"
29 #include "support/gettext.h"
30 #include "support/lstrings.h"
31
32 #include "frontends/alert.h"
33
34 using namespace std;
35 using namespace lyx::support;
36
37 namespace lyx {
38
39
40 InsetHyperlink::InsetHyperlink(Buffer * buf, InsetCommandParams const & p)
41         : InsetCommand(buf, p)
42 {}
43
44
45 ParamInfo const & InsetHyperlink::findInfo(string const & /* cmdName */)
46 {
47         static ParamInfo param_info_;
48         if (param_info_.empty()) {
49                 param_info_.add("name", ParamInfo::LATEX_OPTIONAL);
50                 param_info_.add("target", ParamInfo::LATEX_REQUIRED);
51                 param_info_.add("type", ParamInfo::LATEX_REQUIRED);
52         }
53         return param_info_;
54 }
55
56
57 docstring InsetHyperlink::screenLabel() const
58 {
59         docstring const temp = from_ascii("Hyperlink: ");
60
61         docstring url;
62
63         url += getParam("name");
64         if (url.empty())
65                 url += getParam("target");
66
67         // elide if long
68         if (url.length() > 30) {
69                 url = url.substr(0, 10) + "..."
70                         + url.substr(url.length() - 17, url.length());
71         }
72         return temp + url;
73 }
74
75 void InsetHyperlink::doDispatch(Cursor & cur, FuncRequest & cmd)
76 {
77         switch (cmd.action()) {
78
79         case LFUN_INSET_EDIT:
80                 viewTarget();
81                 break;
82
83         default:
84                 InsetCommand::doDispatch(cur, cmd);
85                 break;
86         }
87 }
88
89
90 bool InsetHyperlink::getStatus(Cursor & cur, FuncRequest const & cmd,
91                 FuncStatus & flag) const
92 {
93         switch (cmd.action()) {
94         case LFUN_INSET_EDIT:
95                 flag.setEnabled(getParam("type").empty() || getParam("type") == "file:");
96                 return true;
97
98         default:
99                 return InsetCommand::getStatus(cur, cmd, flag);
100         }
101 }
102
103
104 void InsetHyperlink::viewTarget() const
105 {
106         if (getParam("type") == "file:") {
107                 FileName url = makeAbsPath(to_utf8(getParam("target")), buffer().filePath());
108                 string const format = formats.getFormatFromFile(url);
109                 formats.view(buffer(), url, format);
110         }
111 }
112
113
114 void InsetHyperlink::latex(otexstream & os,
115                            OutputParams const & runparams) const
116 {
117         docstring url = getParam("target");
118         docstring name = getParam("name");
119         static docstring const backslash = from_ascii("\\");
120         static docstring const braces = from_ascii("{}");
121         static char_type const chars_url[2] = {'%', '#'};
122         static char_type const chars_name[6] = {
123                 '&', '_', '$', '%', '#', '^'};
124
125         // For the case there is no name given, the target is set as name.
126         // Do this before !url.empty() and !name.empty() to handle characters
127         // like the "%" correctly.
128         if (name.empty())
129                 name = url;
130
131         if (!url.empty()) {
132                 // Replace the "\" character by its ASCII code according to the
133                 // URL specifications because "\" is not allowed in URLs and by
134                 // \href. Only do this when the following character is not also
135                 // a "\", because "\\" is valid code
136                 for (size_t i = 0, pos;
137                         (pos = url.find('\\', i)) != string::npos;
138                         i = pos + 2) {
139                         if (url[pos + 1] != '\\')
140                                 url.replace(pos, 1, from_ascii("%5C"));
141                 }
142
143                 // The characters in chars_url[] need to be escaped in the url
144                 // field because otherwise LaTeX will fail when the hyperlink is
145                 // within an argument of another command, e.g. in a \footnote. It
146                 // is important that they are escaped as "\#" and not as "\#{}".
147                 for (int k = 0; k < 2; k++)
148                         for (size_t i = 0, pos;
149                                 (pos = url.find(chars_url[k], i)) != string::npos;
150                                 i = pos + 2)
151                                 url.replace(pos, 1, backslash + chars_url[k]);
152                 
153                 // add "http://" when the type is web (type = empty)
154                 // and no "://" or "run:" is given
155                 docstring type = getParam("type");
156                 if (url.find(from_ascii("://")) == string::npos
157                         && url.find(from_ascii("run:")) == string::npos
158                         && type.empty())
159                         url = from_ascii("http://") + url;
160
161         } // end if (!url.empty())
162
163         // The characters in chars_name[] need to be changed to a command when
164         // they are in the name field.
165         if (!name.empty()) {
166                 // handle the "\" character, but only when the following character
167                 // is not also a "\", because "\\" is valid code
168                 docstring const textbackslash = from_ascii("\\textbackslash{}");
169                 for (size_t i = 0, pos;
170                         (pos = name.find('\\', i)) != string::npos;
171                         i = pos + 2) {
172                         if (name[pos + 1] != '\\')
173                                 name.replace(pos, 1, textbackslash);
174                 }
175                 // The characters in chars_name[] need to be changed to a command
176                 // when they are in the name field.
177                 // Therefore the treatment of "\" must be the first thing
178                 for (int k = 0; k < 6; k++)
179                         for (size_t i = 0, pos;
180                                 (pos = name.find(chars_name[k], i)) != string::npos;
181                                 i = pos + 2)
182                                 name.replace(pos, 1, backslash + chars_name[k] + braces);
183
184                 // replace the tilde by the \sim character as suggested in the
185                 // LaTeX FAQ for URLs
186                 docstring const sim = from_ascii("$\\sim$");
187                 for (size_t i = 0, pos;
188                         (pos = name.find('~', i)) != string::npos;
189                         i = pos + 1)
190                         name.replace(pos, 1, sim);
191                 pair<docstring, docstring> name_latexed =
192                         runparams.encoding->latexString(name, runparams.dryrun);
193                 name = name_latexed.first;
194                 if (!name_latexed.second.empty()) {
195                         // issue a warning about omitted characters
196                         // FIXME: should be passed to the error dialog
197                         frontend::Alert::warning(_("Uncodable characters"),
198                                 bformat(_("The following characters that are used in the href inset are not\n"
199                                           "representable in the current encoding and therefore have been omitted:\n%1$s."),
200                                         name_latexed.second));
201                 }
202         }  // end if (!name.empty())
203         
204         if (runparams.moving_arg)
205                 os << "\\protect";
206
207         // output the ready \href command
208         os << "\\href{" << getParam("type") << url << "}{" << name << '}';
209 }
210
211
212 int InsetHyperlink::plaintext(odocstream & os, OutputParams const &) const
213 {
214         odocstringstream oss;
215
216         oss << '[' << getParam("target");
217         if (getParam("name").empty())
218                 oss << ']';
219         else
220                 oss << "||" << getParam("name") << ']';
221
222         docstring const str = oss.str();
223         os << str;
224         return str.size();
225 }
226
227
228 int InsetHyperlink::docbook(odocstream & os, OutputParams const &) const
229 {
230         os << "<ulink url=\""
231            << subst(getParam("target"), from_ascii("&"), from_ascii("&amp;"))
232            << "\">"
233            << getParam("name")
234            << "</ulink>";
235         return 0;
236 }
237
238
239 docstring InsetHyperlink::xhtml(XHTMLStream & xs, OutputParams const &) const
240 {
241         docstring const & target = 
242                 html::htmlize(getParam("target"), XHTMLStream::ESCAPE_AND);
243         docstring const & name   = getParam("name");
244         xs << html::StartTag("a", to_utf8("href=\"" + target + "\""));
245         xs << (name.empty() ? target : name);
246         xs << html::EndTag("a");
247         return docstring();
248 }
249
250
251 void InsetHyperlink::toString(odocstream & os) const
252 {
253         plaintext(os, OutputParams(0));
254 }
255
256
257 void InsetHyperlink::forToc(docstring & os, size_t) const
258 {
259         docstring const & n = getParam("name");
260         if (!n.empty()) {
261                 os += n;
262                 return;
263         }
264         os += getParam("target");
265 }
266
267
268 docstring InsetHyperlink::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
269 {
270         docstring url = getParam("target");
271         docstring type = getParam("type");
272         docstring guitype = _("www");
273         if (type == "mailto:")
274                 guitype = _("email");
275         else if (type == "file:")
276                 guitype = _("file");
277         return bformat(_("Hyperlink (%1$s) to %2$s"), guitype, url);
278 }
279
280
281 void InsetHyperlink::validate(LaTeXFeatures & features) const
282 {
283         features.require("hyperref");
284 }
285
286
287 string InsetHyperlink::contextMenuName() const
288 {
289         return "context-hyperlink";
290 }
291
292
293 } // namespace lyx