]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.cpp
* src/LyXRC.{cpp,h}:
[lyx.git] / src / buffer_funcs.cpp
1 /**
2  * \file buffer_funcs.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16 #include "Buffer.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "debug.h"
20 #include "DocIterator.h"
21 #include "Counters.h"
22 #include "ErrorList.h"
23 #include "Floating.h"
24 #include "FloatList.h"
25 #include "gettext.h"
26 #include "InsetList.h"
27 #include "InsetIterator.h"
28 #include "Language.h"
29 #include "LaTeX.h"
30 #include "Layout.h"
31 #include "LayoutPtr.h"
32 #include "LyX.h"
33 #include "TextClass.h"
34 #include "TextClassList.h"
35 #include "Paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphList.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
40 #include "TexRow.h"
41 #include "Text.h"
42 #include "TocBackend.h"
43
44 #include "frontends/alert.h"
45
46 #include "insets/InsetBibitem.h"
47 #include "insets/InsetInclude.h"
48
49 #include "support/filetools.h"
50 #include "support/fs_extras.h"
51 #include "support/lyxlib.h"
52
53 #include <boost/bind.hpp>
54
55 using std::min;
56 using std::string;
57
58
59 namespace lyx {
60
61 using namespace std;
62
63 using support::bformat;
64 using support::FileName;
65 using support::libFileSearch;
66 using support::makeAbsPath;
67 using support::makeDisplayPath;
68 using support::onlyFilename;
69 using support::onlyPath;
70 using support::unlink;
71
72 namespace Alert = frontend::Alert;
73
74
75 Buffer * checkAndLoadLyXFile(FileName const & filename)
76 {
77         // File already open?
78         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
79         if (checkBuffer) {
80                 if (checkBuffer->isClean())
81                         return checkBuffer;
82                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
83                 docstring text = bformat(_(
84                                 "The document %1$s is already loaded and has unsaved changes.\n"
85                                 "Do you want to abandon your changes and reload the version on disk?"), file);
86                 if (Alert::prompt(_("Reload saved document?"),
87                                 text, 0, 1,  _("&Reload"), _("&Keep Changes")))
88                         return checkBuffer;
89
90                 // FIXME: should be LFUN_REVERT
91                 if (theBufferList().close(checkBuffer, false))
92                         // Load it again.
93                         return checkAndLoadLyXFile(filename);
94                 // The file could not be closed.
95                 return 0;
96         }
97
98         if (filename.isReadable()) {
99                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
100                 if (!b->loadLyXFile(filename)) {
101                         theBufferList().release(b);
102                         return 0;
103                 }
104                 return b;
105         }
106
107         docstring text = bformat(_("The document %1$s does not yet "
108                 "exist.\n\nDo you want to create a new document?"),
109                 from_utf8(filename.absFilename()));
110         if (!Alert::prompt(_("Create new document?"),
111                         text, 0, 1, _("&Create"), _("Cancel")))
112                 return newFile(filename.absFilename(), string(), true);
113
114         return 0;
115 }
116
117
118 // FIXME newFile() should probably be a member method of Application...
119 Buffer * newFile(string const & filename, string const & templatename,
120                  bool const isNamed)
121 {
122         // get a free buffer
123         Buffer * b = theBufferList().newBuffer(filename);
124         BOOST_ASSERT(b);
125
126         FileName tname;
127         // use defaults.lyx as a default template if it exists.
128         if (templatename.empty())
129                 tname = libFileSearch("templates", "defaults.lyx");
130         else
131                 tname = makeAbsPath(templatename);
132
133         if (!tname.empty()) {
134                 if (!b->readFile(tname)) {
135                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
136                         docstring const text  = bformat(
137                                 _("The specified document template\n%1$s\ncould not be read."),
138                                 file);
139                         Alert::error(_("Could not read template"), text);
140                         theBufferList().release(b);
141                         return 0;
142                 }
143         }
144
145         if (!isNamed) {
146                 b->setUnnamed();
147                 b->setFileName(filename);
148         }
149
150         b->setReadonly(false);
151         b->setFullyLoaded(true);
152
153         return b;
154 }
155
156
157 int countWords(DocIterator const & from, DocIterator const & to)
158 {
159         int count = 0;
160         bool inword = false;
161         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
162                 // Copied and adapted from isLetter() in ControlSpellChecker
163                 if (dit.inTexted()
164                     && dit.pos() != dit.lastpos()
165                     && dit.paragraph().isLetter(dit.pos())
166                     && !dit.paragraph().isDeleted(dit.pos())) {
167                         if (!inword) {
168                                 ++count;
169                                 inword = true;
170                         }
171                 } else if (inword)
172                         inword = false;
173         }
174
175         return count;
176 }
177
178
179 namespace {
180
181 depth_type getDepth(DocIterator const & it)
182 {
183         depth_type depth = 0;
184         for (size_t i = 0 ; i < it.depth() ; ++i)
185                 if (!it[i].inset().inMathed())
186                         depth += it[i].paragraph().getDepth() + 1;
187         // remove 1 since the outer inset does not count
188         return depth - 1;
189 }
190
191 depth_type getItemDepth(ParIterator const & it)
192 {
193         Paragraph const & par = *it;
194         LabelType const labeltype = par.layout()->labeltype;
195
196         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
197                 return 0;
198
199         // this will hold the lowest depth encountered up to now.
200         depth_type min_depth = getDepth(it);
201         ParIterator prev_it = it;
202         while (true) {
203                 if (prev_it.pit())
204                         --prev_it.top().pit();
205                 else {
206                         // start of nested inset: go to outer par
207                         prev_it.pop_back();
208                         if (prev_it.empty()) {
209                                 // start of document: nothing to do
210                                 return 0;
211                         }
212                 }
213
214                 // We search for the first paragraph with same label
215                 // that is not more deeply nested.
216                 Paragraph & prev_par = *prev_it;
217                 depth_type const prev_depth = getDepth(prev_it);
218                 if (labeltype == prev_par.layout()->labeltype) {
219                         if (prev_depth < min_depth) {
220                                 return prev_par.itemdepth + 1;
221                         }
222                         else if (prev_depth == min_depth) {
223                                 return prev_par.itemdepth;
224                         }
225                 }
226                 min_depth = std::min(min_depth, prev_depth);
227                 // small optimization: if we are at depth 0, we won't
228                 // find anything else
229                 if (prev_depth == 0) {
230                         return 0;
231                 }
232         }
233 }
234
235
236 bool needEnumCounterReset(ParIterator const & it)
237 {
238         Paragraph const & par = *it;
239         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
240         depth_type const cur_depth = par.getDepth();
241         ParIterator prev_it = it;
242         while (prev_it.pit()) {
243                 --prev_it.top().pit();
244                 Paragraph const & prev_par = *prev_it;
245                 if (prev_par.getDepth() <= cur_depth)
246                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
247         }
248         // start of nested inset: reset
249         return true;
250 }
251
252
253 // set the label of a paragraph. This includes the counters.
254 void setLabel(Buffer const & buf, ParIterator & it)
255 {
256         TextClass const & textclass = buf.params().getTextClass();
257         Paragraph & par = it.paragraph();
258         LayoutPtr const & layout = par.layout();
259         Counters & counters = textclass.counters();
260
261         if (par.params().startOfAppendix()) {
262                 // FIXME: only the counter corresponding to toplevel
263                 // sectionning should be reset
264                 counters.reset();
265                 counters.appendix(true);
266         }
267         par.params().appendix(counters.appendix());
268
269         // Compute the item depth of the paragraph
270         par.itemdepth = getItemDepth(it);
271
272         if (layout->margintype == MARGIN_MANUAL) {
273                 if (par.params().labelWidthString().empty())
274                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
275         } else {
276                 par.params().labelWidthString(docstring());
277         }
278
279         switch(layout->labeltype) {
280         case LABEL_COUNTER:
281                 if (layout->toclevel <= buf.params().secnumdepth
282                     && (layout->latextype != LATEX_ENVIRONMENT
283                         || isFirstInSequence(it.pit(), it.plist()))) {
284                         counters.step(layout->counter);
285                         par.params().labelString(
286                                 par.expandLabel(layout, buf.params()));
287                 } else
288                         par.params().labelString(docstring());
289                 break;
290
291         case LABEL_ITEMIZE: {
292                 // At some point of time we should do something more
293                 // clever here, like:
294                 //   par.params().labelString(
295                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
296                 // for now, use a simple hardcoded label
297                 docstring itemlabel;
298                 switch (par.itemdepth) {
299                 case 0:
300                         itemlabel = char_type(0x2022);
301                         break;
302                 case 1:
303                         itemlabel = char_type(0x2013);
304                         break;
305                 case 2:
306                         itemlabel = char_type(0x2217);
307                         break;
308                 case 3:
309                         itemlabel = char_type(0x2219); // or 0x00b7
310                         break;
311                 }
312                 par.params().labelString(itemlabel);
313                 break;
314         }
315
316         case LABEL_ENUMERATE: {
317                 // FIXME: Yes I know this is a really, really! bad solution
318                 // (Lgb)
319                 docstring enumcounter = from_ascii("enum");
320
321                 switch (par.itemdepth) {
322                 case 2:
323                         enumcounter += 'i';
324                 case 1:
325                         enumcounter += 'i';
326                 case 0:
327                         enumcounter += 'i';
328                         break;
329                 case 3:
330                         enumcounter += "iv";
331                         break;
332                 default:
333                         // not a valid enumdepth...
334                         break;
335                 }
336
337                 // Maybe we have to reset the enumeration counter.
338                 if (needEnumCounterReset(it))
339                         counters.reset(enumcounter);
340
341                 counters.step(enumcounter);
342
343                 string format;
344
345                 switch (par.itemdepth) {
346                 case 0:
347                         format = N_("\\arabic{enumi}.");
348                         break;
349                 case 1:
350                         format = N_("(\\alph{enumii})");
351                         break;
352                 case 2:
353                         format = N_("\\roman{enumiii}.");
354                         break;
355                 case 3:
356                         format = N_("\\Alph{enumiv}.");
357                         break;
358                 default:
359                         // not a valid enumdepth...
360                         break;
361                 }
362
363                 par.params().labelString(counters.counterLabel(
364                         par.translateIfPossible(from_ascii(format), buf.params())));
365
366                 break;
367         }
368
369         case LABEL_SENSITIVE: {
370                 string const & type = counters.current_float();
371                 docstring full_label;
372                 if (type.empty())
373                         full_label = buf.B_("Senseless!!! ");
374                 else {
375                         docstring name = buf.B_(textclass.floats().getType(type).name());
376                         if (counters.hasCounter(from_utf8(type))) {
377                                 counters.step(from_utf8(type));
378                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
379                                                      name, 
380                                                      counters.theCounter(from_utf8(type)));
381                         } else
382                                 full_label = bformat(from_ascii("%1$s #:"), name);      
383                 }
384                 par.params().labelString(full_label);   
385                 break;
386         }
387
388         case LABEL_NO_LABEL:
389                 par.params().labelString(docstring());
390                 break;
391
392         case LABEL_MANUAL:
393         case LABEL_TOP_ENVIRONMENT:
394         case LABEL_CENTERED_TOP_ENVIRONMENT:
395         case LABEL_STATIC:      
396         case LABEL_BIBLIO:
397                 par.params().labelString(
398                         par.translateIfPossible(layout->labelstring(), 
399                                                 buf.params()));
400                 break;
401         }
402 }
403
404 } // anon namespace
405
406 void updateLabels(Buffer const & buf, ParIterator & parit)
407 {
408         BOOST_ASSERT(parit.pit() == 0);
409
410         depth_type maxdepth = 0;
411         pit_type const lastpit = parit.lastpit();
412         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
413                 // reduce depth if necessary
414                 parit->params().depth(min(parit->params().depth(), maxdepth));
415                 maxdepth = parit->getMaxDepthAfter();
416
417                 // set the counter for this paragraph
418                 setLabel(buf, parit);
419
420                 // Now the insets
421                 InsetList::const_iterator iit = parit->insetList().begin();
422                 InsetList::const_iterator end = parit->insetList().end();
423                 for (; iit != end; ++iit) {
424                         parit.pos() = iit->pos;
425                         iit->inset->updateLabels(buf, parit);
426                 }
427         }
428         
429 }
430
431
432 // FIXME: buf should should be const because updateLabels() modifies
433 // the contents of the paragraphs.
434 void updateLabels(Buffer const & buf, bool childonly)
435 {
436         Buffer const * const master = buf.masterBuffer();
437         // Use the master text class also for child documents
438         TextClass const & textclass = master->params().getTextClass();
439
440         if (!childonly) {
441                 // If this is a child document start with the master
442                 if (master != &buf) {
443                         updateLabels(*master);
444                         return;
445                 }
446
447                 // start over the counters
448                 textclass.counters().reset();
449         }
450
451         Buffer & cbuf = const_cast<Buffer &>(buf);
452
453         if (buf.text().empty()) {
454                 // FIXME: we don't call continue with updateLabels()
455                 // here because it crashes on newly created documents.
456                 // But the TocBackend needs to be initialised
457                 // nonetheless so we update the tocBackend manually.
458                 cbuf.tocBackend().update();
459                 return;
460         }
461
462         // do the real work
463         ParIterator parit = par_iterator_begin(buf.inset());
464         updateLabels(buf, parit);
465
466         cbuf.tocBackend().update();
467         if (!childonly)
468                 cbuf.structureChanged();
469 }
470
471
472 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
473 {
474         if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
475                 Buffer * master = buffer.masterBuffer();
476                 master->tocBackend().updateItem(par_it);
477                 master->structureChanged();
478         }
479 }
480
481
482 } // namespace lyx