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