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