]> git.lyx.org Git - lyx.git/blob - src/insets/InsetText.cpp
9676e459821d94ca81a5aa62ae1262d74b478ddb
[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 void InsetText::xhtml(odocstream & os, OutputParams const & runparams) const
372 {
373         xhtmlParagraphs(paragraphs(), buffer(), os, runparams);
374 }
375
376
377 void InsetText::validate(LaTeXFeatures & features) const
378 {
379         for_each(paragraphs().begin(), paragraphs().end(),
380                  bind(&Paragraph::validate, _1, ref(features)));
381 }
382
383
384 void InsetText::cursorPos(BufferView const & bv,
385                 CursorSlice const & sl, bool boundary, int & x, int & y) const
386 {
387         x = bv.textMetrics(&text_).cursorX(sl, boundary) + TEXT_TO_INSET_OFFSET;
388         y = bv.textMetrics(&text_).cursorY(sl, boundary);
389 }
390
391
392 bool InsetText::showInsetDialog(BufferView *) const
393 {
394         return false;
395 }
396
397
398 void InsetText::setText(docstring const & data, Font const & font, bool trackChanges)
399 {
400         clear();
401         Paragraph & first = paragraphs().front();
402         for (unsigned int i = 0; i < data.length(); ++i)
403                 first.insertChar(i, data[i], font, trackChanges);
404 }
405
406
407 void InsetText::setAutoBreakRows(bool flag)
408 {
409         if (flag == text_.autoBreakRows_)
410                 return;
411
412         text_.autoBreakRows_ = flag;
413         if (flag)
414                 return;
415
416         // remove previously existing newlines
417         ParagraphList::iterator it = paragraphs().begin();
418         ParagraphList::iterator end = paragraphs().end();
419         for (; it != end; ++it)
420                 for (int i = 0; i < it->size(); ++i)
421                         if (it->isNewline(i))
422                                 // do not track the change, because the user
423                                 // is not allowed to revert/reject it
424                                 it->eraseChar(i, false);
425 }
426
427
428 void InsetText::setDrawFrame(bool flag)
429 {
430         drawFrame_ = flag;
431 }
432
433
434 ColorCode InsetText::frameColor() const
435 {
436         return frame_color_;
437 }
438
439
440 void InsetText::setFrameColor(ColorCode col)
441 {
442         frame_color_ = col;
443 }
444
445
446 void InsetText::appendParagraphs(ParagraphList & plist)
447 {
448         // There is little we can do here to keep track of changes.
449         // As of 2006/10/20, appendParagraphs is used exclusively by
450         // LyXTabular::setMultiColumn. In this context, the paragraph break
451         // is lost irreversibly and the appended text doesn't really change
452
453         ParagraphList & pl = paragraphs();
454
455         ParagraphList::iterator pit = plist.begin();
456         ParagraphList::iterator ins = pl.insert(pl.end(), *pit);
457         ++pit;
458         mergeParagraph(buffer().params(), pl,
459                        distance(pl.begin(), ins) - 1);
460
461         for_each(pit, plist.end(),
462                  bind(&ParagraphList::push_back, ref(pl), _1));
463 }
464
465
466 void InsetText::addPreview(PreviewLoader & loader) const
467 {
468         ParagraphList::const_iterator pit = paragraphs().begin();
469         ParagraphList::const_iterator pend = paragraphs().end();
470
471         for (; pit != pend; ++pit) {
472                 InsetList::const_iterator it  = pit->insetList().begin();
473                 InsetList::const_iterator end = pit->insetList().end();
474                 for (; it != end; ++it)
475                         it->inset->addPreview(loader);
476         }
477 }
478
479
480 ParagraphList const & InsetText::paragraphs() const
481 {
482         return text_.paragraphs();
483 }
484
485
486 ParagraphList & InsetText::paragraphs()
487 {
488         return text_.paragraphs();
489 }
490
491
492 void InsetText::updateLabels(ParIterator const & it)
493 {
494         ParIterator it2 = it;
495         it2.forwardPos();
496         LASSERT(&it2.inset() == this && it2.pit() == 0, return);
497         if (producesOutput())
498                 buffer().updateLabels(it2);
499         else {
500                 DocumentClass const & tclass = buffer().masterBuffer()->params().documentClass();
501                 Counters const savecnt = tclass.counters();
502                 buffer().updateLabels(it2);
503                 tclass.counters() = savecnt;
504         }
505 }
506
507
508 void InsetText::addToToc(DocIterator const & cdit)
509 {
510         DocIterator dit = cdit;
511         dit.push_back(CursorSlice(*this));
512         Toc & toc = buffer().tocBackend().toc("tableofcontents");
513
514         BufferParams const & bufparams = buffer_->params();
515         const int min_toclevel = bufparams.documentClass().min_toclevel();
516
517         // For each paragraph, traverse its insets and let them add
518         // their toc items
519         ParagraphList & pars = paragraphs();
520         pit_type pend = paragraphs().size();
521         for (pit_type pit = 0; pit != pend; ++pit) {
522                 Paragraph const & par = pars[pit];
523                 dit.pit() = pit;
524                 // the string that goes to the toc (could be the optarg)
525                 docstring tocstring;
526                 InsetList::const_iterator it  = par.insetList().begin();
527                 InsetList::const_iterator end = par.insetList().end();
528                 for (; it != end; ++it) {
529                         Inset & inset = *it->inset;
530                         dit.pos() = it->pos;
531                         //lyxerr << (void*)&inset << " code: " << inset.lyxCode() << std::endl;
532                         inset.addToToc(dit);
533                         switch (inset.lyxCode()) {
534                         case OPTARG_CODE: {
535                                 if (!tocstring.empty())
536                                         break;
537                                 dit.pos() = 0;
538                                 Paragraph const & insetpar =
539                                         *static_cast<InsetOptArg&>(inset).paragraphs().begin();
540                                 if (!par.labelString().empty())
541                                         tocstring = par.labelString() + ' ';
542                                 tocstring += insetpar.asString(AS_STR_INSETS);
543                                 break;
544                         }
545                         default:
546                                 break;
547                         }
548                 }
549                 // now the toc entry for the paragraph
550                 int const toclevel = par.layout().toclevel;
551                 if (toclevel != Layout::NOT_IN_TOC && toclevel >= min_toclevel) {
552                         dit.pos() = 0;
553                         // insert this into the table of contents
554                         if (tocstring.empty())
555                                 tocstring = par.asString(AS_STR_LABEL | AS_STR_INSETS);
556                         toc.push_back(TocItem(dit, toclevel - min_toclevel, tocstring));
557                 }
558                 
559                 // And now the list of changes.
560                 par.addChangesToToc(dit, buffer());
561         }
562 }
563
564
565 bool InsetText::notifyCursorLeaves(Cursor const & old, Cursor & cur)
566 {
567         if (buffer().isClean())
568                 return Inset::notifyCursorLeaves(old, cur);
569         
570         // find text inset in old cursor
571         Cursor insetCur = old;
572         int scriptSlice = insetCur.find(this);
573         LASSERT(scriptSlice != -1, /**/);
574         insetCur.cutOff(scriptSlice);
575         LASSERT(&insetCur.inset() == this, /**/);
576         
577         // update the old paragraph's words
578         insetCur.paragraph().updateWords();
579         
580         return Inset::notifyCursorLeaves(old, cur);
581 }
582
583
584 bool InsetText::completionSupported(Cursor const & cur) const
585 {
586         //LASSERT(&cur.bv().cursor().inset() != this, return false);
587         return text_.completionSupported(cur);
588 }
589
590
591 bool InsetText::inlineCompletionSupported(Cursor const & cur) const
592 {
593         return completionSupported(cur);
594 }
595
596
597 bool InsetText::automaticInlineCompletion() const
598 {
599         return lyxrc.completion_inline_text;
600 }
601
602
603 bool InsetText::automaticPopupCompletion() const
604 {
605         return lyxrc.completion_popup_text;
606 }
607
608
609 bool InsetText::showCompletionCursor() const
610 {
611         return lyxrc.completion_cursor_text;
612 }
613
614
615 CompletionList const * InsetText::createCompletionList(Cursor const & cur) const
616 {
617         return completionSupported(cur) ? text_.createCompletionList(cur) : 0;
618 }
619
620
621 docstring InsetText::completionPrefix(Cursor const & cur) const
622 {
623         if (!completionSupported(cur))
624                 return docstring();
625         return text_.completionPrefix(cur);
626 }
627
628
629 bool InsetText::insertCompletion(Cursor & cur, docstring const & s,
630         bool finished)
631 {
632         if (!completionSupported(cur))
633                 return false;
634
635         return text_.insertCompletion(cur, s, finished);
636 }
637
638
639 void InsetText::completionPosAndDim(Cursor const & cur, int & x, int & y, 
640         Dimension & dim) const
641 {
642         TextMetrics const & tm = cur.bv().textMetrics(&text_);
643         tm.completionPosAndDim(cur, x, y, dim);
644 }
645
646
647 docstring InsetText::contextMenu(BufferView const &, int, int) const
648 {
649         return from_ascii("context-edit");
650 }
651
652
653 } // namespace lyx