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