]> git.lyx.org Git - lyx.git/blob - src/buffer.C
More Alert/ error message fixes
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
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  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14 #include "bufferlist.h"
15 #include "LyXAction.h"
16 #include "lyxrc.h"
17 #include "lyxlex.h"
18 #include "tex-strings.h"
19 #include "layout.h"
20 #include "bufferview_funcs.h"
21 #include "lyxfont.h"
22 #include "version.h"
23 #include "LaTeX.h"
24 #include "Chktex.h"
25 #include "debug.h"
26 #include "LaTeXFeatures.h"
27 #include "lyxtext.h"
28 #include "gettext.h"
29 #include "language.h"
30 #include "exporter.h"
31 #include "Lsstream.h"
32 #include "format.h"
33 #include "BufferView.h"
34 #include "ParagraphParameters.h"
35 #include "iterators.h"
36 #include "lyxtextclasslist.h"
37 #include "sgml.h"
38 #include "paragraph_funcs.h"
39 #include "author.h"
40
41 #include "frontends/LyXView.h"
42
43 #include "mathed/formulamacro.h"
44 #include "mathed/formula.h"
45
46 #include "insets/inseterror.h"
47 #include "insets/insetbibitem.h"
48 #include "insets/insetbibtex.h"
49 #include "insets/insetinclude.h"
50 #include "insets/insettext.h"
51
52 #include "frontends/Dialogs.h"
53 #include "frontends/Alert.h"
54
55 #include "graphics/Previews.h"
56
57 #include "support/textutils.h"
58 #include "support/filetools.h"
59 #include "support/path.h"
60 #include "support/os.h"
61 #include "support/lyxlib.h"
62 #include "support/FileInfo.h"
63 #include "support/lyxmanip.h"
64 #include "support/lyxtime.h"
65
66 #include <boost/bind.hpp>
67 #include <boost/tuple/tuple.hpp>
68 #include "BoostFormat.h"
69
70 #include <fstream>
71 #include <iomanip>
72 #include <map>
73 #include <stack>
74 #include <list>
75 #include <algorithm>
76
77 #include <cstdlib>
78 #include <cmath>
79 #include <unistd.h>
80 #include <sys/types.h>
81 #include <utime.h>
82
83 #ifdef HAVE_LOCALE
84 #include <locale>
85 #endif
86
87 #ifndef CXX_GLOBAL_CSTD
88 using std::pow;
89 #endif
90
91 using std::ostream;
92 using std::ofstream;
93 using std::ifstream;
94 using std::fstream;
95 using std::ios;
96 using std::setw;
97 using std::endl;
98 using std::pair;
99 using std::make_pair;
100 using std::vector;
101 using std::map;
102 using std::stack;
103 using std::list;
104 using std::for_each;
105
106 using lyx::pos_type;
107 using lyx::textclass_type;
108
109 // all these externs should eventually be removed.
110 extern BufferList bufferlist;
111
112 namespace {
113
114 const int LYX_FORMAT = 223;
115
116 } // namespace anon
117
118 Buffer::Buffer(string const & file, bool ronly)
119         : niceFile(true), lyx_clean(true), bak_clean(true),
120           unnamed(false), read_only(ronly),
121           filename_(file), users(0)
122 {
123         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
124         filepath_ = OnlyPath(file);
125         lyxvc.buffer(this);
126         if (read_only || lyxrc.use_tempdir) {
127                 tmppath = CreateBufferTmpDir();
128         } else {
129                 tmppath.erase();
130         }
131
132         // set initial author
133         authors().record(Author(lyxrc.user_name, lyxrc.user_email));
134 }
135
136
137 Buffer::~Buffer()
138 {
139         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
140         // here the buffer should take care that it is
141         // saved properly, before it goes into the void.
142
143         // make sure that views using this buffer
144         // forgets it.
145         if (users)
146                 users->buffer(0);
147
148         if (!tmppath.empty() && destroyDir(tmppath) != 0) {
149 #if USE_BOOST_FORMAT
150                 boost::format fmt = _("Could not remove the temporary directory %1$s");
151                 fmt % tmppath;
152                 string msg = fmt.str();
153 #else
154                 string msg = _("Could not remove the temporary directory ") + tmppath;
155 #endif
156                 Alert::warning(_("Could not remove temporary directory"), msg);
157         }
158
159         paragraphs.clear();
160
161         // Remove any previewed LaTeX snippets assocoated with this buffer.
162         grfx::Previews::get().removeLoader(this);
163 }
164
165
166 string const Buffer::getLatexName(bool no_path) const
167 {
168         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
169         if (no_path)
170                 return OnlyFilename(name);
171         else
172                 return name;
173 }
174
175
176 pair<Buffer::LogType, string> const Buffer::getLogName() const
177 {
178         string const filename = getLatexName(false);
179
180         if (filename.empty())
181                 return make_pair(Buffer::latexlog, string());
182
183         string path = OnlyPath(filename);
184
185         if (lyxrc.use_tempdir || !IsDirWriteable(path))
186                 path = tmppath;
187
188         string const fname = AddName(path,
189                                      OnlyFilename(ChangeExtension(filename,
190                                                                   ".log")));
191         string const bname =
192                 AddName(path, OnlyFilename(
193                         ChangeExtension(filename,
194                                         formats.extension("literate") + ".out")));
195
196         // If no Latex log or Build log is newer, show Build log
197
198         FileInfo const f_fi(fname);
199         FileInfo const b_fi(bname);
200
201         if (b_fi.exist() &&
202             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
203                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
204                 return make_pair(Buffer::buildlog, bname);
205         }
206         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
207         return make_pair(Buffer::latexlog, fname);
208 }
209
210
211 void Buffer::setReadonly(bool flag)
212 {
213         if (read_only != flag) {
214                 read_only = flag;
215                 updateTitles();
216                 users->owner()->getDialogs().updateBufferDependent(false);
217         }
218 }
219
220
221 AuthorList & Buffer::authors()
222 {
223         return params.authorlist;
224 }
225
226
227 /// Update window titles of all users
228 // Should work on a list
229 void Buffer::updateTitles() const
230 {
231         if (users)
232                 users->owner()->updateWindowTitle();
233 }
234
235
236 /// Reset autosave timer of all users
237 // Should work on a list
238 void Buffer::resetAutosaveTimers() const
239 {
240         if (users)
241                 users->owner()->resetAutosaveTimer();
242 }
243
244
245 void Buffer::setFileName(string const & newfile)
246 {
247         filename_ = MakeAbsPath(newfile);
248         filepath_ = OnlyPath(filename_);
249         setReadonly(IsFileWriteable(filename_) == 0);
250         updateTitles();
251 }
252
253
254 // We'll remove this later. (Lgb)
255 namespace {
256
257 void unknownClass(string const & unknown)
258 {
259         string msg =
260 #if USE_BOOST_FORMAT
261                 boost::io::str(boost::format(
262                         _("Using the default document class, because the "
263                         " class %1$s is unknown.")) % unknown);
264 #else
265                 _("Using the default document class, because the "
266                 " class ") + unknown + (" is unknown."); 
267 #endif
268         Alert::warning(_("Unknown document class"), msg);
269 }
270
271 } // anon
272
273 int Buffer::readHeader(LyXLex & lex)
274 {
275         int unknown_tokens = 0;
276
277         while (lex.isOK()) {
278                 lex.nextToken();
279                 string const token = lex.getString();
280
281                 if (token.empty())
282                         continue;
283
284                 if (token == "\\end_header")
285                         break;
286
287                 lyxerr[Debug::PARSER] << "Handling header token: `"
288                                       << token << '\'' << endl;
289
290                 string unknown = params.readToken(lex, token);
291                 if (!unknown.empty()) {
292                         if (unknown[0] != '\\') {
293                                 unknownClass(unknown);
294                         } else {
295                                 ++unknown_tokens;
296                         }
297                 }
298         }
299         return unknown_tokens;
300 }
301
302
303 // candidate for move to BufferView
304 // (at least some parts in the beginning of the func)
305 //
306 // Uwe C. Schroeder
307 // changed to be public and have one parameter
308 // if par = 0 normal behavior
309 // else insert behavior
310 // Returns false if "\the_end" is not read (Asger)
311 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
312 {
313         int unknown_tokens = 0;
314
315         Paragraph::depth_type depth = 0;
316         bool the_end_read = false;
317
318         if (paragraphs.empty()) {
319                 unknown_tokens += readHeader(lex);
320
321                 if (!params.getLyXTextClass().load()) {
322                         string theclass = params.getLyXTextClass().name();
323                         string msg =
324 #if USE_BOOST_FORMAT
325                                 boost::io::str(boost::format(
326                                         _("Using the default document class, because the "
327                                         " class %1$s could not be loaded.")) % theclass);
328 #else
329                                 _("Using the default document class, because the "
330                                 " class ") + theclass + (" could not be loaded.");
331 #endif
332                         Alert::error(_("Can't load document class"), msg);
333                         params.textclass = 0;
334                 }
335         } else {
336                 // We are inserting into an existing document
337                 users->text->breakParagraph(paragraphs);
338
339                 // We don't want to adopt the parameters from the
340                 // document we insert, so read them into a temporary buffer
341                 // and then discard it
342
343                 Buffer tmpbuf("", false);
344                 tmpbuf.readHeader(lex);
345         }
346
347         while (lex.isOK()) {
348                 lex.nextToken();
349                 string const token = lex.getString();
350
351                 if (token.empty())
352                         continue;
353
354                 lyxerr[Debug::PARSER] << "Handling token: `"
355                                       << token << '\'' << endl;
356
357                 if (token == "\\the_end") {
358                         the_end_read = true;
359                         continue;
360                 }
361
362                 unknown_tokens += readParagraph(lex, token, paragraphs, pit, depth);
363         }
364
365
366         if (unknown_tokens > 0) {
367 #if USE_BOOST_FORMAT
368                 string s;
369                 if (unknown_tokens == 1) {
370                         boost::format fmt(_("Encountered one unknown token when reading the document %1$s."));
371                         fmt % fileName();
372                         s = fmt.str();
373                 } else {
374                         boost::format fmt(_("Encountered %1$s unknown tokens when reading the document %2$s."));
375                         fmt % tostr(unknown_tokens);
376                         fmt % fileName();
377                         s = fmt.str();
378                 }
379 #else
380                 string s = _("Encountered ");
381                 if (unknown_tokens == 1) {
382                         s += _("one unknown token");
383                 } else {
384                         s += tostr(unknown_tokens);
385                         s += _(" unknown tokens");
386                 }
387                 Alert::warning(_("Document format failure"), s);
388 #endif
389         }
390
391         return the_end_read;
392 }
393
394
395 int
396 Buffer::readParagraph(LyXLex & lex, string const & token,
397                       ParagraphList & pars, ParagraphList::iterator & pit,
398                       Paragraph::depth_type & depth)
399 {
400         static Change current_change;
401         int unknown = 0;
402
403         if (token == "\\layout") {
404                 lex.pushToken(token);
405
406                 Paragraph * par = new Paragraph();
407                 par->params().depth(depth);
408                 if (params.tracking_changes)
409                         par->trackChanges();
410                 LyXFont f(LyXFont::ALL_INHERIT, params.language);
411                 par->setFont(0, f);
412
413                 // FIXME: goddamn InsetTabular makes us pass a Buffer
414                 // not BufferParams
415                 unknown += ::readParagraph(*this, *par, lex);
416
417                 // insert after
418                 if (pit != pars.end())
419                         ++pit;
420                 pit = pars.insert(pit, par);
421         } else if (token == "\\begin_deeper") {
422                 ++depth;
423         } else if (token == "\\end_deeper") {
424                 if (!depth) {
425                         lex.printError("\\end_deeper: " "depth is already null");
426                 } else {
427                         --depth;
428                 }
429         } else {
430                 ++unknown;
431         }
432         return unknown;
433 }
434
435
436 // needed to insert the selection
437 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
438                                  LyXFont const & fn,string const & str)
439 {
440         LyXLayout_ptr const & layout = par->layout();
441
442         LyXFont font = fn;
443
444         par->checkInsertChar(font);
445         // insert the string, don't insert doublespace
446         bool space_inserted = true;
447         bool autobreakrows = !par->inInset() ||
448                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
449         for(string::const_iterator cit = str.begin();
450             cit != str.end(); ++cit) {
451                 if (*cit == '\n') {
452                         if (autobreakrows && (!par->empty() || layout->keepempty)) {
453                                 breakParagraph(params, paragraphs, par, pos,
454                                                layout->isEnvironment());
455                                 par = par->next();
456                                 pos = 0;
457                                 space_inserted = true;
458                         } else {
459                                 continue;
460                         }
461                         // do not insert consecutive spaces if !free_spacing
462                 } else if ((*cit == ' ' || *cit == '\t') &&
463                            space_inserted && !layout->free_spacing &&
464                                    !par->isFreeSpacing())
465                 {
466                         continue;
467                 } else if (*cit == '\t') {
468                         if (!layout->free_spacing && !par->isFreeSpacing()) {
469                                 // tabs are like spaces here
470                                 par->insertChar(pos, ' ', font);
471                                 ++pos;
472                                 space_inserted = true;
473                         } else {
474                                 const pos_type nb = 8 - pos % 8;
475                                 for (pos_type a = 0; a < nb ; ++a) {
476                                         par->insertChar(pos, ' ', font);
477                                         ++pos;
478                                 }
479                                 space_inserted = true;
480                         }
481                 } else if (!IsPrintable(*cit)) {
482                         // Ignore unprintables
483                         continue;
484                 } else {
485                         // just insert the character
486                         par->insertChar(pos, *cit, font);
487                         ++pos;
488                         space_inserted = (*cit == ' ');
489                 }
490
491         }
492 }
493
494
495 bool Buffer::readFile(LyXLex & lex, string const & filename)
496 {
497         return readFile(lex, filename, paragraphs.begin());
498 }
499
500
501 // FIXME: all the below Alerts should give the filename..
502 bool Buffer::readFile(LyXLex & lex, string const & filename, ParagraphList::iterator pit)
503 {
504         if (!lex.isOK()) {
505                 Alert::error(_("Document could not be read"),
506                         _("The specified document could not be read."));
507                 return false;
508         }
509
510         lex.next();
511         string const token(lex.getString());
512
513         if (!lex.isOK()) {
514                 Alert::error(_("Document could not be read"),
515                         _("The specified document could not be read."));
516                 return false;
517         }
518
519         // the first token _must_ be...
520         if (token != "\\lyxformat") {
521                 Alert::error(_("Document format failure"),
522                         _("The specified document is not a LyX document."));
523                 return false;
524         }
525
526         lex.eatLine();
527         string tmp_format = lex.getString();
528         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
529         // if present remove ".," from string.
530         string::size_type dot = tmp_format.find_first_of(".,");
531         //lyxerr << "           dot found at " << dot << endl;
532         if (dot != string::npos)
533                         tmp_format.erase(dot, 1);
534         file_format = strToInt(tmp_format);
535         //lyxerr << "format: " << file_format << endl;
536         if (file_format == LYX_FORMAT) {
537                 // current format
538         } else if (file_format > LYX_FORMAT) {
539                 Alert::warning(_("Document format failure"),
540                         _("This document was created with a newer version of "
541                         "LyX. This is likely to cause problems."));
542         } else if (file_format < LYX_FORMAT) {
543                 // old formats
544                 if (file_format < 200) {
545                         Alert::error(_("Document format failure"),
546                                 _("This LyX document is too old to be read "
547                                 "by this version of LyX. Try LyX 0.10."));
548                         return false;
549                 } else if (!filename.empty()) {
550                         string command =
551                                 LibFileSearch("lyx2lyx", "lyx2lyx");
552                         if (command.empty()) {
553                                 Alert::error(_("Conversion script not found"),
554                                         _("The document is from an earlier version "
555                                           "of LyX, but the conversion script lyx2lyx "
556                                           "could not be found."));
557                                 return false;
558                         }
559                         command += " -t"
560                                 +tostr(LYX_FORMAT) + ' '
561                                 + QuoteName(filename);
562                         lyxerr[Debug::INFO] << "Running '"
563                                             << command << '\''
564                                             << endl;
565                         cmd_ret const ret = RunCommand(command);
566                         if (ret.first) {
567                                 Alert::error(_("Conversion script failed"),
568                                         _("The document is from an earlier version "
569                                           "of LyX, but the lyx2lyx script failed "
570                                           "to convert it."));
571                                 return false;
572                         }
573                         istringstream is(STRCONV(ret.second));
574                         LyXLex tmplex(0, 0);
575                         tmplex.setStream(is);
576                         return readFile(tmplex, string(), pit);
577                 } else {
578                         // This code is reached if lyx2lyx failed (for
579                         // some reason) to change the file format of
580                         // the file.
581                         lyx::Assert(false);
582                         return false;
583                 }
584         }
585         bool the_end = readBody(lex, pit);
586         params.setPaperStuff();
587
588         if (!the_end) {
589                 Alert::error(_("Document format failure"),
590                         _("The document ended unexpectedly, which means "
591                           "that it is probably corrupted."));
592         }
593         return true;
594 }
595
596
597 // Should probably be moved to somewhere else: BufferView? LyXView?
598 bool Buffer::save() const
599 {
600         // We don't need autosaves in the immediate future. (Asger)
601         resetAutosaveTimers();
602
603         // make a backup
604         string s;
605         if (lyxrc.make_backup) {
606                 s = fileName() + '~';
607                 if (!lyxrc.backupdir_path.empty())
608                         s = AddName(lyxrc.backupdir_path,
609                                     subst(os::slashify_path(s),'/','!'));
610
611                 // Rename is the wrong way of making a backup,
612                 // this is the correct way.
613                 /* truss cp fil fil2:
614                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
615                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
616                    open("LyXVC.lyx", O_RDONLY)                     = 3
617                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
618                    fstat(4, 0xEFFFF508)                            = 0
619                    fstat(3, 0xEFFFF508)                            = 0
620                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
621                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
622                    read(3, 0xEFFFD4A0, 8192)                       = 0
623                    close(4)                                        = 0
624                    close(3)                                        = 0
625                    chmod("LyXVC3.lyx", 0100644)                    = 0
626                    lseek(0, 0, SEEK_CUR)                           = 46440
627                    _exit(0)
628                 */
629
630                 // Should probably have some more error checking here.
631                 // Doing it this way, also makes the inodes stay the same.
632                 // This is still not a very good solution, in particular we
633                 // might loose the owner of the backup.
634                 FileInfo finfo(fileName());
635                 if (finfo.exist()) {
636                         mode_t fmode = finfo.getMode();
637                         struct utimbuf times = {
638                                 finfo.getAccessTime(),
639                                 finfo.getModificationTime() };
640
641                         ifstream ifs(fileName().c_str());
642                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
643                         if (ifs && ofs) {
644                                 ofs << ifs.rdbuf();
645                                 ifs.close();
646                                 ofs.close();
647                                 ::chmod(s.c_str(), fmode);
648
649                                 if (::utime(s.c_str(), &times)) {
650                                         lyxerr << "utime error." << endl;
651                                 }
652                         } else {
653                                 lyxerr << "LyX was not able to make "
654                                         "backup copy. Beware." << endl;
655                         }
656                 }
657         }
658
659         if (writeFile(fileName())) {
660                 markClean();
661                 removeAutosaveFile(fileName());
662         } else {
663                 // Saving failed, so backup is not backup
664                 if (lyxrc.make_backup) {
665                         lyx::rename(s, fileName());
666                 }
667                 return false;
668         }
669         return true;
670 }
671
672
673 bool Buffer::writeFile(string const & fname) const
674 {
675         if (read_only && (fname == fileName())) {
676                 return false;
677         }
678
679         FileInfo finfo(fname);
680         if (finfo.exist() && !finfo.writable()) {
681                 return false;
682         }
683
684         ofstream ofs(fname.c_str());
685         if (!ofs) {
686                 return false;
687         }
688
689 #ifdef HAVE_LOCALE
690         // Use the standard "C" locale for file output.
691         ofs.imbue(std::locale::classic());
692 #endif
693
694         // The top of the file should not be written by params.
695
696         // write out a comment in the top of the file
697         ofs << '#' << lyx_docversion
698             << " created this file. For more info see http://www.lyx.org/\n"
699             << "\\lyxformat " << LYX_FORMAT << "\n";
700
701         // now write out the buffer paramters.
702         params.writeFile(ofs);
703
704         ofs << "\\end_header\n";
705
706         Paragraph::depth_type depth = 0;
707
708         // this will write out all the paragraphs
709         // using recursive descent.
710         ParagraphList::iterator pit = paragraphs.begin();
711         ParagraphList::iterator pend = paragraphs.end();
712         for (; pit != pend; ++pit)
713                 pit->write(this, ofs, params, depth);
714
715         // Write marker that shows file is complete
716         ofs << "\n\\the_end" << endl;
717
718         ofs.close();
719
720         // how to check if close went ok?
721         // Following is an attempt... (BE 20001011)
722
723         // good() returns false if any error occured, including some
724         //        formatting error.
725         // bad()  returns true if something bad happened in the buffer,
726         //        which should include file system full errors.
727
728         bool status = true;
729         if (!ofs.good()) {
730                 status = false;
731 #if 0
732                 if (ofs.bad()) {
733                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
734                 } else {
735                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
736                                << endl;
737                 }
738 #endif
739         }
740
741         return status;
742 }
743
744
745 namespace {
746
747 pair<int, string> const addDepth(int depth, int ldepth)
748 {
749         int d = depth * 2;
750         if (ldepth > depth)
751                 d += (ldepth - depth) * 2;
752         return make_pair(d, string(d, ' '));
753 }
754
755 }
756
757
758 string const Buffer::asciiParagraph(Paragraph const & par,
759                                     unsigned int linelen,
760                                     bool noparbreak) const
761 {
762         ostringstream buffer;
763         Paragraph::depth_type depth = 0;
764         int ltype = 0;
765         Paragraph::depth_type ltype_depth = 0;
766         bool ref_printed = false;
767 //      if (!par->previous()) {
768 #if 0
769         // begins or ends a deeper area ?
770         if (depth != par->params().depth()) {
771                 if (par->params().depth() > depth) {
772                         while (par->params().depth() > depth) {
773                                 ++depth;
774                         }
775                 } else {
776                         while (par->params().depth() < depth) {
777                                 --depth;
778                         }
779                 }
780         }
781 #else
782         depth = par.params().depth();
783 #endif
784
785         // First write the layout
786         string const & tmp = par.layout()->name();
787         if (compare_no_case(tmp, "itemize") == 0) {
788                 ltype = 1;
789                 ltype_depth = depth + 1;
790         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
791                 ltype = 2;
792                 ltype_depth = depth + 1;
793         } else if (contains(ascii_lowercase(tmp), "ection")) {
794                 ltype = 3;
795                 ltype_depth = depth + 1;
796         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
797                 ltype = 4;
798                 ltype_depth = depth + 1;
799         } else if (compare_ascii_no_case(tmp, "description") == 0) {
800                 ltype = 5;
801                 ltype_depth = depth + 1;
802         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
803                 ltype = 6;
804                 ltype_depth = 0;
805         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
806                 ltype = 7;
807                 ltype_depth = 0;
808         } else {
809                 ltype = 0;
810                 ltype_depth = 0;
811         }
812
813         /* maybe some vertical spaces */
814
815         /* the labelwidthstring used in lists */
816
817         /* some lines? */
818
819         /* some pagebreaks? */
820
821         /* noindent ? */
822
823         /* what about the alignment */
824
825         // linelen <= 0 is special and means we don't have paragraph breaks
826
827         string::size_type currlinelen = 0;
828
829         if (!noparbreak) {
830                 if (linelen > 0)
831                         buffer << "\n\n";
832
833                 buffer << string(depth * 2, ' ');
834                 currlinelen += depth * 2;
835
836                 //--
837                 // we should probably change to the paragraph language in the
838                 // gettext here (if possible) so that strings are outputted in
839                 // the correct language! (20012712 Jug)
840                 //--
841                 switch (ltype) {
842                 case 0: // Standard
843                 case 4: // (Sub)Paragraph
844                 case 5: // Description
845                         break;
846                 case 6: // Abstract
847                         if (linelen > 0) {
848                                 buffer << _("Abstract") << "\n\n";
849                                 currlinelen = 0;
850                         } else {
851                                 string const abst = _("Abstract: ");
852                                 buffer << abst;
853                                 currlinelen += abst.length();
854                         }
855                         break;
856                 case 7: // Bibliography
857                         if (!ref_printed) {
858                                 if (linelen > 0) {
859                                         buffer << _("References") << "\n\n";
860                                         currlinelen = 0;
861                                 } else {
862                                         string const refs = _("References: ");
863                                         buffer << refs;
864                                         currlinelen += refs.length();
865                                 }
866
867                                 ref_printed = true;
868                         }
869                         break;
870                 default:
871                 {
872                         string const parlab = par.params().labelString();
873                         buffer << parlab << ' ';
874                         currlinelen += parlab.length() + 1;
875                 }
876                 break;
877
878                 }
879         }
880
881         if (!currlinelen) {
882                 pair<int, string> p = addDepth(depth, ltype_depth);
883                 buffer << p.second;
884                 currlinelen += p.first;
885         }
886
887         // this is to change the linebreak to do it by word a bit more
888         // intelligent hopefully! (only in the case where we have a
889         // max linelength!) (Jug)
890
891         string word;
892
893         for (pos_type i = 0; i < par.size(); ++i) {
894                 char c = par.getUChar(params, i);
895                 switch (c) {
896                 case Paragraph::META_INSET:
897                 {
898                         Inset const * inset = par.getInset(i);
899                         if (inset) {
900                                 if (linelen > 0) {
901                                         buffer << word;
902                                         currlinelen += word.length();
903                                         word.erase();
904                                 }
905                                 if (inset->ascii(this, buffer, linelen)) {
906                                         // to be sure it breaks paragraph
907                                         currlinelen += linelen;
908                                 }
909                         }
910                 }
911                 break;
912
913                 default:
914                         if (c == ' ') {
915                                 if (linelen > 0 &&
916                                     currlinelen + word.length() > linelen - 10) {
917                                         buffer << "\n";
918                                         pair<int, string> p = addDepth(depth, ltype_depth);
919                                         buffer << p.second;
920                                         currlinelen = p.first;
921                                 }
922
923                                 buffer << word << ' ';
924                                 currlinelen += word.length() + 1;
925                                 word.erase();
926
927                         } else {
928                                 if (c != '\0') {
929                                         word += c;
930                                 } else {
931                                         lyxerr[Debug::INFO] <<
932                                                 "writeAsciiFile: NULL char in structure." << endl;
933                                 }
934                                 if ((linelen > 0) &&
935                                         (currlinelen + word.length()) > linelen)
936                                 {
937                                         buffer << "\n";
938
939                                         pair<int, string> p =
940                                                 addDepth(depth, ltype_depth);
941                                         buffer << p.second;
942                                         currlinelen = p.first;
943                                 }
944                         }
945                         break;
946                 }
947         }
948         buffer << word;
949         return STRCONV(buffer.str());
950 }
951
952
953 void Buffer::writeFileAscii(string const & fname, int linelen)
954 {
955         ofstream ofs(fname.c_str());
956         if (!ofs) {
957                 string const error = strerror(errno);
958                 string const file = MakeDisplayPath(fname, 50);
959 #if USE_BOOST_FORMAT
960                 boost::format fmt(_("Could not save the document\n%1$s\ndue to the error: %2$s"));
961                 fmt % file;
962                 fmt % error;
963                 string text = fmt.str();
964 #else
965                 string text = _("Could not save the document\n");
966                 text += file + _(" due to the error: ");
967                 text += error;
968 #endif
969                 Alert::error(_("Could not save document"), text);
970                 return;
971         }
972         writeFileAscii(ofs, linelen);
973 }
974
975
976 void Buffer::writeFileAscii(ostream & os, int linelen)
977 {
978         ParagraphList::iterator beg = paragraphs.begin();
979         ParagraphList::iterator end = paragraphs.end();
980         ParagraphList::iterator it = beg;
981         for (; it != end; ++it) {
982                 os << asciiParagraph(*it, linelen, it == beg);
983         }
984         os << "\n";
985 }
986
987
988
989 void Buffer::makeLaTeXFile(string const & fname,
990                            string const & original_path,
991                            bool nice, bool only_body, bool only_preamble)
992 {
993         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
994
995         ofstream ofs(fname.c_str());
996         if (!ofs) {
997                 string const error = strerror(errno);
998                 string const file = MakeDisplayPath(fname, 50);
999 #if USE_BOOST_FORMAT
1000                 boost::format fmt(_("Could not open the specified document\n%1$s\ndue to the error: %2$s"));
1001                 fmt % file;
1002                 fmt % error;
1003                 string text = fmt.str();
1004 #else
1005                 string text = _("Could not open the specified document\n");
1006                 text += file + _(" due to the error: ");
1007                 text += error;
1008 #endif
1009                 Alert::error(_("Could not open file"), text);
1010                 return;
1011         }
1012
1013         makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1014
1015         ofs.close();
1016         if (ofs.fail()) {
1017                 lyxerr << "File was not closed properly." << endl;
1018         }
1019 }
1020
1021
1022 void Buffer::makeLaTeXFile(ostream & os,
1023                            string const & original_path,
1024                            bool nice, bool only_body, bool only_preamble)
1025 {
1026         niceFile = nice; // this will be used by Insetincludes.
1027
1028         // validate the buffer.
1029         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1030         LaTeXFeatures features(params);
1031         validate(features);
1032         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1033
1034         texrow.reset();
1035         // The starting paragraph of the coming rows is the
1036         // first paragraph of the document. (Asger)
1037         texrow.start(&*(paragraphs.begin()), 0);
1038
1039         if (!only_body && nice) {
1040                 os << "%% " << lyx_docversion << " created this file.  "
1041                         "For more info, see http://www.lyx.org/.\n"
1042                         "%% Do not edit unless you really know what "
1043                         "you are doing.\n";
1044                 texrow.newline();
1045                 texrow.newline();
1046         }
1047         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1048         // There are a few differences between nice LaTeX and usual files:
1049         // usual is \batchmode and has a
1050         // special input@path to allow the including of figures
1051         // with either \input or \includegraphics (what figinsets do).
1052         // input@path is set when the actual parameter
1053         // original_path is set. This is done for usual tex-file, but not
1054         // for nice-latex-file. (Matthias 250696)
1055         if (!only_body) {
1056                 if (!nice) {
1057                         // code for usual, NOT nice-latex-file
1058                         os << "\\batchmode\n"; // changed
1059                         // from \nonstopmode
1060                         texrow.newline();
1061                 }
1062                 if (!original_path.empty()) {
1063                         string inputpath = os::external_path(original_path);
1064                         subst(inputpath, "~", "\\string~");
1065                         os << "\\makeatletter\n"
1066                             << "\\def\\input@path{{"
1067                             << inputpath << "/}}\n"
1068                             << "\\makeatother\n";
1069                         texrow.newline();
1070                         texrow.newline();
1071                         texrow.newline();
1072                 }
1073
1074                 // Write the preamble
1075                 params.writeLaTeX(os, features, texrow);
1076
1077                 if (only_preamble)
1078                         return;
1079
1080                 // make the body.
1081                 os << "\\begin{document}\n";
1082                 texrow.newline();
1083         } // only_body
1084         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1085
1086         if (!lyxrc.language_auto_begin) {
1087                 os << subst(lyxrc.language_command_begin, "$$lang",
1088                              params.language->babel())
1089                     << endl;
1090                 texrow.newline();
1091         }
1092
1093         latexParagraphs(this, paragraphs, paragraphs.begin(), paragraphs.end(), os, texrow);
1094
1095         // add this just in case after all the paragraphs
1096         os << endl;
1097         texrow.newline();
1098
1099         if (!lyxrc.language_auto_end) {
1100                 os << subst(lyxrc.language_command_end, "$$lang",
1101                              params.language->babel())
1102                     << endl;
1103                 texrow.newline();
1104         }
1105
1106         if (!only_body) {
1107                 os << "\\end{document}\n";
1108                 texrow.newline();
1109
1110                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1111         } else {
1112                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1113                                      << endl;
1114         }
1115
1116         // Just to be sure. (Asger)
1117         texrow.newline();
1118
1119         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1120         lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1121                             << '.' << endl;
1122
1123         // we want this to be true outside previews (for insetexternal)
1124         niceFile = true;
1125 }
1126
1127
1128 bool Buffer::isLatex() const
1129 {
1130         return params.getLyXTextClass().outputType() == LATEX;
1131 }
1132
1133
1134 bool Buffer::isLinuxDoc() const
1135 {
1136         return params.getLyXTextClass().outputType() == LINUXDOC;
1137 }
1138
1139
1140 bool Buffer::isLiterate() const
1141 {
1142         return params.getLyXTextClass().outputType() == LITERATE;
1143 }
1144
1145
1146 bool Buffer::isDocBook() const
1147 {
1148         return params.getLyXTextClass().outputType() == DOCBOOK;
1149 }
1150
1151
1152 bool Buffer::isSGML() const
1153 {
1154         LyXTextClass const & tclass = params.getLyXTextClass();
1155
1156         return tclass.outputType() == LINUXDOC ||
1157                tclass.outputType() == DOCBOOK;
1158 }
1159
1160
1161 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1162 {
1163         ofstream ofs(fname.c_str());
1164
1165         if (!ofs) {
1166                 string const file = MakeDisplayPath(fname, 50);
1167 #if USE_BOOST_FORMAT
1168                 boost::format fmt(_("Could not save the specified document\n%1$s.\n"));
1169                 fmt % file;
1170                 string text = fmt.str();
1171 #else
1172                 string text = _("Could not save the specified document\n");
1173                 text += file + _(".\n");
1174 #endif
1175                 Alert::error(_("Could not save document"), text);
1176                 return;
1177         }
1178
1179         niceFile = nice; // this will be used by included files.
1180
1181         LaTeXFeatures features(params);
1182
1183         validate(features);
1184
1185         texrow.reset();
1186
1187         LyXTextClass const & tclass = params.getLyXTextClass();
1188
1189         string top_element = tclass.latexname();
1190
1191         if (!body_only) {
1192                 ofs << "<!doctype linuxdoc system";
1193
1194                 string preamble = params.preamble;
1195                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1196                          : fname;
1197                 preamble += features.getIncludedFiles(name);
1198                 preamble += features.getLyXSGMLEntities();
1199
1200                 if (!preamble.empty()) {
1201                         ofs << " [ " << preamble << " ]";
1202                 }
1203                 ofs << ">\n\n";
1204
1205                 if (params.options.empty())
1206                         sgml::openTag(ofs, 0, false, top_element);
1207                 else {
1208                         string top = top_element;
1209                         top += ' ';
1210                         top += params.options;
1211                         sgml::openTag(ofs, 0, false, top);
1212                 }
1213         }
1214
1215         ofs << "<!-- "  << lyx_docversion
1216             << " created this file. For more info see http://www.lyx.org/"
1217             << " -->\n";
1218
1219         Paragraph::depth_type depth = 0; // paragraph depth
1220         Paragraph * par = &*(paragraphs.begin());
1221         string item_name;
1222         vector<string> environment_stack(5);
1223
1224         while (par) {
1225                 LyXLayout_ptr const & style = par->layout();
1226                 // treat <toc> as a special case for compatibility with old code
1227                 if (par->isInset(0)) {
1228                         Inset * inset = par->getInset(0);
1229                         Inset::Code lyx_code = inset->lyxCode();
1230                         if (lyx_code == Inset::TOC_CODE) {
1231                                 string const temp = "toc";
1232                                 sgml::openTag(ofs, depth, false, temp);
1233
1234                                 par = par->next();
1235                                 continue;
1236                         }
1237                 }
1238
1239                 // environment tag closing
1240                 for (; depth > par->params().depth(); --depth) {
1241                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1242                         environment_stack[depth].erase();
1243                 }
1244
1245                 // write opening SGML tags
1246                 switch (style->latextype) {
1247                 case LATEX_PARAGRAPH:
1248                         if (depth == par->params().depth()
1249                            && !environment_stack[depth].empty()) {
1250                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1251                                 environment_stack[depth].erase();
1252                                 if (depth)
1253                                         --depth;
1254                                 else
1255                                         ofs << "</p>";
1256                         }
1257                         sgml::openTag(ofs, depth, false, style->latexname());
1258                         break;
1259
1260                 case LATEX_COMMAND:
1261                         if (depth!= 0)
1262                                 sgmlError(par, 0,
1263                                           _("Error: Wrong depth for LatexType Command.\n"));
1264
1265                         if (!environment_stack[depth].empty()) {
1266                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1267                                 ofs << "</p>";
1268                         }
1269
1270                         environment_stack[depth].erase();
1271                         sgml::openTag(ofs, depth, false, style->latexname());
1272                         break;
1273
1274                 case LATEX_ENVIRONMENT:
1275                 case LATEX_ITEM_ENVIRONMENT:
1276                 case LATEX_BIB_ENVIRONMENT:
1277                 {
1278                         string const & latexname = style->latexname();
1279
1280                         if (depth == par->params().depth()
1281                             && environment_stack[depth] != latexname) {
1282                                 sgml::closeTag(ofs, depth, false,
1283                                              environment_stack[depth]);
1284                                 environment_stack[depth].erase();
1285                         }
1286                         if (depth < par->params().depth()) {
1287                                depth = par->params().depth();
1288                                environment_stack[depth].erase();
1289                         }
1290                         if (environment_stack[depth] != latexname) {
1291                                 if (depth == 0) {
1292                                         sgml::openTag(ofs, depth, false, "p");
1293                                 }
1294                                 sgml::openTag(ofs, depth, false, latexname);
1295
1296                                 if (environment_stack.size() == depth + 1)
1297                                         environment_stack.push_back("!-- --");
1298                                 environment_stack[depth] = latexname;
1299                         }
1300
1301                         if (style->latexparam() == "CDATA")
1302                                 ofs << "<![CDATA[";
1303
1304                         if (style->latextype == LATEX_ENVIRONMENT) break;
1305
1306                         if (style->labeltype == LABEL_MANUAL)
1307                                 item_name = "tag";
1308                         else
1309                                 item_name = "item";
1310
1311                         sgml::openTag(ofs, depth + 1, false, item_name);
1312                 }
1313                 break;
1314
1315                 default:
1316                         sgml::openTag(ofs, depth, false, style->latexname());
1317                         break;
1318                 }
1319
1320                 simpleLinuxDocOnePar(ofs, par, depth);
1321
1322                 par = par->next();
1323
1324                 ofs << "\n";
1325                 // write closing SGML tags
1326                 switch (style->latextype) {
1327                 case LATEX_COMMAND:
1328                         break;
1329                 case LATEX_ENVIRONMENT:
1330                 case LATEX_ITEM_ENVIRONMENT:
1331                 case LATEX_BIB_ENVIRONMENT:
1332                         if (style->latexparam() == "CDATA")
1333                                 ofs << "]]>";
1334                         break;
1335                 default:
1336                         sgml::closeTag(ofs, depth, false, style->latexname());
1337                         break;
1338                 }
1339         }
1340
1341         // Close open tags
1342         for (int i = depth; i >= 0; --i)
1343                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1344
1345         if (!body_only) {
1346                 ofs << "\n\n";
1347                 sgml::closeTag(ofs, 0, false, top_element);
1348         }
1349
1350         ofs.close();
1351         // How to check for successful close
1352
1353         // we want this to be true outside previews (for insetexternal)
1354         niceFile = true;
1355 }
1356
1357
1358 // checks, if newcol chars should be put into this line
1359 // writes newline, if necessary.
1360 namespace {
1361
1362 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1363                           string::size_type newcol)
1364 {
1365         colcount += newcol;
1366         if (colcount > lyxrc.ascii_linelen) {
1367                 os << "\n";
1368                 colcount = newcol; // assume write after this call
1369         }
1370 }
1371
1372 enum PAR_TAG {
1373         NONE=0,
1374         TT = 1,
1375         SF = 2,
1376         BF = 4,
1377         IT = 8,
1378         SL = 16,
1379         EM = 32
1380 };
1381
1382
1383 string tag_name(PAR_TAG const & pt) {
1384         switch (pt) {
1385         case NONE: return "!-- --";
1386         case TT: return "tt";
1387         case SF: return "sf";
1388         case BF: return "bf";
1389         case IT: return "it";
1390         case SL: return "sl";
1391         case EM: return "em";
1392         }
1393         return "";
1394 }
1395
1396
1397 inline
1398 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1399 {
1400         p1 = static_cast<PAR_TAG>(p1 | p2);
1401 }
1402
1403
1404 inline
1405 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1406 {
1407         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1408 }
1409
1410 } // anon
1411
1412
1413 // Handle internal paragraph parsing -- layout already processed.
1414 void Buffer::simpleLinuxDocOnePar(ostream & os,
1415         Paragraph * par,
1416         Paragraph::depth_type /*depth*/)
1417 {
1418         LyXLayout_ptr const & style = par->layout();
1419
1420         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1421
1422         // gets paragraph main font
1423         LyXFont font_old;
1424         bool desc_on;
1425         if (style->labeltype == LABEL_MANUAL) {
1426                 font_old = style->labelfont;
1427                 desc_on = true;
1428         } else {
1429                 font_old = style->font;
1430                 desc_on = false;
1431         }
1432
1433         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1434         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1435         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1436         bool is_em = false;
1437
1438         stack<PAR_TAG> tag_state;
1439         // parsing main loop
1440         for (pos_type i = 0; i < par->size(); ++i) {
1441
1442                 PAR_TAG tag_close = NONE;
1443                 list < PAR_TAG > tag_open;
1444
1445                 LyXFont const font = par->getFont(params, i);
1446
1447                 if (font_old.family() != font.family()) {
1448                         switch (family_type) {
1449                         case LyXFont::SANS_FAMILY:
1450                                 tag_close |= SF;
1451                                 break;
1452                         case LyXFont::TYPEWRITER_FAMILY:
1453                                 tag_close |= TT;
1454                                 break;
1455                         default:
1456                                 break;
1457                         }
1458
1459                         family_type = font.family();
1460
1461                         switch (family_type) {
1462                         case LyXFont::SANS_FAMILY:
1463                                 tag_open.push_back(SF);
1464                                 break;
1465                         case LyXFont::TYPEWRITER_FAMILY:
1466                                 tag_open.push_back(TT);
1467                                 break;
1468                         default:
1469                                 break;
1470                         }
1471                 }
1472
1473                 if (font_old.series() != font.series()) {
1474                         switch (series_type) {
1475                         case LyXFont::BOLD_SERIES:
1476                                 tag_close |= BF;
1477                                 break;
1478                         default:
1479                                 break;
1480                         }
1481
1482                         series_type = font.series();
1483
1484                         switch (series_type) {
1485                         case LyXFont::BOLD_SERIES:
1486                                 tag_open.push_back(BF);
1487                                 break;
1488                         default:
1489                                 break;
1490                         }
1491
1492                 }
1493
1494                 if (font_old.shape() != font.shape()) {
1495                         switch (shape_type) {
1496                         case LyXFont::ITALIC_SHAPE:
1497                                 tag_close |= IT;
1498                                 break;
1499                         case LyXFont::SLANTED_SHAPE:
1500                                 tag_close |= SL;
1501                                 break;
1502                         default:
1503                                 break;
1504                         }
1505
1506                         shape_type = font.shape();
1507
1508                         switch (shape_type) {
1509                         case LyXFont::ITALIC_SHAPE:
1510                                 tag_open.push_back(IT);
1511                                 break;
1512                         case LyXFont::SLANTED_SHAPE:
1513                                 tag_open.push_back(SL);
1514                                 break;
1515                         default:
1516                                 break;
1517                         }
1518                 }
1519                 // handle <em> tag
1520                 if (font_old.emph() != font.emph()) {
1521                         if (font.emph() == LyXFont::ON) {
1522                                 tag_open.push_back(EM);
1523                                 is_em = true;
1524                         }
1525                         else if (is_em) {
1526                                 tag_close |= EM;
1527                                 is_em = false;
1528                         }
1529                 }
1530
1531                 list < PAR_TAG > temp;
1532                 while (!tag_state.empty() && tag_close) {
1533                         PAR_TAG k =  tag_state.top();
1534                         tag_state.pop();
1535                         os << "</" << tag_name(k) << '>';
1536                         if (tag_close & k)
1537                                 reset(tag_close,k);
1538                         else
1539                                 temp.push_back(k);
1540                 }
1541
1542                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1543                     j != temp.end(); ++j) {
1544                         tag_state.push(*j);
1545                         os << '<' << tag_name(*j) << '>';
1546                 }
1547
1548                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1549                     j != tag_open.end(); ++j) {
1550                         tag_state.push(*j);
1551                         os << '<' << tag_name(*j) << '>';
1552                 }
1553
1554                 char c = par->getChar(i);
1555
1556                 if (c == Paragraph::META_INSET) {
1557                         Inset * inset = par->getInset(i);
1558                         inset->linuxdoc(this, os);
1559                         font_old = font;
1560                         continue;
1561                 }
1562
1563                 if (style->latexparam() == "CDATA") {
1564                         // "TeX"-Mode on == > SGML-Mode on.
1565                         if (c != '\0')
1566                                 os << c;
1567                         ++char_line_count;
1568                 } else {
1569                         bool ws;
1570                         string str;
1571                         boost::tie(ws, str) = sgml::escapeChar(c);
1572                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
1573                                 // in freespacing mode, spaces are
1574                                 // non-breaking characters
1575                                 if (desc_on) {// if char is ' ' then...
1576
1577                                         ++char_line_count;
1578                                         sgmlLineBreak(os, char_line_count, 6);
1579                                         os << "</tag>";
1580                                         desc_on = false;
1581                                 } else  {
1582                                         sgmlLineBreak(os, char_line_count, 1);
1583                                         os << c;
1584                                 }
1585                         } else {
1586                                 os << str;
1587                                 char_line_count += str.length();
1588                         }
1589                 }
1590                 font_old = font;
1591         }
1592
1593         while (!tag_state.empty()) {
1594                 os << "</" << tag_name(tag_state.top()) << '>';
1595                 tag_state.pop();
1596         }
1597
1598         // resets description flag correctly
1599         if (desc_on) {
1600                 // <tag> not closed...
1601                 sgmlLineBreak(os, char_line_count, 6);
1602                 os << "</tag>";
1603         }
1604 }
1605
1606
1607 // Print an error message.
1608 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
1609         string const & /*message*/) const
1610 {
1611 #ifdef WITH_WARNINGS
1612 #warning This is wrong we cannot insert an inset like this!!!
1613         // I guess this was Jose' so I explain you more or less why this
1614         // is wrong. This way you insert something in the paragraph and
1615         // don't tell it to LyXText (row rebreaking and undo handling!!!)
1616         // I deactivate this code, have a look at BufferView::insertErrors
1617         // how you should do this correctly! (Jug 20020315)
1618 #endif
1619 #if 0
1620         // insert an error marker in text
1621         InsetError * new_inset = new InsetError(message);
1622         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1623                          params.language));
1624 #endif
1625 }
1626
1627
1628 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1629 {
1630         ofstream ofs(fname.c_str());
1631         if (!ofs) {
1632                 string const file = MakeDisplayPath(fname, 50);
1633 #if USE_BOOST_FORMAT
1634                 boost::format fmt(_("Could not save the specified document\n%1$s.\n"));
1635                 fmt % file;
1636                 string text = fmt.str();
1637 #else
1638                 string text = _("Could not save the specified document\n");
1639                 text += file + _(".\n");
1640 #endif
1641                 Alert::error(_("Could not save document"), text);
1642                 return;
1643                 return;
1644         }
1645
1646         Paragraph * par = &*(paragraphs.begin());
1647
1648         niceFile = nice; // this will be used by Insetincludes.
1649
1650         LaTeXFeatures features(params);
1651         validate(features);
1652
1653         texrow.reset();
1654
1655         LyXTextClass const & tclass = params.getLyXTextClass();
1656         string top_element = tclass.latexname();
1657
1658         if (!only_body) {
1659                 ofs << "<!DOCTYPE " << top_element
1660                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1661
1662                 string preamble = params.preamble;
1663                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1664                          : fname;
1665                 preamble += features.getIncludedFiles(name);
1666                 preamble += features.getLyXSGMLEntities();
1667
1668                 if (!preamble.empty()) {
1669                         ofs << "\n [ " << preamble << " ]";
1670                 }
1671                 ofs << ">\n\n";
1672         }
1673
1674         string top = top_element;
1675         top += " lang=\"";
1676         top += params.language->code();
1677         top += '"';
1678
1679         if (!params.options.empty()) {
1680                 top += ' ';
1681                 top += params.options;
1682         }
1683         sgml::openTag(ofs, 0, false, top);
1684
1685         ofs << "<!-- DocBook file was created by " << lyx_docversion
1686             << "\n  See http://www.lyx.org/ for more information -->\n";
1687
1688         vector<string> environment_stack(10);
1689         vector<string> environment_inner(10);
1690         vector<string> command_stack(10);
1691
1692         bool command_flag = false;
1693         Paragraph::depth_type command_depth = 0;
1694         Paragraph::depth_type command_base = 0;
1695         Paragraph::depth_type cmd_depth = 0;
1696         Paragraph::depth_type depth = 0; // paragraph depth
1697
1698         string item_name;
1699         string command_name;
1700
1701         while (par) {
1702                 string sgmlparam;
1703                 string c_depth;
1704                 string c_params;
1705                 int desc_on = 0; // description mode
1706
1707                 LyXLayout_ptr const & style = par->layout();
1708
1709                 // environment tag closing
1710                 for (; depth > par->params().depth(); --depth) {
1711                         if (environment_inner[depth] != "!-- --") {
1712                                 item_name = "listitem";
1713                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1714                                 if (environment_inner[depth] == "varlistentry")
1715                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
1716                         }
1717                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1718                         environment_stack[depth].erase();
1719                         environment_inner[depth].erase();
1720                 }
1721
1722                 if (depth == par->params().depth()
1723                    && environment_stack[depth] != style->latexname()
1724                    && !environment_stack[depth].empty()) {
1725                         if (environment_inner[depth] != "!-- --") {
1726                                 item_name= "listitem";
1727                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
1728                                 if (environment_inner[depth] == "varlistentry")
1729                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1730                         }
1731
1732                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1733
1734                         environment_stack[depth].erase();
1735                         environment_inner[depth].erase();
1736                 }
1737
1738                 // Write opening SGML tags.
1739                 switch (style->latextype) {
1740                 case LATEX_PARAGRAPH:
1741                         sgml::openTag(ofs, depth + command_depth,
1742                                     false, style->latexname());
1743                         break;
1744
1745                 case LATEX_COMMAND:
1746                         if (depth != 0)
1747                                 sgmlError(par, 0,
1748                                           _("Error: Wrong depth for LatexType Command.\n"));
1749
1750                         command_name = style->latexname();
1751
1752                         sgmlparam = style->latexparam();
1753                         c_params = split(sgmlparam, c_depth,'|');
1754
1755                         cmd_depth = lyx::atoi(c_depth);
1756
1757                         if (command_flag) {
1758                                 if (cmd_depth < command_base) {
1759                                         for (Paragraph::depth_type j = command_depth;
1760                                              j >= command_base; --j) {
1761                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1762                                                 ofs << endl;
1763                                         }
1764                                         command_depth = command_base = cmd_depth;
1765                                 } else if (cmd_depth <= command_depth) {
1766                                         for (int j = command_depth;
1767                                              j >= int(cmd_depth); --j) {
1768                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1769                                                 ofs << endl;
1770                                         }
1771                                         command_depth = cmd_depth;
1772                                 } else
1773                                         command_depth = cmd_depth;
1774                         } else {
1775                                 command_depth = command_base = cmd_depth;
1776                                 command_flag = true;
1777                         }
1778                         if (command_stack.size() == command_depth + 1)
1779                                 command_stack.push_back(string());
1780                         command_stack[command_depth] = command_name;
1781
1782                         // treat label as a special case for
1783                         // more WYSIWYM handling.
1784                         // This is a hack while paragraphs can't have
1785                         // attributes, like id in this case.
1786                         if (par->isInset(0)) {
1787                                 Inset * inset = par->getInset(0);
1788                                 Inset::Code lyx_code = inset->lyxCode();
1789                                 if (lyx_code == Inset::LABEL_CODE) {
1790                                         command_name += " id=\"";
1791                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
1792                                         command_name += '"';
1793                                         desc_on = 3;
1794                                 }
1795                         }
1796
1797                         sgml::openTag(ofs, depth + command_depth, false, command_name);
1798
1799                         item_name = c_params.empty() ? "title" : c_params;
1800                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
1801                         break;
1802
1803                 case LATEX_ENVIRONMENT:
1804                 case LATEX_ITEM_ENVIRONMENT:
1805                         if (depth < par->params().depth()) {
1806                                 depth = par->params().depth();
1807                                 environment_stack[depth].erase();
1808                         }
1809
1810                         if (environment_stack[depth] != style->latexname()) {
1811                                 if (environment_stack.size() == depth + 1) {
1812                                         environment_stack.push_back("!-- --");
1813                                         environment_inner.push_back("!-- --");
1814                                 }
1815                                 environment_stack[depth] = style->latexname();
1816                                 environment_inner[depth] = "!-- --";
1817                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
1818                         } else {
1819                                 if (environment_inner[depth] != "!-- --") {
1820                                         item_name= "listitem";
1821                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
1822                                         if (environment_inner[depth] == "varlistentry")
1823                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1824                                 }
1825                         }
1826
1827                         if (style->latextype == LATEX_ENVIRONMENT) {
1828                                 if (!style->latexparam().empty()) {
1829                                         if (style->latexparam() == "CDATA")
1830                                                 ofs << "<![CDATA[";
1831                                         else
1832                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
1833                                 }
1834                                 break;
1835                         }
1836
1837                         desc_on = (style->labeltype == LABEL_MANUAL);
1838
1839                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1840                         sgml::openTag(ofs, depth + 1 + command_depth,
1841                                     false, environment_inner[depth]);
1842
1843                         item_name = desc_on ? "term" : "para";
1844                         sgml::openTag(ofs, depth + 1 + command_depth,
1845                                     false, item_name);
1846                         break;
1847                 default:
1848                         sgml::openTag(ofs, depth + command_depth,
1849                                     false, style->latexname());
1850                         break;
1851                 }
1852
1853                 simpleDocBookOnePar(ofs, par, desc_on,
1854                                     depth + 1 + command_depth);
1855                 par = par->next();
1856
1857                 string end_tag;
1858                 // write closing SGML tags
1859                 switch (style->latextype) {
1860                 case LATEX_COMMAND:
1861                         end_tag = c_params.empty() ? "title" : c_params;
1862                         sgml::closeTag(ofs, depth + command_depth,
1863                                      false, end_tag);
1864                         break;
1865                 case LATEX_ENVIRONMENT:
1866                         if (!style->latexparam().empty()) {
1867                                 if (style->latexparam() == "CDATA")
1868                                         ofs << "]]>";
1869                                 else
1870                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
1871                         }
1872                         break;
1873                 case LATEX_ITEM_ENVIRONMENT:
1874                         if (desc_on == 1) break;
1875                         end_tag = "para";
1876                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
1877                         break;
1878                 case LATEX_PARAGRAPH:
1879                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1880                         break;
1881                 default:
1882                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1883                         break;
1884                 }
1885         }
1886
1887         // Close open tags
1888         for (int d = depth; d >= 0; --d) {
1889                 if (!environment_stack[depth].empty()) {
1890                         if (environment_inner[depth] != "!-- --") {
1891                                 item_name = "listitem";
1892                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1893                                if (environment_inner[depth] == "varlistentry")
1894                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1895                         }
1896
1897                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1898                 }
1899         }
1900
1901         for (int j = command_depth; j >= 0 ; --j)
1902                 if (!command_stack[j].empty()) {
1903                         sgml::closeTag(ofs, j, false, command_stack[j]);
1904                         ofs << endl;
1905                 }
1906
1907         ofs << "\n\n";
1908         sgml::closeTag(ofs, 0, false, top_element);
1909
1910         ofs.close();
1911         // How to check for successful close
1912
1913         // we want this to be true outside previews (for insetexternal)
1914         niceFile = true;
1915 }
1916
1917
1918 void Buffer::simpleDocBookOnePar(ostream & os,
1919                                  Paragraph * par, int & desc_on,
1920                                  Paragraph::depth_type depth) const
1921 {
1922         bool emph_flag = false;
1923
1924         LyXLayout_ptr const & style = par->layout();
1925
1926         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
1927
1928         int char_line_count = depth;
1929         //if (!style.free_spacing)
1930         //      os << string(depth,' ');
1931
1932         // parsing main loop
1933         for (pos_type i = 0; i < par->size(); ++i) {
1934                 LyXFont font = par->getFont(params, i);
1935
1936                 // handle <emphasis> tag
1937                 if (font_old.emph() != font.emph()) {
1938                         if (font.emph() == LyXFont::ON) {
1939                                 if (style->latexparam() == "CDATA")
1940                                         os << "]]>";
1941                                 os << "<emphasis>";
1942                                 if (style->latexparam() == "CDATA")
1943                                         os << "<![CDATA[";
1944                                 emph_flag = true;
1945                         } else if (i) {
1946                                 if (style->latexparam() == "CDATA")
1947                                         os << "]]>";
1948                                 os << "</emphasis>";
1949                                 if (style->latexparam() == "CDATA")
1950                                         os << "<![CDATA[";
1951                                 emph_flag = false;
1952                         }
1953                 }
1954
1955
1956                 if (par->isInset(i)) {
1957                         Inset * inset = par->getInset(i);
1958                         // don't print the inset in position 0 if desc_on == 3 (label)
1959                         if (i || desc_on != 3) {
1960                                 if (style->latexparam() == "CDATA")
1961                                         os << "]]>";
1962                                 inset->docbook(this, os, false);
1963                                 if (style->latexparam() == "CDATA")
1964                                         os << "<![CDATA[";
1965                         }
1966                 } else {
1967                         char c = par->getChar(i);
1968                         bool ws;
1969                         string str;
1970                         boost::tie(ws, str) = sgml::escapeChar(c);
1971
1972                         if (style->pass_thru) {
1973                                 os << c;
1974                         } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
1975                                         os << str;
1976                         } else if (desc_on ==1) {
1977                                 ++char_line_count;
1978                                 os << "\n</term><listitem><para>";
1979                                 desc_on = 2;
1980                         } else {
1981                                 os << ' ';
1982                         }
1983                 }
1984                 font_old = font;
1985         }
1986
1987         if (emph_flag) {
1988                 if (style->latexparam() == "CDATA")
1989                         os << "]]>";
1990                 os << "</emphasis>";
1991                 if (style->latexparam() == "CDATA")
1992                         os << "<![CDATA[";
1993         }
1994
1995         // resets description flag correctly
1996         if (desc_on == 1) {
1997                 // <term> not closed...
1998                 os << "</term>\n<listitem><para>&nbsp;</para>";
1999         }
2000         if (style->free_spacing)
2001                 os << '\n';
2002 }
2003
2004
2005 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2006 // Other flags: -wall -v0 -x
2007 int Buffer::runChktex()
2008 {
2009         if (!users->text) return 0;
2010
2011         users->owner()->busy(true);
2012
2013         // get LaTeX-Filename
2014         string const name = getLatexName();
2015         string path = filePath();
2016
2017         string const org_path = path;
2018         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
2019                 path = tmppath;
2020         }
2021
2022         Path p(path); // path to LaTeX file
2023         users->owner()->message(_("Running chktex..."));
2024
2025         // Remove all error insets
2026         bool const removedErrorInsets = users->removeAutoInsets();
2027
2028         // Generate the LaTeX file if neccessary
2029         makeLaTeXFile(name, org_path, false);
2030
2031         TeXErrors terr;
2032         Chktex chktex(lyxrc.chktex_command, name, filePath());
2033         int res = chktex.run(terr); // run chktex
2034
2035         if (res == -1) {
2036                 Alert::error(_("chktex failure"),
2037                         _("Could not run chktex successfully."));
2038         } else if (res > 0) {
2039                 // Insert all errors as errors boxes
2040                 users->insertErrors(terr);
2041         }
2042
2043         // if we removed error insets before we ran chktex or if we inserted
2044         // error insets after we ran chktex, this must be run:
2045         if (removedErrorInsets || res) {
2046 #warning repaint needed here, or do you mean update() ?
2047                 users->repaint();
2048                 users->fitCursor();
2049         }
2050         users->owner()->busy(false);
2051
2052         return res;
2053 }
2054
2055
2056 void Buffer::validate(LaTeXFeatures & features) const
2057 {
2058         LyXTextClass const & tclass = params.getLyXTextClass();
2059
2060         if (params.tracking_changes) {
2061                 features.require("dvipost");
2062                 features.require("color");
2063         }
2064
2065         // AMS Style is at document level
2066         if (params.use_amsmath == BufferParams::AMS_ON
2067             || tclass.provides(LyXTextClass::amsmath))
2068                 features.require("amsmath");
2069
2070         for_each(paragraphs.begin(), paragraphs.end(),
2071                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2072
2073         // the bullet shapes are buffer level not paragraph level
2074         // so they are tested here
2075         for (int i = 0; i < 4; ++i) {
2076                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2077                         int const font = params.user_defined_bullets[i].getFont();
2078                         if (font == 0) {
2079                                 int const c = params
2080                                         .user_defined_bullets[i]
2081                                         .getCharacter();
2082                                 if (c == 16
2083                                    || c == 17
2084                                    || c == 25
2085                                    || c == 26
2086                                    || c == 31) {
2087                                         features.require("latexsym");
2088                                 }
2089                         } else if (font == 1) {
2090                                 features.require("amssymb");
2091                         } else if ((font >= 2 && font <= 5)) {
2092                                 features.require("pifont");
2093                         }
2094                 }
2095         }
2096
2097         if (lyxerr.debugging(Debug::LATEX)) {
2098                 features.showStruct();
2099         }
2100 }
2101
2102
2103 vector<string> const Buffer::getLabelList() const
2104 {
2105         /// if this is a child document and the parent is already loaded
2106         /// Use the parent's list instead  [ale990407]
2107         if (!params.parentname.empty()
2108             && bufferlist.exists(params.parentname)) {
2109                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2110                 if (tmp)
2111                         return tmp->getLabelList();
2112         }
2113
2114         vector<string> label_list;
2115         for (inset_iterator it = inset_const_iterator_begin();
2116              it != inset_const_iterator_end(); ++it) {
2117                 vector<string> const l = it->getLabelList();
2118                 label_list.insert(label_list.end(), l.begin(), l.end());
2119         }
2120         return label_list;
2121 }
2122
2123
2124 // This is also a buffer property (ale)
2125 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2126 {
2127         /// if this is a child document and the parent is already loaded
2128         /// use the parent's list instead  [ale990412]
2129         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2130                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2131                 if (tmp) {
2132                         tmp->fillWithBibKeys(keys);
2133                         return;
2134                 }
2135         }
2136
2137         for (inset_iterator it = inset_const_iterator_begin();
2138                 it != inset_const_iterator_end(); ++it) {
2139                 if (it->lyxCode() == Inset::BIBTEX_CODE)
2140                         static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2141                 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2142                         static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2143                 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2144                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2145                         string const key = bib.getContents();
2146                         string const opt = bib.getOptions();
2147                         string const ref; // = pit->asString(this, false);
2148                         string const info = opt + "TheBibliographyRef" + ref;
2149                         keys.push_back(pair<string, string>(key, info));
2150                 }
2151         }
2152 }
2153
2154
2155 bool Buffer::isDepClean(string const & name) const
2156 {
2157         DepClean::const_iterator it = dep_clean_.find(name);
2158         if (it == dep_clean_.end())
2159                 return true;
2160         return it->second;
2161 }
2162
2163
2164 void Buffer::markDepClean(string const & name)
2165 {
2166         dep_clean_[name] = true;
2167 }
2168
2169
2170 bool Buffer::dispatch(string const & command, bool * result)
2171 {
2172         // Split command string into command and argument
2173         string cmd;
2174         string line = ltrim(command);
2175         string const arg = trim(split(line, cmd, ' '));
2176
2177         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2178 }
2179
2180
2181 bool Buffer::dispatch(int action, string const & argument, bool * result)
2182 {
2183         bool dispatched = true;
2184
2185         switch (action) {
2186                 case LFUN_EXPORT: {
2187                         bool const tmp = Exporter::Export(this, argument, false);
2188                         if (result)
2189                                 *result = tmp;
2190                         break;
2191                 }
2192
2193                 default:
2194                         dispatched = false;
2195         }
2196         return dispatched;
2197 }
2198
2199
2200 void Buffer::resizeInsets(BufferView * bv)
2201 {
2202         /// then remove all LyXText in text-insets
2203         for_each(paragraphs.begin(), paragraphs.end(),
2204                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2205 }
2206
2207
2208 void Buffer::redraw()
2209 {
2210 #warning repaint needed here, or do you mean update() ?
2211         users->repaint();
2212         users->fitCursor();
2213 }
2214
2215
2216 void Buffer::changeLanguage(Language const * from, Language const * to)
2217 {
2218
2219         ParIterator end = par_iterator_end();
2220         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2221                 (*it)->changeLanguage(params, from, to);
2222 }
2223
2224
2225 bool Buffer::isMultiLingual()
2226 {
2227         ParIterator end = par_iterator_end();
2228         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2229                 if ((*it)->isMultiLingual(params))
2230                         return true;
2231
2232         return false;
2233 }
2234
2235
2236 void Buffer::inset_iterator::setParagraph()
2237 {
2238         while (pit != pend) {
2239                 it = pit->insetlist.begin();
2240                 if (it != pit->insetlist.end())
2241                         return;
2242                 ++pit;
2243         }
2244 }
2245
2246
2247 Inset * Buffer::getInsetFromID(int id_arg) const
2248 {
2249         for (inset_iterator it = inset_const_iterator_begin();
2250                  it != inset_const_iterator_end(); ++it)
2251         {
2252                 if (it->id() == id_arg)
2253                         return &(*it);
2254                 Inset * in = it->getInsetFromID(id_arg);
2255                 if (in)
2256                         return in;
2257         }
2258         return 0;
2259 }
2260
2261
2262 Paragraph * Buffer::getParFromID(int id) const
2263 {
2264         if (id < 0)
2265                 return 0;
2266
2267         // why should we allow < 0 ??
2268         //lyx::Assert(id >= 0);
2269
2270         ParConstIterator it(par_iterator_begin());
2271         ParConstIterator end(par_iterator_end());
2272
2273         for (; it != end; ++it) {
2274                 // go on then, show me how to remove
2275                 // the cast
2276                 if ((*it)->id() == id) {
2277                         return const_cast<Paragraph*>(*it);
2278                 }
2279         }
2280
2281         return 0;
2282 }
2283
2284
2285 ParIterator Buffer::par_iterator_begin()
2286 {
2287         return ParIterator(&*(paragraphs.begin()));
2288 }
2289
2290
2291 ParIterator Buffer::par_iterator_end()
2292 {
2293         return ParIterator();
2294 }
2295
2296 ParConstIterator Buffer::par_iterator_begin() const
2297 {
2298         return ParConstIterator(&*(paragraphs.begin()));
2299 }
2300
2301
2302 ParConstIterator Buffer::par_iterator_end() const
2303 {
2304         return ParConstIterator();
2305 }
2306
2307
2308
2309 void Buffer::addUser(BufferView * u)
2310 {
2311         users = u;
2312 }
2313
2314
2315 void Buffer::delUser(BufferView *)
2316 {
2317         users = 0;
2318 }
2319
2320
2321 Language const * Buffer::getLanguage() const
2322 {
2323         return params.language;
2324 }
2325
2326
2327 bool Buffer::isClean() const
2328 {
2329         return lyx_clean;
2330 }
2331
2332
2333 bool Buffer::isBakClean() const
2334 {
2335         return bak_clean;
2336 }
2337
2338
2339 void Buffer::markClean() const
2340 {
2341         if (!lyx_clean) {
2342                 lyx_clean = true;
2343                 updateTitles();
2344         }
2345         // if the .lyx file has been saved, we don't need an
2346         // autosave
2347         bak_clean = true;
2348 }
2349
2350
2351 void Buffer::markBakClean()
2352 {
2353         bak_clean = true;
2354 }
2355
2356
2357 void Buffer::setUnnamed(bool flag)
2358 {
2359         unnamed = flag;
2360 }
2361
2362
2363 bool Buffer::isUnnamed()
2364 {
2365         return unnamed;
2366 }
2367
2368
2369 void Buffer::markDirty()
2370 {
2371         if (lyx_clean) {
2372                 lyx_clean = false;
2373                 updateTitles();
2374         }
2375         bak_clean = false;
2376
2377         DepClean::iterator it = dep_clean_.begin();
2378         DepClean::const_iterator const end = dep_clean_.end();
2379
2380         for (; it != end; ++it) {
2381                 it->second = false;
2382         }
2383 }
2384
2385
2386 string const & Buffer::fileName() const
2387 {
2388         return filename_;
2389 }
2390
2391
2392 string const & Buffer::filePath() const
2393 {
2394         return filepath_;
2395 }
2396
2397
2398 bool Buffer::isReadonly() const
2399 {
2400         return read_only;
2401 }
2402
2403
2404 BufferView * Buffer::getUser() const
2405 {
2406         return users;
2407 }
2408
2409
2410 void Buffer::setParentName(string const & name)
2411 {
2412         params.parentname = name;
2413 }
2414
2415
2416 Buffer::inset_iterator::inset_iterator()
2417         : pit(0), pend(0)
2418 {}
2419
2420
2421 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2422         : pit(p), pend(e)
2423 {
2424         setParagraph();
2425 }
2426
2427
2428 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2429 {
2430         if (pit != pend) {
2431                 ++it;
2432                 if (it == pit->insetlist.end()) {
2433                         ++pit;
2434                         setParagraph();
2435                 }
2436         }
2437         return *this;
2438 }
2439
2440
2441 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2442 {
2443         inset_iterator tmp = *this;
2444         ++*this;
2445         return tmp;
2446 }
2447
2448
2449 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2450 {
2451         return *it.getInset();
2452 }
2453
2454
2455 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2456 {
2457         return it.getInset();
2458 }
2459
2460
2461 Paragraph * Buffer::inset_iterator::getPar()
2462 {
2463         return &(*pit);
2464 }
2465
2466
2467 lyx::pos_type Buffer::inset_iterator::getPos() const
2468 {
2469         return it.getPos();
2470 }
2471
2472
2473 bool operator==(Buffer::inset_iterator const & iter1,
2474                 Buffer::inset_iterator const & iter2)
2475 {
2476         return iter1.pit == iter2.pit
2477                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2478 }
2479
2480
2481 bool operator!=(Buffer::inset_iterator const & iter1,
2482                 Buffer::inset_iterator const & iter2)
2483 {
2484         return !(iter1 == iter2);
2485 }