]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
079fa342551e356bb845d03f27ac5cd33de37e75
[lyx.git] / src / insets / InsetText.cpp
1 /**
2  * \file InsetText.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetText.h"
14
15 #include "insets/InsetOptArg.h"
16
17 #include "buffer_funcs.h"
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "CompletionList.h"
22 #include "CoordCache.h"
23 #include "Cursor.h"
24 #include "CutAndPaste.h"
25 #include "DispatchResult.h"
26 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "InsetCaption.h"
30 #include "InsetList.h"
31 #include "Intl.h"
32 #include "Language.h"
33 #include "Lexer.h"
34 #include "lyxfind.h"
35 #include "LyXRC.h"
36 #include "MetricsInfo.h"
37 #include "output_docbook.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "OutputParams.h"
41 #include "output_plaintext.h"
42 #include "paragraph_funcs.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "ParIterator.h"
46 #include "Row.h"
47 #include "sgml.h"
48 #include "TexRow.h"
49 #include "TextClass.h"
50 #include "Text.h"
51 #include "TextMetrics.h"
52 #include "TocBackend.h"
53
54 #include "frontends/alert.h"
55 #include "frontends/Painter.h"
56
57 #include "support/debug.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
60
61 #include <boost/bind.hpp>
62 #include "support/lassert.h"
63
64 using namespace std;
65 using namespace lyx::support;
66
67 using boost::bind;
68 using boost::ref;
69
70 namespace lyx {
71
72 using graphics::PreviewLoader;
73
74
75 /////////////////////////////////////////////////////////////////////
76
77 InsetText::InsetText(Buffer const & buf, UsePlain type)
78         : drawFrame_(false), frame_color_(Color_insetframe)
79 {
80         setBuffer(const_cast<Buffer &>(buf));
81         initParagraphs(type);
82 }
83
84
85 InsetText::InsetText(InsetText const & in)
86         : Inset(in), text_()
87 {
88         text_.autoBreakRows_ = in.text_.autoBreakRows_;
89         drawFrame_ = in.drawFrame_;
90         frame_color_ = in.frame_color_;
91         text_.paragraphs() = in.text_.paragraphs();
92         setParagraphOwner();
93 }
94
95
96 void InsetText::setBuffer(Buffer & buf)
97 {
98         ParagraphList::iterator end = paragraphs().end();
99         for (ParagraphList::iterator it = paragraphs().begin(); it != end; ++it)
100                 it->setBuffer(buf);
101         Inset::setBuffer(buf);
102 }
103
104
105 void InsetText::initParagraphs(UsePlain type)
106 {
107         LASSERT(paragraphs().empty(), /**/);
108         paragraphs().push_back(Paragraph());
109         Paragraph & ourpar = paragraphs().back();
110         ourpar.setInsetOwner(this);
111         DocumentClass const & dc = buffer_->params().documentClass();
112         if (type == DefaultLayout)
113                 ourpar.setDefaultLayout(dc);
114         else
115                 ourpar.setPlainLayout(dc);
116 }
117
118
119 void InsetText::setParagraphOwner()
120 {
121         for_each(paragraphs().begin(), paragraphs().end(),
122                  bind(&Paragraph::setInsetOwner, _1, this));
123 }
124
125
126 void InsetText::clear()
127 {
128         ParagraphList & pars = paragraphs();
129         LASSERT(!pars.empty(), /**/);
130
131         // This is a gross hack...
132         Layout const & old_layout = pars.begin()->layout();
133
134         pars.clear();
135         pars.push_back(Paragraph());
136         pars.begin()->setInsetOwner(this);
137         pars.begin()->setLayout(old_layout);
138 }
139
140
141 Dimension const InsetText::dimension(BufferView const & bv) const
142 {
143         TextMetrics const & tm = bv.textMetrics(&text_);
144         Dimension dim = tm.dimension();
145         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
146         dim.des += TEXT_TO_INSET_OFFSET;
147         dim.asc += TEXT_TO_INSET_OFFSET;
148         return dim;
149 }
150
151
152 void InsetText::write(ostream & os) const
153 {
154         os << "Text\n";
155         text_.write(buffer(), os);
156 }
157
158
159 void InsetText::read(Lexer & lex)
160 {
161         clear();
162
163         // delete the initial paragraph
164         Paragraph oldpar = *paragraphs().begin();
165         paragraphs().clear();
166         ErrorList errorList;
167         lex.setContext("InsetText::read");
168         bool res = text_.read(buffer(), lex, errorList, this);
169
170         if (!res)
171                 lex.printError("Missing \\end_inset at this point. ");
172
173         // sanity check
174         // ensure we have at least one paragraph.
175         if (paragraphs().empty())
176                 paragraphs().push_back(oldpar);
177         // Force default font, if so requested
178         // This avoids paragraphs in buffer language that would have a
179         // foreign language after a document language change, and it ensures
180         // that all new text in ERT and similar gets the "latex" language,
181         // since new text inherits the language from the last position of the
182         // existing text.  As a side effect this makes us also robust against
183         // bugs in LyX that might lead to font changes in ERT in .lyx files.
184         fixParagraphsFont();
185 }
186
187
188 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
189 {
190         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
191
192         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
193
194         // Hand font through to contained lyxtext:
195         tm.font_.fontInfo() = mi.base.font;
196         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
197
198         // This can happen when a layout has a left and right margin,
199         // and the view is made very narrow. We can't do better than 
200         // to draw it partly out of view (bug 5890).
201         if (mi.base.textwidth < 1)
202                 mi.base.textwidth = 1;
203
204         if (hasFixedWidth())
205                 tm.metrics(mi, dim, mi.base.textwidth);
206         else
207                 tm.metrics(mi, dim);
208         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
209         dim.asc += TEXT_TO_INSET_OFFSET;
210         dim.des += TEXT_TO_INSET_OFFSET;
211         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
212 }
213
214
215 void InsetText::draw(PainterInfo & pi, int x, int y) const
216 {
217         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
218
219         if (drawFrame_ || pi.full_repaint) {
220                 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
221                 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
222                 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
223                 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
224                 if (pi.full_repaint)
225                         pi.pain.fillRectangle(xframe, yframe, w, h,
226                                 pi.backgroundColor(this));
227
228                 if (drawFrame_)
229                         pi.pain.rectangle(xframe, yframe, w, h, frameColor());
230         }
231         ColorCode const old_color = pi.background_color;
232         pi.background_color = pi.backgroundColor(this, false);
233
234         tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
235
236         pi.background_color = old_color;
237 }
238
239
240 docstring InsetText::editMessage() const
241 {
242         return _("Opened Text Inset");
243 }
244
245
246 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
247 {
248         pit_type const pit = front ? 0 : paragraphs().size() - 1;
249         pos_type pos = front ? 0 : paragraphs().back().size();
250
251         // if visual information is not to be ignored, move to extreme right/left
252         if (entry_from != ENTRY_DIRECTION_IGNORE) {
253                 Cursor temp_cur = cur;
254                 temp_cur.pit() = pit;
255                 temp_cur.pos() = pos;
256                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
257                 pos = temp_cur.pos();
258         }
259
260         text_.setCursor(cur.top(), pit, pos);
261         cur.clearSelection();
262         cur.finishUndo();
263 }
264
265
266 Inset * InsetText::editXY(Cursor & cur, int x, int y)
267 {
268         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
269 }
270
271
272 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
273 {
274         LYXERR(Debug::ACTION, "InsetText::doDispatch()"
275                 << " [ cmd.action = " << cmd.action << ']');
276
277         switch (cmd.action) {
278         case LFUN_PASTE:
279         case LFUN_CLIPBOARD_PASTE:
280         case LFUN_SELECTION_PASTE:
281         case LFUN_PRIMARY_SELECTION_PASTE:
282                 text_.dispatch(cur, cmd);
283                 // If we we can only store plain text, we must reset all
284                 // attributes.
285                 // FIXME: Change only the pasted paragraphs
286                 fixParagraphsFont();
287                 break;
288         default:
289                 text_.dispatch(cur, cmd);
290         }
291         
292         if (!cur.result().dispatched())
293                 Inset::doDispatch(cur, cmd);
294 }
295
296
297 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
298         FuncStatus & status) const
299 {
300         switch (cmd.action) {
301         case LFUN_LAYOUT:
302                 status.setEnabled(!forcePlainLayout());
303                 return true;
304
305         case LFUN_LAYOUT_PARAGRAPH:
306         case LFUN_PARAGRAPH_PARAMS:
307         case LFUN_PARAGRAPH_PARAMS_APPLY:
308         case LFUN_PARAGRAPH_SPACING:
309         case LFUN_PARAGRAPH_UPDATE:
310                 status.setEnabled(allowParagraphCustomization());
311                 return true;
312         default:
313                 // Dispatch only to text_ if the cursor is inside
314                 // the text_. It is not for context menus (bug 5797).
315                 bool ret = false;
316                 if (cur.text() == &text_)
317                         ret = text_.getStatus(cur, cmd, status);
318                 
319                 if (!ret)
320                         ret = Inset::getStatus(cur, cmd, status);
321                 return ret;
322         }
323 }
324
325
326 void InsetText::fixParagraphsFont()
327 {
328         Font font(inherit_font, buffer().params().language);
329         if (getLayout().isForceLtr())
330                 font.setLanguage(latex_language);
331         if (getLayout().isPassThru()) {
332                 ParagraphList::iterator par = paragraphs().begin();
333                 ParagraphList::iterator const end = paragraphs().end();
334                 while (par != end) {
335                         par->resetFonts(font);
336                         par->params().clear();
337                         ++par;
338                 }
339         }
340 }
341
342
343 void InsetText::setChange(Change const & change)
344 {
345         ParagraphList::iterator pit = paragraphs().begin();
346         ParagraphList::iterator end = paragraphs().end();
347         for (; pit != end; ++pit) {
348                 pit->setChange(change);
349         }
350 }
351
352
353 void InsetText::acceptChanges()
354 {
355         text_.acceptChanges(buffer().params());
356 }
357
358
359 void InsetText::rejectChanges()
360 {
361         text_.rejectChanges(buffer().params());
362 }
363
364
365 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
366 {
367         TexRow texrow;
368         latexParagraphs(buffer(), text_, os, texrow, runparams);
369         return texrow.rows();
370 }
371
372
373 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
374 {
375         ParagraphList::const_iterator beg = paragraphs().begin();
376         ParagraphList::const_iterator end = paragraphs().end();
377         ParagraphList::const_iterator it = beg;
378         bool ref_printed = false;
379         int len = 0;
380         for (; it != end; ++it) {
381                 if (it != beg) {
382                         os << '\n';
383                         if (runparams.linelen > 0)
384                                 os << '\n';
385                 }
386                 odocstringstream oss;
387                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
388                 docstring const str = oss.str();
389                 os << str;
390                 // FIXME: len is not computed fully correctly; in principle,
391                 // we have to count the characters after the last '\n'
392                 len = str.size();
393         }
394
395         return len;
396 }
397
398
399 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
400 {
401         docbookParagraphs(paragraphs(), buffer(), os, runparams);
402         return 0;
403 }
404
405
406 docstring InsetText::xhtml(odocstream & os, OutputParams const & runparams) const
407 {
408         xhtmlParagraphs(paragraphs(), buffer(), os, runparams);
409         return docstring();
410 }
411
412
413 void InsetText::validate(LaTeXFeatures & features) const
414 {
415         for_each(paragraphs().begin(), paragraphs().end(),
416                  bind(&Paragraph::validate, _1, ref(features)));
417 }
418
419
420 void InsetText::cursorPos(BufferView const & bv,
421                 CursorSlice const & sl, bool boundary, int & x, int & y) const
422 {
423         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
424         y = bv.textMetrics(&text_).cursorY(sl, boundary);
425 }
426
427
428 bool InsetText::showInsetDialog(BufferView *) const
429 {
430         return false;
431 }
432
433
434 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
435 {
436         clear();
437         Paragraph & first = paragraphs().front();
438         for (unsigned int i = 0; i < data.length(); ++i)
439                 first.insertChar(i, data[i], font, trackChanges);
440 }
441
442
443 void InsetText::setAutoBreakRows(bool flag)
444 {
445         if (flag == text_.autoBreakRows_)
446                 return;
447
448         text_.autoBreakRows_ = flag;
449         if (flag)
450                 return;
451
452         // remove previously existing newlines
453         ParagraphList::iterator it = paragraphs().begin();
454         ParagraphList::iterator end = paragraphs().end();
455         for (; it != end; ++it)
456                 for (int i = 0; i < it->size(); ++i)
457                         if (it->isNewline(i))
458                                 // do not track the change, because the user
459                                 // is not allowed to revert/reject it
460                                 it->eraseChar(i, false);
461 }
462
463
464 void InsetText::setDrawFrame(bool flag)
465 {
466         drawFrame_ = flag;
467 }
468
469
470 ColorCode InsetText::frameColor() const
471 {
472         return frame_color_;
473 }
474
475
476 void InsetText::setFrameColor(ColorCode col)
477 {
478         frame_color_ = col;
479 }
480
481
482 void InsetText::appendParagraphs(ParagraphList & plist)
483 {
484         // There is little we can do here to keep track of changes.
485         // As of 2006/10/20, appendParagraphs is used exclusively by
486         // LyXTabular::setMultiColumn. In this context, the paragraph break
487         // is lost irreversibly and the appended text doesn't really change
488
489         ParagraphList & pl = paragraphs();
490
491         ParagraphList::iterator pit = plist.begin();
492         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
493         ++pit;
494         mergeParagraph(buffer().params(), pl,
495                        distance(pl.begin(), ins) - 1);
496
497         for_each(pit, plist.end(),
498                  bind(&ParagraphList::push_back, ref(pl), _1));
499 }
500
501
502 void InsetText::addPreview(PreviewLoader & loader) const
503 {
504         ParagraphList::const_iterator pit = paragraphs().begin();
505         ParagraphList::const_iterator pend = paragraphs().end();
506
507         for (; pit != pend; ++pit) {
508                 InsetList::const_iterator it  = pit->insetList().begin();
509                 InsetList::const_iterator end = pit->insetList().end();
510                 for (; it != end; ++it)
511                         it->inset->addPreview(loader);
512         }
513 }
514
515
516 ParagraphList const & InsetText::paragraphs() const
517 {
518         return text_.paragraphs();
519 }
520
521
522 ParagraphList & InsetText::paragraphs()
523 {
524         return text_.paragraphs();
525 }
526
527
528 void InsetText::updateLabels(ParIterator const & it)
529 {
530         ParIterator it2 = it;
531         it2.forwardPos();
532         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
533         if (producesOutput())
534                 buffer().updateLabels(it2);
535         else {
536                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
537                 Counters const savecnt = tclass.counters();
538                 buffer().updateLabels(it2);
539                 tclass.counters() = savecnt;
540         }
541 }
542
543
544 void InsetText::addToToc(DocIterator const & cdit)
545 {
546         DocIterator dit = cdit;
547         dit.push_back(CursorSlice(*this));
548         Toc & toc = buffer().tocBackend().toc("tableofcontents");
549
550         BufferParams const & bufparams = buffer_->params();
551         const int min_toclevel = bufparams.documentClass().min_toclevel();
552
553         // For each paragraph, traverse its insets and let them add
554         // their toc items
555         ParagraphList & pars = paragraphs();
556         pit_type pend = paragraphs().size();
557         for (pit_type pit = 0; pit != pend; ++pit) {
558                 Paragraph const & par = pars[pit];
559                 dit.pit() = pit;
560                 // the string that goes to the toc (could be the optarg)
561                 docstring tocstring;
562                 InsetList::const_iterator it  = par.insetList().begin();
563                 InsetList::const_iterator end = par.insetList().end();
564                 for (; it != end; ++it) {
565                         Inset & inset = *it->inset;
566                         dit.pos() = it->pos;
567                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
568                         inset.addToToc(dit);
569                         switch (inset.lyxCode()) {
570                         case OPTARG_CODE: {
571                                 if (!tocstring.empty())
572                                         break;
573                                 dit.pos() = 0;
574                                 Paragraph const & insetpar =
575                                         *static_cast<InsetOptArg&>(inset).paragraphs().begin();
576                                 if (!par.labelString().empty())
577                                         tocstring = par.labelString() + ' ';
578                                 tocstring += insetpar.asString(AS_STR_INSETS);
579                                 break;
580                         }
581                         default:
582                                 break;
583                         }
584                 }
585                 // now the toc entry for the paragraph
586                 int const toclevel = par.layout().toclevel;
587                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
588                         dit.pos() = 0;
589                         // insert this into the table of contents
590                         if (tocstring.empty())
591                                 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
592                         toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
593                 }
594                 
595                 // And now the list of changes.
596                 par.addChangesToToc(dit, buffer());
597         }
598 }
599
600
601 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
602 {
603         if (buffer().isClean())
604                 return Inset::notifyCursorLeaves(old, cur);
605         
606         // find text inset in old cursor
607         Cursor insetCur = old;
608         int scriptSlice = insetCur.find(this);
609         LASSERT(scriptSlice != -1, /**/);
610         insetCur.cutOff(scriptSlice);
611         LASSERT(&insetCur.inset() == this, /**/);
612         
613         // update the old paragraph's words
614         insetCur.paragraph().updateWords();
615         
616         return Inset::notifyCursorLeaves(old, cur);
617 }
618
619
620 bool InsetText::completionSupported(Cursor const & cur) const
621 {
622         //LASSERT(&cur.bv().cursor().inset() != this, return false);
623         return text_.completionSupported(cur);
624 }
625
626
627 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
628 {
629         return completionSupported(cur);
630 }
631
632
633 bool InsetText::automaticInlineCompletion() const
634 {
635         return lyxrc.completion_inline_text;
636 }
637
638
639 bool InsetText::automaticPopupCompletion() const
640 {
641         return lyxrc.completion_popup_text;
642 }
643
644
645 bool InsetText::showCompletionCursor() const
646 {
647         return lyxrc.completion_cursor_text;
648 }
649
650
651 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
652 {
653         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
654 }
655
656
657 docstring InsetText::completionPrefix(Cursor const & cur) const
658 {
659         if (!completionSupported(cur))
660                 return docstring();
661         return text_.completionPrefix(cur);
662 }
663
664
665 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
666         bool finished)
667 {
668         if (!completionSupported(cur))
669                 return false;
670
671         return text_.insertCompletion(cur, s, finished);
672 }
673
674
675 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
676         Dimension & dim) const
677 {
678         TextMetrics const & tm = cur.bv().textMetrics(&text_);
679         tm.completionPosAndDim(cur, x, y, dim);
680 }
681
682
683 docstring InsetText::contextMenu(BufferView const &, int, int) const
684 {
685         return from_ascii("context-edit");
686 }
687
688
689 InsetCaption const * InsetText::getCaptionInset() const
690 {
691         ParagraphList::const_iterator pit = paragraphs().begin();
692         for (; pit != paragraphs().end(); ++pit) {
693                 InsetList::const_iterator it = pit->insetList().begin();
694                 for (; it != pit->insetList().end(); ++it) {
695                         Inset & inset = *it->inset;
696                         if (inset.lyxCode() == CAPTION_CODE) {
697                                 InsetCaption const * ins =
698                                         static_cast<InsetCaption const *>(it->inset);
699                                 return ins;
700                         }
701                 }
702         }
703         return 0;
704 }
705
706
707 docstring InsetText::getCaptionText(OutputParams const & runparams) const
708 {
709         InsetCaption const * ins = getCaptionInset();
710         if (ins == 0)
711                 return docstring();
712
713         odocstringstream ods;
714         ins->getCaptionAsPlaintext(ods, runparams);
715         return ods.str();
716 }
717
718
719 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
720 {
721         InsetCaption const * ins = getCaptionInset();
722         if (ins == 0)
723                 return docstring();
724
725         odocstringstream ods;
726         docstring def = ins->getCaptionAsHTML(ods, runparams);
727         if (!def.empty())
728                 ods << def << '\n';
729         return ods.str();
730 }
731
732
733 } // namespace lyx