]> git.lyx.org Git - lyx.git/blob - src/insets/InsetQuotes.cpp
ef9629ff6cd047528a05ef87b094bf620fd85699
[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
118 InsetQuotes::InsetQuotes(Buffer * buf, char_type c, QuoteTimes t,
119                          string const & s, string const & l)
120         : Inset(buf), times_(t), pass_thru_(false)
121 {
122         if (buf) {
123                 language_ = l.empty() ? buf->params().quotes_language : getLanguage(l);
124                 fontenc_ = (buf->params().fontenc == "global")
125                         ? lyxrc.fontenc : buf->params().fontenc;
126         } else {
127                 language_ = l.empty() ? EnglishQuotes : getLanguage(l);
128                 fontenc_ = lyxrc.fontenc;
129         }
130
131         if (s == "left")
132                 side_ = LeftQuote;
133         else if (s == "right")
134                 side_ = RightQuote;
135         else
136                 setSide(c);
137 }
138
139
140 docstring InsetQuotes::layoutName() const
141 {
142         return from_ascii("Quotes");
143 }
144
145
146 void InsetQuotes::setSide(char_type c)
147 {
148         // Decide whether left or right
149         switch (c) {
150         case ' ':
151         case '(':
152         case '[':
153                 side_ = LeftQuote;   // left quote
154                 break;
155         default:
156                 side_ = RightQuote;  // right quote
157         }
158 }
159
160
161 void InsetQuotes::parseString(string const & s, bool const allow_wildcards)
162 {
163         string str = s;
164         if (str.length() != 3) {
165                 lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
166                         " bad string length." << endl;
167                 str = "eld";
168         }
169
170         int i;
171
172         // '.' wildcard means: keep current language
173         if (!allow_wildcards || str[0] != '.') {
174                 for (i = 0; i < 6; ++i) {
175                         if (str[0] == language_char[i]) {
176                                 language_ = QuoteLanguage(i);
177                                 break;
178                         }
179                 }
180                 if (i >= 6) {
181                         lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
182                                 " bad language specification." << endl;
183                         language_ = EnglishQuotes;
184                 }
185         }
186
187         // '.' wildcard means: keep current side
188         if (!allow_wildcards || str[1] != '.') {
189                 for (i = 0; i < 2; ++i) {
190                         if (str[1] == side_char[i]) {
191                                 side_ = QuoteSide(i);
192                                 break;
193                         }
194                 }
195                 if (i >= 2) {
196                         lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
197                                 " bad side specification." << endl;
198                         side_ = LeftQuote;
199                 }
200         }
201
202         // '.' wildcard means: keep current times
203         if (!allow_wildcards || str[2] != '.') {
204                 for (i = 0; i < 2; ++i) {
205                         if (str[2] == times_char[i]) {
206                                 times_ = QuoteTimes(i);
207                                 break;
208                         }
209                 }
210                 if (i >= 2) {
211                         lyxerr << "ERROR (InsetQuotes::InsetQuotes):"
212                                 " bad times specification." << endl;
213                         times_ = DoubleQuotes;
214                 }
215         }
216 }
217
218
219 InsetQuotes::QuoteLanguage InsetQuotes::getLanguage(string const & s)
220 {
221         QuoteLanguage ql = EnglishQuotes;
222         
223         if (s == "english")
224                 ql = EnglishQuotes;
225         else if (s == "swedish")
226                 ql = SwedishQuotes;
227         else if (s == "german")
228                 ql = GermanQuotes;
229         else if (s == "polish")
230                 ql = PolishQuotes;
231         else if (s == "french")
232                 ql = FrenchQuotes;
233         else if (s == "danish")
234                 ql = DanishQuotes;
235
236         return ql;
237 }
238
239
240 map<string, docstring> InsetQuotes::getTypes() const
241 {
242         map<string, docstring> res;
243
244         int l, s, t;
245         QuoteLanguage lang;
246         QuoteSide side;
247         QuoteTimes times;
248         string type;
249
250         // get all quote types
251         for (l = 0; l < 6; ++l) {
252                 lang = QuoteLanguage(l);
253                 for (s = 0; s < 2; ++s) {
254                         side = QuoteSide(s);
255                         for (t = 0; t < 2; ++t) {
256                                 type += language_char[lang];
257                                 type += side_char[s];
258                                 times = QuoteTimes(t);
259                                 type += times_char[t];
260                                 res[type] = docstring(1, display_quote_char[times][quote_index[side][lang]]);
261                                 type.clear();
262                         }
263                 }
264         }
265         return res;
266 }
267
268
269 docstring InsetQuotes::displayString() const
270 {
271         // In PassThru, we use straight quotes
272         if (pass_thru_)
273                 return (times_ == DoubleQuotes) ? from_ascii("\"") : from_ascii("'");
274
275         int const index = quote_index[side_][language_];
276         docstring retdisp = docstring(1, display_quote_char[times_][index]);
277
278         // in French, thin spaces are added inside double guillemets
279         // FIXME: this should be done by a separate quote type.
280         if (prefixIs(context_lang_, "fr")
281             && times_ == DoubleQuotes && language_ == FrenchQuotes) {
282                 // THIN SPACE (U+2009)
283                 char_type const thin_space = 0x2009;
284                 if (side_ == LeftQuote)
285                         retdisp += thin_space;
286                 else
287                         retdisp = thin_space + retdisp;
288         }
289
290         return retdisp;
291 }
292
293
294 void InsetQuotes::metrics(MetricsInfo & mi, Dimension & dim) const
295 {
296         FontInfo & font = mi.base.font;
297         frontend::FontMetrics const & fm = theFontMetrics(font);
298         dim.asc = fm.maxAscent();
299         dim.des = fm.maxDescent();
300         dim.wid = fm.width(displayString());
301 }
302
303
304 void InsetQuotes::draw(PainterInfo & pi, int x, int y) const
305 {
306         FontInfo font = pi.base.font;
307         font.setPaintColor(pi.textColor(font.realColor()));
308         pi.pain.text(x, y, displayString(), font);
309 }
310
311
312 string InsetQuotes::getType() const
313 {
314         string text;
315         text += language_char[language_];
316         text += side_char[side_];
317         text += times_char[times_];
318         return text;
319 }
320
321
322 void InsetQuotes::write(ostream & os) const
323 {
324         os << "Quotes " << getType();
325 }
326
327
328 void InsetQuotes::read(Lexer & lex)
329 {
330         lex.setContext("InsetQuotes::read");
331         lex.next();
332         parseString(lex.getString());
333         lex >> "\\end_inset";
334 }
335
336
337 void InsetQuotes::doDispatch(Cursor & cur, FuncRequest & cmd)
338 {
339         switch (cmd.action()) {
340         case LFUN_INSET_MODIFY: {
341                 string const first_arg = cmd.getArg(0);
342                 bool const change_type = first_arg == "changetype";
343                 if (!change_type) {
344                         // not for us
345                         // this will not be handled higher up
346                         cur.undispatched();
347                         return;
348                 }
349                 cur.recordUndoInset(this);
350                 parseString(cmd.getArg(1), true);
351                 cur.buffer()->updateBuffer();
352                 break;
353         }
354         default:
355                 Inset::doDispatch(cur, cmd);
356                 break;
357         }
358 }
359
360
361 bool InsetQuotes::getStatus(Cursor & cur, FuncRequest const & cmd,
362                 FuncStatus & flag) const
363 {
364         switch (cmd.action()) {
365
366         case LFUN_INSET_MODIFY: {
367                 string const first_arg = cmd.getArg(0);
368                 if (first_arg == "changetype") {
369                         string const type = cmd.getArg(1);
370                         flag.setOnOff(type == getType());
371                         flag.setEnabled(!pass_thru_);
372                         return true;
373                 }
374                 return Inset::getStatus(cur, cmd, flag);
375         }
376
377         default:
378                 return Inset::getStatus(cur, cmd, flag);
379         }
380 }
381
382
383 void InsetQuotes::latex(otexstream & os, OutputParams const & runparams) const
384 {
385         const int quoteind = quote_index[side_][language_];
386         docstring qstr;
387
388         // In pass-thru context, we output plain quotes
389         if (runparams.pass_thru)
390                 qstr = (times_ == DoubleQuotes) ? from_ascii("\"") : from_ascii("'");
391         else if (runparams.use_polyglossia) {
392                 // For polyglossia, we directly output the respective unicode chars 
393                 // (spacing and kerning is then handled respectively)
394                 qstr = docstring(1, display_quote_char[times_][quoteind]);
395         }
396         else if (language_ == FrenchQuotes && times_ == DoubleQuotes
397                  && prefixIs(runparams.local_font->language()->code(), "fr")) {
398                 // Specific guillemets of French babel
399                 // including correct French spacing
400                 if (side_ == LeftQuote)
401                         qstr = from_ascii("\\og");
402                 else
403                         qstr = from_ascii("\\fg");
404         } else if (fontenc_ == "T1"
405                    && !runparams.local_font->language()->internalFontEncoding()) {
406                 // Quotation marks for T1 font encoding
407                 // (using ligatures)
408                 qstr = from_ascii(latex_quote_t1[times_][quoteind]);
409         } else if (runparams.local_font->language()->internalFontEncoding()) {
410                 // Quotation marks for internal font encodings
411                 // (ligatures not featured)
412                 qstr = from_ascii(latex_quote_noligatures[times_][quoteind]);
413 #ifdef DO_USE_DEFAULT_LANGUAGE
414         } else if (doclang == "default") {
415 #else
416         } else if (!runparams.use_babel || runparams.isFullUnicode()) {
417 #endif
418                 // Standard quotation mark macros
419                 // These are also used by babel
420                 // without fontenc (XeTeX/LuaTeX)
421                 qstr = from_ascii(latex_quote_ot1[times_][quoteind]);
422         } else {
423                 // Babel shorthand quotation marks (for T1/OT1)
424                 qstr = from_ascii(latex_quote_babel[times_][quoteind]);
425         }
426
427         if (!runparams.pass_thru) {
428                 // Guard against unwanted ligatures with preceding text
429                 char_type const lastchar = os.lastChar();
430                 // !` ?` => !{}` ?{}`
431                 if (prefixIs(qstr, from_ascii("`"))
432                     && (lastchar == '!' || lastchar == '?'))
433                         os << "{}";
434                 // ``` ''' ,,, <<< >>>
435                 // => `{}`` '{}'' ,{},, <{}<< >{}>>
436                 if (contains(from_ascii(",'`<>"), lastchar)
437                     && prefixIs(qstr, lastchar))
438                         os << "{}";
439         }
440
441         os << qstr;
442
443         if (prefixIs(qstr, from_ascii("\\")))
444                 // properly terminate the command depending on the context
445                 os << termcmd;
446 }
447
448
449 int InsetQuotes::plaintext(odocstringstream & os, 
450         OutputParams const &, size_t) const
451 {
452         docstring const str = displayString();
453         os << str;
454         return str.size();
455 }
456
457
458 docstring InsetQuotes::getQuoteEntity() const {
459         const int quoteind = quote_index[side_][language_];
460         docstring res = from_ascii(html_quote[times_][quoteind]);
461         // in French, thin spaces are added inside double guillemets
462         // FIXME: this should be done by a separate quote type.
463         if (prefixIs(context_lang_, "fr")
464             && times_ == DoubleQuotes && language_ == FrenchQuotes) {
465                 // THIN SPACE (U+2009)
466                 docstring const thin_space = from_ascii("&#x2009;");
467                 if (side_ == LeftQuote)
468                         res += thin_space;
469                 else
470                         res = thin_space + res;
471         }
472         return res;
473 }
474
475
476 int InsetQuotes::docbook(odocstream & os, OutputParams const &) const
477 {
478         os << getQuoteEntity();
479         return 0;
480 }
481
482
483 docstring InsetQuotes::xhtml(XHTMLStream & xs, OutputParams const &) const
484 {
485         xs << XHTMLStream::ESCAPE_NONE << getQuoteEntity();
486         return docstring();
487 }
488
489
490 void InsetQuotes::toString(odocstream & os) const
491 {
492         os << displayString();
493 }
494
495
496 void InsetQuotes::forOutliner(docstring & os, size_t const, bool const) const
497 {
498         os += displayString();
499 }
500
501
502 void InsetQuotes::updateBuffer(ParIterator const & it, UpdateType /* utype*/)
503 {
504         BufferParams const & bp = buffer().masterBuffer()->params();
505         pass_thru_ = it.paragraph().isPassThru();
506         context_lang_ = it.paragraph().getFontSettings(bp, it.pos()).language()->code();
507 }
508
509
510 void InsetQuotes::validate(LaTeXFeatures & features) const
511 {
512         char type = quote_char[quote_index[side_][language_]];
513
514 #ifdef DO_USE_DEFAULT_LANGUAGE
515         if (features.bufferParams().language->lang() == "default"
516 #else
517         if (!features.useBabel()
518 #endif
519             && !features.usePolyglossia() && fontenc_ != "T1") {
520                 if (times_ == SingleQuotes)
521                         switch (type) {
522                         case ',': features.require("quotesinglbase"); break;
523                         case '<': features.require("guilsinglleft");  break;
524                         case '>': features.require("guilsinglright"); break;
525                         default: break;
526                         }
527                 else
528                         switch (type) {
529                         case ',': features.require("quotedblbase");   break;
530                         case '<': features.require("guillemotleft");  break;
531                         case '>': features.require("guillemotright"); break;
532                         default: break;
533                         }
534         }
535 }
536
537
538 string InsetQuotes::contextMenuName() const
539 {
540         return "context-quote";
541 }
542
543 } // namespace lyx