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