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