]> git.lyx.org Git - lyx.git/blob - src/insets/InsetHyperlink.cpp
Let hyperlink insets to be longer if name is given.
[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         // TODO: replace with unicode hyperlink character = U+1F517
64         docstring const temp = _("Hyperlink: ");
65
66         docstring url;
67
68         url += getParam("name");
69         if (url.empty()) {
70                 url += getParam("target");
71
72                 // elide if long and no name was provided
73                 if (url.length() > 30) {
74                         docstring end = url.substr(url.length() - 17, url.length());
75                         support::truncateWithEllipsis(url, 13);
76                         url += end;
77                 }
78         } else {
79                 // elide if long (approx number of chars in line of article class)
80                 if (url.length() > 80) {
81                         docstring end = url.substr(url.length() - 67, url.length());
82                         support::truncateWithEllipsis(url, 13);
83                         url += end;
84                 }
85         }
86         return temp + url;
87 }
88
89
90 void InsetHyperlink::doDispatch(Cursor & cur, FuncRequest & cmd)
91 {
92         switch (cmd.action()) {
93
94         case LFUN_INSET_EDIT:
95                 viewTarget();
96                 break;
97
98         default:
99                 InsetCommand::doDispatch(cur, cmd);
100                 break;
101         }
102 }
103
104
105 bool InsetHyperlink::getStatus(Cursor & cur, FuncRequest const & cmd,
106                 FuncStatus & flag) const
107 {
108         switch (cmd.action()) {
109         case LFUN_INSET_EDIT:
110                 flag.setEnabled(getParam("type").empty() || getParam("type") == "file:");
111                 return true;
112
113         default:
114                 return InsetCommand::getStatus(cur, cmd, flag);
115         }
116 }
117
118
119 void InsetHyperlink::viewTarget() const
120 {
121         if (getParam("type") == "file:") {
122                 FileName url = makeAbsPath(to_utf8(getParam("target")), buffer().filePath());
123                 string const format = theFormats().getFormatFromFile(url);
124                 theFormats().view(buffer(), url, format);
125         }
126 }
127
128
129 void InsetHyperlink::latex(otexstream & os,
130                            OutputParams const & runparams) const
131 {
132         docstring url = getParam("target");
133         docstring name = getParam("name");
134         static char_type const chars_url[2] = {'%', '#'};
135
136         // For the case there is no name given, the target is set as name.
137         // Do this before !url.empty() and !name.empty() to handle characters
138         // such as % correctly.
139         if (name.empty())
140                 name = url;
141
142         if (!url.empty()) {
143                 // Use URI/URL-style percent-encoded string (hexadecimal).
144                 // We exclude some characters that must not be transformed
145                 // in hrefs: % # / : ? = & ! * ' ( ) ; @ + $ , [ ]
146                 // or that we need to treat manually: \.
147                 url = to_percent_encoding(url, from_ascii("%#\\/:?=&!*'();@+$,[]"));
148                 // We handle \ manually since \\ is valid
149                 for (size_t i = 0, pos;
150                         (pos = url.find('\\', i)) != string::npos;
151                         i = pos + 2) {
152                         if (url[pos + 1] != '\\')
153                                 url.replace(pos, 1, from_ascii("%5C"));
154                 }
155
156                 // The characters in chars_url[] need to be escaped in the url
157                 // field because otherwise LaTeX will fail when the hyperlink is
158                 // within an argument of another command, e.g. in a \footnote. It
159                 // is important that they are escaped as "\#" and not as "\#{}".
160                 // FIXME this is not necessary in outside of commands.
161                 for (int k = 0; k < 2; k++)
162                         for (size_t i = 0, pos;
163                                 (pos = url.find(chars_url[k], i)) != string::npos;
164                                 i = pos + 2)
165                                 url.replace(pos, 1, from_ascii("\\") + chars_url[k]);
166
167                 // add "http://" when the type is web (type = empty)
168                 // and no "://" or "run:" is given
169                 docstring type = getParam("type");
170                 if (url.find(from_ascii("://")) == string::npos
171                         && url.find(from_ascii("run:")) == string::npos
172                         && type.empty())
173                         url = from_ascii("http://") + url;
174
175         } // end if (!url.empty())
176
177         if (!name.empty()) {
178                 name = params().prepareCommand(runparams, name,
179                                         ParamInfo::HANDLING_LATEXIFY);
180                 // replace the tilde by the \sim character as suggested in the
181                 // LaTeX FAQ for URLs
182                 if (getParam("literal") != from_ascii("true")) {
183                         docstring const sim = from_ascii("$\\sim$");
184                         for (size_t i = 0, pos;
185                                 (pos = name.find('~', i)) != string::npos;
186                                 i = pos + 1)
187                                 name.replace(pos, 1, sim);
188                 }
189         }
190
191         if (runparams.moving_arg)
192                 os << "\\protect";
193
194         // output the ready \href command
195         os << "\\href{" << getParam("type") << url << "}{" << name << '}';
196 }
197
198
199 int InsetHyperlink::plaintext(odocstringstream & os,
200         OutputParams const &, size_t) const
201 {
202         odocstringstream oss;
203
204         oss << '[' << getParam("target");
205         if (getParam("name").empty())
206                 oss << ']';
207         else
208                 oss << "||" << getParam("name") << ']';
209
210         docstring const str = oss.str();
211         os << str;
212         return str.size();
213 }
214
215
216 int InsetHyperlink::docbook(odocstream & os, OutputParams const &) const
217 {
218         os << "<ulink url=\""
219            << subst(getParam("target"), from_ascii("&"), from_ascii("&amp;"))
220            << "\">"
221            << sgml::escapeString(getParam("name"))
222            << "</ulink>";
223         return 0;
224 }
225
226
227 docstring InsetHyperlink::xhtml(XHTMLStream & xs, OutputParams const &) const
228 {
229         docstring const & target =
230                 html::htmlize(getParam("target"), XHTMLStream::ESCAPE_AND);
231         docstring const & name   = getParam("name");
232         xs << html::StartTag("a", to_utf8("href=\"" + target + "\""));
233         xs << (name.empty() ? target : name);
234         xs << html::EndTag("a");
235         return docstring();
236 }
237
238
239 void InsetHyperlink::toString(odocstream & os) const
240 {
241         odocstringstream ods;
242         plaintext(ods, OutputParams(0), INT_MAX);
243         os << ods.str();
244 }
245
246
247 void InsetHyperlink::forOutliner(docstring & os, size_t const, bool const) const
248 {
249         docstring const & n = getParam("name");
250         if (!n.empty()) {
251                 os += n;
252                 return;
253         }
254         os += getParam("target");
255 }
256
257
258 docstring InsetHyperlink::toolTip(BufferView const & /*bv*/, int /*x*/, int /*y*/) const
259 {
260         docstring url = getParam("target");
261         docstring type = getParam("type");
262         docstring guitype = _("www");
263         if (type == "mailto:")
264                 guitype = _("email");
265         else if (type == "file:")
266                 guitype = _("file");
267         return bformat(_("Hyperlink (%1$s) to %2$s"), guitype, url);
268 }
269
270
271 void InsetHyperlink::validate(LaTeXFeatures & features) const
272 {
273         features.require("hyperref");
274         InsetCommand::validate(features);
275 }
276
277
278 string InsetHyperlink::contextMenuName() const
279 {
280         return "context-hyperlink";
281 }
282
283
284 } // namespace lyx