pandoc.py 25.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
# -*- coding: utf-8 -*-*

import math
import os.path
import subprocess

document = []
footnoteIndex = 1
bibliographies = []
toc = False

def newPage():
	''' End the current page.
    '''
    
	global document
	
	document.append('\\newpage')

def pageBreak():
	''' Same as newPage, except it is more a friendly request : it may or may not end the page.
	'''
	
	global document
	
	document.append('\\pagebreak')
	
def rawText (text):
	''' Add raw text to the document.
	
	:param text: text to add
	'''
	
	global document
	
	document.append(text)
	
def paragraph (text):
	''' Add a paragraph in the document (a section of text separate by blank lines)
	
	:param text: paragraph text to add
	'''
	
	newLine()
	rawText(text)
	newLine()
	
def header (text, level=1, identifier=''):
	''' Add a header in the document.

	:param text: header text
	:param level: hierarchical level (1 is the higher)
	:param identifier: a specific identifier can be added in order to referenced it in the document (see Reference section). 
	Pandoc generate automatic based on the header text (See http://pandoc.org/MANUAL.html#header-identifiers)
	'''
	
	global document
	 
	header = '\n' + '#' * level + ' ' + text
	
	if identifier != '':
		header = header + ' ' + '{' + identifier + '}'
	
	#~ header += '\n'
	
	document.append(header)
	
def quoteBlock (texts, quoteChar='>'):
	''' Add a block quotation in the document by using the email convention.
	
	:param texts: hierarchical list of text representing the quote
	:param quoteChar: quote character
	
	>>> quoteBlock(['text1', ['text2', ['text3'], 'text4'], 'text5'])
	'''
	
	global document
	## ['text1', ['text2', ['text3'], 'text4'], 'text5']
	## > text1
	## > > text2
	## > > > text3
	## > > text4
	## > text5
	
	for text in texts:
		if type (text) is str:
			quote = quoteChar + ' ' + text + '\n'
			document.append(quote)
		elif type (text) is list :
			quoteBlock (text, quoteChar + ' >')
	
def codeBlock (text):
	''' Add a block of verbatim code to the document.
	
	:param text: code text, can be a string or a list which each element will be a line
	'''
	
	global document
	
	if type (text) is str:
		textitems = text.split('\n')
	elif type (text) is list:
		textitems = text
	
	code  = ''
	for textitem in textitems:
		code  = code + ' ' * 4 + textitem + '\n'
	
	document.append(code)
	
def codeBlockFenced (text, attributes=''):
	''' Add a block of verbatim code to the document. Fenced are added before and after the block of code. This form of code block is useful if the user wants to add attributes to it.
	
	:param text: code text
	:param attributes: attributes to add the code block
	'''
	
	global document
	
	fenced = '~' * 3
	
	code  = fenced
	if attributes != '':
		code = code + attributes 
		
	code = code + '\n' + text 
	
	## if there is no newline at the end of the text, add one
	if text[len(text)-1] != '\n':
		code = code + '\n'
	
	code = code + fenced
	
	document.append(code)

def lineBlock (text):
	''' Add a block of line to the document. 
	
	:param text: can be a string containing multiple lines ('\n' is the line separator) or a list of lines
	
	>>> lineBlock ('line 1 \nline 2 \nline 3')
	>>> lineBlock (['line 1', 'line 2', 'line 3'])
	'''
	
	global document
	
	if type (text) is str:
		textitems = text.split('\n')
	elif type (text) is list:
		textitems = text
	
	lines = ''
	for textitem in textitems:
		lines  = lines + '| ' + textitem + '\n'
	
	document.append(lines)
	
def listBlock (texts, loose=False):
	''' Add a list to the document. 
	
	:param texts: hierarchical list of text (3 levels maximum)
	:param loose: The loose option can be set to True to have a loose list in which each items are separated by spaces

	>>> listBlock ([a, [a, [a, b], b, c], b, c])
	'''
	
	global document
	
	## loose list or not
	if loose == True:
		cr = '\n' * 2
	else:
		cr = '\n'
	
	## format the text list. 3 level are available : [a, [a, [a, b], b, c], b, c]
	## * a
	##    + a
	##        - a
	##        - b
	##    + b
	##    + c
	## * b
	## * c
	textList = ''
	for texts1 in texts:
		if type (texts1) is str:
			textList = textList + '* ' + texts1 + cr
		elif type (texts1) is list:
			for texts2 in texts1:
				if type (texts2) is str:
					textList = textList + ' ' * 4 + '+ ' + texts2 + cr
				elif type (texts2) is list:
					for texts3 in texts2:
						if type (texts3) is str:
							textList = textList + ' ' * 8 + '- ' + texts3 + cr
	
	newLine()
	document.append(textList)
	
def orderedlistBlock (texts):
	''' Add an ordered list to the document. 
	
	:param texts: list of text element

	>>> orderedlistBlock(['ab', 'bc', 'cd'])
	'''
	
	global document
	
	textList = ''
	index = 1
	for text in texts:
		if type (text) is str:
			textList = textList + str(index) + '. ' + text + '\n'
			index = index + 1
	
	document.append(textList)

def newDocument(title = '', authors = [], date = ''):
	''' First library command to execute in the python script in order to initialize a pandoc document. 
	
	:param title: title of the document
	:param authors: list of authors of the document
	:param date: date of the document
	
	>>> newDocument('title\nof the document', ['author1', 'author2'], '25 june\n2017')
	'''
	
	global document
	 
	document = []
	
	if title != '':
		titleItems = title.split('\n')
		
		leads = '% '
		for items in titleItems:
			 document.append(leads + items)
			 leads = '  '
	else:
		if (authors != []) or (date != ''):
			document.append('%')

	if authors != []:
		tmp = ';'.join(authors)
		document.append('% ' + tmp)
	else:
		if date != '':
			document.append('%')
		
	if date != '':
		dateItems = date.split('\n')
		date = ' '.join(dateItems) 
		
		document.append('% ' + date)
	
def newLine ():
	''' Add a blank line to the document.
	'''
	
	global document
	
	document.append('')
	
def horizontalRule (char='-', number=10):
	''' Add an horizontal rule to the document. 
	
	:param char: character use for the rule among '-' (default), '_' or '*'
	:param number: number of char in the rule. Shall not be lower than 3
	
	>>> horizontalRule ()
	>>> horizontalRule ('*', 4)
	>>> horizontalRule ('_', 20)
	'''
	
	global document

	if ((char == '-') or (char == '_') or (char == '*')) and (number >= 3): 
		horiRule = '\n' + char * number
	
	document.append(horiRule)

## tableType can be equal to '' for simple and multiline table, 'grid' for grid table and 'pipe' for pipe table
def table (tableList, caption='', colSep=' ', tableType=''):
	''' Add a table to the document. 
	
	:param tableList: The table is given in a 2 dimensions list : each row of the list is a row of the table. The first one is the header and the header description. Each element of the header list is a list containing 3 data : the text header, the alignment and the size of the column (this last information can be omitted).
	:param caption: caption of the table
	:param colSep:
290
	:param tableType: table type : '' for simple and multiline table, 'grid' for grid table and 'pipe' for pipe table.
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
	
	>>> table ([['tt1', 'right', 10],['title2', 'left', 1],['t3', 'center', 10], ['t4', 'default', 40]], \
				['12', '12', '123', '12'], \
				['123', '123', '1234', '1234'], \
				['1', '1', '1', '1'] \
				])
	'''
	
	global document
	
	tableHeaders = tableList[0]
	
	maxLen = [0] * len(tableHeaders)
	sizelinePerCol = [[] for _ in tableHeaders]
	
	## the table list where header data (position, col size, ...) has been removed
	header = False
	tableList2 = []
	positions = [''] * len(tableHeaders)
	for i, headerData in enumerate(tableHeaders):
		## purge the headers from data except for the text
		headerText = headerData[0]
		if (tableType == 'pipe') and (headerText == ''):
			 headerText = ' '
		if len(headerText) > 0:
			header = True
			try:
				tableList2[0].append(headerText)
			except IndexError:
				tableList2.append([headerText])
		
		position = headerData[1]
		positions[i] = position
		## check if a size has been given by the user
		try:
			headerSize = headerData[2]
			if (position == 'right') or (position == 'left'):
				headerSize -= 2
			elif position == 'center':
				headerSize -= 4
			else:
				headerSize = 0
		except IndexError:
			headerSize = 0
			
		## initialize the list with user column size
		sizelinePerCol[i].append(headerSize)
	
	## add the rest of table list
	tableList2 += tableList[1:]

	## compute the number of rows of the final table and check if it is a multi line table
	nbRows = 0
	multiLine = False
	for j, row in enumerate(tableList2):
		numberOfRow = []
		for i, value in enumerate(row):
			textItems = value.split('\n')
			
			if tableType == 'pipe':
				tmp = ' '.join(textItems) 
				textItems = [tmp]

			if len(textItems) > 1:
				 multiLine = True

			for textItem in textItems: 
				sizelinePerCol[i].append(len(textItem))
				
			numberOfRow.append(len(textItems))
				
		nbRows += max(numberOfRow)
		
	## compute the max text lenght per column
	space = ' '
	headerLine = ''
	rowLine = ''
	if (tableType == '') and (multiLine == True):
		rowLine = '\n'
		
	for i, headerData in enumerate(tableHeaders):
		maxLen[i] = max(sizelinePerCol[i])
		 
		headerText = headerData[0]
		if tableType != 'pipe':
			textItems = headerText.split('\n')
			textLen = len(textItems[0])
		else:
			textLen = len(headerText)
			
		## compute header line and rowline if necessary
		position = positions[i]
		if tableType == '':
			if position == 'right':
				headerLine += '-' * (maxLen[i] + 2)
			elif position == 'left':
				headerLine += '-' * (maxLen[i] + 2)
			elif position == 'center':
				shift = int(round((maxLen[i] - textLen + 4) / 2))
					
				headerLine += '-' * (textLen + 2 * shift)
			else:
				if header == True:
					dashLen = textLen
				else: # no header
					dashLen = maxLen[i]
					
				headerLine += '-' * dashLen
				if (i < len(tableHeaders) - 1) and (header == True): ## when text in row of a default alignement header is greater than the header size 
					headerLine += space * (maxLen[i] - textLen)
				
			## add th column separator to the dashed line
			if i < len(tableHeaders) - 1:
				headerLine += colSep
		elif tableType == 'grid':
			if header == False:
				headerDash = '-'
			else:
				headerDash = '='

			if position == 'right':
				headerLine += '+' + headerDash * (maxLen[i] + 1) + ':'
			elif position == 'left':
				headerLine += '+' + ':' + headerDash * (maxLen[i] + 1)
			elif position == 'center':
				headerLine += '+' + ':' + headerDash * maxLen[i] + ':'
			else:
				headerLine += '+' + headerDash * (maxLen[i] + 2)
			
			rowLine += '+' + '-' * (maxLen[i] + 2)
			
			if (i == len(tableHeaders) - 1):
				headerLine += '+'
				rowLine += '+'
		elif tableType == 'pipe':
			headerDash = '-'
			
			if position == 'right':
				headerLine += '|' + headerDash * (maxLen[i] + 1) + ':'
			elif position == 'left':
				headerLine += '|' + ':' + headerDash * (maxLen[i] + 1)
			elif position == 'center':
				headerLine += '|' + ':' + headerDash * maxLen[i] + ':'
			else:
				headerLine += '|' + headerDash * (maxLen[i] + 2)
			
			if (i == len(tableHeaders) - 1):
				headerLine += '|'

	## compute the table top and bottom line 
	topTableLine = ''
	bottomTableLine = ""
	if tableType == '':
		if header == True:
			if multiLine == True:
				bottomTableLine = '-' * len(headerLine)
				topTableLine = bottomTableLine + '\n'
		else:
			bottomTableLine = headerLine
			topTableLine = bottomTableLine + '\n' 
	elif tableType == 'grid':
		if header == True:
			bottomTableLine = rowLine
			topTableLine = bottomTableLine + '\n'
		else:
			bottomTableLine = rowLine
			topTableLine = headerLine + '\n'

	## transform the tablelist2 multi line into a tablelist3 monoline
	tableList3 = [[''] * len(tableHeaders) for _ in range(0, nbRows)]
	nextRowIndex = 0
	headerIndex = 0
	rowIndexes = []
	for i, row in enumerate(tableList2):
		kMax = 0
		for j, texts in enumerate(row):
			textItems = texts.split('\n')
			
			if tableType == 'pipe':
				tmp = ' '.join(textItems) 
				textItems = [tmp]
 
			#~ print 'textItems', textItems
			for k, textItem in enumerate(textItems):
				tableList3[nextRowIndex+k][j] = textItem
				kMax = max(kMax, k)
				if (header == True) and (i == 0):
					headerIndex = kMax
			
		nextRowIndex += kMax + 1
		
		## compute the row indexes
		if ((i != 0) or (header == False)) and (i != len(tableList2)-1):
			rowIndexes.append(nextRowIndex)

	table = ''
	
	## finally write the the table
	for i, row in enumerate(tableList3):
		## add the row line if necessary
		if (i in rowIndexes) and (rowLine != ''):
			table += rowLine + '\n'
			
		for j, text in enumerate(row):
			#~ print j, text 
			textLen = len(text)
			
			position = positions[j]
			colLen = maxLen[j]
			if tableType == '':
				if position == 'right':
					table += space * (colLen - textLen + 2) + text
				elif position == 'left':
					table += text + space * (colLen - textLen + 2)
				elif position == 'center':
					shift = int(round((colLen - textLen + 4) / 2))
					table += space * shift + text + space * shift + space * int(textLen%2)
				else:
					table += text + space * (colLen - textLen)

				table += colSep
			elif tableType == 'grid':
				table += '| ' + text + space * (colLen - textLen) + ' '
				
				if (j == len(tableHeaders) - 1):
					table += '|'
			elif tableType == 'pipe':
				table += '| ' + text + space * (colLen - textLen) + ' '
				
				if (j == len(tableHeaders) - 1):
					table += '|'
				
		## write the header line
		if (header == True) and (i == headerIndex):
			table += '\n' + headerLine
					
		table = table + '\n'

	## write the table top and bottom line
	table = '\n' + topTableLine + table + bottomTableLine
		
	table += '\n'
		
	## write the table caption
	if caption != '':
		table += '\nTable: ' + caption + '\n'

	document.append(table)
	
def italic(text):
	''' Return an italic text (pandoc emphase).
	
	param text: text to put in italic

	>>> rawText('this is an ' + italic('italic') + ' emphase')
	'''
	
	emphasChar = '*'
	text = emphasChar + text.strip(' ') + emphasChar
	
	return text
	
def bold(text):
	''' Return a bold text (pandoc strong emphase).
	
	param text: text to put in bold

	>>> rawText('this is a ' + bold('bold') + ' emphase')
	'''
	
	emphasChar = '**'
	text = emphasChar + text.strip(' ') + emphasChar
	
	return text
	
def strikeout (text):
	''' Return a strikeout text.

	param text: text to strikeout
	
	>>> rawText('this is a ' + strikeout('strike out')) 
	'''
	
	text = '~~' + text.strip(' ') + '~~'
	
	return text
	
def power(text):
	''' Return a power text.

	param text: text which power apply
	
	>>> rawText('power : 2' + power('10'))
	'''
	
	text = '^' + text.strip(' ') + '^'
	
	return text

def indice(text):
	''' Return an indice text.
	
	param text: text which indice apply
	
	>>> rawText('indice : H' + indice('2') + '0')
	'''
	
	text = '~' + text.strip(' ') + '~'
	
	return text

def verbatim(text, attributes = ''):
	''' Return a verbatim text.
	
	param text: text which verbatim apply
	param attributes: attributes to apply to the verbatim text
	
	>>> rawText('verbatim text : ' + verbatim('this is a verbatim text') + '\n')
	'''
	
	verbatimChar = '`'
	if text.find(verbatimChar) != -1:
		verbatimChar = ' `` '
		
	text = verbatimChar + text.strip(' ') + verbatimChar
	
	if attributes != '':
		text += '{' + attributes+ '}'
	
	return text

def smallCaps(text):
	''' Return a smallcaps text. Small capitals (usually abbreviated small caps) are uppercase (capital) characters set at the same height and weight as surrounding lowercase (small) letters.

	param text: text to put in small capitals
	
	>>> rawText('small caps text : ' + smallCaps('this is a smallcaps text'))
	'''
	
	text = '[' + text + ']{style="font-variant:small-caps;"}'
	
	return text
	
def math(text):
	''' Return a math formula. The formula shall be latex math formula.

	param text: latext math formula
	
	>>> rawText('math formula : ' + math('\\sqrt{\\frac{x^2}{3}}'))
	'''
	
	text = '$' + text.strip(' ') + '$'
	
	return text

def email(email, text = ''):
	''' Return an email link (<http://google.com>) or if the text is specified an inline email link ([inline link](http://fsf.org "click here for a good time!")).

	param email: email text
	param text: for inline link, text on which the email apply
	
	>>> email('sam@green.eggs.ham')
	>>> email('sam@green.eggs.ham', 'Write me !')
	'''
	
	if text == '':
		email = '<' + email.strip(' ') + '>'
	else:
		email = '[' + text + '](mailto:' + email + ')'
		
	return email

def url(url, text = '', title = ''):
	''' Return an url link or if the text is specified an inline url link.
	
	param url: url text
	param text: for inline link, text on which the url apply
	param title: title associated to the url
	
	>>> url('http://google.com')
	>>> url('http://fsf.org', 'inline link', 'click here for a good time!')
	'''
	
	if text == '':
		url = '<' + url.strip(' ') + '>'
	else:
		url = '[' + text + '](' + url
		if title != '':
			url += ' "' + title + '"'
			
		url +=')'
		
	return url

def reference(ref, text = ''):
	''' Return a reference text.
	
	Reference link : [inline link][Foo], ref is a defined reference : [Foo]: /bar/baz
	Implicit reference link : See [my website][], no url, the text is the reference : [my website]: http://foo.bar.baz
	Internal links : use header identifiers to reference the document structure : See the [Introduction](#introduction) or See the [Introduction] with the following reference [Introduction]: #introduction 
	
	param ref: identifier of the reference. Can be a header reference or a reference defined thanks to the definedReference command.
	param text: if specified, an inline link is done on the text.
	
	>>> reference('#introduction', 'Introduction')
	>>> reference('My Website')
	'''
	
	if ref.find('#') != -1: ## internal links (header)
		if text != '':
			reference = '[' + text + '](' + ref + ')'
		else:
			reference = '[' + ref + ']'
	else:
		if text != '':
			reference = '[' + text + '][' + ref + ']'
		else:
			#~ reference = '[' + ref + '][]'
			reference = '[' + ref + ']' ## shortcut_reference_links
		
	return reference

def definedReference(ref, text, title='', attributes=''):
	''' Add a reference definition to the document.
	
	Examples of use:
	
	* inline link:
	Here is [my link][FOO]
	
	[Foo]: /bar/baz
	
	* implicit reference can be done :
	See [my website][].
	
	[my website]: http://foo.bar.baz

	* image reference :
	[movie reel]: movie.gif
	
	param ref: the real reference : an url, an image filename, … 
	param text: the identifier used by the reference command 
	param title: title associated to the reference definition
	param attributes: attributes that can be applied to the definition
	
	>>> definedReference('http://fsf.org', 'FSF', 'click here for a good time!')
	>>> definedReference('http://truc.org', 'My Website')
	>>> definedReference('#introduction', 'Introduction')
	>>> definedReference('BladeRunner.gif', 'Blade Runner', 'title', 'width=10cm height=20px')
	'''
	
	global document
	
	reference = '[' + text + ']: ' + ref
	
	if title != '':
		reference += ' "' + title + '"'
	
	if attributes != '':
		reference += ' {' + attributes + '}'
	
	document.append(reference)

def image (ref, text = '', title = '', width = '', height = ''):
	''' Return an image link text. 
	
	param ref: can be a filename or a predefined reference (see the  definedReference command). 
	param text: ifspecified, the link will be made on it. 
	param title: text which will be attach to the image (popup text depending of the output format of the pandoc convertion). 
	param width: image width. Can be given with unit (px, cm, mm, in, inch and %). There must not be any spaces between the number and the unit.
	param height: image height. Can be given with unit (px, cm, mm, in, inch and %). There must not be any spaces between the number and the unit.
	
	>>> imageRef = image('la_lune.jpg', width = '50%')
	>>> image('Blade Runner')
	'''
	
	if ref.find('.') != -1: ## image filename
	#~ if text != '':
		image = '![' + text + '](' + ref
		if title != '':
			image += ' "' + title + '"'
		
		image += ')'
			
	else:
		image = '![' + ref + ']'
		
	if (width != '') or (height != ''):
		image += '{'
		if width != '':
			image += ' width=' + width
		if height != '':
			image += ' height=' + height
		
		image += ' }'
		
	return image

def spans(text, attributes):
	''' Return a span text. A span allow the user to give attributes to a text.
	
	param text: text to span
	param attributes: attributes to apply on the text
	'''
	
	spans = '[' + text + ']{' + attributes + '}'
	
	return spans

def footnote(ident = '', text = ''):
	''' Return a footnote text. 
	
	Two forms of pandoc footnote exists : a text is given, in the case of an inline footnote (the note is located on the current text). 
	In the other hand, if no text is given, the text return will be a footnote identifier. 
	It will be automatically compute or assign through the ident argument.
	
	param ident: identifier of he footnote
	param text: text of the footnote
	'''
	
	global footnoteIndex
	
	if ident != '':
		footnote = '[^' + ident + ']'
	else:
		if text == '':
			footnote = '[^' + str(footnoteIndex) + ']'
			footnoteIndex += 1
		else: ## inline_notes
			footnote = '^[' + text + ']'
			
	return footnote
	
def definedFootnote(ident, text, indent = '\n\n'):
	''' Add a footnote definition to the document. 
	
	In the case of footnote using identifier, this command is use to define it. 
	
	param ident: identifier of the footnote
	param text: text associated to the footnote
	param indent: used in the case of text which contains multiple paragraph
	'''
	
	global document
	
	reference = '[^' + ident + ']: '
	
	## find if there is several paragraph on the text footnote
	textItems = text.split(indent)
	
	for textItem in textItems:
		reference += textItem
		reference += ident + '\t'
	 
	document.append(reference)

def citations(*args):
	''' Return a citation text. 
	
	param args: list of identifier follow by, optionally, a locator.
	'''
	
	cite = '['
	
	newKey = False
	for a in args:
		if a.find('@') != -1:
			if newKey == False:
				cite += a
				newKey = True
			else:
				cite += ';' + a
				newKey = False
		else:
			cite += ', ' + a
	
	cite += ']'
	
	return cite

#~ class BiblioGraphyError(Exception):
	#~ def __init__(self, value):
		#~ self.value = value
	#~ def __str__(self):
		#~ return repr(self.value)

def addBibliography(filename):
	''' Add a bibliography file.
	
	param filename: bibliography filename
	'''
	
	global bibliographies
	
	if os.path.isfile(filename) == True: 
		bibliographies.append(filename)
	else:
		raise NameError('bibliography file ' + filename + ' does not exists')
		#~ raise BiblioGraphyError(filename + ' does not exists')

def addTOC ():
	''' If the user wants to add a table of content in his document, this command has to be placed in the script before the convert command.
	'''
	
	global toc
	
	toc = True
	
def removeFormatting(text):
	''' Return a text without all its formatting. A backslash is added to the following character : *, _, ~, ^, {, }, $, >, <, ", \. 
	This function can be used if, for example, a text from external sources (i.e. the taste library) contains characters which can be interpreted by pandoc.
	
	param text: text on which the pandoc formatting has to be removed
	'''
	charsToReplace = ['*', '_', '~','^', '{', '}', '$', '>', '<', '"', '\\']
	for charToReplace in charsToReplace:
		replaceStr = '\\' + charToReplace
		text = text.replace(charToReplace, replaceStr)
		
	return text 

def finalizeDocument():
	''' Commands which finalizes the document. It shall be called when no more element has to be added to the document. 
	'''
	
	global bibliographies
	
	if bibliographies != []:
		header('References')
		
def printDocument (printLine=False):
	''' Display the document in its current state.
	
	param printLine: boolean for printing the line number
	'''
	
	global document
	
	index = 1
	for item in document:
		if printLine == False:
			print item
		else:
			print 'line ' + str(index) + item
			index = index + 1

def serialize (filename):
	''' Serialize in a file the content of the document.
	
	param filename: name of the file where the document will be serialize
	'''
	
	global document
	
	fo = open(filename, 'w')
	
	for item in document:
		fo.write(item + '\n')
	
	fo.close()
	
	return 0
	
def convert(destination, toFormat, source = ''):
	''' Call the pandoc command in order to convert the source document into a specified format and serialize it to the destination filename. 

	Only pdf output has been tested, the format has to be latex and the extension of the file has to be pdf.
	
	param destination: name of the destination file (i.e. test.pdf)
	param toFormat: format of the conversion (i.e. latex)
	param source: source file. If no source is given, the current document is serialized and converted
	
	>>> convert('test.pdf', 'latex')
	'''
	
	global toc
	
	generate = False
	if source != '':
		if os.path.isfile(source) != True:
			 generate = True
	else:
		generate = True
		
	if generate == True:
		source = 'tmp.md'
		serialize (source)
	
	command = ['pandoc', '-fmarkdown', '-t' + toFormat, '-o' + destination, '--smart']
	if toc == True:
		command.append('--toc')
	
	command.append(source)
	
	try:
		subprocess.call(command)
	except :
		print 'convertion impossible : pandoc is not found'
989 990 991 992 993

def svgToPdf (source):
    ''' Call the inkscape command in order to convert the source svg file into pdf format. 

	param source: svg source file. The destination pdf filename is generated based on the source filename.
994
	
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
	>>> convert('test.pdf', 'latex')
	'''
    
	destination = ''
	convert = False
	if source != '':
		if os.path.isfile(source) == True:
			 convert = True

	if convert == True:
		## get the destination filename base on the source filename
		destination = os.path.splitext(source)[0] ## get the filename without the extension
		destination += '.pdf' ## add the extension
		
		## inkscape -D -z --file=ex.svg --export-pdf=ex.pdf
		command = ['inkscape', '-D', '-z', '--file=' + source, '--export-pdf=' + destination]

		try:
			subprocess.call(command)
		except :
			print 'pdf convertion impossible'

	return destination