Search code examples
nsis

Select section by variable


!include "MUI2.nsh"
!include "FileFunc.nsh"
!include "LogicLib.nsh"
;---------------------------------------------------------------------------
;---------------------------------------------------------------------------
ShowInstDetails show
RequestExecutionLevel admin
;---------------------------------------------------------------------------
Name "Test"
Outfile "Test.exe"
;---------------------------------------------------------------------------
!insertmacro MUI_PAGE_COMPONENTS
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
;---------------------------------------------------------------------------
!insertmacro MUI_LANGUAGE "English"
;---------------------------------------------------------------------------



LangString DESC_sec1 ${LANG_ENGLISH} "sec1 files"
Section /o "sec1" sec1

SectionEnd

LangString DESC_sec2 ${LANG_ENGLISH} "sec2 files"
Section /o "sec2" sec2

SectionEnd

LangString DESC_sec3 ${LANG_ENGLISH} "sec3 files"
Section /o "sec3" sec3

SectionEnd


Var test
Function .OnInit
  StrCpy $test "sec2"
  !insertmacro SelectSection $test

FunctionEnd

How to select section at runtime by section name? In eample always selected 1st section (think its a bug)

But if i rewrite like this

!insertmacro SelectSection ${sec2}

All works fine...

Is there way to select section by name from variable?

some long text some long text some long text some long text some long text some long text some long text some long text


Solution

  • Sections are accessed by their ID which is a number set at compile time:

    Section "Foo"
    SectionEnd
    Section "Bar" SID_BAR
    SectionEnd
    Section "Baz"
    SectionEnd
    
    Page Components
    Page InstFiles
    
    !include Sections.nsh
    
    Function .onInit
      !insertmacro UnselectSection ${SID_BAR}
    FunctionEnd
    

    If you want to use the display name then you have to manually enumerate the sections:

    Section "Foo"
    SectionEnd
    Section "Bar"
    SectionEnd
    Section "Baz"
    SectionEnd
    
    Page Components
    Page InstFiles
    
    !macro GetSectionIdFromName name outvar
    Push "${name}"
    Call GetSectionIdFromName 
    Pop ${outvar} ; ID of section, "" if not found
    !macroend
    Function GetSectionIdFromName 
    Exch $1 ; Name
    Push $2
    Push $3
    StrCpy $2 -1
    ClearErrors
    loop:
        IntOp $2 $2 + 1
        SectionGetText $2 $3
        IfErrors fail
        StrCmp $3 $1 "" loop
        StrCpy $1 $2
        Goto done
    fail:
    StrCpy $1 ""
    done:
    Pop $3
    Pop $2
    Exch $1
    FunctionEnd
    
    
    !include Sections.nsh
    !include LogicLib.nsh
    
    Function .onInit
      StrCpy $1 "Bar" ; The name we are looking for
      !insertmacro GetSectionIdFromName $1 $0
      ${If} $0 != ""
          !insertmacro UnselectSection $0
      ${EndIf}
    FunctionEnd