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