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