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