]> git.lyx.org Git - lyx.git/blob - src/insets/InsetQuotes.cpp
Context menu for quote insets
[lyx.git] / src / insets / InsetQuotes.cpp
1 /**
2  * \file InsetQuotes.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jean-Marc Lasgouttes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetQuotes.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "BufferView.h"
18 #include "Cursor.h"
19 #include "Dimension.h"
20 #include "Font.h"
21 #include "FuncStatus.h"
22 #include "FuncRequest.h"
23 #include "Language.h"
24 #include "LaTeXFeatures.h"
25 #include "Lexer.h"
26 #include "LyXRC.h"
27 #include "MetricsInfo.h"
28 #include "OutputParams.h"
29 #include "output_xhtml.h"
30 #include "Paragraph.h"
31 #include "ParIterator.h"
32 #include "texstream.h"
33
34 #include "frontends/FontMetrics.h"
35 #include "frontends/Painter.h"
36
37 #include "support/debug.h"
38 #include "support/docstring.h"
39 #include "support/docstream.h"
40 #include "support/lstrings.h"
41
42 using namespace std;
43 using namespace lyx::support;
44
45 namespace lyx {
46
47 namespace {
48
49 /* codes used to read/write quotes to LyX files
50  * e    ``english''
51  * s    ''swedish''
52  * g    ,,german``
53  * p    ,,polish''
54  * f    <<french>>
55  * a    >>danish<<
56  */
57
58 char const * const language_char = "esgpfa";
59 char const * const side_char = "lr" ;
60 char const * const times_char = "sd";
61
62 // List of known quote chars
63 char const * const quote_char = ",'`<>";
64
65 // Unicode characters needed by each quote type
66 char_type const display_quote_char[2][5] = {
67         { 0x201a, 0x2019, 0x2018, 0x2039, 0x203a},
68         { 0x201e, 0x201d, 0x201c, 0x00ab, 0x00bb}
69 };
70
71 // Index of chars used for the quote. Index is [side, language]
72 int quote_index[2][6] = {
73         { 2, 1, 0, 0, 3, 4 },    // "'',,<>"
74         { 1, 1, 2, 1, 4, 3 }     // "`'`'><"
75 };
76
77 // Corresponding LaTeX code, for double and single quotes.
78 char const * const latex_quote_t1[2][5] = {
79         { "\\quotesinglbase",  "'", "`",
80     "\\guilsinglleft", "\\guilsinglright" },
81   { ",,", "''", "``", "<<", ">>" }
82 };
83
84 char const * const latex_quote_ot1[2][5] = {
85         { "\\quotesinglbase",  "'", "`",
86     "\\guilsinglleft", "\\guilsinglright" },
87   { "\\quotedblbase", "''", "``",
88     "\\guillemotleft", "\\guillemotright" }
89 };
90
91 char const * const latex_quote_noligatures[2][5] = {
92         { "\\quotesinglbase",  "\\textquoteleft", "\\textquoteright",
93     "\\guilsinglleft", "\\guilsinglright" },
94   { "\\quotedblbase", "\\textquotedblleft", "\\textquotedblright",
95     "\\guillemotleft", "\\guillemotright" }
96 };
97
98 char const * const latex_quote_babel[2][5] = {
99         { "\\glq",  "'", "`", "\\flq", "\\frq" },
100   { "\\glqq", "''", "``", "\\flqq", "\\frqq" }
101 };
102
103 char const * const html_quote[2][5] = {
104         { "&sbquo;",  "&rsquo;", "&lsquo;",
105           "&lsaquo;", "&rsaquo;" },
106   { "&bdquo;", "&rdquo;", "&ldquo;", "&laquo;", "&raquo;" }
107 };
108
109 } // namespace anon
110
111
112 InsetQuotes::InsetQuotes(Buffer * buf, string const & str) : Inset(buf)
113 {
114         parseString(str);
115 }
116
117 InsetQuotes::InsetQuotes(Buffer * buf, char_type c, QuoteTimes t,
118                          string const & s, string const & l)
119         : Inset(buf), times_(t), pass_thru_(false)
120 {
121         if (buf) {
122                 language_ = l.empty() ? buf->params().quotes_language : getLanguage(l);
123                 fontenc_ = (buf->params().fontenc == "global")
124                         ? lyxrc.fontenc : buf->params().fontenc;
125         } else {
126                 language_ = l.empty() ? EnglishQuotes : getLanguage(l);
127                 fontenc_ = lyxrc.fontenc;
128         }
129
130         if (s == "left")
131                 side_ = LeftQuote;
132         else if (s == "right")
133                 side_ = RightQuote;
134         else
135                 setSide(c);
136 }
137
138
139 docstring InsetQuotes::layoutName() const
140 {
141         return from_ascii("Quotes");
142 }
143
144
145 void InsetQuotes::setSide(char_type c)
146 {
147         // Decide whether left or right
148         switch (c) {
149         case ' ':
150         case '(':
151         case '[':
152                 side_ = LeftQuote;   // left quote
153                 break;
154         default:
155                 side_ = RightQuote;  // right quote
156         }
157 }
158
159
160 void InsetQuotes::parseString(string const & s)
161 {
162         string str = s;
163         if (str.length() != 3) {
164                 lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
165                         " bad string length." << endl;
166                 str = "eld";
167         }
168
169         int i;
170
171         for (i = 0; i < 6; ++i) {
172                 if (str[0] == language_char[i]) {
173                         language_ = QuoteLanguage(i);
174                         break;
175                 }
176         }
177         if (i >= 6) {
178                 lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
179                         " bad language specification." << endl;
180                 language_ = EnglishQuotes;
181         }
182
183         for (i = 0; i < 2; ++i) {
184                 if (str[1] == side_char[i]) {
185                         side_ = QuoteSide(i);
186                         break;
187                 }
188         }
189         if (i >= 2) {
190                 lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
191                         " bad side specification." << endl;
192                 side_ = LeftQuote;
193         }
194
195         for (i = 0; i < 2; ++i) {
196                 if (str[2] == times_char[i]) {
197                         times_ = QuoteTimes(i);
198                         break;
199                 }
200         }
201         if (i >= 2) {
202                 lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
203                         " bad times specification." << endl;
204                 times_ = DoubleQuotes;
205         }
206 }
207
208 InsetQuotes::QuoteLanguage InsetQuotes::getLanguage(string const & s)
209 {
210         QuoteLanguage ql = EnglishQuotes;
211         
212         if (s == "english")
213                 ql = EnglishQuotes;
214         else if (s == "swedish")
215                 ql = SwedishQuotes;
216         else if (s == "german")
217                 ql = GermanQuotes;
218         else if (s == "polish")
219                 ql = PolishQuotes;
220         else if (s == "french")
221                 ql = FrenchQuotes;
222         else if (s == "danish")
223                 ql = DanishQuotes;
224
225         return ql;
226 }
227
228
229 map<string, docstring> InsetQuotes::getTypes() const
230 {
231         map<string, docstring> res;
232
233         int l, s, t;
234         QuoteLanguage lang;
235         QuoteSide side;
236         QuoteTimes times;
237         string type;
238
239         // get all quote types
240         for (l = 0; l < 6; ++l) {
241                 lang = QuoteLanguage(l);
242                 for (s = 0; s < 2; ++s) {
243                         side = QuoteSide(s);
244                         for (t = 0; t < 2; ++t) {
245                                 type += language_char[lang];
246                                 type += side_char[s];
247                                 times = QuoteTimes(t);
248                                 type += times_char[t];
249                                 res[type] = docstring(1, display_quote_char[times][quote_index[side][lang]]);
250                                 type.clear();
251                         }
252                 }
253         }
254         return res;
255 }
256
257
258 docstring InsetQuotes::displayString() const
259 {
260         // In PassThru, we use straight quotes
261         if (pass_thru_)
262                 return (times_ == DoubleQuotes) ? from_ascii("\"") : from_ascii("'");
263
264         int const index = quote_index[side_][language_];
265         docstring retdisp = docstring(1, display_quote_char[times_][index]);
266
267         // in French, thin spaces are added inside double guillemets
268         // FIXME: this should be done by a separate quote type.
269         if (prefixIs(context_lang_, "fr")
270             && times_ == DoubleQuotes && language_ == FrenchQuotes) {
271                 // THIN SPACE (U+2009)
272                 char_type const thin_space = 0x2009;
273                 if (side_ == LeftQuote)
274                         retdisp += thin_space;
275                 else
276                         retdisp = thin_space + retdisp;
277         }
278
279         return retdisp;
280 }
281
282
283 void InsetQuotes::metrics(MetricsInfo & mi, Dimension & dim) const
284 {
285         FontInfo & font = mi.base.font;
286         frontend::FontMetrics const & fm = theFontMetrics(font);
287         dim.asc = fm.maxAscent();
288         dim.des = fm.maxDescent();
289         dim.wid = fm.width(displayString());
290 }
291
292
293 void InsetQuotes::draw(PainterInfo & pi, int x, int y) const
294 {
295         FontInfo font = pi.base.font;
296         font.setPaintColor(pi.textColor(font.realColor()));
297         pi.pain.text(x, y, displayString(), font);
298 }
299
300 string InsetQuotes::getType() const
301 {
302         string text;
303         text += language_char[language_];
304         text += side_char[side_];
305         text += times_char[times_];
306         return text;
307 }
308         
309 void InsetQuotes::write(ostream & os) const
310 {
311         os << "Quotes " << getType();
312 }
313
314
315 void InsetQuotes::read(Lexer & lex)
316 {
317         lex.setContext("InsetQuotes::read");
318         lex.next();
319         parseString(lex.getString());
320         lex >> "\\end_inset";
321 }
322
323
324 void InsetQuotes::doDispatch(Cursor & cur, FuncRequest & cmd)
325 {
326         switch (cmd.action()) {
327         case LFUN_INSET_MODIFY: {
328                 string const first_arg = cmd.getArg(0);
329                 bool const change_type = first_arg == "changetype";
330                 if (!change_type) {
331                         // not for us
332                         // this will not be handled higher up
333                         cur.undispatched();
334                         return;
335                 }
336                 cur.recordUndoInset(this);
337                 parseString(cmd.getArg(1));
338                 cur.buffer()->updateBuffer();
339                 break;
340         }
341         default:
342                 Inset::doDispatch(cur, cmd);
343                 break;
344         }
345 }
346
347
348 bool InsetQuotes::getStatus(Cursor & cur, FuncRequest const & cmd,
349                 FuncStatus & flag) const
350 {
351         switch (cmd.action()) {
352
353         case LFUN_INSET_MODIFY: {
354                 string const first_arg = cmd.getArg(0);
355                 if (first_arg == "changetype") {
356                         string const type = cmd.getArg(1);
357                         flag.setOnOff(type == getType());
358                         flag.setEnabled(!pass_thru_);
359                         return true;
360                 }
361                 return Inset::getStatus(cur, cmd, flag);
362         }
363
364         default:
365                 return Inset::getStatus(cur, cmd, flag);
366         }
367 }
368
369
370 void InsetQuotes::latex(otexstream & os, OutputParams const & runparams) const
371 {
372         const int quoteind = quote_index[side_][language_];
373         docstring qstr;
374
375         // In pass-thru context, we output plain quotes
376         if (runparams.pass_thru)
377                 qstr = (times_ == DoubleQuotes) ? from_ascii("\"") : from_ascii("'");
378         else if (runparams.use_polyglossia) {
379                 // For polyglossia, we directly output the respective unicode chars 
380                 // (spacing and kerning is then handled respectively)
381                 qstr = docstring(1, display_quote_char[times_][quoteind]);
382         }
383         else if (language_ == FrenchQuotes && times_ == DoubleQuotes
384                  && prefixIs(runparams.local_font->language()->code(), "fr")) {
385                 // Specific guillemets of French babel
386                 // including correct French spacing
387                 if (side_ == LeftQuote)
388                         qstr = from_ascii("\\og");
389                 else
390                         qstr = from_ascii("\\fg");
391         } else if (fontenc_ == "T1"
392                    && !runparams.local_font->language()->internalFontEncoding()) {
393                 // Quotation marks for T1 font encoding
394                 // (using ligatures)
395                 qstr = from_ascii(latex_quote_t1[times_][quoteind]);
396         } else if (runparams.local_font->language()->internalFontEncoding()) {
397                 // Quotation marks for internal font encodings
398                 // (ligatures not featured)
399                 qstr = from_ascii(latex_quote_noligatures[times_][quoteind]);
400 #ifdef DO_USE_DEFAULT_LANGUAGE
401         } else if (doclang == "default") {
402 #else
403         } else if (!runparams.use_babel || runparams.isFullUnicode()) {
404 #endif
405                 // Standard quotation mark macros
406                 // These are also used by babel
407                 // without fontenc (XeTeX/LuaTeX)
408                 qstr = from_ascii(latex_quote_ot1[times_][quoteind]);
409         } else {
410                 // Babel shorthand quotation marks (for T1/OT1)
411                 qstr = from_ascii(latex_quote_babel[times_][quoteind]);
412         }
413
414         if (!runparams.pass_thru) {
415                 // Guard against unwanted ligatures with preceding text
416                 char_type const lastchar = os.lastChar();
417                 // !` ?` => !{}` ?{}`
418                 if (prefixIs(qstr, from_ascii("`"))
419                     && (lastchar == '!' || lastchar == '?'))
420                         os << "{}";
421                 // ``` ''' ,,, <<< >>>
422                 // => `{}`` '{}'' ,{},, <{}<< >{}>>
423                 if (contains(from_ascii(",'`<>"), lastchar)
424                     && prefixIs(qstr, lastchar))
425                         os << "{}";
426         }
427
428         os << qstr;
429
430         if (prefixIs(qstr, from_ascii("\\")))
431                 // properly terminate the command depending on the context
432                 os << termcmd;
433 }
434
435
436 int InsetQuotes::plaintext(odocstringstream & os, 
437         OutputParams const &, size_t) const
438 {
439         docstring const str = displayString();
440         os << str;
441         return str.size();
442 }
443
444
445 docstring InsetQuotes::getQuoteEntity() const {
446         const int quoteind = quote_index[side_][language_];
447         docstring res = from_ascii(html_quote[times_][quoteind]);
448         // in French, thin spaces are added inside double guillemets
449         // FIXME: this should be done by a separate quote type.
450         if (prefixIs(context_lang_, "fr")
451             && times_ == DoubleQuotes && language_ == FrenchQuotes) {
452                 // THIN SPACE (U+2009)
453                 docstring const thin_space = from_ascii("&#x2009;");
454                 if (side_ == LeftQuote)
455                         res += thin_space;
456                 else
457                         res = thin_space + res;
458         }
459         return res;
460 }
461
462
463 int InsetQuotes::docbook(odocstream & os, OutputParams const &) const
464 {
465         os << getQuoteEntity();
466         return 0;
467 }
468
469
470 docstring InsetQuotes::xhtml(XHTMLStream & xs, OutputParams const &) const
471 {
472         xs << XHTMLStream::ESCAPE_NONE << getQuoteEntity();
473         return docstring();
474 }
475
476
477 void InsetQuotes::toString(odocstream & os) const
478 {
479         os << displayString();
480 }
481
482
483 void InsetQuotes::forOutliner(docstring & os, size_t const, bool const) const
484 {
485         os += displayString();
486 }
487
488
489 void InsetQuotes::updateBuffer(ParIterator const & it, UpdateType /* utype*/)
490 {
491         BufferParams const & bp = buffer().masterBuffer()->params();
492         pass_thru_ = it.paragraph().isPassThru();
493         context_lang_ = it.paragraph().getFontSettings(bp, it.pos()).language()->code();
494 }
495
496
497 void InsetQuotes::validate(LaTeXFeatures & features) const
498 {
499         char type = quote_char[quote_index[side_][language_]];
500
501 #ifdef DO_USE_DEFAULT_LANGUAGE
502         if (features.bufferParams().language->lang() == "default"
503 #else
504         if (!features.useBabel()
505 #endif
506             && !features.usePolyglossia() && fontenc_ != "T1") {
507                 if (times_ == SingleQuotes)
508                         switch (type) {
509                         case ',': features.require("quotesinglbase"); break;
510                         case '<': features.require("guilsinglleft");  break;
511                         case '>': features.require("guilsinglright"); break;
512                         default: break;
513                         }
514                 else
515                         switch (type) {
516                         case ',': features.require("quotedblbase");   break;
517                         case '<': features.require("guillemotleft");  break;
518                         case '>': features.require("guillemotright"); break;
519                         default: break;
520                         }
521         }
522 }
523
524
525 string InsetQuotes::contextMenuName() const
526 {
527         return "context-quote";
528 }
529
530 } // namespace lyx