]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
926a20de6ce5f625b8bad3e6654d606b38b99c74
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "update_flags.h"
16
17 #include "insets/InsetCode.h"
18
19 #include "support/strfwd.h"
20 #include "support/types.h"
21 #include "support/SignalSlot.h"
22
23 #include <list>
24 #include <set>
25 #include <string>
26 #include <vector>
27
28
29 namespace lyx {
30
31 class BiblioInfo;
32 class BufferParams;
33 class BufferSet;
34 class DispatchResult;
35 class DocIterator;
36 class docstring_list;
37 class ErrorItem;
38 class ErrorList;
39 class FuncRequest;
40 class FuncStatus;
41 class Inset;
42 class InsetRef;
43 class InsetLabel;
44 class Font;
45 class Format;
46 class Lexer;
47 class LyXRC;
48 class Text;
49 class LyXVC;
50 class LaTeXFeatures;
51 class Language;
52 class MacroData;
53 class MacroNameSet;
54 class MacroSet;
55 class OutputParams;
56 class Paragraph;
57 class ParConstIterator;
58 class ParIterator;
59 class ParagraphList;
60 class TeXErrors;
61 class TexRow;
62 class TocBackend;
63 class Undo;
64 class WordLangTuple;
65
66 namespace frontend {
67 class GuiBufferDelegate;
68 class WorkAreaManager;
69 }
70
71 namespace support {
72 class FileName;
73 class FileNameList;
74 }
75
76 /** The buffer object.
77  * This is the buffer object. It contains all the informations about
78  * a document loaded into LyX.
79  * The buffer object owns the Text (wrapped in an InsetText), which
80  * contains the individual paragraphs of the document.
81  *
82  *
83  * I am not sure if the class is complete or
84  * minimal, probably not.
85  * \author Lars Gullik Bjønnes
86  */
87 class Buffer {
88 public:
89         /// What type of log will \c getLogName() return?
90         enum LogType {
91                 latexlog, ///< LaTeX log
92                 buildlog  ///< Literate build log
93         };
94
95         /// Result of \c readFile()
96         enum ReadStatus {
97                 failure, ///< The file could not be read
98                 success, ///< The file could not be read
99                 wrongversion ///< The version of the file does not match ours
100         };
101
102
103         /// Method to check if a file is externally modified, used by
104         /// isExternallyModified()
105         /**
106          * timestamp is fast but inaccurate. For example, the granularity
107          * of timestamp on a FAT filesystem is 2 second. Also, various operations
108          * may touch the timestamp of a file even when its content is unchanged.
109          *
110          * checksum is accurate but slow, which can be a problem when it is
111          * frequently used, or used for a large file on a slow (network) file
112          * system.
113          *
114          * FIXME: replace this method with support/FileMonitor.
115          */
116         enum CheckMethod {
117                 checksum_method,  ///< Use file checksum
118                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
119         };
120
121         ///
122         enum UpdateScope {
123                 UpdateMaster,
124                 UpdateChildOnly
125         };
126
127         /// Constructor
128         explicit Buffer(std::string const & file, bool readonly = false,
129                 Buffer const * cloned_buffer = 0);
130
131         /// Destructor
132         ~Buffer();
133
134         ///
135         Buffer * clone() const;
136         ///
137         bool isClone() const;
138
139         /** High-level interface to buffer functionality.
140             This function parses a command string and executes it.
141         */
142         void dispatch(std::string const & command, DispatchResult & result);
143
144         /// Maybe we know the function already by number...
145         void dispatch(FuncRequest const & func, DispatchResult & result);
146
147         /// Can this function be exectued?
148         /// \return true if we made a decision
149         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
150
151         /// read a new document from a string
152         bool readString(std::string const &);
153         /// load a new file
154         bool readFile(support::FileName const & filename);
155
156         /// read the header, returns number of unknown tokens
157         int readHeader(Lexer & lex);
158
159         /** Reads a file without header.
160             \param par if != 0 insert the file.
161             \return \c true if file is not completely read.
162         */
163         bool readDocument(Lexer &);
164
165         ///
166         DocIterator getParFromID(int id) const;
167         /// do we have a paragraph with this id?
168         bool hasParWithID(int id) const;
169
170         ///
171         frontend::WorkAreaManager & workAreaManager() const;
172
173         /** Save file.
174             Takes care of auto-save files and backup file if requested.
175             Returns \c true if the save is successful, \c false otherwise.
176         */
177         bool save() const;
178
179         /// Write document to stream. Returns \c false if unsuccesful.
180         bool write(std::ostream &) const;
181         /// save emergency file
182         /// \return a status message towards the user.
183         docstring emergencyWrite();
184         /// Write file. Returns \c false if unsuccesful.
185         bool writeFile(support::FileName const &) const;
186
187         /// Loads LyX file \c filename into buffer, *  and return success
188         bool loadLyXFile(support::FileName const & s);
189
190         /// Fill in the ErrorList with the TeXErrors
191         void bufferErrors(TeXErrors const &, ErrorList &) const;
192
193         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
194         bool makeLaTeXFile(support::FileName const & filename,
195                            std::string const & original_path,
196                            OutputParams const &,
197                            bool output_preamble = true,
198                            bool output_body = true) const;
199         /** Export the buffer to LaTeX.
200             If \p os is a file stream, and params().inputenc is "auto" or
201             "default", and the buffer contains text in different languages
202             with more than one encoding, then this method will change the
203             encoding associated to \p os. Therefore you must not call this
204             method with a string stream if the output is supposed to go to a
205             file. \code
206             ofdocstream ofs;
207             ofs.open("test.tex");
208             writeLaTeXSource(ofs, ...);
209             ofs.close();
210             \endcode is NOT equivalent to \code
211             odocstringstream oss;
212             writeLaTeXSource(oss, ...);
213             ofdocstream ofs;
214             ofs.open("test.tex");
215             ofs << oss.str();
216             ofs.close();
217             \endcode
218          */
219         void writeLaTeXSource(odocstream & os,
220                            std::string const & original_path,
221                            OutputParams const &,
222                            bool output_preamble = true,
223                            bool output_body = true) const;
224         ///
225         void makeDocBookFile(support::FileName const & filename,
226                              OutputParams const & runparams_in,
227                              bool only_body = false) const;
228         ///
229         void writeDocBookSource(odocstream & os, std::string const & filename,
230                              OutputParams const & runparams_in,
231                              bool only_body = false) const;
232         ///
233         void makeLyXHTMLFile(support::FileName const & filename,
234                              OutputParams const & runparams_in,
235                              bool only_body = false) const;
236         ///
237         void writeLyXHTMLSource(odocstream & os,
238                              OutputParams const & runparams_in,
239                              bool only_body = false) const;
240         /// returns the main language for the buffer (document)
241         Language const * language() const;
242         /// get l10n translated to the buffers language
243         docstring const B_(std::string const & l10n) const;
244
245         ///
246         int runChktex();
247         /// return true if the main lyx file does not need saving
248         bool isClean() const;
249         ///
250         bool isBakClean() const;
251         ///
252         bool isDepClean(std::string const & name) const;
253
254         /// whether or not disk file has been externally modified
255         bool isExternallyModified(CheckMethod method) const;
256
257         /// save timestamp and checksum of the given file.
258         void saveCheckSum(support::FileName const & file) const;
259
260         /// mark the main lyx file as not needing saving
261         void markClean() const;
262
263         ///
264         void markBakClean() const;
265
266         ///
267         void markDepClean(std::string const & name);
268
269         ///
270         void setUnnamed(bool flag = true);
271
272         /// Whether or not a filename has been assigned to this buffer
273         bool isUnnamed() const;
274
275         /// Whether or not this buffer is internal.
276         ///
277         /// An internal buffer does not contain a real document, but some auxiliary text segment.
278         /// It is not associated with a filename, it is never saved, thus it does not need to be
279         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
280         bool isInternal() const;
281
282         /// Mark this buffer as dirty.
283         void markDirty();
284
285         /// Returns the buffer's filename. It is always an absolute path.
286         support::FileName fileName() const;
287
288         /// Returns the buffer's filename. It is always an absolute path.
289         std::string absFileName() const;
290
291         /// Returns the the path where the buffer lives.
292         /// It is always an absolute path.
293         std::string filePath() const;
294
295         /** A transformed version of the file name, adequate for LaTeX.
296             \param no_path optional if \c true then the path is stripped.
297         */
298         std::string latexName(bool no_path = true) const;
299
300         /// Get the name and type of the log.
301         std::string logName(LogType * type = 0) const;
302
303         /// Change name of buffer. Updates "read-only" flag.
304         void setFileName(std::string const & newfile);
305
306         /// Set document's parent Buffer.
307         void setParent(Buffer const *);
308         Buffer const * parent() const;
309
310         // Collect all relative buffer
311         std::vector<Buffer const *> allRelatives() const;
312
313         /** Get the document's master (or \c this if this is not a
314             child document)
315          */
316         Buffer const * masterBuffer() const;
317
318         /// \return true if \p child is a child of this \c Buffer.
319         bool isChild(Buffer * child) const;
320         
321         /// return a vector with all children (and grandchildren)
322         std::vector<Buffer *> getChildren(bool grand_children = true) const;
323
324         /// Is buffer read-only?
325         bool isReadonly() const;
326
327         /// Set buffer read-only flag
328         void setReadonly(bool flag = true);
329
330         /// returns \c true if the buffer contains a LaTeX document
331         bool isLatex() const;
332         /// returns \c true if the buffer contains a DocBook document
333         bool isDocBook() const;
334         /// returns \c true if the buffer contains a Wed document
335         bool isLiterate() const;
336
337         /** Validate a buffer for LaTeX.
338             This validates the buffer, and returns a struct for use by
339             #makeLaTeX# and others. Its main use is to figure out what
340             commands and packages need to be included in the LaTeX file.
341             It (should) also check that the needed constructs are there
342             (i.e. that the \refs points to coresponding \labels). It
343             should perhaps inset "error" insets to help the user correct
344             obvious mistakes.
345         */
346         void validate(LaTeXFeatures &) const;
347
348         /// Update the cache with all bibfiles in use (including bibfiles
349         /// of loaded child documents).
350         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
351         ///
352         void invalidateBibinfoCache();
353         /// Return the cache with all bibfiles in use (including bibfiles
354         /// of loaded child documents).
355         support::FileNameList const & 
356                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
357         /// \return the bibliography information for this buffer's master,
358         /// or just for it, if it isn't a child.
359         BiblioInfo const & masterBibInfo() const;
360         /// \return the bibliography information for this buffer ONLY.
361         BiblioInfo const & localBibInfo() const;
362         ///
363         void getLabelList(std::vector<docstring> &) const;
364
365         ///
366         void changeLanguage(Language const * from, Language const * to);
367
368         ///
369         bool isMultiLingual() const;
370
371         ///
372         BufferParams & params();
373         BufferParams const & params() const;
374
375         /** The list of paragraphs.
376             This is a linked list of paragraph, this list holds the
377             whole contents of the document.
378          */
379         ParagraphList & paragraphs();
380         ParagraphList const & paragraphs() const;
381
382         /// LyX version control object.
383         LyXVC & lyxvc();
384         LyXVC const & lyxvc() const;
385
386         /// Where to put temporary files.
387         std::string const temppath() const;
388
389         /// Used when typesetting to place errorboxes.
390         TexRow const & texrow() const;
391         TexRow & texrow();
392
393         ///
394         ParIterator par_iterator_begin();
395         ///
396         ParConstIterator par_iterator_begin() const;
397         ///
398         ParIterator par_iterator_end();
399         ///
400         ParConstIterator par_iterator_end() const;
401
402         // Position of the child buffer where it appears first in the master.
403         DocIterator firstChildPosition(Buffer const * child);
404
405         /** \returns true only when the file is fully loaded.
406          *  Used to prevent the premature generation of previews
407          *  and by the citation inset.
408          */
409         bool isFullyLoaded() const;
410         /// Set by buffer_funcs' newFile.
411         void setFullyLoaded(bool);
412
413         /// Our main text (inside the top InsetText)
414         Text & text() const;
415
416         /// Our top InsetText
417         Inset & inset() const;
418
419         //
420         // Macro handling
421         //
422         /// Collect macro definitions in paragraphs
423         void updateMacros() const;
424         /// Iterate through the whole buffer and try to resolve macros
425         void updateMacroInstances() const;
426
427         /// List macro names of this buffer, the parent and the children
428         void listMacroNames(MacroNameSet & macros) const;
429         /// Collect macros of the parent and its children in front of this buffer.
430         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
431
432         /// Return macro defined before pos (or in the master buffer)
433         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
434         /// Return macro defined anywhere in the buffer (or in the master buffer)
435         MacroData const * getMacro(docstring const & name, bool global = true) const;
436         /// Return macro defined before the inclusion of the child
437         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
438
439         /// Collect user macro names at loading time
440         typedef std::set<docstring> UserMacroSet;
441         UserMacroSet usermacros;
442
443         /// Replace the inset contents for insets which InsetCode is equal
444         /// to the passed \p inset_code.
445         void changeRefsIfUnique(docstring const & from, docstring const & to,
446                 InsetCode code);
447
448         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
449         /// including preamble
450         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
451                 bool full_source) const;
452
453         /// Access to error list.
454         /// This method is used only for GUI visualisation of Buffer related
455         /// errors (like parsing or LateX compilation). This method is const
456         /// because modifying the returned ErrorList does not touch the document
457         /// contents.
458         ErrorList & errorList(std::string const & type) const;
459
460         /// The Toc backend.
461         /// This is useful only for screen visualisation of the Buffer. This
462         /// method is const because modifying this backend does not touch
463         /// the document contents.
464         TocBackend & tocBackend() const;
465
466         ///
467         Undo & undo();
468
469         /// This function is called when the buffer is changed.
470         void changed() const;
471         ///
472         void updateTocItem(std::string const &, DocIterator const &) const;
473         /// This function is called when the buffer structure is changed.
474         void structureChanged() const;
475         /// This function is called when some parsing error shows up.
476         void errors(std::string const & err, bool from_master = false) const;
477         /// This function is called when the buffer busy status change.
478         void setBusy(bool on) const;
479         /// This function is called when the buffer readonly status change.
480         void setReadOnly(bool on) const;
481         /// Update window titles of all users.
482         void updateTitles() const;
483         /// Reset autosave timers for all users.
484         void resetAutosaveTimers() const;
485         ///
486         void message(docstring const & msg) const;
487
488         ///
489         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
490         ///
491         bool hasGuiDelegate() const;
492
493         ///
494         void autoSave() const;
495         ///
496         void removeAutosaveFile() const;
497         ///
498         void moveAutosaveFile(support::FileName const & old) const;
499         ///
500         support::FileName getAutosaveFilename() const;
501
502         /// return the format of the buffer on a string
503         std::string bufferFormat() const;
504         /// return the default output format of the current backend
505         std::string getDefaultOutputFormat() const;
506
507         ///
508         bool doExport(std::string const & format, bool put_in_tempdir,
509                 std::string & result_file) const;
510         ///
511         bool doExport(std::string const & format, bool put_in_tempdir) const;
512         ///
513         bool preview(std::string const & format) const;
514         ///
515         bool isExportable(std::string const & format) const;
516         ///
517         std::vector<Format const *> exportableFormats(bool only_viewable) const;
518         ///
519         bool isExportableFormat(std::string const & format) const;
520
521         ///
522         typedef std::vector<std::pair<InsetRef *, ParIterator> > References;
523         References & references(docstring const & label);
524         References const & references(docstring const & label) const;
525         void clearReferenceCache() const;
526         void setInsetLabel(docstring const & label, InsetLabel const * il);
527         InsetLabel const * insetLabel(docstring const & label) const;
528
529         /// return a list of all used branches (also in children)
530         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
531
532         /// sets the buffer_ member for every inset in this buffer.
533         // FIXME This really shouldn't be needed, but at the moment it's not
534         // clear how to do it just for the individual pieces we need.
535         void setBuffersForInsets() const;
536         /// Updates screen labels and some other information associated with
537         /// insets and paragraphs. Actually, it's more like a general "recurse
538         /// through the Buffer" routine, that visits all the insets and paragraphs.
539         void updateLabels() const { updateLabels(UpdateMaster, false); }
540         /// \param scope: whether to start with the master document or just
541         /// do this one.
542         /// \param output: whether we are preparing for output.
543         void updateLabels(UpdateScope scope, bool output) const;
544         /// 
545         void updateLabels(ParIterator & parit, bool output) const;
546
547         /// Spellcheck starting from \p from.
548         /// \p from initial position, will then points to the next misspelled
549         ///    word.
550         /// \p to will points to the end of the next misspelled word.
551         /// \p word_lang will contain the found misspelled word.
552         /// \return progress if a new word was found.
553         int spellCheck(DocIterator & from, DocIterator & to,
554                 WordLangTuple & word_lang, docstring_list & suggestions) const;
555
556 private:
557         /// search for macro in local (buffer) table or in children
558         MacroData const * getBufferMacro(docstring const & name,
559                                          DocIterator const & pos) const;
560         /** Update macro table starting with position of it
561             \param it in some text inset
562         */
563         void updateMacros(DocIterator & it,
564                                      DocIterator & scope) const;
565         ///
566         void setLabel(ParIterator & it) const;
567         ///
568         void collectRelatives(BufferSet & bufs) const;
569
570         ///
571         bool readFileHelper(support::FileName const & s);
572         ///
573         std::vector<std::string> backends() const;
574         /** Inserts a file into a document
575             \return \c false if method fails.
576         */
577         ReadStatus readFile(Lexer &, support::FileName const & filename,
578                             bool fromString = false);
579
580         /** If we have branches that use the file suffix
581             feature, return the file name with suffix appended.
582         */
583         support::FileName exportFileName() const;
584
585         /// Use the Pimpl idiom to hide the internals.
586         class Impl;
587         /// The pointer never changes although *pimpl_'s contents may.
588         Impl * const d;
589         ///
590         frontend::GuiBufferDelegate * gui_;
591
592         /// This function is called when the buffer structure is changed.
593         Signal structureChanged_;
594         /// This function is called when some parsing error shows up.
595         //Signal errors(std::string const &) = 0;
596         /// This function is called when some message shows up.
597         //Signal message(docstring const &) = 0;
598         /// This function is called when the buffer busy status change.
599         //Signal setBusy(bool) = 0;
600         /// Reset autosave timers for all users.
601         Signal resetAutosaveTimers_;
602 };
603
604
605 } // namespace lyx
606
607 #endif