Build A XML TextEditor.docx
《Build A XML TextEditor.docx》由会员分享,可在线阅读,更多相关《Build A XML TextEditor.docx(37页珍藏版)》请在冰豆网上搜索。
BuildAXMLTextEditor
BuildinganEclipseTextEditorwithJFaceText
HowtocreateanenhancedEclipseXMLeditorusingJFaceText
AuthorsNote:
Ihadoriginallyintendedtohavethisarticlepublishedexternally.Timeconstraintspreventmefromputtinginthenecessaryefforttoachievethis,butitshouldstillbeaworthwhilereadfortheaspiringEclipseplugindeveloper.
Introduction
JFaceTextisasophisticatedframeworkwhichallowsanEclipseplug-indevelopertobuildtexteditorswithadvancedfeatures,suchassyntaxhighlighting,basiccontentassistanceandcodeformatting.Inmyview,anunderstandingofJFaceTextisveryimportantforEclipsedevelopersbecausemostEclipseplug-insinvolveatexteditorofsomekind.ItisnotaneasyAPItounderstand,butisverypowerful.
IwrotethisarticlebecausefounditdifficulttofinddocumentationonthisimpressiveAPI.Forexample,Istruggledtofindmaterialwhichexplainsthedocumentpartitioningprocessverywell.Ifyoudon'tknowwhatthisisrightnow,don'tworry,sincethisisoneofthemajorareascoveredinthisarticle.
TheartideisbuiltaroundthedefaultexampleXMLeditorprovidedasanEclipseplugindevelopmenttemplate.BeforewetalkinmoredetailabouttheAPIs,letssetthescenebydescribingtheapplicationwearegoingtouse.
Part1:
SettingtheScene
TheApplication
ThefirstlikelystepforanyoneintendingtowriteanEclipseeditorplugin,andaJFaceTextbasededitorinparticular,istocreateanewEclipsePluginDevelopmentEnvironmentwiththeXMLeditorexampleasatemplate.
Youcandothisasfollows:
1.File->New->Project...
2.SelectPlug-inProject
Thenfollowthewizardscreenuntilyougettothe Templates selectionasshownbelow:
Hereyouchecktheboxtocreatetheplug-inusingoneofthetemplates,andselectthetemplatePlug-inwithaneditor.EclipseverykindlygeneratesforyouaworkingXMLeditor,albeitonewhichdoesverylittle.
TheXMLeditorwhichEclipsegenerateslookslikethis:
Ofcourse,yougetallthesourcecode,andthegeneratedapplicationisquitenicelywritten,soitmakesanexcellentstartingpointforlearningthenewtechnology.TheXMLeditorisclearlymorethanjustatexteditor–ithassyntaxhighlighting.What'smissingthough,aresomereallyusefulfeatures:
∙errormarking.Ifwemodifyourdocumentreplacingsomeofthemarkupwithrandomtext,wewantvisualcluesthatthedocumentisnotwell-formed.NormallyEclipsedoesthisbysquigglyredlinesundertheoffendingtext,anerroricononthelefthandruler,andanentryinthe'Problems'view
∙contentassist.We'vegotaDTD,sowhycan'tthetoolusethistofigurewhatbitsoftextyoucouldaddtoaparticularpartofthedocument?
∙acontentoutline.Eclipsetypicallyusesthe'Outline'viewtoprovideavisual(usuallytree-based)representationofourdocument,whichwecanusetonavigateeasilybetweendifferentpartsofthedocument.We'dliketobeabletousethismechanism
∙formattingsupport.Wewantbeabletoformatsomeoneelse's(orourown)messyXMLintoanicelylaidoutdocument.Ideally,weevenwanttobeabletoformatpartofourdocumentinisolation
∙moresyntaxhighlightingoptions.Thebasictexteditoronlyprovidescolourdifferentiationforelementsandattributes.Whatifwewanttorepresentotherpartsofourdocumentinthisway?
Soyouwantallofthesefeaturesandmore,andwhatyouhaveisthebasictexteditorsource,wheredoyougofromhere?
That'swhatthisarticleisallabout.Iamnoexpert.Hopefully,however,Ihavelearntenoughtoknowwhatiseasytoachieve,andgivesomehelpfulindicationsonhowtoaccomplishthemoredifficultbits.
Youcanuse thislinktodownloadthefullsourcecodeonwhichthisarticleisbased.
Part2:
GettingtoKnowJFaceText
TextEditors
TheJFaceTextframeworkisordinarilyusedwithanEclipsetexteditor,forwhichtheabstractbaseclassisa AbstractTextEditor (packageandpluginname).Normally,itwouldbemostconvenienttosubclassTextEditor,whichiswhattheprovidedXMLeditordoesinaclassnamed XMLEditor.
TheEclipseprovided XMLEditor classitselfdoesdoesnotdomuch–itsimplyusesthebaseclassfunctionality,anddelegatesthejobofaddingadditionalfeatures.
publicclassXMLEditorextendsTextEditor
{
privateColorManagercolorManager;
publicXMLEditor()
{
super();
colorManager=newColorManager();
setSourceViewerConfiguration(newXMLConfiguration(colorManager));
setDocumentProvider(newXMLDocumentProvider());
}
publicvoiddispose()
{
colorManager.dispose();
super.dispose();
}
}
Itsfirstdelegateisa SourceViewerConfiguration classinstance,whichisusedtoaddadditionalfeaturestotheeditor'suserinterface.Thesecondisaninstanceofthe IDocumentProvider interface,whichencapsulatesthemechanismforcreatingaJFaceTextrepresentationofthedocumentbeingeditedfromitssource(suchasafileinthefilesystem).Understandinghowtousethe SourceViewerConfiguration andtheDocumentProvider isnecessary,sowewillcoverbothlaterinthearticle.
WewillalsoseethatwhenaddingadditionalfeaturestotheXMLeditor,suchaserrormarkingandcontentoutlining,wewillalsoneedtoaddsomeenhancementstotheXMLeditorclass.
JFaceTextDocuments
WhenworkingwithJFaceText,thedocumentyouareeditingworkswithan IDocument instance.The IDocument containsthetextofyourdocument,andcanbeusedtoqueryitsstructure.The IDocument canalsobeusedtomarkforpositionsinthedocument,whichtheframeworkcanusetostoredocumentpartitioninformationandothermetadata,suchashighlightingranges.We'lllearnmoreaboutdocumentpartitioninglaterinthearticle.Positionsarestoredindocumentsasinstancesofthe Position classorsubclasses.
Yourapplicationprobablywon'toftenneedtouseanythingotherthanthedefaultprovided IDocument implementations.Alltheprovided IDocument implementationsarealsopartition-aware,thatis,canbedividedintonon-overlappingregionsoftext.PartitionsplayanimportantroleinJFacetext,sowewillbecoveringtheminsomedetaillaterinthearticle.
The IDocument interfaceisdesignedtoworkwithoutanyknowledgeofhowitisstored.Thatis,an IDocument instancehasnoknowledgeofwhetherithasbeenloadedfromthefilesystem,fromadatabaseorfromanyothersource.Thejobofcreatingthedocumentinstanceandinitiatingtheprocessthatsetsthedocumentsinitialstateisthejobofthe IDocumentProvider.Eclipseprovidesexcellentoutoftheboxsupportformloadingdocumentsfromthefilesystem,throughthe FileDocumentProvider class.
Wesawwhenintroductingthe XMLEditor classhowthe IDocumentProvider instanceismadeavailabletotheeditor.Wecannotsimplyusethe FileDocumentProvider asis,becausethe FileDocumentProviderhasnoknowledgeofourplugin'spartitioningscheme.
TheXMLeditor'sdocumentproviderremediesthisbyoverridingonlyonemethod– createDocument() -withthefollowingcode:
protectedIDocumentcreateDocument(Objectelement)throwsCoreException
{
IDocumentdocument=super.createDocument(element);
...
returndocument;
}
UnlessyoualreadyknowJFaceText,therewouldbenopointatthisstagedescribingthecodethatgoesinthismethod,excepttosaythatinadditiontotheinheritedbehaviour,itconfiguresthedocument'spartitioningmechanism.Atthisstage,youmaynotbeveryclearonwhatpartitioningis,orhowitworks.SincepartitioningissocentraltothewayJFaceTextworks,wewillnowtalkaboutitinabitmoredetail.
Partitioning
WhenyouopenadocumentwhichusesJFaceText,theframeworkdividesthedocumentintopartitions,thatis,aregionoftextwithinthedocument.Thesepartitionsarenon-overlapping.Thepartitionsarecategorised,sothateachpartitionisassociatedwithaparticular"contenttype".
Theeasiestwaytounderstandpartitioningisbyviewinganexample.Ihaveaddedasimplemechanismtoeasilyprintthedocumentpartitioningtotheconsole,whichIwilldescribelater.Fornow,weareconcernedabouthowthedocumentispartitioned.
Below,wehaveanabridgedversionofthepartitioningforthedocumentshownabove.
Partitiontype:
__xml_pi,offset:
0,length:
21
Text:
xmlversion="1.0"?
>
---------------------------
Partitiontype:
__dftl_partition_content_type,offset:
21,length:
2
Text:
---------------------------
Partitiontype:
__xml_doctype,offset:
23,length:
36
Text:
DOCTYPEworldSYSTEM"cities.dtd">
---------------------------
Partitiontype:
__dftl_partition_content_type,offset:
59,length:
2
Text:
---------------------------
Partitiontype:
__xml_start_tag,offset:
61,length:
7
Text:
---------------------------
Partitiontype:
__dftl_partition_content_type,offset:
68,length:
5
Text:
---------------------------
Partitiontype:
__xml_start_tag,offset:
73,length:
27
Text:
---------------------------
Partitiontype:
__dftl_partition_content_type,offset:
100,length:
4
Text:
--------------------------
Partitiontype:
__xml_start_tag,offset:
104,length:
13
Text:
---------------------------
...restofdocumentuntilend...
Partitiontype:
__xml_end_tag,offset:
1301,length:
8
Text:
---------------------------
Noticeafewthingsaboutthedocument'spartitioning:
∙fromthedocumentoffsetsforeachpartition,wecanseethattheyarenon-overlapping
∙eachpartitionhasapartitiontype.Bydefault,thepartitiontypeis __dftl_partition_content_type.Here,thecontenttypehasnotbeenspecified
∙Ifwescanthroughthelisting,weseethatthereareonlytwootherpartitiontypes:
__xml_tag an