emaildump.py 16.4 KB
Newer Older
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
1
2
3
4
5
6
7
8
9
10
from arc.arcpreferences import PreferenceManager as PM
from arctool import ARCTool
from Default.emailfilter import EmailFilterTable, EmailFilterLogicValidator
from PyQt5.QtCore import QUrl, Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import arc.arcclasses as arcclasses
import arc.arcgui as arcgui
import quopri
import re
11
12
import imaplib
import email
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
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

class Plugin(arcclasses.Plugin):
	headers = '|'.join(
		['From','Date','Sent','To','Cc','Bcc','Subject','Importance']
	)

	def __init__(self,package):
		super(Plugin,self).__init__(None,package)

		self.__name__ = "emaildump"
		# Required
		self.name = "Email Dump"
		self.authors = ["unonu"]
		self.version = (0,0,1)
		self.description="Finds a group of emails and dumps their information."
		self.contexts = ['Date']

		self.emails = []
		self.emailIds = {}
		self.fragments = {}
		self.fetched = False

		self.contextFilters = []

		self.igHeader = False
38
		self.igPles = False
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
		self.igReplies= False
		self.igDup 	  = False
		self.igFirstDup = False
		self.igImages = False
		self.igFormat = False
		self.igSpace = False

		self.delim = ''

	#needed
	def setupUi(self):
		#Filter
		self.widget.emailFilterTable = EmailFilterTable()
		self.widget.emailFilterTable.tableChanged.connect(
53
54
55
56
			lambda x: self.widget.fetchButton.setProperty('enabled',
				(x > 0
				or self.widget.contextCheck.isChecked()
				or self.widget.selectEdit.text() != ''))
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
		)
		self.widget.emailFilterTable.tableChanged.connect(
				ARCTool.signalProfileChanged
		)

		self.widget.tableLayout.addWidget(self.widget.emailFilterTable)
		self.widget.fetchButton.clicked.connect(self.makeRequest)
		self.widget.logicBox.setValidator(EmailFilterLogicValidator())
		self.widget.selectEdit.textChanged.connect(
			lambda x: self.widget.fetchButton.setEnabled(
				x != '' or len(self.widget.emailFilterTable) > 0
			)
		)

		#Options
		self.widget.contextCheck.stateChanged.connect(
			lambda x : self.widget.fetchButton.setEnabled(x > 0)
		)
		self.widget.headerCheck.stateChanged.connect(
			lambda x: self.setIgHeader(x > 0)
		)
78
79
80
		self.widget.plesCheck.stateChanged.connect(
			lambda x: self.setIgPles(x > 0)
		)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
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
		self.widget.quoteCheck.stateChanged.connect(
			lambda x: self.setIgReplies(x > 0)
		)
		self.widget.dupCheck.stateChanged.connect(
			lambda x: self.setIgDup(x > 0)
		)
		self.widget.firstCheck.stateChanged.connect(
			lambda x: self.setIgFirstDup(x > 0)
		)
		self.widget.imageCheck.stateChanged.connect(
			lambda x: self.setIgImages(x > 0)
		)
		self.widget.formatCheck.stateChanged.connect(
			lambda x: self.setIgFormat(x > 0)
		)
		self.widget.spaceCheck.stateChanged.connect(
			lambda x: self.setIgSpace(x > 0)
		)
		self.widget.delimeterEdit.textChanged.connect(
			lambda: self.updateDelim()
		)
		self.widget.dupCheck.stateChanged.connect(
			lambda x: self.widget.dupWidget.setEnabled(x > 0)
		)
		self.widget.dupStrength.valueChanged.connect(
			lambda x: self.widget.dupLabel.setText('%d Words' %(x))
		)

	#call super
	def update(self):
		super(Plugin,self).update()

		#updated from extras
		if 'filters' in self.extras:
			self.widget.emailFilterTable.fromSerial(self.extras['filters'])

	#needed
	def storeOptions(self):
		self.options['logicBox'] =\
			(self.widget.logicBox.text(),'text')
		self.options['selectEdit'] =\
122
			(self.widget.selectEdit.text(),'text')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
123
124
125
126
127
128
		self.options['delimeterEdit'] =\
			(self.widget.delimeterEdit.text(), 'text')
		self.options['contextCheck'] =\
			(self.widget.contextCheck.isChecked(), 'checked')
		self.options['headerCheck'] =\
			(self.widget.headerCheck.isChecked(), 'checked')
129
130
		self.options['plesCheck'] =\
			(self.widget.plesCheck.isChecked(), 'checked')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
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
		self.options['quoteCheck'] =\
			(self.widget.quoteCheck.isChecked(), 'checked')
		self.options['dupCheck'] =\
			(self.widget.dupCheck.isChecked(), 'checked')
		self.options['firstCheck'] =\
			(self.widget.dupCheck.isChecked(), 'checked')
		self.options['imageCheck'] =\
			(self.widget.imageCheck.isChecked(), 'checked')
		self.options['formatCheck'] =\
			(self.widget.formatCheck.isChecked(), 'checked')
		self.options['spaceCheck'] =\
			(self.widget.spaceCheck.isChecked(), 'checked')
		self.options['dupStrength'] =\
			(self.widget.dupStrength.value(), 'value')

		self.extras['filters'] = self.widget.emailFilterTable.serialize()

	#override
	def generate(self):
		if not self.fetched:
			r = self.makeRequest()
			if r < 0:
				return None

		doc = QTextDocument()
		cursor = QTextCursor(doc)

		_c = _b = None
		for message in self.emails:
			_c = cursor.charFormat()
			_b = cursor.blockFormat()
			text = ''
			for part in message.walk():
				typ = part.get_content_type()
				dis = part.get('Content-Disposition')
				if dis != 'attachment':
					if typ == 'text/plain':
						try:
							text = ('<p>'
170
171
172
								+ re.sub(r'(?<=\r)\n',r'<br/>',
								part.get_payload(decode=True).decode('utf-8'))
								+ '</p>'
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
173
174
175
176
177
178
							)
						except UnicodeDecodeError:
							print("Couldn't decode this part")
							continue
					elif typ == 'text/html':
						try:
179
							text = part.get_payload(decode=True) \
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
180
181
182
183
								.decode('utf-8')
						except UnicodeDecodeError:
							print("Couldn't decode this part")
							continue
184
					elif 'image/' in typ and self.igImages is not True:
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
185
186
187
188
189
190
191
192
193
194
195
196
197
						# Embed image
						# print('embed image')
						dis = dis.split(';',1)
						# print(part.get('Content-ID'))
						# print(dis[1])
						if dis[0] == 'inline':
							img = QImage()
							img.loadFromData(part.get_payload(decode=True))
							doc.addResource(
								doc.ImageResource,
								QUrl('cid:'+part.get('Content-ID')[1:-1]),
								img
							)
198
			# print('message converted')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
199
200
			if self.igReplies:
				text = self.stripReplies(message,text)
201
202
			# if self.igPles:
			# 	text = self.stripPleasantries(text)
203
			# print('replies ignored')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
204
205
			if self.igHeader:
				text = self.stripHeaders(message,text)
206
			# print('header ignored')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
207
208
			cursor.insertHtml(text)
			if self.delim != '':
209
210
				cursor.insertHtml('<br/><p>' + chr(2) + '</p><br/><br/>')
			# print('message inserted')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
211
212
213
214
215
216
217
218
219
220
			cursor.insertBlock()
			cursor.setCharFormat(_c)
			cursor.setBlockFormat(_b)

		if self.igFormat:
			cursor.select(cursor.Document)
			cursor.setCharFormat(_c)
			cursor.setBlockFormat(_b)
		if self.igImages:
			doc.setHtml(self.stripImages(doc.toHtml()))
221
			print('images stripped')
222

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
223
224
		if self.igDup:
			doc.setHtml(self.stripDuplicate(doc.toHtml()))
225
			print('duplicates stripped')
226
		# Delimiter (before ples strip in case we accdntly lose a marker)
227
228
229
		doc.setHtml(doc.toHtml().replace(chr(2),self.delim))
		if self.igPles:
			plc = QTextCursor(doc)
230
231
			go = True
			while go:
232
233
				plc.movePosition(plc.EndOfBlock,plc.KeepAnchor)
				text = plc.selectedText()
234
235
236
237
238
239
240
241
				words = [w for w in re.split(r'\s',text) if w != '']
				# Removes things that aren't lists or tables or links
				if (len(words) <= 4 and plc.currentList() is None
					and plc.currentTable() is None
					and text != self.delim
					and not re.search('https?://',text)
					and not re.search('(^|\s).\)\s',text)):
					# print(text)
242
					plc.removeSelectedText()
243
				go = plc.movePosition(plc.NextBlock)
244
			print('pleasantries forgone')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
245

246
247
248
249
		if self.igSpace:
			doc.setHtml(self.collapseSpace(doc.toHtml()))
			print('whitespace stripped')

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
		# print("generated")
		return doc

	def makeRequest(self):
		# make async? or at least talk to the user

		# Logic
		req, r, i = self.widget.emailFilterTable.getRequest(
			self.widget.logicBox.text()
		)

		if not req and r == 2:
			ARCTool.getStatusBar().showMessage(
				"Couldn't find filter label '%s'" %(i)
			)
			self.widget.logicBox.setSelection(
				self.widget.logicBox.text().find(i),len(i)
			)
			return -1

270
271
272
		if req == '':
			req = 'ALL'

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
		# Context
		if self.widget.contextCheck.isChecked():
			b = ARCTool.getContext().getBegin("d-MMM-yyyy")
			e = ARCTool.getContext().getEnd()
			if b:
				req += ' SINCE %s' %(b)
			if e:
				e = e.addDays(1)
				e = e.toString("d-MMM-yyyy")
				req += ' BEFORE %s' %(e)


		protocol = imaplib.IMAP4_SSL if PM.getPreference('Default Package',
														 'emailssl')\
									 else imaplib.IMAP4

		with protocol(
			PM.getPreference('Default Package','emailserver'),
291
			int(PM.getPreference('Default Package','emailport') or 993)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
292
293
294
295
296
		) as M:
		
			passDialog = arcgui.LoginDialog(self.widget)
			try:
				passDialog.credentials.connect(
297
					lambda x, y: M.login(x,y) if not(x==y=='') else print('')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
298
				)
299
				passDialog.exec()
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
300
301
302
303
304
305
306
307
			except:
				ARCTool.getStatusBar().showMessage(
					"Couldn't login to IMAP server."
				)
				return -1

			try:
				ARCTool.getStatusBar().showMessage(
308
					"Selecting mailbox..."
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
309
310
				)
				mailbox = self.widget.selectEdit.text()
311
				mailbox = re.sub(r'(["])',r'\\\g<0>',mailbox)
312
313
				if ((mailbox == '' or mailbox.lower() =='inbox')
					and req == 'ALL'):
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
314
					ARCTool.getStatusBar().showMessage(
315
316
						"Can't select Inbox without at least one filter.",
						5000
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
317
318
					)
					return -1
319
320
				M.select('"'+mailbox+'"' if mailbox != '' else 'INBOX',
					readonly=True)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
321
322
				try:
					ARCTool.getStatusBar().showMessage(
323
324
325
						"Searching %s..." %(
							mailbox if mailbox != '' else 'Inbox'
						)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
326
327
328
329
					)
					typ, data = M.search(None, req)
				except protocol.error as e:
					ARCTool.getStatusBar().showMessage(
330
						"Couldn't search mailbox: "+str(e), 5000
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
331
332
333
					)
				else:
					ARCTool.getStatusBar().showMessage(
334
						"Fetching Messages..."
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
335
336
					)
					self.emails = []
337
338
339
340
341
342
					_ = 1
					nums = data[0].split()
					for num in nums:
						ARCTool.getStatusBar().showMessage(
							"Fetching Message %d of %d..." %(_,len(nums))
						)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
343
344
345
346
347
348
349
						typ, data = M.fetch(num, '(RFC822)')
						self.emails.append(
							email.message_from_bytes(data[0][1])
						)
						id = self.emails[-1].get('Message-ID')
						if id:
							self.emailIds[id] = self.emails[-1]
350
						_ +=1
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
351
352
353
					M.close()
			except protocol.error as e:
				ARCTool.getStatusBar().showMessage(
354
					"Couldn't select mailbox: "+str(e), 5000
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
355
356
357
358
359
360
				)
				return -1

		ARCTool.getStatusBar().showMessage(
			"Fetched %d message%s" %(len(self.emails),
				'' if len(self.emails) == 1 else 's'
361
362
			),
			5000
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
363
364
365
366
367
368
369
		)
		self.fetched = True
		return 0

	def setIgHeader(self, b):
		self.igHeader = b

370
371
372
	def setIgPles(self, b):
		self.igPles = b

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
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
	def setIgReplies(self, b):
		self.igReplies = b

	def setIgDup(self, b):
		self.igDup = b

	def setIgFirstDup(self, b):
		self.igFirstDup = b

	def setIgImages(self, b):
		self.igImages = b

	def setIgFormat(self, b):
		self.igFormat = b

	def setIgSpace(self, b):
		self.igSpace = b

	def updateDelim(self):
		self.delim = self.widget.delimeterEdit.text()

	def stripHeaders(self,message,text):
		text = re.sub('(?P<p><p )?.*?(?:%s):.+(?(p)[^`]*?</p>)\n?'\
			%(self.headers),'',text)
		return text

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
	def stripPleasantries(self,text):
		return text

		# deltas = []
		# blocks = re.split('<br/?>',text)
		# if len(blocks) == 1:
		# 	return text

		# print('enough blocks')
		# for b in blocks[:]:
		# 	_b = re.sub(r'(?s)\s*<.+?>\s*', '',b)
		# 	_b = re.sub('\xa0',' ',_b)
		# 	_b = re.sub(r'&nbsp;',' ',_b)
		# 	if len(re.split(r'\b',_b)) < 4:
				# blocks.remove(b)
		# print(blocks)
		# return ''.join(blocks)
		# breaks = re.findall('<br/?>',text)
		# blockIndex = [
		# 	len(blocks[x]) + len(breaks[x]) for x in range(len(breaks))
		# ] + [len(blocks[-1])]
		# print('block indicies', blockIndex)
		# for i in range(1,len(blocks)):
		# 	blockIndex[i] += blockIndex[i-1]

		# for b in blocks:
		# 	b = re.sub(r'(?s)\s*<.+?>\s*', '',b)
		
		# wc = len(blocks[0])
		# for i in range(1,len(blocks)):
		# 	deltas.append( abs(len(blocks[i]) - len(blocks[i-1])) )
		# 	wc = len(blocks[i])
		# avg = wc/len(blocks)

		# deltaN = sum(deltas) / (2*wc)
		# blockLens = [len(b) for b in blocks]
		
		# if deltaN > avg/max(blockLens):
		# 	asc = 0
		# 	while deltas[asc] < avg:
		# 		asc += 1
		# 	des = len(deltas) - 1
		# 	# Naive approach, should really check to see if other islands exist
		# 	while des > asc and deltas[des] < avg:
		# 		des -= 1

		# 	print('start/stop block index', asc, des)
		# 	text = text[blockIndex[asc]:blockIndex[des]]
		# return text

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
449
450
451
452
453
454
455
456
457
458
	def stripImages(self,text):
		text = re.sub('(?s)<img .+?(?:/>|</img>)','',text)
		return text

	def collapseSpace(self,text):
		# Collapse Spaces
		text = re.sub('\xa0',' ',text)
		text = re.sub(' +',' ',text)

		# Collapse Breaks
459
460
461
462
		text = re.sub(r'(?s)<br>\s*(?:</br>)?','<br/>',text)
		text = re.sub(r'(?s)(?<=>)\s*<br\s*/?>\s*(?=<)', '',text)
		text = re.sub(r'(?s)\s*<span( [^>]+)?>\s*</span>\s*','',text)
		text = re.sub(r'(?s)\s*<p( [^>]+)?>\s*</p>\s*','',text)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
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

		return text

	def stripReplies(self,message,text):
		ids = message.get("References")
		if ids:
			ids = re.split(',| ',ids)
			ids = [i.strip() for i in ids if i != '']
			# print(ids)
			for id in ids:
				if id in self.emailIds:
					# Remove this previous emails content from me
					ref = ''
					for part in self.emailIds[id].walk():
						typ = part.get_content_type()
						dis = part.get('Content-Disposition')
						if dis != 'attachment':
							if typ == 'text/plain' or typ == 'text/html':
								ref = part.get_payload(decode=True)\
									.decode('utf-8')
					# if self.igHeader:
					# 	ref = self.stripHeaders(self.emailIds[id[-2]],ref)

					bodyText = re.search('(?s)<body[^>]*?>(.+)</body>',text)
					bodyRef = re.search('(?s)<body[^>]*?>(.+)</body>',ref)
					if bodyText and bodyRef:
						bodyText = bodyText.group(1).strip()
						container = text.split(bodyText)
						bodyRef = bodyRef.group(1).strip()
						bodyText = re.sub('\xa0',' ',bodyText)
						bodyRef = re.sub('\xa0',' ',bodyRef)
						bodyTags = re.findall(r'\s*<.+?>\s*',bodyText)
						bodyText = re.sub(r'\s*<.+?>\s*',chr(1),bodyText)
						bodyRef = [re.escape(p) for p in \
							re.split(r'\s*<.+?>\s*',bodyRef) if p != '']
						bodyRef = '(?s)' + (chr(1)+'+').join(bodyRef)
						bodyRef = re.sub(r'(\\\s)+',r'\\s+',bodyRef)

						# Search for the original message within the reply
						partial = re.search(bodyRef,bodyText)
						if partial:
							excise = partial.group(0).count(chr(1))
							offset =\
								bodyText[:bodyText.find(partial.group(0))]\
								.count(chr(1))
							bodyText = bodyText.replace(partial.group(0),'')
							bodyTags = (bodyTags[:offset]
										+ bodyTags[offset+excise:])
							# Replace the tags
							for t in bodyTags:
								bodyText = bodyText.replace(chr(1),t,1)
							text = container[0] + bodyText + container[1]
						# We messed up? Impossible...
						# else:
						# 	print(bodyText)
						# 	print('-------vvvvvv------')
						# 	print(bodyRef)
		return text

	def stripDuplicate(self, text):
		num = self.widget.dupStrength.value()
		globs = {}
		body = re.search('(?s)<body[^>]*?>(.+)</body>',text).group(1)
		container = text.split(body)
		tags = re.findall(r'(?s)\s*<.+?>\s*',body)
528
		# Replace tags
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
529
		stripped = re.sub(r'(?s)\s*<.+?>\s*',chr(1),body)
530
		# Replace 
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
531
532
		stripped = re.sub('\xa0',' ',stripped)
		stripped = re.sub(r'&nbsp;',' ',stripped)
533
534
535
		spaces = re.findall(r'(?s)\s+',stripped)
		stripped = re.sub(r'(?s)\s+',r' ',stripped)
		print("stripped")
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
536
		_ = []
537
538
539
		# for word in re.finditer(r'(?:^| )(.+?)(?:(?= )|$)',stripped):
		for word in re.finditer(r'(?:\b)(.+?)(?:\b)',stripped):
		# for word in re.finditer(r'(?:\s)(.+?)(?:\s)',stripped):
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
540
541
542
543
544
545
546
547
			_.append((word.group(1),word.start(1),word.end(1)))
			if len(_) == num:
				hsh = ''.join(x[0].replace(chr(1),'') for x in _).__hash__()
				if hsh not in globs:
					globs[hsh] = []
				globs[hsh].append((_[0][1],_[-1][2]))
				_.pop(0)

548
		print("globbed")
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
549
550
551
552
		chains = []
		ranges = []
		for d in globs:
			if len(globs[d]) > 1:
553
				ranges += globs[d][1 if self.igFirstDup else 0:]
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
554
555
556
557
558
		ranges.sort()
		for r in ranges:
			if len(chains) == 0:
				chains.append([r[0],r[1]])
				continue
559
			if r[0] <= chains[-1][1] and r[1] > chains[-1][1]:
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
560
				chains[-1][1] = r[1]
561
			elif r[0] > chains[-1][1]:
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
562
				chains.append([r[0],r[1]])
563
564
		print("chained")
		# Only remove the text but keep the tags
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
565
		offset = 0
566
		# print('#chains=',len(chains))
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
567
568
569
570
571
572
		for c in chains:
			# Could partition, but I want variable names
			chunk = stripped[c[0]-offset:c[1]-offset]
			head = stripped[:c[0]-offset]
			tail = stripped[c[1]-offset:]
			# print(chunk)
573
574
575
			lh, lt = len(head), len(tail)
			# print(lh, lt, lh-lt)

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
576
577
578
			tagsRemoved = chunk.count(chr(1))
			spaceRemoved = chunk.count(' ')
			offset += len(chunk) - tagsRemoved
579
580
			spaces = (spaces[:head.count(' ')]
					  + spaces[head.count(' ') + spaceRemoved:])
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
581
582

			stripped = head + chr(1)*tagsRemoved + tail
583
		print("excised")
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
584
585
586
587
588

		for s in spaces:
			stripped = stripped.replace(' ',s,1)
		for t in tags:
			stripped = stripped.replace(chr(1),t,1)
589
		print("replaced")
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
590
591

		return container[0] + stripped + container[1]