[Question]
  [
What happens when the `CapsLock` key on your keyboard doesn't have a notch in it?
*"This hPPENS."*
The goal of this program is to consistently emulate keyboard misses where each `A` press is replaced with `CapsLock`. Uppercase 'A's from the source should yield the same effect. **When `CapsLock` is enabled, capitalization is reversed.**
# Test Cases
```
"The quick brown fox jumps over the lazy dog."
-> "The quick brown fox jumps over the lZY DOG."
"Compilation finished successfully."
-> "CompilTION FINISHED SUCCESSFULLY."
"What happens when the CapsLock key on your keyboard doesn't have a notch in it?"
-> "WhT Hppens when the CPSlOCK KEY ON YOUR KEYBOrd doesn't hVE  notch in it?"
"The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness."
-> "The end of the institution, mINTENnce, ND dministrTION OF GOVERNMENT, IS TO SECURE THE EXISTENCE OF THE BODY POLITIC, TO PROTECT IT, nd to furnish the individuLS WHO COMPOSE IT WITH THE POWER OF ENJOYING IN Sfety ND TRnquillity their nTURl rights, ND THE BLESSINGS OF LIFE: nd whenever these greT OBJECTS re not obtINED, THE PEOPLE Hve  RIGHT TO lter the government, ND TO Tke meSURES NECESSry for their sFETY, PROSPERITY nd hPPINESS."
"aAaaaaAaaaAAaAa"
-> "" (Without the notch, no one can hear you scream)
"CapsLock locks cAPSlOCK"
-> "CPSlOCK LOCKS CPSlOCK"
"wHAT IF cAPSlOCK IS ALREADY ON?"
-> "wHt if CPSlOCK IS lreDY ON?"
```
The winning criterion is, as usual, the size of the submitted program's source code.
  
[Answer]
# [AutoHotKey](https://autohotkey.com), 7 bytes
```
a::vk14
```
// Is this valid? This really do what OP want -- replace `a` by `CapsLock (vk14)`.
Run this program, and type the input from keyboard..
[Answer]
# [V](https://github.com/DJMcMayhem/V), 9 bytes
```
ò/ãa
xg~$
```
[Try it online!](https://tio.run/##VVA7WoRADO49RQpLPu09hxfIQoCsQzJOAiyNl/EGXmEPhpkFC7t5/O9l3@8/r/dvfLoNX8/7/j4SkHSgPXgcWczZZ2eVBiZkcRKUlhrAAGE3sbB5wQqonEEXKjKReANs4ApG7VzoIUa3wFKw/9Qv2m2QNbFz21RwLurUOrAfBvHUzyUsxjNNxwt3MyaDdVRodcpq8e6wsh@YrCuVakBy1Y1lCBYY9uTbIVlQPmdOYbpVAhcQ9LlggsLD6HY613iJzELBqlzint4eX@tIQlGzYsJ8KIQOerlGcAOMrqL17rEWdc0RijQnghEXAjx8ajdMfsj82@0s7vhBMBFazGcg1EYYLBv0Ws7cR6umrmaZCp8NR8w5rM1efgE "V – Try It Online")
Hexdump:
```
00000000: f22f e361 0a78 677e 24                   ./.a.xg~$
```
Explanation:
```
ò       " Recursively:
 /ãa    "   Move forward to the next 'a' (upper or lowercase)
        "   This will break the loop when there are no more 'a's
x       "   Delete the 'a'
 g~$    "   Toggle the case of every character after the cursor's position.
```
[Answer]
# Vim, 16 bytes
```
qq/\ca
xg~$@qq@q
```
Assumes the input is on a single line
## Explanation
```
qq            Start a loop
 /\ca␊         Find the first occurence of an a, end the loop if there are none left
 xg~$          Remove it and invert the case of the rest of the file
@qq@q         End the loop 
```
[Answer]
# C, 72 bytes
*Thanks to @Ton Hospel for helping to save 16 bytes!*
```
t,c;f(char*s){for(t=0;c=*s++;6305%c?putchar(isalpha(c)?c^t:c):(t^=32));}
```
[Try it online!](https://tio.run/##bVLNbtswDL73KYgCw@zWG4oV2yFBEAS97rYCuxVgZNpWIkuaSCf1ij57RjkO0AHRQZYlkt8Pab60xpxOUpllU5gO0x2Xb01IhawelmZ1x/f3yx@PD98/mXUcJAcUltHFDgtTrs2LLEy5KORl9fitLJfvJ@sFerS@KG/ebkBXU9w@dwR/Bmv2sE3h6KEJr7Ab@sgQDpRA9Nnh3xHq0H69LZegQFzc6ulS4Cn00ToUGzTZessd1cCDMcTcDM6N19N@dyjQYYzkGY4d@QnqCSP/DEpmTyNowTEMKZ@3AVOtHIj955x2IEDwQTWD9WBlfRUjayNfQ2im4tazWBky02ryQcijN1QBahDWfWYv6SxFc9rsgO/JSwWWQQIwmSHRVIxeNZY0@1J9G@oRYnBWrKlycExByIiyOwPoVTOkbNDMprYHWw/osv4ARn0MrPcCRyvnmBiO2gMFIL8Lo/VtVsvYkIznkgm9Ns8p6JgTbAKPMiR0kGzbCc/ImZ7TfmgFzuWcbWgxPWXnaW60greJtC1hu1PiDKha1WT9F3WL6upMikJ0dGnChJO1oZN5Xj76NgsX3BP0hKz2MXjKw4Fp1GlLM@@zqiq7xpGSnRXmCVFo5utThBvUlbfNRj9XY4R@PeP/W359P/0D)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
Γ·§?m\:€"Aa
```
[Try it online!](https://tio.run/##yygtzv7//9zkQ9sPLbfPjbF61LRGyTHx////SuUejiEKnm4KyY4BwTn@zt4KnsEKjj5Bro4ukQr@fvZKAA "Husk – Try It Online")
## Explanation
I'm using the somewhat obscure overloading of `Γ` called `listNF`, which constructs recursive functions that operate on lists.
It corresponds to the following Haskell pattern:
```
listNF f = g
  where g (x : xs) = f g x xs
        g [] = []
```
The idea is that `listNF` takes a helper function `f` and returns a new function `g`, which takes a list.
The function `f` takes a function, which will always be `g`, and the head `x` and tail `xs` of the list, and does something with them.
In our application, `f` calls `g` recursively on `xs`.
The program is interpreted like this:
```
Γ (· (§ (?m\) : (€"Aa")))
Γ (                     )  Create a function g that takes a list (x:xs) and applies a function on x and xs.
   · (                 )   Compose g with second argument of function in parentheses.
                           Instead of x and xs, the function is called on x and the result of a recursive call of g on xs.
                (€"Aa")    Check if x is 'A' or 'a'.
        (?m\)              If it is, then swap the case of every char in g(xs).
      §       :            Otherwise, prepend x to g(xs).
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~33~~ ~~21~~ 17 bytes
```
i(Tv`lL`Ll`a.*
a
```
[**Try it online**](https://tio.run/##TVK9jtswDN79FFyKOxRGgK5diuDWjAfcGsambSayqIpUcr6XTynbB9SDLUvk90dlMo746/nj9dw8@fX9fg6n8ymc8fCzweb5fJ8I/hbubnDJ8ogwyCdcy5wU5E4ZzI8Dfi3Qy3ho3mROHNBYvJAj60Q9aOk6Uh1KCMuh@ZjQYMKUKCo8JoorxBsmPYmT3GgBb16k5Lq@CObesUnjS227EyBEsW4CjsD2p6n6KPYgwwrEUY2tVAUtzMjRKGLsqAX0IuznqsryJtF7xuoizhStBVYwAaWuZFrB6NNrybu/0S/SL5AksHHX1uKUxagzV7IR@NZQcjW@q@n5zn3BUL0KdJ6PqO8bPNi2miQPz9EJKF5l4ThWZ4oD2bJBZow@gOCkS23gDBGtZAyQeZxMd@YqL3jOjqAVLvBAv9ejmjLtw3LyMZOPQC5XF66A7tUD9X/ztKhvN1EkKdB34CtP9YbB9pn/n9tu3PBGMBOqx6cQqQ4d8@I3Ju@6N1dtTU0TZd4d1tvg1KqHBo/oT30dj/75Bw)
**Explanation:**
```
i(              i is for case-insensitive, the paren makes it modify both stages
  Tv`           Transliteration, with simple overlaps (v) - 1 match at every start pos
     lL`Ll`     Replace lowercase with uppercase, and vice versa
           a.*  Every 'a' will match, overlapping to the end of the string
                This swaps the case on all letters after each 'a'
a               Replace all 'a's with nothing
```
*-12 bytes thanks to Martin*  
*-4 bytes thanks to Leo*
[Answer]
# Python, 63 bytes
```
f=lambda s:s and[s[0]+f(s[1:]),f(s[1:]).swapcase()][s[0]in"aA"]
```
Another Python solution, works in Python 2 and 3.
Takes a very long time for all but small inputs.
[Answer]
# [R](https://www.r-project.org/), 92 bytes
```
cat(`[<-`(v<-el(strsplit(scan(,""),"a|A")),w<-c(F,T),chartr("a-zA-Z","A-Za-z",v)[w]),sep="")
```
Thank @Giuseppe for fixing the answer.
**Explanation**
```
# Write
cat(
  # Replace and return, this is the function that powers
  # the R store at index operations, a[i]<-b
  `[<-`(
    # First arg - what to replace = extract first list element
    # of a string input after splitting at a or A
    v<-el(strsplit(scan(,""),"a|A")),
    # Second arg - index to replace = abuse vector recycling
    # to create infinite F, T, F, T, F, etc series
    w<-c(F,T),
    # Third arg - replacement values = replace with case toggled letters
    chartr("a-zA-Z","A-Za-z",v)[w]),
  # Write without separation
  sep="")
```
[Try it online!](https://tio.run/##VVJLbtwwDL0KoZUNyD1AMVlk0xNk1aBAODI9ZipLqkjbddC7T6l4uuhG0Od9CdV75GvFenQL6ZxH6e8BtXt7vQxv3XYZKHaiVUpk7SRg6rxzvXf459n1vd8vQ@i@@Zfehxmr1s7h8PE8fHfe2Wp757f@df/Re6HyZMy7e5kJKI2QJ1DbchJlXZVz8rAgJ6WEKZAHNBCOCye2ANgAjXPLG9W0UFIPLKAZhMJa6VOMfhuWjP1P/ZrHA0q28Bx8A5ealYIC62lgV9NazWJ@pBl543HFKLDPGUJeSha7V9hZT0zJO9VmQOk9H5xuxgLBifQ4JSumXytHMz0agSsk1LVihMq3WeXh3OJFEjEFaXKRJ/r6@bTPlMhqNoyZ3yqhQr6@W3ABtK4pt7PatGj0ZyjKJRLMuBHg6dO6YdRT5r@5PYor/iRYCMXGJ5AoWBj7CDDl@sh9tvJtalKo8qPhjKWYtcgXd/8L "R – Try It Online")
[Answer]
# Java 8, ~~119~~ ~~108~~ 98 bytes
```
s->{int f=0,t;for(int c:s)if((t=c&95)==65)f^=1;else System.out.printf("%c",f<1|t<66|t>90?c:c^32);}
```
-11 bytes thanks to *@OlivierGrégoire*.  
-10 bytes thanks to *@Nevay*.
**Explanation:**
[Try it online.](https://tio.run/##bVRhT9tADP2@X2FV2pZKpYJNIEEpqOo2DY3BtCKNCYHkXpzmyvUuu3NaMuC3d74knUa1qk2bnP3e87PdOS5xxxVk5@n9WhkMAb6ito@vALRl8hkqgot4C7B0OgWVqBz9zS2E7kCePstH3oGRtYILsDCEddg5eZRsyIa7PR5kzifxTh2Frs6ShIfqzeF@dzg82O9md8O9AZlAMKkC06LvSu4XXsKzpPNadXrZ8d4THx8cPPHJ4e6pOlJ37991B8/rQcNblFMjvC19LXAh8pMJC8bs5ha7jXSmwEnnKif4VWp1D1PvVhYy9wDzclEEcEvywHJs8HcFqZv1O3V5m8yxWxTaCImTLG11yCmFUCpFIWSlMdVW/I8cGXIsxNgAq5xsDT7GIpw7ob@nCgSpcqWPv6cOfSqsFOzbmLYkQLCOVS5NAM2nL8FjGWRTcFmNqm1gzWXU1qurZ7JoFfUAJQjTRdTLvhEvObNYrF2Q5R7oAOwgkCo91WD0ILEk2Rv0qUsrKJzRYnAvBhfeMSkWWQ2BPMpKHy1p1aR6qdMSTSzcgRLnnPRXM6w0NzGFW4ndQiBj5yppVCwzYEZcNZAerfTJCGkVE7QHi1x6NOD1LOfQMkd5RjogCCHCGZ3RUX0ULae2p0I@8yT9cNO5CA@AUqu4K/csblHaa0SRKwxt3K95Ym1ouB2Nf31rC2e8J1gQBrEvgKU4DugrGSzf6m6q6kXXQkFetxXG0RDqELbmBkcor3gZjeRrawg342PkEkCNvk3M5fjLy6DV59EVnH36ewpnExidf/84@vATLi@2Jukarx86/9njepHqkGaRZNmbPbJ9lYQ@u7H8B4y8xyrptoDb@2ts0gI/r/8A)
```
s->{                           // Method with char-array parameter and no return-type
  int f=0,t;                   //  Flag-integer, starting at 0
  for(int c:s)                 //  Loop over the characters of the input as integers
    if((t=c&95)==65)           //   If the current character is an 'A' or 'a':
      f^=1;                    //    Toggle the flag (0→1 or 1→0)
    else                       //   Else:
      System.out.printf("%c",  //    Print integer as character
        f<1|                   //     If the flag-integer is 0,
        t<66|t>90?             //     or the current character isn't a letter:
         c                     //      Simply output the character as is
        :                      //     Else (the flag it 1 and it's a letter)
         c^32);}               //      Print it with its case reversed
```
[Answer]
# JavaScript (ES6), ~~93~~ ~~88~~ ~~84~~ 82 bytes
*(saved 5 bytes thanks to @Shaggy, 4 bytes thanks to @user81655, and 2 bytes thanks to @l4m2.)*
```
a=>a.replace(A=/./g,c=>c in{a,A}?(A=!A,''):A?c:c[`to${c<{}?'Low':'Upp'}erCase`]())
```
**Test cases:**
```
let f=
a=>a.replace(A=/./g,c=>c in{a,A}?(A=!A,''):A?c:c[`to${c<{}?'Low':'Upp'}erCase`]())
console.log(f("The quick brown fox jumps over the lazy dog."));
console.log(f("Compilation finished successfully."));
console.log(f("What happens when the CapsLock key on your keyboard doesn't have a notch in it?"));
console.log(f("The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights, and the blessings of life: and whenever these great objects are not obtained, the people have a right to alter the government, and to take measures necessary for their safety, prosperity and happiness."));
console.log(f("aAaaaaAaaaAAaAa"));
console.log(f("CapsLock locks cAPSlOCK"));
console.log(f("wHAT IF cAPSlOCK IS ALREADY ON?"));
```
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 105 bytes
```
"$args"|% t*y|%{if($_-in97,65){$c=!$c}else{Write-Host -n($_,("$_"|%("*per","*wer")[$_-in65..90]))[!!$c]}}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f9fSSWxKL1YqUZVoUSrska1OjNNQyVeNzPP0lzHzFSzWiXZVlEluTY1pzi1OrwosyRV1yO/uERBNw@oSkdDSSUeqFNDSasgtUhJR0kLaLaSZjRYv5mpnp6lQaymZrQi0IDY2tr/QLucEwuKffKTsxVygESxQrJjQHCOv7O3EgA "PowerShell Core – Try It Online")
What with no real ternary operator and no default alias for printing to screen, it's not that short.
* `% t*y` expands to `| ForEach-Object -Method ToCharArray` equiv. of `"$args".ToCharArray()`
* `Write-Host -n` is for the parameter `-NoNewLine`
* `"$_"` turns the `[char]` type back to `[string]` (chars have no upper/lower case in .Net)
* `|% *per` does the same method call shortcut as earlier, but for `.ToUpper()`, same with `.ToLower()`
* `($a,$b)[boolean test]` abused as fake-ternary operator
* `!!$c` force-casts to `[bool]` here it starts undefined `$null` so it gets forced it into existence as "caps lock: $false".
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~31~~ ~~30~~ 29 bytes
-1 byte thanks to [@nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof)
-1 byte thanks to [@ikegami](https://codegolf.stackexchange.com/users/3324/ikegami)
```
#!/usr/bin/perl -p
s/a([^a]*)a?/$1^uc$1^lc$1/egi
```
[Try it online!](https://tio.run/##Fcs9C8IwEIfxr/IfBF9AQgfnDq7uDtLCNT1MaLk7klTplze2y49neYzTfKs1Ozq9euouZ2rdoekXvzFvOH7HWp@BCgKZsWR8AwtKYNzJ8kP9hIlXqGDVJe09KKURo3KW4759GATR4gOiIJb2p1aiSq5X@wM "Perl 5 – Try It Online")
[Answer]
# C, 167 168 158 131 bytes
Thanks for @Martin Ender for the code review: I've switched the stream processing for string processing to help with reusability. Also many thanks to @RiaD and @ceilingcat for their suggestions.
```
c,d;(*t[][2])()={{isupper,tolower},{islower,toupper}};f(char*s){for(d=1;c=*s++;)t[0][1](c)==97?d=!d:putchar(t[!t[d][0](c)][1](c));}
```
[Try it online!](https://tio.run/##RY/LTsMwEEX3@QpX3dhpitpKFQLXIN6fwMLyIozt1FKII3sCgsi/TnCqClZz77lnM7BuAKal66AdtCGHiNr5i@NN8Y8Av3qT0QSV5rREqeROMcrEOLo49L0JFfrWf5qQqkxOKZPTkhK3FI51KCMbrQ9Uiy0HUcbVijOUGyW3igIT4uryVouFvu4HnHWKcoFSq2zk@WwxnibXIXmvXUc/vNNsLAiZdRLlbr9XvMjdWWobg5HGikT3bbylkeWYH@sYI3PjWQsGh9CRDS/SVL@BNrYhd/cPj0/PL3/3zH/AtnUTp/Vr3ba/ "C (gcc) – Try It Online")
# How does it work?
```
/* int c is the input character,
   int d is the Caps Lock flag (1=off, 0=on)  starting as "Off". */
int c, d;
/* array of comparison functions and transformation functions for each state */
(*t[][2])() = {{isupper, tolower}, {islower, toupper}};
f(char *s) {
  /* Loop if we haven't hit the terminator */
  for(d = 1; c = *s++;)
    t[0][1](c) == 97 ?
      /* If tolower(c)=='a' then flip the Caps Lock state */
      d=!d:
      /* Otherwise, convert character according to the following table:
                       Character case
         Caps Lock  UPPER       LOWER
                ON  tolower()   toupper()
               OFF  toupper()   tolower()
      */
      putchar(t[!t[d][0](c)][1](c));
  }
}
```
# Notes
* `s[][]` is where the magic happens: `[][0]` is the comparison function and `[][1]` is the related transformation function for each state.
* `!` is applied to the comparison function to force it into the range [0,1].
[Answer]
# [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) routine (C64), 51 bytes
```
A0 00 84 FE B1 FC F0 2A C9 41 F0 06 90 1A C9 C1 D0 08 A9 80 45 FE 85 FE B0 11
B0 06 C9 5B B0 08 90 04 C9 DB B0 02 45 FE 20 16 E7 C8 D0 D6 E6 FD D0 D2 60
```
Expects a pointer to a 0-terminated input string in `$fc/$fd`, outputs to the screen.
### Commented disassembly
```
 .caps:
A0 00       LDY #$00
84 FE       STY $FE             ; init capslock state
 .loop:
B1 FC       LDA ($FC),Y         ; next char from string
F0 2A       BEQ .done           ; NUL -> we're done
C9 41       CMP #$41            ; compare to 'a'
F0 06       BEQ .isa            ; if equal, toggle capslock
90 1A       BCC .out            ; if smaller, direct output
C9 C1       CMP #$C1            ; compare to 'A'
D0 08       BNE .ctog           ; if not equal, check for letter
 .isa:
A9 80       LDA #$80            ; toggle bit 7 in caps lock state
45 FE       EOR $FE
85 FE       STA $FE
B0 11       BCS .next           ; and go on
 .ctog:
B0 06       BCS .cZ             ; if char larger 'A', check for 'Z'
C9 5B       CMP #$5B            ; compare with 'z'+1
B0 08       BCS .out            ; larger or equal -> direct output
90 04       BCC .tog            ; smaller -> apply capslock
 .cZ:
C9 DB       CMP #$DB            ; compare with 'Z'+1
B0 02       BCS .out            ; larger or equal -> direct output
 .tog:
45 FE       EOR $FE             ; toggle bit from capslock state
 .out:
20 16 E7    JSR $E716           ; output char
 .next:
C8          INY                 ; and loop to next char
D0 D6       BNE .loop
E6 FD       INC $FD
D0 D2       BNE .loop
.done:
60          RTS
```
---
### Example assembler program using the routine:
**[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22caps.prg%22:%22data:;base64,AQgLCOIHnjIwNjEAAACpF40Y0KnYoAggHqup4YX8qQiF/SArCKkIhf1MpQigAITMhP6l/YUCIELx8PuF+yl/ySCwEskN8A7JFNDrpf7QBqUCxf3w4abP8Ap4pNOx0Sl/kdFYpfsgFuemz/AMeKTTsdEJgJHRWKX7yRTwH6T+kfzJDfAJyIT+0K3m/dCpqQCk/sjQAub9kfzmzGCk/tACxv2IhP6wkKAAhP6x/PAqyUHwBpAaycHQCKmARf6F/rARsAbJW7AIkATJ27ACRf4gFufI0Nbm/dDSYA1JTlBVVD4gAA==%22%7D,%22vice%22:%7B%22-autostart%22:%22caps.prg%22%7D%7D)**
[![screenshot](https://i.stack.imgur.com/fhfI6.png)](https://i.stack.imgur.com/fhfI6.png)
**Code in [ca65](http://cc65.github.io/doc/ca65.html) syntax:**
```
.import caps ; link with routine above
.segment "BHDR" ; BASIC header
                .word   $0801           ; load address
                .word   $080b           ; pointer next BASIC line
                .word   2018            ; line number
                .byte   $9e             ; BASIC token "SYS"
                .byte   "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes
.bss
string:         .res    $800
.data
prompt:         .byte   $d, "input> ", $0
.code
                lda     #$17            ; set upper/lower mode
                sta     $d018
                lda     #<prompt        ; display prompt
                ldy     #>prompt
                jsr     $ab1e
                lda     #<string        ; read string into buffer
                sta     $fc
                lda     #>string
                sta     $fd
                jsr     readline
                lda     #>string        ; call our caps routine on buffer
                sta     $fd
                jmp     caps
; read a line of input from keyboard, terminate it with 0
; expects pointer to input buffer in $fc/$fd
; NO protection agains buffer overflows !!!
.proc readline
                ldy     #$0
                sty     $cc             ; enable cursor blinking
                sty     $fe             ; temporary for loop variable
                lda     $fd
                sta     $2              ; initial page of string buffer
getkey:         jsr     $f142           ; get character from keyboard
                beq     getkey
                sta     $fb             ; save to temporary
                and     #$7f
                cmp     #$20            ; check for control character
                bcs     prepout         ; no -> to normal flow
                cmp     #$d             ; was it enter/return?
                beq     prepout         ; -> normal flow
                cmp     #$14            ; was it backspace/delete?
                bne     getkey          ; if not, get next char
                lda     $fe             ; check current index
                bne     prepout         ; not zero -> ok
                lda     $2              ; otherwise check if we're in the
                cmp     $fd             ;    first page of the buffer
                beq     getkey          ; if yes, can't use backspace
prepout:        ldx     $cf             ; check cursor phase
                beq     output          ; invisible -> to output
                sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and clear 
                and     #$7f            ;   cursor in
                sta     ($d1),y         ;   current row
                cli                     ; enable interrupts
output:         lda     $fb             ; load character
                jsr     $e716           ;   and output
                ldx     $cf             ; check cursor phase
                beq     store           ; invisible -> to store
                sei                     ; no interrupts
                ldy     $d3             ; get current screen column
                lda     ($d1),y         ; and show
                ora     #$80            ;   cursor in
                sta     ($d1),y         ;   current row
                cli                     ; enable interrupts
                lda     $fb             ; load character
store:          cmp     #$14            ; was it backspace/delete?
                beq     backspace       ; to backspace handling code
                ldy     $fe             ; load buffer index
                sta     ($fc),y         ; store character in buffer
                cmp     #$d             ; was it enter/return?
                beq     done            ; then we're done.
                iny                     ; advance buffer index
                sty     $fe
                bne     getkey          ; not zero -> ok
                inc     $fd             ; otherwise advance buffer page
                bne     getkey
done:           lda     #$0             ; terminate string in buffer with zero
                ldy     $fe             ; get buffer index
                iny
                bne     termidxok       ; and advance ...
                inc     $fd
termidxok:      sta     ($fc),y         ; store terminator in buffer
                inc     $cc             ; disable cursor blinking
                rts                     ; return
backspace:      ldy     $fe             ; load buffer index
                bne     bsidxok         ; if zero
                dec     $fd             ;   decrement current page
bsidxok:        dey                     ; decrement buffer index
                sty     $fe
                bcs     getkey          ; and get next key
.endproc        
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~42~~ 41 bytes
```
->s{s.sub!(/a(.*)/i){$1.swapcase}?redo:s}
```
[Try it online!](https://tio.run/##jVJNb5tAFLz7V0xRrdqVQ9RrJMei2K5RUBwFu5FrcVjDUjYhu5QHcWiS3@4@qLHanrqHtx8zb2Z2tUW1qw/J@HB2SS9kU7V7NzgXA/vj8FwNX95/smkv8kiQfJsUMjYX9HbY9oCttUolflQqesCuMHuNxDzjvnrMCeZJFigZzsTPGrH5blsj/Bf/2wbT5RfbCkethWsec5WJUhmmK60olTGoiiJJlFRZVrPwkbTylteYe9desJhNEaxddxYE87Xvb05qd6kokYo8l5qwT6VuPV2Rk2841YOswT61qYpmvTOiiDm8JP2haXuSENCmjFIoDVVO2PouXWHxr95NkC3dK1zNNuBIm@X6tll/Xv6p9nWGv7WOEYUjeDTFcXhii9NTdDEzLoTI@W3T3P9o6HMJOvuubb9wVvDmJz68AI5/O3OmTbrmDvtFCZWcYjOeFfKIhr3QloJTxgavSudVOYJ8zmVUyviV9aPMaIkxWsiOUlGQfW@UZqiQVGUlY8m2RUM@44lgDfo0RJ9wdsnVQh/bThLjcdc3gZULYvgCViJUxh@oNbOVpoY8OhK7fdiTOj78Ag "Ruby – Try It Online")
A lambda accepting a string, mutating the string in place, and returning it. The trick here is that `sub` returns the string (a truthy value) if a substitution was made, and returns `nil` otherwise. The existence of `swapcase` is pretty handy, too.
-1 byte: Replace boolean logic with ternary operator, thanks to [Asone Tuhid](https://codegolf.stackexchange.com/users/77598/asone-tuhid)
```
->s{
  s.sub!(/a(.*)/i){     # Replace "a" followed by anything with
    $1.swapcase         #   the case-swapped capture group
  } ? redo              # If a match was found, restart the block
    : s                 # Otherwise, return the modified string
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
Œu=”Aœp⁸ŒsJḤ$¦
```
[Try it online!](https://tio.run/##VVC7UcRADG1FAaGHApghICWmAZ0t2zrW2mUln3EGLRwxGUMNFzNzhXCNGC02Adl@3n9PIczLcj6Ot5eX97vzW7q8ns5Hvf8@fVx9fS7L8tATkDQQWzA/sqixjcZRKhiQxUhQaqoAHYTNwMJqGQugcLp4oCwDiVXAChZBqR4z/YrRs2PJ2X/qu9jMkGJg47oq4JSjUW3Athr4Uztmt@i3NA0fuBkxKEx9hDoOKaq/G0xsKybFiXIxINnHmaVzFii2ZPMqmVGeRg5uOhcCZxC0MWOAzF1vujmXeIFUXUGLXOCWbn6/pp6EvGbBuHmXCQ3ibu/BFdC7Six387WoqdZQFFMg6PFAgKtP6YbBVpl/u23FDR8JBkL1@RSEag@DeYY25i332qoqq2mizFvDHlNya9XrHw "Jelly – Try It Online")
Full program.
Explanation:
```
Œu=”Aœp⁸ŒsJḤ$¦ Arguments: x
Œu             Uppercase x
  =”A          ^ Equals 'A' (vectorizes)
     œp⁸       ^ Partition ⁸ [⁸=x]
             ¦ Apply link A, keep results at specific indices B
        Œs     A: Swap case
            $  B: Form a >=2-link monadic chain
          JḤ      Arguments: y
          J       Get list indices ([1, length(list)]) of y
           Ḥ      Double (vectorizes) ^
                  This way, we only "apply" link A to even indices, so every second
                  element, starting from the secondd one.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
õ?„AaS¡Dvć?š
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8Fb7Rw3zHBODDy10KTvSbn904f//4RmJJQoZiQUFqXnFCuUZqXkKJRmpCs6JBcU@@cnZCtmplQr5eQqV@aVFIHZSfmJRikJKfmpxnjpIW1mqQqJCXn5JcoZCZp5CZok9AA "05AB1E – Try It Online")
**Explanation**
```
õ?             # print an empty string (to account for the special case of only A's)
  „AaS¡        # split on occurrences of "A" or "a"
       D       # duplicate
        v      # for each element in the top copy
         ć?    # extract and print the head of the other copy
           š   # switch the case of the rest of the other copy
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 70 bytes
```
#//.{x___,"a"|"A",y___}:>Join[{x},ToUpperCase@#+ToLowerCase@#-#&@{y}]&
```
[Try it online!](https://tio.run/##NY69DoIwFEZf5aYkOIi6G38wbMbBQeNAGnLFmjaEe0lbBYI8e8XB7TvDd3Jq9FrV6E2J4fmibYhWq@XQFUWRCBQfcRBJP8G43h3ZUD50Y3Lha9Mom6FTaTS/8InbPy2iOB36UcbhbA35XAjY7GDy5plGi6VX1uXiptGDxklCDlqtCKYGyLBxJy4rqFQPTNDzy/72ndE@4MHK0ex3eytAIPalBkNg/F5IKcMX "Wolfram Language (Mathematica) – Try It Online")
Takes input and output as a list of characters. For convenience I've added code in the footer to convert this from and back to a string.
# How it works
The `#//.{x___,"a"|"A",y___}:>Join[{x},`...`{y}]&` part is standard: we find the first `A` (uppercase or lowercase), reverse case of that comes after the `A`, and repeat until there are no more `A`'s to be found.
The interesting part is how we reverse case: the function `ToUpperCase@# + ToLowerCase@# - #&`. We add together the upper-cased version of the input and the lower-cased version of the input, then subtract the actual input. For example, given the list `{"I","n","P","u","T"}` this computes
```
{"I","N","P","U","T"}+{"i","n","p","u","t"}-{"I","n","P","u","T"}
```
which threads over lists as
```
{"I"+"i"-"I","N"+"n"-"n","P"+"p"-"P","U"+"u"-"u","T"+"t"-"T"}
```
and although Mathematica doesn't have any particular way of adding two strings, it's smart enough to simplify `a+b-a` to `b` for any values of `a` and `b`, including string values, so this simplifies to `{"i","N","p","U","t"}`.
[Answer]
# [PHP](http://php.net) ~~101~~ 99 bytes
```
for($s=$argn;$i<strlen($s);$i++)lcfirst($s[$i])==a?$s=strtolower($s)^strtoupper($s)^$s:print$s[$i];
```
Run like this:
```
echo '[the input]' | php -nR '[the code]'
```
Ungolfed:
```
for ($s = $argn; $i < strlen($s); $i++) {
    if (lcfirst($s[$i]) == 'a') {
        $s = strtolower($s) ^ strtoupper($s) ^ $s; // Flip the whole string's case.
    } else {
        print $s[$i]; // Print the current letter.
    }
}
```
This just loops through the string with a for loop, and on each iteration it checks if the current letter is `a`, if so, then flip the case of the whole string (method from [here](https://stackoverflow.com/a/6612519/3088508)), and if not, then print the current letter.
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 307 bytes
```
CHARACTER(999)F,G
G=' '
READ(*,'(A)')F
N=1
M=1
DO I=1,999
IF(F(I:I)=='a'.OR.F(I:I)=='A')THEN
M=-M
ELSEIF(M==1)THEN
G(N:N)=F(I:I)
N=N+1
ELSE
J=IACHAR(F(I:I))
SELECTCASE(J)
CASE(65:90)
G(N:N)=ACHAR(J+32)
CASE(97:122)
G(N:N)=ACHAR(J-32)
CASE DEFAULT
G(N:N)=F(I:I)
ENDSELECT
N=N+1
ENDIF
ENDDO
PRINT*,TRIM(G)
END
```
[Try it online!](https://tio.run/##XY7BjoMgEIbv8xTegFabxaa7wYQDkcFiFDfIPoCHtrc2afr@LpW6yfbAwMz/zc9/vt0f9@laXM7pMc/1UXlVB/RUCMFM3kAjSUbAo9J0kxOqGGEGnOTQx6OHzEqeRxasoYbayjIpyUR2g9/9tYqwcEQXN4oesBsxsr2UPE0b6irHZKKjs9vyBYJWWvXM8/JlMGKHdajViLRlsNyfh0p8sNUj4e12X75k8VXxsnzXi1XPNBr104W3DOh0@mpN47Q1z6oH@PbWhU0evO1ps6Dz/DiNYfpffgE "Fortran (GFortran) – Try It Online")
Since Fortran has not "advanced" tools for dealing with strings, I came up with this little monster.
Indented and commented:
```
CHARACTER(999)F,G	!Define input and output strings (up to 999 characters)
G=' '			!Fill output with spaces
READ(*,'(A)')F		!Take input
N=1			!Represent the position to be written in output string
M=1			!M=-1: Change case; M=1: Do not change case
DO I=1,999
	IF(F(I:I)=='a'.OR.F(I:I)=='A')THEN	!If the character is A...
		M=-M				!Ah-ha - you pressed cPS-LOCK!
	ELSEIF(M==1)THEN			!Case the character is not A, and do not need to change case...
		G(N:N)=F(I:I)			!...only copy the character
		N=N+1
	ELSE !Otherwise...
		J=IACHAR(F(I:I))			!...get ascii of current character
		SELECTCASE(J)
			CASE(65:90)			!If is upper case,
				G(N:N)=ACHAR(J+32)	!now is lower case
			CASE(97:122)			!If is lower case,
				G(N:N)=ACHAR(J-32)	!now is upper case
			CASE DEFAULT			!If do not belong to alphabet,
				G(N:N)=F(I:I)		!simply copy the character
		ENDSELECT
		N=N+1
	ENDIF
ENDDO
PRINT*,TRIM(G) !Trim out trailing spaces
END !That's all folks!
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~23~~ 20 bytes
```
'a A'Yb&Ybt2L)Yo2L(g
```
[Try it online!](https://tio.run/##TVJNb9RADL3zK3xqQIp6WIkDCLGNWlArVhTRHsgBqd7ESbydzISxs2n484tnExA5TDT@eM/veXpUd3q6evvx6t2H8mJbbn@eMoQiK/cX5V43uzdl2Oxet6ebzY/bU/bYEfwauXqGfQyThya8wGHsB4FwpAhqaYe/Z6hDe5m9yq5DP7BD5WCl7Fk6qkHGqiKRZnRuTkUJk3wNoTn3sxdlHVNPDj2yV/LoK8oBrQjrPuFoXECtp03MvievObCABhCqxkhnMHqxWrLuv@j7UM8wBMfKVZ6KhxiUKgXWhcBCzRjTqOs0NR@5HtEJTF2AyhQFsbjCxLrUDGEy7UZA/hBm9q11gWBDOi@QEb2Z5ox0Tg0cwaOOER1EbjuVlTmN58wZQ5AE57ih9@fU1JGn1WAjbyOhQtgfbHABNK0@pLuaW1Tny1AUBkfQ4ZEAF56kDZ2ue/rft1W44jNBTyhmn4CntCaMs205rnMvqvLkmgwUeVXY4TAYtUjaJxZoXzqKwn7pGeAgu2CPxtkhUBXfHtz99RfLTLfFI9x9/heCuwcodt8/FTcl3H/dZn8A "MATL – Try It Online")
### Explanation:
```
'a A'Yb   % form a cell array containing {'a', 'A'}
&Yb       % split input into substrings, with either of those ('a' or 'A') as delimiters
t2L)      % extract out the even positioned cells from that result
Yo        % switch the case of those substrings
2L(       % place the result back in even positioned cells of the original cell array
g         % convert cell array to matrix, concatenating all substrings in the process
          % implicit output
```
---
Older answer (23 bytes):
["H@'aA'm?~XHx}@w~?Yo]&h](https://tio.run/##TVJNb9QwEL3zK0YcmkvEAakHECIbtVRbUVFEe@geVmI2mSTeOrbxTDYbJPrXt@NNQOTgyPPx3rw37lHs6efq8vPqw6fNRbEptqe361WGZdYXL0/r45/V@FJs/PaiO2231@@f1qfssSP4NZjqGXbRjw4af4T90AcGf6AIommLvyeoffsue5Nd@T4Yi2K8lhpnuKMaeKgqYm4Ga6dUlDDJ1eCbc79xLEaG1JNDj8YJOXQV5YBahHWfcCTOoNrTJmbXk5McDIN4YKqGSGcwOmotafdf9J2vJwjeGjFVnopD9EKVgJGZQEPNENOoyzS1OZh6QMswdh4qVeRZ4wKjkbkm@FG1KwG5vZ@Ma7ULGBuSaYaM6NQ0q6RTajARHMoQ0UI0bSe8MKfxrDqjCJzgrGno4zk1duRoMVjJ20go4Hd7HZwBVavz6S7qFtX5PBT5YAk6PBDgzJO0oZVlT//7tggXfCboCVntY3CU1oRx0i3HZe5ZVZ5c40DRLAo7DEGpmdM@sUT90lGW@kvPAAPfeX00Vg@Gqvz@YO@vvmpmXJePcHvzLwS3D1De/fhSXm/g/luRvQI)
Other methods I tried: 
```
0w"@t'aA'm?x~}y?Yo]w]]xv!
t'aA'mXHYsot&y*XzcYowf([]H(
t'aA'mXHYsoy3Y2m*32*Z~c[]H(
```
[Answer]
# [Julia 1.0](http://julialang.org/), 82 bytes
```
s->foldl((b,c)->c∈"aA" ? !b : (print(c+32isletter(c)sign('_'-c)b);b),s,init=1<0)
```
## Explanation
### De-golfed:
```
function f(s::String)::Bool
    foldl(s, init=false) do b, c
        if c ∈ "aA"
            return !b
        else
            print(c + 32 * (isletter(c) & b) * sign('_'-c))
            return b
        end
    end
end
```
`foldl(f, s, init=false)`: takes a function `f` that maps a state and a `Char` `c` to a new state. Applys `f` repeatedly over each `Char` of the string `s`, always passing the state previously returned by `f` back to `f`. `init` is the initial state. Here the state represents whether caps-lock is on.
`if c in "aA"`: If `c` is an upper- or lowercase `'a'`, just return the opposite state.
`isletter(c) & b`: `Bool`, returns true iff `c` is a letter and `b` indicates, that caps-lock is on.
`sign('_'-c)`: `-1` if `c` is lowercase, `1` if `c` is uppercase.
`print(c + 32 * (isletter(c) & b) * sign('_'-c))`: `Bool`s act like 0/1 under simple arithmetic operations, so if caps-lock should have an effect, this either adds or substracts 32 from `c`, returning a `Char` with opposite case. Then just print that.
[Try it online!](https://tio.run/##ZVLNbtNAEL73KYZcYgsHUbgV2soKICoqimglxAmN1@N4k82u2RkncZ@gz8mLhNnERaj1YW3vznx/O8veWTzd7ZvzPc8umuBql2VVYfLZhfnz8DDBcgKX8KKCM8i6aL1k5uXbN5YdiVDMTM524bPpr@nM5FX@rsoLLqy3cn76/nW@b7LJXUvwu7dmBVUMWw9N2MGyX3cMYUMRRI8d3g9Qh8WrSX5y4HA@y0@0dx7WnXUoNmifonJLNXBvDDE3vXPDs44fLQq02HXkGbYt@QPBHDu@DiphRQMo1hD6mL6rgLFWZmI/TW0bAgQfxLRgPVi5fAqfzJCvITQHXOtZrPRJXwFr1ELy6A0VgFqE9Tpplng0oD2LZNmvyUsBlkECMJk@0gGMdlpL2v2IXoV6gC44K9YUqbiLQciICjsS6FbTxxTLqKa2G1v36JL1AEbTC6z7Alsrx5oubDV0JSC/DIP1i2SUsSEZjpARvd6WU9IhNdgIHqWP6CDaRSs8Mid5Tm9BETjBOdvQ2eEohU7jzSr5IpLeSKiWKpwB1avmq/@iaVFdHEVR6Bw95n/gSd7QyTgg/@c2GhdcEawJWeNj8JRGAuOg4xVH3UdXRUqNO4p2dJiGQ6mZn80OlqhPWspSX8@G8XGInC4Mpvx2627mX56WbT@Xd3D16d85XN1Cef39Y/nhJ9x81Yna/wU "Julia 1.0 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `s`, ~~12~~ ~~10~~ 9 bytes
*Saved 2 bytes by using `ṡ` to split the string with a regex.*
*Saved 1 byte by using `⁽` to define the function.*
```
`a|A`ṡ⁽Nẇ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%60a%7CA%60%E1%B9%A1%E2%81%BDN%E1%BA%87&inputs=The%20end%20of%20the%20institution%2C%20mAintenance%2C%20and%20administration%20of%20government%2C%20is%20to%20secure%20the%20existence%20of%20the%20body%20politic%2C%20to%20protect%20it%2C%20and%20to%20furnish%20the%20individuals%20who%20compose%20it%20with%20the%20power%20of%20enjoying%20in%20safety%20and%20tranquility%20their%20natural%20rights%2C%20and%20the%20blessings%20of%20life%3A%20and%20whenever%20these%20great%20objects%20are%20not%20obtained%2C%20the%20people%20have%20a%20right%20to%20alter%20the%20government%2C%20and%20to%20take%20measures%20necessary%20for%20their%20safety%2C%20prosperity%20and%20happiness.&header=&footer=)
Explanation:
```
           # Implicit input
`a|A`ṡ     # Split string every instance 'a' OR 'A'
      ⁽N   # Define a function that swaps the casing of strings
        ẇ  # Apply the function to every 2nd string
           # 's' flag: concatenate top of the stack and print
```
[Answer]
# [Haskell](https://www.haskell.org/), 92 bytes
```
import Data.Char
g x|x<'['=toLower x|1>0=toUpper x
f(a:b)|elem a"aA"=f$g<$>b|1>0=a:f b
f x=x
```
[Try it online!](https://tio.run/##HcpBC8IgGAbgu7/iQ4TVJeo65iDWra6dOr2WbpJOMSGD/XdbHR94Jrye2rlarY8hZTohYzdMSGykspSuuTUyh0t467T60O9XXWP8iZkNWrVdtNOewHHk0oixE736P7SGFDNUZKkedpYx2TkLw8/6owLSg@7IvH4B "Haskell – Try It Online")
## Explanation
First we declare `g` to be the function that maps lowercase to upper case and uppercase to lowercase. This is actually the majority of our bytecount. Then we define the function `f`. If the input to `f` is of the form `a:b` we do
```
f(a:b)
 |elem a"aA"=f$g<$>b
 |1>0=a:f b
```
`a` and `A` match the first pattern and thus we apply `f` to the input with it's case inverted. Otherwise we move `a` out front and apply `f` to `b`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
ω(F·+otm\↕·≠_'a
```
[Try it online!](https://tio.run/##yygtzv7//3ynhtuh7dr5Jbkxj9qmHtr@qHNBvHri////QzJSFQpLM5OzFZKK8svzFNLyKxSySnMLihXyy1KLFEqA0jmJVZUKKfnpegA "Husk – Try It Online")
### Explanation
```
ω(F·+(tm\)↕·≠_'a) -- example input: "Bar, baz and Foo."
ω(              ) -- apply the following, until fixpoint is reached:
          ↕       -- | split string with predicate
           · _    -- | | the lower-cased character
            ≠ 'a  -- | | is not 'a'
                  -- | : ("B","ar, baz and Foo.")
  F               -- | apply the following to the tuple
    +             -- | | join the elements with..
   · (   )        -- | | ..the second element: "ar, baz and Foo."
       m\         -- | | | swap case: "AR, BAZ AND fOO."
      t           -- | | | tail: "R, BAZ AND fOO."
                  -- | : "BR, BAZ AND fOO."
                  -- : "BR, Bz ND fOO."
```
[Answer]
# Rust, 330 bytes
```
fn main(){let mut i=String::new();std::io::stdin().read_line(&mut i);let mut o=vec![];let mut c=false;for l in i.trim().as_bytes(){if*l==65||*l==97{c=!c;}else if c{if l.is_ascii_uppercase(){o.push((*l).to_ascii_lowercase());}else{o.push((*l).to_ascii_uppercase());}}else{o.push(*l);}}println!("{}",String::from_utf8(o).unwrap());}
```
Ungolfed
```
fn main() {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input);
    let mut output_chars = vec![];
    let mut capslock = false;
    for letter in input.trim().as_bytes() {
        if *letter == 65 || *letter == 97 {
            capslock = !capslock;
        } else if capslock {
            if letter.is_ascii_uppercase() {
                output_chars.push((*letter).to_ascii_lowercase());
            } else {
                output_chars.push((*letter).to_ascii_uppercase());
            }
        } else {
            output_chars.push(*letter);
        }
    }
    println!("{}", String::from_utf8(output_chars).unwrap());
}
```
Since this uses bytes instead of chars in the loop, 65 and 97 are the byte values for 'A' and 'a'.
I'm new to Rust, so this might be golfable further.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 16 bytes
```
e/a.*/i_År\l_c^H
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=ZS9hLiovaV/FclxsX2NeSA==&input=IldoYXQgaGFwcGVucyB3aGVuIHRoZSBDYXBzTG9jayBrZXkgb24geW91ciBrZXlib2FyZCBkb2Vzbid0IGhhdmUgYSBub3RjaCBpbiBpdD8i)
---
## Explanation
```
e                   :Recursively replace
 /a.*/i             :RegEx /a.*/gi
       _            :Pass each match through a function
        Å           :  Slice off the first character
         r          :  Replace
          \l        :  RegEx /[A-Za-z]/g
            _       :  Pass each match though a function
             c^     :    Bitwise XOR the character code
               H    :    With 32
```
[Answer]
## PHP 4, 77 76 75
```
foreach(spliti(a,$argn)as$b)echo$a++&1?strtoupper($b)^strtolower($b)^$b:$b;
```
Split into substrings by `A` (case insensitive) then toogle every second case.
[Try it out here](http://sandbox.onlinephpfunctions.com/code/206f5b4a49de3f1343b2b10f0a07614a79caa3b1).
---
Old version
```
for(;a&$c=$argn[$i++];)trim($c,aA)?print($c^chr($f*ctype_alpha($c))):$f^=32;
```
walks over the string and toogles a flag if the current char is `a` or `A` else the char gets toogled depending on the flag and echoed.
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~141~~ 92 bytes
```
	I =INPUT
S	I ANY("Aa") REM . R =REPLACE(R,&LCASE &UCASE,&UCASE &LCASE) :S(S)
	OUTPUT =I
END
```
[Try it online!](https://tio.run/##JYxBC4IwAEbP@is@PJiCdOoUSIjtIJjJpkTHqYOJsYlbhb9@KZ3e44PvGaU7/To55xVIi6puG59tmlXPKMh4EIOSG46gSCmpyywnEU3CMs8YQdjuSP7Af4xxZhGLfe/eNltrS/qkujr3kNxC8nkWyuArhYKVAjmfTan7CZNYoRVW/V527zRfBgxaGHXYbx8BDqVtLzEqjPbyAw "SNOBOL4 (CSNOBOL4) – Try It Online")
Assumes a single line of input.
A whopping 49 bytes saved by [@ninjalj](https://codegolf.stackexchange.com/users/267/ninjalj)!
Line `S` does all the work, explained below:
```
I                    # in the subject string I match the following PATTERN:
 ANY("Aa")           # match A or a and
 REM . R             # match the remainder of I, assigning this to R
 =REPLACE(           # replace the PATTERN above with
          R, ...)    # R with swapped cases.
   :S(S)             # and if there was a match, goto S, else goto next line 
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 12 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ìo'½`║â↨╪U?5
```
[Run and debug it online](https://staxlang.xyz/#p=8d6f27ab60ba8317d8553f35&i=The+quick+brown+fox+jumps+over+the+lazy+dog.%0ACompilation+finished+successfully.%0AWhat+happens+when+the+CapsLock+key+on+your+keyboard+doesn%27t+have+a+notch+in+it%3F%0AThe+end+of+the+institution,+maintenance,+and+administration+of+government,+is+to+secure+the+existence+of+the+body+politic,+to+protect+it,+and+to+furnish+the+individuals+who+compose+it+with+the+power+of+enjoying+in+safety+and+tranquillity+their+natural+rights,+and+the+blessings+of+life%3A+and+whenever+these+great+objects+are+not+obtained,+the+people+have+a+right+to+alter+the+government,+and+to+take+measures+necessary+for+their+safety,+prosperity+and+happiness.%0AaAaaaaAaaaAAaAa&a=1&m=2)
It splits on a regex, and then alternately toggles case. Here's the same program, unpacked, ungolfed, and commented.
```
"a|A"|s split on regex /a|A/
rE  reverse and explode array to stack
W   repeat forever...
p   print top of stack with no newline
:~p print top of stack, case inverted, with no newline
```
[Run this one](https://staxlang.xyz/#c=%22a%7CA%22%7Cs%09split+on+regex+%2Fa%7CA%2F%0ArE%09reverse+and+explode+array+to+stack%0AW%09repeat+forever...%0Ap%09print+top+of+stack+with+no+newline%0A%3A%7Ep%09print+top+of+stack,+case+inverted,+with+no+newline&i=The+quick+brown+fox+jumps+over+the+lazy+dog.%0ACompilation+finished+successfully.%0AWhat+happens+when+the+CapsLock+key+on+your+keyboard+doesn%27t+have+a+notch+in+it%3F%0AThe+end+of+the+institution,+maintenance,+and+administration+of+government,+is+to+secure+the+existence+of+the+body+politic,+to+protect+it,+and+to+furnish+the+individuals+who+compose+it+with+the+power+of+enjoying+in+safety+and+tranquillity+their+natural+rights,+and+the+blessings+of+life%3A+and+whenever+these+great+objects+are+not+obtained,+the+people+have+a+right+to+alter+the+government,+and+to+take+measures+necessary+for+their+safety,+prosperity+and+happiness.%0AaAaaaaAaaaAAaAa&a=1&m=2)
]