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