]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
0a5cb92764662f2f38916c41ae24fcb974a6c8d7
[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 }
178
179
180 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
181 {
182         TextMetrics & tm = mi.base.bv->textMetrics(&text_);
183
184         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
185
186         // Hand font through to contained lyxtext:
187         tm.font_.fontInfo() = mi.base.font;
188         mi.base.textwidth -= 2 * TEXT_TO_INSET_OFFSET;
189
190         // This can happen when a layout has a left and right margin,
191         // and the view is made very narrow. We can't do better than 
192         // to draw it partly out of view (bug 5890).
193         if (mi.base.textwidth < 1)
194                 mi.base.textwidth = 1;
195
196         if (hasFixedWidth())
197                 tm.metrics(mi, dim, mi.base.textwidth);
198         else
199                 tm.metrics(mi, dim);
200         mi.base.textwidth += 2 * TEXT_TO_INSET_OFFSET;
201         dim.asc += TEXT_TO_INSET_OFFSET;
202         dim.des += TEXT_TO_INSET_OFFSET;
203         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
204 }
205
206
207 void InsetText::draw(PainterInfo & pi, int x, int y) const
208 {
209         TextMetrics & tm = pi.base.bv->textMetrics(&text_);
210
211         if (drawFrame_ || pi.full_repaint) {
212                 int const w = tm.width() + TEXT_TO_INSET_OFFSET;
213                 int const yframe = y - TEXT_TO_INSET_OFFSET - tm.ascent();
214                 int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
215                 int const xframe = x + TEXT_TO_INSET_OFFSET / 2;
216                 if (pi.full_repaint)
217                         pi.pain.fillRectangle(xframe, yframe, w, h,
218                                 pi.backgroundColor(this));
219
220                 if (drawFrame_)
221                         pi.pain.rectangle(xframe, yframe, w, h, frameColor());
222         }
223         ColorCode const old_color = pi.background_color;
224         pi.background_color = pi.backgroundColor(this, false);
225
226         tm.draw(pi, x + TEXT_TO_INSET_OFFSET, y);
227
228         pi.background_color = old_color;
229 }
230
231
232 docstring InsetText::editMessage() const
233 {
234         return _("Opened Text Inset");
235 }
236
237
238 void InsetText::edit(Cursor & cur, bool front, EntryDirection entry_from)
239 {
240         pit_type const pit = front ? 0 : paragraphs().size() - 1;
241         pos_type pos = front ? 0 : paragraphs().back().size();
242
243         // if visual information is not to be ignored, move to extreme right/left
244         if (entry_from != ENTRY_DIRECTION_IGNORE) {
245                 Cursor temp_cur = cur;
246                 temp_cur.pit() = pit;
247                 temp_cur.pos() = pos;
248                 temp_cur.posVisToRowExtremity(entry_from == ENTRY_DIRECTION_LEFT);
249                 pos = temp_cur.pos();
250         }
251
252         text_.setCursor(cur.top(), pit, pos);
253         cur.clearSelection();
254         cur.finishUndo();
255 }
256
257
258 Inset * InsetText::editXY(Cursor & cur, int x, int y)
259 {
260         return cur.bv().textMetrics(&text_).editXY(cur, x, y);
261 }
262
263
264 void InsetText::doDispatch(Cursor & cur, FuncRequest & cmd)
265 {
266         LYXERR(Debug::ACTION, "InsetText::doDispatch()"
267                 << " [ cmd.action = " << cmd.action << ']');
268
269         switch (cmd.action) {
270         case LFUN_PASTE:
271         case LFUN_CLIPBOARD_PASTE:
272         case LFUN_SELECTION_PASTE:
273         case LFUN_PRIMARY_SELECTION_PASTE:
274                 text_.dispatch(cur, cmd);
275                 // If we we can only store plain text, we must reset all
276                 // attributes.
277                 // FIXME: Change only the pasted paragraphs
278                 fixParagraphsFont();
279                 break;
280         default:
281                 text_.dispatch(cur, cmd);
282         }
283         
284         if (!cur.result().dispatched())
285                 Inset::doDispatch(cur, cmd);
286 }
287
288
289 bool InsetText::getStatus(Cursor & cur, FuncRequest const & cmd,
290         FuncStatus & status) const
291 {
292         switch (cmd.action) {
293         case LFUN_LAYOUT:
294                 status.setEnabled(!forcePlainLayout());
295                 return true;
296
297         case LFUN_LAYOUT_PARAGRAPH:
298         case LFUN_PARAGRAPH_PARAMS:
299         case LFUN_PARAGRAPH_PARAMS_APPLY:
300         case LFUN_PARAGRAPH_SPACING:
301         case LFUN_PARAGRAPH_UPDATE:
302                 status.setEnabled(allowParagraphCustomization());
303                 return true;
304         default:
305                 // Dispatch only to text_ if the cursor is inside
306                 // the text_. It is not for context menus (bug 5797).
307                 bool ret = false;
308                 if (cur.text() == &text_)
309                         ret = text_.getStatus(cur, cmd, status);
310                 
311                 if (!ret)
312                         ret = Inset::getStatus(cur, cmd, status);
313                 return ret;
314         }
315 }
316
317
318 void InsetText::fixParagraphsFont()
319 {
320         Font font(inherit_font, buffer().params().language);
321         if (getLayout().isForceLtr())
322                 font.setLanguage(latex_language);
323         if (getLayout().isPassThru()) {
324                 ParagraphList::iterator par = paragraphs().begin();
325                 ParagraphList::iterator const end = paragraphs().end();
326                 while (par != end) {
327                         par->resetFonts(font);
328                         par->params().clear();
329                         ++par;
330                 }
331         }
332 }
333
334
335 void InsetText::setChange(Change const & change)
336 {
337         ParagraphList::iterator pit = paragraphs().begin();
338         ParagraphList::iterator end = paragraphs().end();
339         for (; pit != end; ++pit) {
340                 pit->setChange(change);
341         }
342 }
343
344
345 void InsetText::acceptChanges()
346 {
347         text_.acceptChanges(buffer().params());
348 }
349
350
351 void InsetText::rejectChanges()
352 {
353         text_.rejectChanges(buffer().params());
354 }
355
356
357 int InsetText::latex(odocstream & os, OutputParams const & runparams) const
358 {
359         TexRow texrow;
360         latexParagraphs(buffer(), text_, os, texrow, runparams);
361         return texrow.rows();
362 }
363
364
365 int InsetText::plaintext(odocstream & os, OutputParams const & runparams) const
366 {
367         ParagraphList::const_iterator beg = paragraphs().begin();
368         ParagraphList::const_iterator end = paragraphs().end();
369         ParagraphList::const_iterator it = beg;
370         bool ref_printed = false;
371         int len = 0;
372         for (; it != end; ++it) {
373                 if (it != beg) {
374                         os << '\n';
375                         if (runparams.linelen > 0)
376                                 os << '\n';
377                 }
378                 odocstringstream oss;
379                 writePlaintextParagraph(buffer(), *it, oss, runparams, ref_printed);
380                 docstring const str = oss.str();
381                 os << str;
382                 // FIXME: len is not computed fully correctly; in principle,
383                 // we have to count the characters after the last '\n'
384                 len = str.size();
385         }
386
387         return len;
388 }
389
390
391 int InsetText::docbook(odocstream & os, OutputParams const & runparams) const
392 {
393         docbookParagraphs(paragraphs(), buffer(), os, runparams);
394         return 0;
395 }
396
397
398 docstring InsetText::xhtml(odocstream & os, OutputParams const & runparams) const
399 {
400         xhtmlParagraphs(paragraphs(), buffer(), os, runparams);
401         return docstring();
402 }
403
404
405 void InsetText::validate(LaTeXFeatures & features) const
406 {
407         for_each(paragraphs().begin(), paragraphs().end(),
408                  bind(&Paragraph::validate, _1, ref(features)));
409 }
410
411
412 void InsetText::cursorPos(BufferView const & bv,
413                 CursorSlice const & sl, bool boundary, int & x, int & y) const
414 {
415         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
416         y = bv.textMetrics(&text_).cursorY(sl, boundary);
417 }
418
419
420 bool InsetText::showInsetDialog(BufferView *) const
421 {
422         return false;
423 }
424
425
426 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
427 {
428         clear();
429         Paragraph & first = paragraphs().front();
430         for (unsigned int i = 0; i < data.length(); ++i)
431                 first.insertChar(i, data[i], font, trackChanges);
432 }
433
434
435 void InsetText::setAutoBreakRows(bool flag)
436 {
437         if (flag == text_.autoBreakRows_)
438                 return;
439
440         text_.autoBreakRows_ = flag;
441         if (flag)
442                 return;
443
444         // remove previously existing newlines
445         ParagraphList::iterator it = paragraphs().begin();
446         ParagraphList::iterator end = paragraphs().end();
447         for (; it != end; ++it)
448                 for (int i = 0; i < it->size(); ++i)
449                         if (it->isNewline(i))
450                                 // do not track the change, because the user
451                                 // is not allowed to revert/reject it
452                                 it->eraseChar(i, false);
453 }
454
455
456 void InsetText::setDrawFrame(bool flag)
457 {
458         drawFrame_ = flag;
459 }
460
461
462 ColorCode InsetText::frameColor() const
463 {
464         return frame_color_;
465 }
466
467
468 void InsetText::setFrameColor(ColorCode col)
469 {
470         frame_color_ = col;
471 }
472
473
474 void InsetText::appendParagraphs(ParagraphList & plist)
475 {
476         // There is little we can do here to keep track of changes.
477         // As of 2006/10/20, appendParagraphs is used exclusively by
478         // LyXTabular::setMultiColumn. In this context, the paragraph break
479         // is lost irreversibly and the appended text doesn't really change
480
481         ParagraphList & pl = paragraphs();
482
483         ParagraphList::iterator pit = plist.begin();
484         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
485         ++pit;
486         mergeParagraph(buffer().params(), pl,
487                        distance(pl.begin(), ins) - 1);
488
489         for_each(pit, plist.end(),
490                  bind(&ParagraphList::push_back, ref(pl), _1));
491 }
492
493
494 void InsetText::addPreview(PreviewLoader & loader) const
495 {
496         ParagraphList::const_iterator pit = paragraphs().begin();
497         ParagraphList::const_iterator pend = paragraphs().end();
498
499         for (; pit != pend; ++pit) {
500                 InsetList::const_iterator it  = pit->insetList().begin();
501                 InsetList::const_iterator end = pit->insetList().end();
502                 for (; it != end; ++it)
503                         it->inset->addPreview(loader);
504         }
505 }
506
507
508 ParagraphList const & InsetText::paragraphs() const
509 {
510         return text_.paragraphs();
511 }
512
513
514 ParagraphList & InsetText::paragraphs()
515 {
516         return text_.paragraphs();
517 }
518
519
520 void InsetText::updateLabels(ParIterator const & it)
521 {
522         ParIterator it2 = it;
523         it2.forwardPos();
524         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
525         if (producesOutput())
526                 buffer().updateLabels(it2);
527         else {
528                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
529                 Counters const savecnt = tclass.counters();
530                 buffer().updateLabels(it2);
531                 tclass.counters() = savecnt;
532         }
533 }
534
535
536 void InsetText::addToToc(DocIterator const & cdit)
537 {
538         DocIterator dit = cdit;
539         dit.push_back(CursorSlice(*this));
540         Toc & toc = buffer().tocBackend().toc("tableofcontents");
541
542         BufferParams const & bufparams = buffer_->params();
543         const int min_toclevel = bufparams.documentClass().min_toclevel();
544
545         // For each paragraph, traverse its insets and let them add
546         // their toc items
547         ParagraphList & pars = paragraphs();
548         pit_type pend = paragraphs().size();
549         for (pit_type pit = 0; pit != pend; ++pit) {
550                 Paragraph const & par = pars[pit];
551                 dit.pit() = pit;
552                 // the string that goes to the toc (could be the optarg)
553                 docstring tocstring;
554                 InsetList::const_iterator it  = par.insetList().begin();
555                 InsetList::const_iterator end = par.insetList().end();
556                 for (; it != end; ++it) {
557                         Inset & inset = *it->inset;
558                         dit.pos() = it->pos;
559                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
560                         inset.addToToc(dit);
561                         switch (inset.lyxCode()) {
562                         case OPTARG_CODE: {
563                                 if (!tocstring.empty())
564                                         break;
565                                 dit.pos() = 0;
566                                 Paragraph const & insetpar =
567                                         *static_cast<InsetOptArg&>(inset).paragraphs().begin();
568                                 if (!par.labelString().empty())
569                                         tocstring = par.labelString() + ' ';
570                                 tocstring += insetpar.asString(AS_STR_INSETS);
571                                 break;
572                         }
573                         default:
574                                 break;
575                         }
576                 }
577                 // now the toc entry for the paragraph
578                 int const toclevel = par.layout().toclevel;
579                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
580                         dit.pos() = 0;
581                         // insert this into the table of contents
582                         if (tocstring.empty())
583                                 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
584                         toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
585                 }
586                 
587                 // And now the list of changes.
588                 par.addChangesToToc(dit, buffer());
589         }
590 }
591
592
593 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
594 {
595         if (buffer().isClean())
596                 return Inset::notifyCursorLeaves(old, cur);
597         
598         // find text inset in old cursor
599         Cursor insetCur = old;
600         int scriptSlice = insetCur.find(this);
601         LASSERT(scriptSlice != -1, /**/);
602         insetCur.cutOff(scriptSlice);
603         LASSERT(&insetCur.inset() == this, /**/);
604         
605         // update the old paragraph's words
606         insetCur.paragraph().updateWords();
607         
608         return Inset::notifyCursorLeaves(old, cur);
609 }
610
611
612 bool InsetText::completionSupported(Cursor const & cur) const
613 {
614         //LASSERT(&cur.bv().cursor().inset() != this, return false);
615         return text_.completionSupported(cur);
616 }
617
618
619 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
620 {
621         return completionSupported(cur);
622 }
623
624
625 bool InsetText::automaticInlineCompletion() const
626 {
627         return lyxrc.completion_inline_text;
628 }
629
630
631 bool InsetText::automaticPopupCompletion() const
632 {
633         return lyxrc.completion_popup_text;
634 }
635
636
637 bool InsetText::showCompletionCursor() const
638 {
639         return lyxrc.completion_cursor_text;
640 }
641
642
643 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
644 {
645         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
646 }
647
648
649 docstring InsetText::completionPrefix(Cursor const & cur) const
650 {
651         if (!completionSupported(cur))
652                 return docstring();
653         return text_.completionPrefix(cur);
654 }
655
656
657 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
658         bool finished)
659 {
660         if (!completionSupported(cur))
661                 return false;
662
663         return text_.insertCompletion(cur, s, finished);
664 }
665
666
667 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
668         Dimension & dim) const
669 {
670         TextMetrics const & tm = cur.bv().textMetrics(&text_);
671         tm.completionPosAndDim(cur, x, y, dim);
672 }
673
674
675 docstring InsetText::contextMenu(BufferView const &, int, int) const
676 {
677         return from_ascii("context-edit");
678 }
679
680
681 InsetCaption const * InsetText::getCaptionInset() const
682 {
683         ParagraphList::const_iterator pit = paragraphs().begin();
684         for (; pit != paragraphs().end(); ++pit) {
685                 InsetList::const_iterator it = pit->insetList().begin();
686                 for (; it != pit->insetList().end(); ++it) {
687                         Inset & inset = *it->inset;
688                         if (inset.lyxCode() == CAPTION_CODE) {
689                                 InsetCaption const * ins =
690                                         static_cast<InsetCaption const *>(it->inset);
691                                 return ins;
692                         }
693                 }
694         }
695         return 0;
696 }
697
698
699 docstring InsetText::getCaptionText(OutputParams const & runparams) const
700 {
701         InsetCaption const * ins = getCaptionInset();
702         if (ins == 0)
703                 return docstring();
704
705         odocstringstream ods;
706         ins->getCaptionAsPlaintext(ods, runparams);
707         return ods.str();
708 }
709
710
711 docstring InsetText::getCaptionHTML(OutputParams const & runparams) const
712 {
713         InsetCaption const * ins = getCaptionInset();
714         if (ins == 0)
715                 return docstring();
716
717         odocstringstream ods;
718         docstring def = ins->getCaptionAsHTML(ods, runparams);
719         if (!def.empty())
720                 ods << def << '\n';
721         return ods.str();
722 }
723
724
725 } // namespace lyx