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