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