import pywikibot
import pywikibot.pagegenerators as pg 

bold='\'\'\''
newline='\n'
table_cell_end='||'
commit=True

def action_one_page(p):
  last=['','','','']  
  last2=last3=''
  bold_open=False
  italics_open=False

  oldtxt=p.text
  newtxt=''
  close=[bold,newline,table_cell_end]
         
  for c in oldtxt:
    printit=False
    if ((c==newline) or (last2 in close) or (last3 in close)):
      if (c==newline): 
        last[3]=last[2]=last[1]=last2=last3='' 
        d=' '  
      else: 
        d=c 
      printit=True  
      if (bold_open):
        bold_open=False
        if (c==newline):            
          newtxt=newtxt+bold   #+'√'
        else:
          l=len(newtxt)-2  
          newtxt=newtxt[:l]+bold+newtxt[l:l+2]
      
    
    last[3]=last[2]
    last[2]=last[1]
    last[1]=c

    last2=last[2]+c
    last3=last[3]+last[2]+c
    
    """
    if (c!=newline): 
      d=c 
    else: 
      d=' '  
    print(f'[{d}][{last3}][{last2}][{last[3]}][{last[2]}][{last[1]}][{bold_open}]')
    """    
    
    
    
    if (last3==bold):
       bold_open=not bold_open
       last[3]=last[2]=last[1]=last2=last3='' 
        
    #if (printit): print(f'[{d}][{last3}][{last2}][{last[3]}][{last[2]}][{last[1]}][{bold_open}]')       
    newtxt+=c
         
         
  if (p.text!=newtxt):
    if (commit):
     p.put(newtxt,summary=f'close bold tags')
    else:
     print(newtxt)   
  else:
     print(f'{p.title()} is not changed')
  #print(newtxt)
    

def pages_from_cat(thiscat):
  cat=pywikibot.Category(site,thiscat)
  gen=pg.CategorizedPageGenerator(cat,123)
  for page in gen:
    yield(page)
 
site=pywikibot.Site('nl','wikipedia')
p=pywikibot.Page(site,'IJslands vrouwenvoetbalelftal')
action_one_page(p)
#Wielersport op de Olympische Zomerspelen 2008/mountainbike mannen
#for page in pages_from_cat('Categorie:Mountainbike op de Olympische Spelen'):
#    action_one_page(page)
print('Klaar')
IJslands vrouwenvoetbalelftal is not changed
Klaar