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