]> git.lyx.org Git - lyx.git/blob - src/buffer.C
a84ca170f605256f1aa585943bcc7d00fa09a342
[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 "counters.h"
20 #include "Bullet.h"
21 #include "Chktex.h"
22 #include "debug.h"
23 #include "errorlist.h"
24 #include "exporter.h"
25 #include "format.h"
26 #include "funcrequest.h"
27 #include "gettext.h"
28 #include "iterators.h"
29 #include "language.h"
30 #include "LaTeX.h"
31 #include "LaTeXFeatures.h"
32 #include "LyXAction.h"
33 #include "lyxlex.h"
34 #include "lyxtext.h"
35 #include "lyxrc.h"
36 #include "lyxvc.h"
37 #include "lyx_main.h"
38 #include "messages.h"
39 #include "output.h"
40 #include "output_docbook.h"
41 #include "output_latex.h"
42 #include "output_linuxdoc.h"
43 #include "paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "sgml.h"
47 #include "texrow.h"
48 #include "undo.h"
49 #include "version.h"
50
51 #include "insets/insetbibitem.h"
52 #include "insets/insetbibtex.h"
53 #include "insets/insetinclude.h"
54 #include "insets/insettext.h"
55
56 #include "frontends/Alert.h"
57
58 #include "graphics/Previews.h"
59
60 #include "support/FileInfo.h"
61 #include "support/filetools.h"
62 #include "support/gzstream.h"
63 #include "support/lyxlib.h"
64 #include "support/os.h"
65 #include "support/path.h"
66 #include "support/textutils.h"
67 #include "support/tostr.h"
68
69 #include <boost/bind.hpp>
70
71 #include "support/std_sstream.h"
72
73 #include <iomanip>
74 #include <stack>
75
76 #include <utime.h>
77
78 using lyx::pos_type;
79 using lyx::par_type;
80
81 using lyx::support::AddName;
82 using lyx::support::atoi;
83 using lyx::support::bformat;
84 using lyx::support::ChangeExtension;
85 using lyx::support::cmd_ret;
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::ios;
119 using std::ostream;
120 using std::ostringstream;
121 using std::ofstream;
122 using std::pair;
123 using std::stack;
124 using std::vector;
125 using std::string;
126
127
128 // all these externs should eventually be removed.
129 extern BufferList bufferlist;
130
131 namespace {
132
133 const int LYX_FORMAT = 230;
134
135 } // namespace anon
136
137
138 typedef std::map<string, bool> DepClean;
139
140 struct Buffer::Impl
141 {
142         Impl(Buffer & parent, string const & file, bool readonly);
143
144         limited_stack<Undo> undostack;
145         limited_stack<Undo> redostack;
146         BufferParams params;
147         LyXVC lyxvc;
148         string temppath;
149         TexRow texrow;
150
151         /// need to regenerate .tex?
152         DepClean dep_clean;
153
154         /// is save needed?
155         mutable bool lyx_clean;
156
157         /// is autosave needed?
158         mutable bool bak_clean;
159
160         /// is this a unnamed file (New...)?
161         bool unnamed;
162
163         /// buffer is r/o
164         bool read_only;
165
166         /// name of the file the buffer is associated with.
167         string filename;
168
169         /// The path to the document file.
170         string filepath;
171
172         boost::scoped_ptr<Messages> messages;
173
174         /** Set to true only when the file is fully loaded.
175          *  Used to prevent the premature generation of previews
176          *  and by the citation inset.
177          */
178         bool file_fully_loaded;
179
180         /// our LyXText that should be wrapped in an InsetText
181         InsetText inset;
182 };
183
184
185 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
186         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
187           filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
188                 inset(params)
189 {
190         lyxvc.buffer(&parent);
191         temppath = createBufferTmpDir();
192         // FIXME: And now do something if temppath == string(), because we
193         // assume from now on that temppath points to a valid temp dir.
194         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
195 }
196
197
198 Buffer::Buffer(string const & file, bool ronly)
199         : pimpl_(new Impl(*this, file, ronly))
200 {
201         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
202 }
203
204
205 Buffer::~Buffer()
206 {
207         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
208         // here the buffer should take care that it is
209         // saved properly, before it goes into the void.
210
211         closing();
212
213         if (!temppath().empty() && destroyDir(temppath()) != 0) {
214                 Alert::warning(_("Could not remove temporary directory"),
215                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
216         }
217
218         // Remove any previewed LaTeX snippets associated with this buffer.
219         lyx::graphics::Previews::get().removeLoader(*this);
220 }
221
222
223 LyXText & Buffer::text() const
224 {
225         return const_cast<LyXText &>(pimpl_->inset.text_);
226 }
227
228
229 InsetBase & Buffer::inset() const
230 {
231         return const_cast<InsetText &>(pimpl_->inset);
232 }
233
234
235 limited_stack<Undo> & Buffer::undostack()
236 {
237         return pimpl_->undostack;
238 }
239
240
241 limited_stack<Undo> const & Buffer::undostack() const
242 {
243         return pimpl_->undostack;
244 }
245
246
247 limited_stack<Undo> & Buffer::redostack()
248 {
249         return pimpl_->redostack;
250 }
251
252
253 limited_stack<Undo> const & Buffer::redostack() const
254 {
255         return pimpl_->redostack;
256 }
257
258
259 BufferParams & Buffer::params()
260 {
261         return pimpl_->params;
262 }
263
264
265 BufferParams const & Buffer::params() const
266 {
267         return pimpl_->params;
268 }
269
270
271 ParagraphList & Buffer::paragraphs()
272 {
273         return text().paragraphs();
274 }
275
276
277 ParagraphList const & Buffer::paragraphs() const
278 {
279         return text().paragraphs();
280 }
281
282
283 LyXVC & Buffer::lyxvc()
284 {
285         return pimpl_->lyxvc;
286 }
287
288
289 LyXVC const & Buffer::lyxvc() const
290 {
291         return pimpl_->lyxvc;
292 }
293
294
295 string const & Buffer::temppath() const
296 {
297         return pimpl_->temppath;
298 }
299
300
301 TexRow & Buffer::texrow()
302 {
303         return pimpl_->texrow;
304 }
305
306
307 TexRow const & Buffer::texrow() const
308 {
309         return pimpl_->texrow;
310 }
311
312
313 string const Buffer::getLatexName(bool no_path) const
314 {
315         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
316         return no_path ? OnlyFilename(name) : name;
317 }
318
319
320 pair<Buffer::LogType, string> const Buffer::getLogName() const
321 {
322         string const filename = getLatexName(false);
323
324         if (filename.empty())
325                 return make_pair(Buffer::latexlog, string());
326
327         string const path = temppath();
328
329         string const fname = AddName(path,
330                                      OnlyFilename(ChangeExtension(filename,
331                                                                   ".log")));
332         string const bname =
333                 AddName(path, OnlyFilename(
334                         ChangeExtension(filename,
335                                         formats.extension("literate") + ".out")));
336
337         // If no Latex log or Build log is newer, show Build log
338
339         FileInfo const f_fi(fname);
340         FileInfo const b_fi(bname);
341
342         if (b_fi.exist() &&
343             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
344                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
345                 return make_pair(Buffer::buildlog, bname);
346         }
347         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
348         return make_pair(Buffer::latexlog, fname);
349 }
350
351
352 void Buffer::setReadonly(bool flag)
353 {
354         if (pimpl_->read_only != flag) {
355                 pimpl_->read_only = flag;
356                 readonly(flag);
357         }
358 }
359
360
361 void Buffer::setFileName(string const & newfile)
362 {
363         pimpl_->filename = MakeAbsPath(newfile);
364         pimpl_->filepath = OnlyPath(pimpl_->filename);
365         setReadonly(IsFileWriteable(pimpl_->filename) == 0);
366         updateTitles();
367 }
368
369
370 // We'll remove this later. (Lgb)
371 namespace {
372
373 void unknownClass(string const & unknown)
374 {
375         Alert::warning(_("Unknown document class"),
376                 bformat(_("Using the default document class, because the "
377                         "class %1$s is unknown."), unknown));
378 }
379
380 } // anon
381
382
383 int Buffer::readHeader(LyXLex & lex)
384 {
385         int unknown_tokens = 0;
386
387         while (lex.isOK()) {
388                 lex.nextToken();
389                 string const token = lex.getString();
390
391                 if (token.empty())
392                         continue;
393
394                 if (token == "\\end_header")
395                         break;
396
397                 lyxerr[Debug::PARSER] << "Handling header token: `"
398                                       << token << '\'' << endl;
399
400
401                 string unknown = params().readToken(lex, token);
402                 if (!unknown.empty()) {
403                         if (unknown[0] != '\\') {
404                                 unknownClass(unknown);
405                         } else {
406                                 ++unknown_tokens;
407                                 string const s = bformat(_("Unknown token: "
408                                                            "%1$s %2$s\n"),
409                                                          token,
410                                                          lex.getString());
411                                 error(ErrorItem(_("Header error"), s,
412                                                 -1, 0, 0));
413                         }
414                 }
415         }
416         return unknown_tokens;
417 }
418
419
420 // Uwe C. Schroeder
421 // changed to be public and have one parameter
422 // Returns false if "\end_document" is not read (Asger)
423 bool Buffer::readBody(LyXLex & lex)
424 {
425         if (paragraphs().empty()) {
426                 readHeader(lex);
427                 if (!params().getLyXTextClass().load()) {
428                         string theclass = params().getLyXTextClass().name();
429                         Alert::error(_("Can't load document class"), bformat(
430                                         "Using the default document class, because the "
431                                         " class %1$s could not be loaded.", theclass));
432                         params().textclass = 0;
433                 }
434         } else {
435                 // We don't want to adopt the parameters from the
436                 // document we insert, so read them into a temporary buffer
437                 // and then discard it
438
439                 Buffer tmpbuf("", false);
440                 tmpbuf.readHeader(lex);
441         }
442
443         return text().read(*this, lex);
444 }
445
446
447 // needed to insert the selection
448 void Buffer::insertStringAsLines(ParagraphList & pars,
449         par_type & par, pos_type & pos,
450         LyXFont const & fn, string const & str)
451 {
452         LyXLayout_ptr const & layout = pars[par].layout();
453
454         LyXFont font = fn;
455
456         pars[par].checkInsertChar(font);
457         // insert the string, don't insert doublespace
458         bool space_inserted = true;
459         bool autobreakrows = !pars[par].inInset() ||
460                 static_cast<InsetText *>(pars[par].inInset())->getAutoBreakRows();
461         for(string::const_iterator cit = str.begin();
462             cit != str.end(); ++cit) {
463                 if (*cit == '\n') {
464                         if (autobreakrows && (!pars[par].empty() || pars[par].allowEmpty())) {
465                                 breakParagraph(params(), paragraphs(), par, pos,
466                                                layout->isEnvironment());
467                                 ++par;
468                                 pos = 0;
469                                 space_inserted = true;
470                         } else {
471                                 continue;
472                         }
473                         // do not insert consecutive spaces if !free_spacing
474                 } else if ((*cit == ' ' || *cit == '\t') &&
475                            space_inserted && !pars[par].isFreeSpacing()) {
476                         continue;
477                 } else if (*cit == '\t') {
478                         if (!pars[par].isFreeSpacing()) {
479                                 // tabs are like spaces here
480                                 pars[par].insertChar(pos, ' ', font);
481                                 ++pos;
482                                 space_inserted = true;
483                         } else {
484                                 const pos_type n = 8 - pos % 8;
485                                 for (pos_type i = 0; i < n; ++i) {
486                                         pars[par].insertChar(pos, ' ', font);
487                                         ++pos;
488                                 }
489                                 space_inserted = true;
490                         }
491                 } else if (!IsPrintable(*cit)) {
492                         // Ignore unprintables
493                         continue;
494                 } else {
495                         // just insert the character
496                         pars[par].insertChar(pos, *cit, font);
497                         ++pos;
498                         space_inserted = (*cit == ' ');
499                 }
500
501         }
502 }
503
504
505 bool Buffer::readFile(string const & filename)
506 {
507         // Check if the file is compressed.
508         string const format = getExtFromContents(filename);
509         if (format == "gzip" || format == "zip" || format == "compress") {
510                 params().compressed = true;
511         }
512
513         // remove dummy empty par
514         paragraphs().clear();
515         bool ret = readFile(filename, paragraphs().size());
516
517         // After we have read a file, we must ensure that the buffer
518         // language is set and used in the gui.
519         // If you know of a better place to put this, please tell me. (Lgb)
520         updateDocLang(params().language);
521
522         return ret;
523 }
524
525
526 bool Buffer::readFile(string const & filename, par_type pit)
527 {
528         LyXLex lex(0, 0);
529         lex.setFile(filename);
530         return readFile(lex, filename, pit);
531 }
532
533
534 bool Buffer::fully_loaded() const
535 {
536         return pimpl_->file_fully_loaded;
537 }
538
539
540 void Buffer::fully_loaded(bool value)
541 {
542         pimpl_->file_fully_loaded = value;
543 }
544
545
546 bool Buffer::readFile(LyXLex & lex, string const & filename, par_type pit)
547 {
548         BOOST_ASSERT(!filename.empty());
549
550         if (!lex.isOK()) {
551                 Alert::error(_("Document could not be read"),
552                              bformat(_("%1$s could not be read."), filename));
553                 return false;
554         }
555
556         lex.next();
557         string const token(lex.getString());
558
559         if (!lex.isOK()) {
560                 Alert::error(_("Document could not be read"),
561                              bformat(_("%1$s could not be read."), filename));
562                 return false;
563         }
564
565         // the first token _must_ be...
566         if (token != "\\lyxformat") {
567                 lyxerr << "Token: " << token << endl;
568
569                 Alert::error(_("Document format failure"),
570                              bformat(_("%1$s is not a LyX document."),
571                                        filename));
572                 return false;
573         }
574
575         lex.eatLine();
576         string tmp_format = lex.getString();
577         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
578         // if present remove ".," from string.
579         string::size_type dot = tmp_format.find_first_of(".,");
580         //lyxerr << "           dot found at " << dot << endl;
581         if (dot != string::npos)
582                         tmp_format.erase(dot, 1);
583         int file_format = strToInt(tmp_format);
584         //lyxerr << "format: " << file_format << endl;
585
586         if (file_format > LYX_FORMAT) {
587                 Alert::warning(_("Document format failure"),
588                                bformat(_("%1$s was created with a newer"
589                                          " version of LyX. This is likely to"
590                                          " cause problems."),
591                                          filename));
592         } else if (file_format < LYX_FORMAT) {
593                 string const tmpfile = tempName();
594                 if (tmpfile.empty()) {
595                         Alert::error(_("Conversion failed"),
596                                      bformat(_("%1$s is from an earlier"
597                                               " version of LyX, but a temporary"
598                                               " file for converting it could"
599                                               " not be created."),
600                                               filename));
601                         return false;
602                 }
603                 string command = LibFileSearch("lyx2lyx", "lyx2lyx");
604                 if (command.empty()) {
605                         Alert::error(_("Conversion script not found"),
606                                      bformat(_("%1$s is from an earlier"
607                                                " version of LyX, but the"
608                                                " conversion script lyx2lyx"
609                                                " could not be found."),
610                                                filename));
611                         return false;
612                 }
613                 command += " -t"
614                         + tostr(LYX_FORMAT)
615                         + " -o " + tmpfile + ' '
616                         + QuoteName(filename);
617                 lyxerr[Debug::INFO] << "Running '"
618                                     << command << '\''
619                                     << endl;
620                 cmd_ret const ret = RunCommand(command);
621                 if (ret.first != 0) {
622                         Alert::error(_("Conversion script failed"),
623                                      bformat(_("%1$s is from an earlier version"
624                                               " of LyX, but the lyx2lyx script"
625                                               " failed to convert it."),
626                                               filename));
627                         return false;
628                 } else {
629                         bool ret = readFile(tmpfile, pit);
630                         // Do stuff with tmpfile name and buffer name here.
631                         return ret;
632                 }
633
634         }
635
636         bool the_end = readBody(lex);
637         params().setPaperStuff();
638
639 #warning Look here!
640 #if 0
641         if (token == "\\end_document")
642                 the_end_read = true;
643
644         if (!the_end) {
645                 Alert::error(_("Document format failure"),
646                              bformat(_("%1$s ended unexpectedly, which means"
647                                        " that it is probably corrupted."),
648                                        filename));
649         }
650 #endif 
651         pimpl_->file_fully_loaded = true;
652         return true;
653 }
654
655
656 // Should probably be moved to somewhere else: BufferView? LyXView?
657 bool Buffer::save() const
658 {
659         // We don't need autosaves in the immediate future. (Asger)
660         resetAutosaveTimers();
661
662         // make a backup
663         string s;
664         if (lyxrc.make_backup) {
665                 s = fileName() + '~';
666                 if (!lyxrc.backupdir_path.empty())
667                         s = AddName(lyxrc.backupdir_path,
668                                     subst(os::slashify_path(s),'/','!'));
669
670                 // Rename is the wrong way of making a backup,
671                 // this is the correct way.
672                 /* truss cp fil fil2:
673                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
674                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
675                    open("LyXVC.lyx", O_RDONLY)                     = 3
676                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
677                    fstat(4, 0xEFFFF508)                            = 0
678                    fstat(3, 0xEFFFF508)                            = 0
679                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
680                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
681                    read(3, 0xEFFFD4A0, 8192)                       = 0
682                    close(4)                                        = 0
683                    close(3)                                        = 0
684                    chmod("LyXVC3.lyx", 0100644)                    = 0
685                    lseek(0, 0, SEEK_CUR)                           = 46440
686                    _exit(0)
687                 */
688
689                 // Should probably have some more error checking here.
690                 // Doing it this way, also makes the inodes stay the same.
691                 // This is still not a very good solution, in particular we
692                 // might loose the owner of the backup.
693                 FileInfo finfo(fileName());
694                 if (finfo.exist()) {
695                         mode_t fmode = finfo.getMode();
696                         struct utimbuf times = {
697                                 finfo.getAccessTime(),
698                                 finfo.getModificationTime() };
699
700                         ifstream ifs(fileName().c_str());
701                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
702                         if (ifs && ofs) {
703                                 ofs << ifs.rdbuf();
704                                 ifs.close();
705                                 ofs.close();
706                                 ::chmod(s.c_str(), fmode);
707
708                                 if (::utime(s.c_str(), &times)) {
709                                         lyxerr << "utime error." << endl;
710                                 }
711                         } else {
712                                 lyxerr << "LyX was not able to make "
713                                         "backup copy. Beware." << endl;
714                         }
715                 }
716         }
717
718         if (writeFile(fileName())) {
719                 markClean();
720                 removeAutosaveFile(fileName());
721         } else {
722                 // Saving failed, so backup is not backup
723                 if (lyxrc.make_backup)
724                         rename(s, fileName());
725                 return false;
726         }
727         return true;
728 }
729
730
731 bool Buffer::writeFile(string const & fname) const
732 {
733         if (pimpl_->read_only && fname == fileName())
734                 return false;
735
736         FileInfo finfo(fname);
737         if (finfo.exist() && !finfo.writable())
738                 return false;
739
740         bool retval;
741
742         if (params().compressed) {
743                 gz::ogzstream ofs(fname.c_str());
744                 if (!ofs)
745                         return false;
746
747                 retval = do_writeFile(ofs);
748
749         } else {
750                 ofstream ofs(fname.c_str());
751                 if (!ofs)
752                         return false;
753
754                 retval = do_writeFile(ofs);
755         }
756
757         return retval;
758 }
759
760
761 bool Buffer::do_writeFile(ostream & ofs) const
762 {
763 #ifdef HAVE_LOCALE
764         // Use the standard "C" locale for file output.
765         ofs.imbue(std::locale::classic());
766 #endif
767
768         // The top of the file should not be written by params().
769
770         // write out a comment in the top of the file
771         ofs << "#LyX " << lyx_version
772             << " created this file. For more info see http://www.lyx.org/\n"
773             << "\\lyxformat " << LYX_FORMAT << "\n";
774
775         // now write out the buffer parameters.
776         params().writeFile(ofs);
777
778         ofs << "\\end_header\n";
779
780         // write the text
781         text().write(*this, ofs);
782
783         // Write marker that shows file is complete
784         ofs << "\n\\end_document" << endl;
785
786         // Shouldn't really be needed....
787         //ofs.close();
788
789         // how to check if close went ok?
790         // Following is an attempt... (BE 20001011)
791
792         // good() returns false if any error occured, including some
793         //        formatting error.
794         // bad()  returns true if something bad happened in the buffer,
795         //        which should include file system full errors.
796
797         bool status = true;
798         if (!ofs) {
799                 status = false;
800                 lyxerr << "File was not closed properly." << endl;
801         }
802
803         return status;
804 }
805
806
807 void Buffer::makeLaTeXFile(string const & fname,
808                            string const & original_path,
809                            OutputParams const & runparams,
810                            bool output_preamble, bool output_body)
811 {
812         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
813
814         ofstream ofs;
815         if (!openFileWrite(ofs, fname))
816                 return;
817
818         makeLaTeXFile(ofs, original_path,
819                       runparams, output_preamble, output_body);
820
821         ofs.close();
822         if (ofs.fail())
823                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
824 }
825
826
827 void Buffer::makeLaTeXFile(ostream & os,
828                            string const & original_path,
829                            OutputParams const & runparams_in,
830                            bool output_preamble, bool output_body)
831 {
832         OutputParams runparams = runparams_in;
833
834         // validate the buffer.
835         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
836         LaTeXFeatures features(*this, params(), runparams.nice);
837         validate(features);
838         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
839
840         texrow().reset();
841         // The starting paragraph of the coming rows is the
842         // first paragraph of the document. (Asger)
843         texrow().start(paragraphs().begin()->id(), 0);
844
845         if (output_preamble && runparams.nice) {
846                 os << "%% LyX " << lyx_version << " created this file.  "
847                         "For more info, see http://www.lyx.org/.\n"
848                         "%% Do not edit unless you really know what "
849                         "you are doing.\n";
850                 texrow().newline();
851                 texrow().newline();
852         }
853         lyxerr[Debug::INFO] << "lyx header finished" << endl;
854         // There are a few differences between nice LaTeX and usual files:
855         // usual is \batchmode and has a
856         // special input@path to allow the including of figures
857         // with either \input or \includegraphics (what figinsets do).
858         // input@path is set when the actual parameter
859         // original_path is set. This is done for usual tex-file, but not
860         // for nice-latex-file. (Matthias 250696)
861         if (output_preamble) {
862                 if (!runparams.nice) {
863                         // code for usual, NOT nice-latex-file
864                         os << "\\batchmode\n"; // changed
865                         // from \nonstopmode
866                         texrow().newline();
867                 }
868                 if (!original_path.empty()) {
869                         string inputpath = os::external_path(original_path);
870                         subst(inputpath, "~", "\\string~");
871                         os << "\\makeatletter\n"
872                             << "\\def\\input@path{{"
873                             << inputpath << "/}}\n"
874                             << "\\makeatother\n";
875                         texrow().newline();
876                         texrow().newline();
877                         texrow().newline();
878                 }
879
880                 // Write the preamble
881                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
882
883                 if (!output_body)
884                         return;
885
886                 // make the body.
887                 os << "\\begin{document}\n";
888                 texrow().newline();
889         } // output_preamble
890         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
891
892         if (!lyxrc.language_auto_begin) {
893                 os << subst(lyxrc.language_command_begin, "$$lang",
894                              params().language->babel())
895                     << endl;
896                 texrow().newline();
897         }
898
899         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
900
901         // add this just in case after all the paragraphs
902         os << endl;
903         texrow().newline();
904
905         if (!lyxrc.language_auto_end) {
906                 os << subst(lyxrc.language_command_end, "$$lang",
907                              params().language->babel())
908                     << endl;
909                 texrow().newline();
910         }
911
912         if (output_preamble) {
913                 os << "\\end{document}\n";
914                 texrow().newline();
915
916                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
917         } else {
918                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
919                                      << endl;
920         }
921
922         // Just to be sure. (Asger)
923         texrow().newline();
924
925         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
926         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
927                             << '.' << endl;
928 }
929
930
931 bool Buffer::isLatex() const
932 {
933         return params().getLyXTextClass().outputType() == LATEX;
934 }
935
936
937 bool Buffer::isLinuxDoc() const
938 {
939         return params().getLyXTextClass().outputType() == LINUXDOC;
940 }
941
942
943 bool Buffer::isLiterate() const
944 {
945         return params().getLyXTextClass().outputType() == LITERATE;
946 }
947
948
949 bool Buffer::isDocBook() const
950 {
951         return params().getLyXTextClass().outputType() == DOCBOOK;
952 }
953
954
955 bool Buffer::isSGML() const
956 {
957         LyXTextClass const & tclass = params().getLyXTextClass();
958
959         return tclass.outputType() == LINUXDOC ||
960                tclass.outputType() == DOCBOOK;
961 }
962
963
964 void Buffer::makeLinuxDocFile(string const & fname,
965                               OutputParams const & runparams,
966                               bool body_only)
967 {
968         ofstream ofs;
969         if (!openFileWrite(ofs, fname))
970                 return;
971
972         LaTeXFeatures features(*this, params(), runparams.nice);
973         validate(features);
974
975         texrow().reset();
976
977         LyXTextClass const & tclass = params().getLyXTextClass();
978
979         string top_element = tclass.latexname();
980
981         if (!body_only) {
982                 ofs << tclass.class_header();
983
984                 string preamble = params().preamble;
985                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
986                          : fname;
987                 preamble += features.getIncludedFiles(name);
988                 preamble += features.getLyXSGMLEntities();
989
990                 if (!preamble.empty()) {
991                         ofs << " [ " << preamble << " ]";
992                 }
993                 ofs << ">\n\n";
994
995                 if (params().options.empty())
996                         sgml::openTag(ofs, 0, false, top_element);
997                 else {
998                         string top = top_element;
999                         top += ' ';
1000                         top += params().options;
1001                         sgml::openTag(ofs, 0, false, top);
1002                 }
1003         }
1004
1005         ofs << "<!-- LyX "  << lyx_version
1006             << " created this file. For more info see http://www.lyx.org/"
1007             << " -->\n";
1008
1009         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1010
1011         if (!body_only) {
1012                 ofs << "\n\n";
1013                 sgml::closeTag(ofs, 0, false, top_element);
1014         }
1015
1016         ofs.close();
1017         if (ofs.fail())
1018                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1019 }
1020
1021
1022 void Buffer::makeDocBookFile(string const & fname,
1023                              OutputParams const & runparams,
1024                              bool only_body)
1025 {
1026         ofstream ofs;
1027         if (!openFileWrite(ofs, fname))
1028                 return;
1029
1030         LaTeXFeatures features(*this, params(), runparams.nice);
1031         validate(features);
1032
1033         texrow().reset();
1034
1035         LyXTextClass const & tclass = params().getLyXTextClass();
1036         string top_element = tclass.latexname();
1037
1038         if (!only_body) {
1039                 ofs << subst(tclass.class_header(), "#", top_element);
1040
1041                 string preamble = params().preamble;
1042                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1043                          : fname;
1044                 preamble += features.getIncludedFiles(name);
1045                 preamble += features.getLyXSGMLEntities();
1046
1047                 if (!preamble.empty()) {
1048                         ofs << "\n [ " << preamble << " ]";
1049                 }
1050                 ofs << ">\n\n";
1051         }
1052
1053         string top = top_element;
1054         top += " lang=\"";
1055         top += params().language->code();
1056         top += '"';
1057
1058         if (!params().options.empty()) {
1059                 top += ' ';
1060                 top += params().options;
1061         }
1062         sgml::openTag(ofs, 0, false, top);
1063
1064         ofs << "<!-- SGML/XML file was created by LyX " << lyx_version
1065             << "\n  See http://www.lyx.org/ for more information -->\n";
1066
1067         params().getLyXTextClass().counters().reset();
1068         docbookParagraphs(*this, paragraphs(), ofs, runparams);
1069
1070         ofs << "\n\n";
1071         sgml::closeTag(ofs, 0, false, top_element);
1072
1073         ofs.close();
1074         if (ofs.fail())
1075                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1076 }
1077
1078
1079 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1080 // Other flags: -wall -v0 -x
1081 int Buffer::runChktex()
1082 {
1083         busy(true);
1084
1085         // get LaTeX-Filename
1086         string const name = getLatexName();
1087         string const path = temppath();
1088         string const org_path = filePath();
1089
1090         Path p(path); // path to LaTeX file
1091         message(_("Running chktex..."));
1092
1093         // Generate the LaTeX file if neccessary
1094         OutputParams runparams;
1095         runparams.flavor = OutputParams::LATEX;
1096         runparams.nice = false;
1097         makeLaTeXFile(name, org_path, runparams);
1098
1099         TeXErrors terr;
1100         Chktex chktex(lyxrc.chktex_command, name, filePath());
1101         int res = chktex.run(terr); // run chktex
1102
1103         if (res == -1) {
1104                 Alert::error(_("chktex failure"),
1105                              _("Could not run chktex successfully."));
1106         } else if (res > 0) {
1107                 // Insert all errors as errors boxes
1108                 bufferErrors(*this, terr);
1109         }
1110
1111         busy(false);
1112
1113         return res;
1114 }
1115
1116
1117 void Buffer::validate(LaTeXFeatures & features) const
1118 {
1119         LyXTextClass const & tclass = params().getLyXTextClass();
1120
1121         if (params().tracking_changes) {
1122                 features.require("dvipost");
1123                 features.require("color");
1124         }
1125
1126         // AMS Style is at document level
1127         if (params().use_amsmath == BufferParams::AMS_ON
1128             || tclass.provides(LyXTextClass::amsmath))
1129                 features.require("amsmath");
1130
1131         for_each(paragraphs().begin(), paragraphs().end(),
1132                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1133
1134         // the bullet shapes are buffer level not paragraph level
1135         // so they are tested here
1136         for (int i = 0; i < 4; ++i) {
1137                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1138                         int const font = params().user_defined_bullet(i).getFont();
1139                         if (font == 0) {
1140                                 int const c = params()
1141                                         .user_defined_bullet(i)
1142                                         .getCharacter();
1143                                 if (c == 16
1144                                    || c == 17
1145                                    || c == 25
1146                                    || c == 26
1147                                    || c == 31) {
1148                                         features.require("latexsym");
1149                                 }
1150                         } else if (font == 1) {
1151                                 features.require("amssymb");
1152                         } else if ((font >= 2 && font <= 5)) {
1153                                 features.require("pifont");
1154                         }
1155                 }
1156         }
1157
1158         if (lyxerr.debugging(Debug::LATEX)) {
1159                 features.showStruct();
1160         }
1161 }
1162
1163
1164 void Buffer::getLabelList(std::vector<string> & list) const
1165 {
1166         /// if this is a child document and the parent is already loaded
1167         /// Use the parent's list instead  [ale990407]
1168         if (!params().parentname.empty()
1169             && bufferlist.exists(params().parentname)) {
1170                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1171                 if (tmp) {
1172                         tmp->getLabelList(list);
1173                         return;
1174                 }
1175         }
1176
1177         for (inset_iterator it = inset_const_iterator_begin();
1178              it != inset_const_iterator_end(); ++it) {
1179                 it->getLabelList(*this, list);
1180         }
1181 }
1182
1183
1184 // This is also a buffer property (ale)
1185 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys)
1186         const
1187 {
1188         /// if this is a child document and the parent is already loaded
1189         /// use the parent's list instead  [ale990412]
1190         if (!params().parentname.empty() &&
1191             bufferlist.exists(params().parentname)) {
1192                 Buffer const * tmp = bufferlist.getBuffer(params().parentname);
1193                 if (tmp) {
1194                         tmp->fillWithBibKeys(keys);
1195                         return;
1196                 }
1197         }
1198
1199         for (inset_iterator it = inset_const_iterator_begin();
1200                 it != inset_const_iterator_end(); ++it) {
1201                 if (it->lyxCode() == InsetOld::BIBTEX_CODE) {
1202                         InsetBibtex const & inset =
1203                                 dynamic_cast<InsetBibtex const &>(*it);
1204                         inset.fillWithBibKeys(*this, keys);
1205                 } else if (it->lyxCode() == InsetOld::INCLUDE_CODE) {
1206                         InsetInclude const & inset =
1207                                 dynamic_cast<InsetInclude const &>(*it);
1208                         inset.fillWithBibKeys(*this, keys);
1209                 } else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
1210                         InsetBibitem const & inset =
1211                                 dynamic_cast<InsetBibitem const &>(*it);
1212                         string const key = inset.getContents();
1213                         string const opt = inset.getOptions();
1214                         string const ref; // = pit->asString(this, false);
1215                         string const info = opt + "TheBibliographyRef" + ref;
1216                         keys.push_back(pair<string, string>(key, info));
1217                 }
1218         }
1219 }
1220
1221
1222 bool Buffer::isDepClean(string const & name) const
1223 {
1224         DepClean::const_iterator it = pimpl_->dep_clean.find(name);
1225         if (it == pimpl_->dep_clean.end())
1226                 return true;
1227         return it->second;
1228 }
1229
1230
1231 void Buffer::markDepClean(string const & name)
1232 {
1233         pimpl_->dep_clean[name] = true;
1234 }
1235
1236
1237 bool Buffer::dispatch(string const & command, bool * result)
1238 {
1239         return dispatch(lyxaction.lookupFunc(command), result);
1240 }
1241
1242
1243 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1244 {
1245         bool dispatched = true;
1246
1247         switch (func.action) {
1248                 case LFUN_EXPORT: {
1249                         bool const tmp = Exporter::Export(this, func.argument, false);
1250                         if (result)
1251                                 *result = tmp;
1252                         break;
1253                 }
1254
1255                 default:
1256                         dispatched = false;
1257         }
1258         return dispatched;
1259 }
1260
1261
1262 void Buffer::changeLanguage(Language const * from, Language const * to)
1263 {
1264         lyxerr << "Changing Language!" << endl;
1265
1266         // Take care of l10n/i18n
1267         updateDocLang(to);
1268
1269         ParIterator end = par_iterator_end();
1270         for (ParIterator it = par_iterator_begin(); it != end; ++it)
1271                 it->changeLanguage(params(), from, to);
1272 }
1273
1274
1275 void Buffer::updateDocLang(Language const * nlang)
1276 {
1277         pimpl_->messages.reset(new Messages(nlang->code()));
1278 }
1279
1280
1281 bool Buffer::isMultiLingual() const
1282 {
1283         ParConstIterator end = par_iterator_end();
1284         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1285                 if (it->isMultiLingual(params()))
1286                         return true;
1287
1288         return false;
1289 }
1290
1291
1292 void Buffer::inset_iterator::setParagraph()
1293 {
1294         while (pit != pars_->size()) {
1295                 it = (*pars_)[pit].insetlist.begin();
1296                 if (it != (*pars_)[pit].insetlist.end())
1297                         return;
1298                 ++pit;
1299         }
1300 }
1301
1302
1303 ParIterator Buffer::getParFromID(int id) const
1304 {
1305 #warning FIXME: const correctness! (Andre)
1306         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
1307         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
1308
1309 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
1310         if (id < 0) {
1311                 // John says this is called with id == -1 from undo
1312                 lyxerr << "getParFromID(), id: " << id << endl;
1313                 return end;
1314         }
1315
1316         for (; it != end; ++it)
1317                 if (it->id() == id)
1318                         return it;
1319
1320         return end;
1321 }
1322
1323
1324 bool Buffer::hasParWithID(int id) const
1325 {
1326         ParConstIterator it = par_iterator_begin();
1327         ParConstIterator end = par_iterator_end();
1328
1329         if (id < 0) {
1330                 // John says this is called with id == -1 from undo
1331                 lyxerr << "hasParWithID(), id: " << id << endl;
1332                 return 0;
1333         }
1334
1335         for (; it != end; ++it)
1336                 if (it->id() == id)
1337                         return true;
1338
1339         return false;
1340 }
1341
1342
1343 ParIterator Buffer::par_iterator_begin()
1344 {
1345         return ParIterator(0, paragraphs());
1346 }
1347
1348
1349 ParIterator Buffer::par_iterator_end()
1350 {
1351         return ParIterator(paragraphs().size(), paragraphs());
1352 }
1353
1354
1355 ParConstIterator Buffer::par_iterator_begin() const
1356 {
1357         return ParConstIterator(0, paragraphs());
1358 }
1359
1360
1361 ParConstIterator Buffer::par_iterator_end() const
1362 {
1363         return ParConstIterator(paragraphs().size(), paragraphs());
1364 }
1365
1366
1367 Language const * Buffer::getLanguage() const
1368 {
1369         return params().language;
1370 }
1371
1372
1373 string const Buffer::B_(string const & l10n) const
1374 {
1375         if (pimpl_->messages.get()) {
1376                 return pimpl_->messages->get(l10n);
1377         }
1378
1379         return _(l10n);
1380 }
1381
1382
1383 bool Buffer::isClean() const
1384 {
1385         return pimpl_->lyx_clean;
1386 }
1387
1388
1389 bool Buffer::isBakClean() const
1390 {
1391         return pimpl_->bak_clean;
1392 }
1393
1394
1395 void Buffer::markClean() const
1396 {
1397         if (!pimpl_->lyx_clean) {
1398                 pimpl_->lyx_clean = true;
1399                 updateTitles();
1400         }
1401         // if the .lyx file has been saved, we don't need an
1402         // autosave
1403         pimpl_->bak_clean = true;
1404 }
1405
1406
1407 void Buffer::markBakClean()
1408 {
1409         pimpl_->bak_clean = true;
1410 }
1411
1412
1413 void Buffer::setUnnamed(bool flag)
1414 {
1415         pimpl_->unnamed = flag;
1416 }
1417
1418
1419 bool Buffer::isUnnamed() const
1420 {
1421         return pimpl_->unnamed;
1422 }
1423
1424
1425 void Buffer::markDirty()
1426 {
1427         if (pimpl_->lyx_clean) {
1428                 pimpl_->lyx_clean = false;
1429                 updateTitles();
1430         }
1431         pimpl_->bak_clean = false;
1432
1433         DepClean::iterator it = pimpl_->dep_clean.begin();
1434         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1435
1436         for (; it != end; ++it) {
1437                 it->second = false;
1438         }
1439 }
1440
1441
1442 string const & Buffer::fileName() const
1443 {
1444         return pimpl_->filename;
1445 }
1446
1447
1448 string const & Buffer::filePath() const
1449 {
1450         return pimpl_->filepath;
1451 }
1452
1453
1454 bool Buffer::isReadonly() const
1455 {
1456         return pimpl_->read_only;
1457 }
1458
1459
1460 void Buffer::setParentName(string const & name)
1461 {
1462         params().parentname = name;
1463 }
1464
1465
1466 Buffer::inset_iterator::inset_iterator(ParagraphList & pars, base_type p)
1467         : pit(p), pars_(&pars)
1468 {
1469         setParagraph();
1470 }
1471
1472
1473 Buffer::inset_iterator Buffer::inset_iterator_begin()
1474 {
1475         return inset_iterator(paragraphs(), 0);
1476 }
1477
1478
1479 Buffer::inset_iterator Buffer::inset_iterator_end()
1480 {
1481         return inset_iterator(paragraphs(), paragraphs().size());
1482 }
1483
1484
1485 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
1486 {
1487         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1488         return inset_iterator(pars, 0);
1489 }
1490
1491
1492 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
1493 {
1494         ParagraphList & pars = const_cast<ParagraphList&>(paragraphs());
1495         return inset_iterator(pars, pars.size());
1496 }
1497
1498
1499 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
1500 {
1501         if (pit != pars_->size()) {
1502                 ++it;
1503                 if (it == (*pars_)[pit].insetlist.end()) {
1504                         ++pit;
1505                         setParagraph();
1506                 }
1507         }
1508         return *this;
1509 }
1510
1511
1512 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
1513 {
1514         inset_iterator tmp = *this;
1515         ++*this;
1516         return tmp;
1517 }
1518
1519
1520 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
1521 {
1522         return *it->inset;
1523 }
1524
1525
1526 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
1527 {
1528         return it->inset;
1529 }
1530
1531
1532 lyx::par_type Buffer::inset_iterator::getPar() const
1533 {
1534         return pit;
1535 }
1536
1537
1538 lyx::pos_type Buffer::inset_iterator::getPos() const
1539 {
1540         return it->pos;
1541 }
1542
1543
1544 bool operator==(Buffer::inset_iterator const & iter1,
1545                 Buffer::inset_iterator const & iter2)
1546 {
1547         return iter1.pit == iter2.pit && iter1.it == iter2.it;
1548 }
1549
1550
1551 bool operator!=(Buffer::inset_iterator const & iter1,
1552                 Buffer::inset_iterator const & iter2)
1553 {
1554         return !(iter1 == iter2);
1555 }