text:
Bring out the inner llama of a sentence
Your objective is to take input like
Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good.

and create an array of the indexes of the string where the letters that make up the word "Llama" appear (one of each in order).  For example, let me show the letters pointed at with carets to show the indexes:
Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good.
                                            ^                      ^        ^                            ^        ^

So the array would look like:
[44, 67, 76, 105, 114]

(If your application uses a indexing that's not 0-based, the numbers will look different.  That's fine.)
If the text has no llama, then the array should be empty, nil, null, or undefined.
Any code language is accepted.  This is a code-golf contest, so the least characters win!

Still, which letters should we choose? In your example, could we do {67, 68, 76, 91, 100} - both l's of "actually"?

@Ypnypn Choose the first instances of the letters.  An l was found before, so it doesn't get the second l of actually

@TheWobbuffet You keep changing your username and picture. There was a time when you were "Doorknob" and had his picture. Now, your pic is a sheep. You should change it to a llama.

What about 0-based vs 1-based indexing? Can we just use the indexing used by our language or do all submissions have to conform to one convention (which one)?

@Quincunx The sheep says '42' on it!

@m.buettner I really don't care about that.  Whichever one you want.  Also, which programming languages use 1-based indexing? :P

@TheWobbuffet way too many maths oriented ones :-/ (Matlab, Mathematica, Julia, I don't know about R)... also Lua and Smalltalk. The only one of those relevant to code golfing would be Mathematica though, but probably not for string manipulation tasks.

Do you just want the function that does it or the whole program? Do you want the input/output code as well?

@m.buettner Oh, I see.  Math.

@malik A function that takes input and returns the array, or a variable in a function that can be changed by the programmer and a variable that is set to the array.

Your numbers are wrong btw, should be 44, 67, 76, 105, 114 (as you can see in several answers)

@aditsu Ok, edited.

@m.buettner What makes you think mathematica outperforms at golfing? Compared to MATLAB for instance?

@DennisJaheruddin depends on the task (I know I've seen a few really concise Matlab answers on here), but Mathematica can be really useful for some tasks because it just has built-in support for so many high-level tasks like graph manipulation and combinatorics and image manipulation a d stuff... Also, try searching this site for "mathematica" and "matlab" ;)

@TheWobbuffet — AppleScript counts starting at 1. Like humans do, in fact.

@TheWobbuffet classic APL also starts at 1, although there is a flag to set it to 0. I come from a C background, so 0-indexing makes a lot of sense to me, but after learning APL I must admit that 1-indexing is very nice and overall more intuitive. You should give it a try!

@NicolasBarbulesco So does my 7-year-old cousin who I can't convince he moves his monopoly guy one less amount of times

Is input guaranteed to only have 0 or 1 "llama"s?  If there are two or more llamas, correct output would just be indexes for the first?  Note sure I expect an answer given the age of this, but asking anyway.

CJam - 33
lel"llama"{1$#)_T+:T\@>}/;]___|=*

It gets the 1-based indexes (2 more bytes for 0-based)
Explanation:
l reads a line from the input (replace with q for whole input)
el converts to lowercase
"llama"{...}/ executes the block for each "llama" letter
1$ copies the current string
# finds the index of the letter
)_ increments and duplicates
T+:T adds T (initially 0), updates T and leaves it on the stack
\@ swaps items around, now we have current-T, index, string
> slices the string starting at the index
; pops the remaining string
] gathers the indexes in an array
At this point we have all the 1-based indexes; iff any letter was not found, the array will have duplicates.
___ makes 3 more copies of the array
| (with 2 array copies) removes duplicates
= compares, resulting in 0 if there were duplicates or 1 if not
* multiplies the array 0 or 1 times accordingly

http://sourceforge.net/p/cjam/wiki/Home/ for more info on the language. New to me.

sed, 299+1
Yes, sed can find a llama. No, sed can't do math. This is the longest answer so far, at 299+1 characters, because I had to teach sed to count.
This answer requires a sed with extended regular expressions (sed -E or sed -r). I used OpenBSD sed(1). Input is one string per line. (Therefore, the string may not contain a newline.) Output is a line of numbers, or nothing.
Usage (+1 character for -r):
$ echo 'All arms on all shoulders may ache.' | sed -rf llama.sed
1 2 12 26 30

Source code (299 characters):
s/%/z/g
s/(.*)[Aa]/\1%/
s/(.*)[Mm](.*%)/\1%\2/
s/(.*)[Aa]((.*%){2})/\1%\2/
s/(.*)[Ll]((.*%){3})/\1%\2/
s/(.*)[Ll]((.*%){4})/\1%\2/
/(.*%){5}/!d
s/[^%]/z/g
:w
s/(z*)%/\10 z\1/
s/z*$//
s/z0/1/
s/z1/2/
s/z2/3/
s/z3/4/
s/z4/5/
s/z5/6/
s/z6/7/
s/z7/8/
s/z8/9/
s/([0-9]z*)z9/z\10/g
s/(z*)z9/1\10/
/[%z]/bw

The program first replaces the llama with five %. (All % in this program are literal.) The first command s/%/z/g changes any % to z in the input line. The next five commands find the llama, so All arms on all shoulders may ache. becomes A%% arms on %ll shoulders %ay %che. Because each .* is greedy, I always finds the llama on the right: llama llama would become llama %%%%%. If I can't get five %, then /(.*%){5}/!d deletes the input line and skips the next commands.
s/[^%]/z/g changes every character but % to z. Then I enter a loop. s/(z*)%/\10 z\1/ changes the first % to 0, copies zero or more z from left to right, and adds one more z to right. This is so the number of z will equal the index. For example, zz%zzz%... becomes zz0 zzzzzzzz%... because the first % was at index 2, and the next % is at index 8. s/z*$// removes extra z from the end of the string.
The next eleven commands count z by removing each z and counting up from 0. It counts like zzz0, zz1, z2, 3. Also, 1zzzz9 becomes z1zzz0 (later 23), or zzzz9 becomes 1zzz0 (later 13). This loop continues until there are no more % or z.

+1 for teaching sed to count. It is easier to teach a llama to count than sed.

Perl, 52 bytes
The solution is provided as function that takes the string as argument and returns a list of positions.

One-based positions, case-sensitive search, without newlines: 52 bytes
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/;@+[1..$#+]}

The case-sensitive search returns an empty array in the example of the question, because after matching the first three letters the lowercase letter m is missing in the input text.
Support of newlines: + 1 byte = 53 bytes
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/s;@+[1..$#+]}

The text can now span several lines.
Case-insensitive search: + 1 byte = 54 bytes
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/si;@+[1..$#+]}

Now the example in the question reports a list of index positions,
they are one-based numbers:
[45 68 77 106 115]

Zero-based positions: + 9 bytes = 63 bytes
sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/si;map{$_-1}@+[1..$#+]}

Result for the example in the question:
[44 67 76 105 114]

Ungolfed:
The latter variant includes more or less the other variants.
sub l {
    # pop() gets the last argument
    pop() =~ /(l).*?(l).*?(a).*?(m).*?(a)/si;
    # the letters inbetween are matched against ".*?",
    # the non-greedy variant of ".*". Thus ".*?"
    # matches only as few as possible characters.
    # The modifier /i controls the case-sensitivity
    # and means ignore case. Without the case matters.
    # Modifier /s treats the string as single line,
    # even if it contains newlines.
    map { $_-1 }   # subtract 1 for zero-based positions
        @+[1..$#+]
    # Array @+ contains the end-positions of the last
    # submatches, and of the whole match in the first position.
    # Therefore the first value is sliced away.
    # @+ is available since Perl 5.6.
}

# test
my @result = l(<<"END_STR");
Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good.
END_STR
print "[@result]\n";

This also assumes that the input is ASCII, or at least not full Unicode. Unless Perl's regexes correctly respect grapheme boundaries these days (they certainly did not back when I had the misfortune of using it.)

@Trejkaz: Unicode does not matter at all here: (a) "llama" is ASCII and its letters does not collide with any non-ASCII Unicode character or its byte representation in UTF-8. (b) With multi-byte encodings in mind, the term "index" in the question would be underspecified. Index can relate to the character position or the byte (storage) position. (c) Supporting any encoding with characters positions would mean, that the encoding should be known and needs to be provided as additional argument.

Your first two solutions print [] and the third prints [    ] for me (the longer ones work correctly). I'm running "perl, v5.8.8 built for msys-64int". Do you have a bug, or does it work on a different version of perl?

@TimS.: [] is correct for the first solution, M is not matched in a case-sensitive search. The question is quite unclear regarding case-sensitivity.

Ok, so [] is acceptable for the first two. But the first three solutions are still not working right for me: if you give it input that should return indexes, it returns [    ]

Here's a golfish example. It's based on your one-based, case-sensitive, without-newline code. sub l{pop=~/(l).*?(l).*?(a).*?(m).*?(a)/;@+[1..$#+]};my@r=l("llama");print"[@r]\n"; And, actually, I can verify that it works generally, just not for my version of Perl. So, don't worry about it, your solution is valid.

@HeikoOberdiek even if you completely ignore encodings (because I was talking about the character set, technically) - if the last "a" you match is followed by a U+0308 combining diaresis then it is arguably no longer an "a" the same letter and shouldn't be considered a match. By the same token, if ä as a single character appears, that would not be considered a match, so I would say that in the presence of Unicode, this algorithm is at best inconsistent (and at worst, complete rubbish.)

@Trejkaz: a + U+308 in UTF-8 is the byte sequence 0x61 0xCC 0x88. And this is string aÃà in Mac OS Roman and a would be correctly matched. The question does not specify an encoding. What do you expect from an code golf program to handle an unspecified and unknown encoding? Analyzing all thinkable and unthinkable encodings and calculate the result for each possible encoding assumption?

@HeikoOberdiek Irrespective of the encoding, an ä should not match, because it is not an a. That's exactly the incorrect behaviour I am pointing out. I'm glad you have finally noticed the bug. :)

@Trejkaz: There is no bug, only an underspecified question.

Fortran - 154 148
Fortran sucks at golfing, but just to prove that parsing strings can be done in a math-based language, I did it:
function f result(r);integer::r(5),j=1;do i=1,len(s);if(s(i:i)==a(j:j).or.s(i:i)==b(j:j)) then;r(j)=i;j=j+1;endif;enddo;if(any(r==0))r=0;endfunction

I saved a few characters by eliminating the not-required f at the end of endfunction and used if(any(r==0)) instead of if(.not.all(r>0)).
This requires:

s to be the string with text
a to be the lower-case test (i.e., llama)
b to be the upper-case test (i.e., LLAMA)

The full, un-golfed program is
program find_llama
   character(len=123) :: s = "Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good."
   character(len=5) :: a="llama",b="LLAMA"

   print *,f()
 contains
   function f result(r)
     integer::r(5),j=1
     do i=1,len(s)
        if(s(i:i)==a(j:j).or.s(i:i)==b(j:j)) then
           r(j)=i
           j=j+1
        endif
     enddo
     if(any(r==0)) r=0
   end function
end program find_llama

Modern Fortran is at least allowed on the pitch & putt areas. FORTRAN IV would still be playing crazy golf.

@ClickRick: Fortran IV is something I have not learned. Not sure that I want to. Something about forced indentation and capitalization disturbs me.

Ruby, 56 65 63
Edit: +9 characters so that it is case-insensitive.
Defines a function (lambda, technically) f.
f=->s{i=0;'LLAMA'.chars.map{|c|i=s.upcase.index(c,i+1)||break}}

Returns nil if there is no llama. If it has to be [] (empty array), then just add ||[] before the last } for a total of 4 extra characters.
Readable version:
innerLlama = -> str{
    index = 0;
    str.downcase!
    arr = 'llama'.each_char.map{|char|
        index = str.index(char, index + 1)
        break unless index
    }
    # uncomment this line for empty array on failure
    #arr || []
}

I apologize for editing my question after some time, but I just added that the array, if no llama, can be nil,null,empty, or undefined.

So you did it with a llambda?

@Doorknob would be two bytes shorter by using upcase instead of downcase no?

@dstarh Yep, thanks

Think you can get case-insensitivity a byte cheaper by doing index(/#{c}/i instead of upcase.

This answer fails if the first l of 'llama' is at index 0. One fix is to change i=0 to i=-1, but this costs 1 character. A different fix is to change ,i+1) to i)+1, which causes it to count from 1, but costs nothing.

C# - 119
Takes string, outputs array. Null if no llama in string.
int[]a(string s){var i=0;var o="llama".Select((x,y)=>i=s.IndexOf(x,y>0?i+1:0));return o.All(x=>x>=0)?o.ToArray():null;}

I am impressed.  Way smaller than any of my ideas for this one.  I did find you could make it smaller by initializing i to -1 and putting the .ToArray() on the .Select statement, like so int[]a(string s){var i=-1;var o="llama".Select(x=>i=s.IndexOf(x,i+1)).ToArray();return o.All(x=>x>=0)?o:null;}

C - 53
Compile with:
gcc -D L=\"llama\" -D W=\"Lie\ is\ good.\ \ I\ just\ ate\ a\ bunch\ of\ pies\ early\ this\ morning.\ \ Actually,\ it\ was\ closer\ to\ the\ afternoon.\ \ Mornings\ are\ good.\"

I tested this compile command with cygwin's gcc. Other environments might handle spaces, and other special characters differently.
The 0-based result is stored into array r. Its contents are undefined if there is no llama in the string.

Case-sensitive (53)
i,m,r[5];main(){for(;W[i];i++)W[i]==L[m]?r[m++]=i:i;}
Case-insensitive (58)
i,m,r[5];main(){for(;W[i];i++)(W[i]|96)==L[m]?r[m++]=i:i;}

Python, 100
I am the worst golfer ever. :P
Thanks to @xnor for shaving off 6 bytes.
g,n,o='llama',0,[]
for i in s:
 if g:exec("o+=[n];g=g[1:];"*(i.lower()==g[0])+"n+=1")
o*=len(o)>4

o contains the array after.
EDIT: Fixed.
EDIT 2: len(g) to g, o==5 to o>4 as per @xnor's suggestions.
EDIT 3: @WolframH fixed it.

o*=(len(o)==5) is excellent. It's horrible, but I love it!

I don't think the outer parentheses on that line are necessary. You could save two characters by removing them.

@user2357112 On that second last line? I'll remove 'em.

I assume s is the input string, right? Shouldn't then s.lower be i.lower? However, that doe

@WolframH ah, yes, will fix tomorrow.

that comment should have been: I assume s is the input string, right? Shouldn't then s.lower be i.lower? However, that doesn't work, because after exhaustion of g accessing g[0] is an IndexError. Try replacing the first + with or, maybe that helps.

@WolframH Fixed it :D And it's 8 characters shorter!

You can shorter if len(g) to if g (Python treats the empty string/list as False) and o*=len(o)==5 to o*=len(o)>4

@xnor Thanks :D Editing now.

if lg: is probably meant to be if g:. Could you move the if g: into the exec() and then put the exec on the same line as the for loop?

@WolframH The first is correct, I've tried the second one but with the only way I know to get it to work, it's longer.

@WolframH Thanks for the input/fixing/golfing btw ;D

Python 71
Assumes input in s. Output in o.
F=s.lower().find
o=F('l'),
for c in'lama':o+=F(c,o[-1]+1),
o*=min(o)>=0

Edit: Changed from lists to tuples to save 2 bytes.

Multiplying lists by booleans is fun, isn't it? ;D

I like how you dodge the problem of o needing to start nonempty to take o[-1]. Maybe it's shorter though to just start o as [-1] and later do o=o[1:]? Annoyingly, the initial -1 trips up checking if o contains -1.

@xnor: I don't think the -1-Idea can be made to work. At least, I didn't succeed :-( However, I changed lists to tuples to save 2 bytes. :-)

JavaScript (ECMAScript 6) - 68 Characters
(/((((.*l).*l).*a).*m).*a/.exec(s)||[]).map(x=>x.length-1).reverse()

Assumes that the string to test is in the variable s. If you want to turn it into a function then prepend f=s=> (for an additional 5 characters).
Outputs:
[]

Case Insensitive - 69 Characters
(/((((.*l).*l).*a).*m).*a/i.exec(s)||[]).map(x=>x.length-1).reverse()

Outputs:
[68, 80, 93, 105, 114]

Case Insensitive & First Match - 74 Characters
(/((((.*?l).*?l).*?a).*?m).*?a/i.exec(s)||[]).map(x=>x.length-1).reverse()

Outputs:
[44, 67, 76, 105, 114]

Language Java
 final int[] wordIndexInSentence(String sentence, String word)
  {
    final int[] returnArr = new int[word.length()];
    int fromIndex = 0;
    word = word.toUpperCase();
    sentence = sentence.toUpperCase();
    for (int i = 0; i < word.length(); i++)
    {
      final char c = word.charAt(i);
      returnArr[i] = sentence.indexOf(c, fromIndex);
      fromIndex = returnArr[i] > 0 ? returnArr[i] + 1 : fromIndex;
    }
    return returnArr;
  }

Rebol, 97
f: func[s][a: copy[]foreach n"llama"[if none? s: find s n[return[]]append a index? s s: next s]a]

Usage example in Rebol console:
>> f "Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good."
== [45 68 77 106 115]

>> f "nearly llami"
== []

>> f "Llama"
== [1 2 3 4 5]

>> f reverse "llama"
== []

Rebol uses 1-based indexing.  Returns empty list [] if no llama sequence found (case insensitive).
Ungolfed:
f: func [s] [
    a: copy []
    foreach n "llama" [
        if none? s: find s n [return []]
        append a index? s
        s: next s
    ]
    a
]

Python 100
import re
x=input()
print[re.search(r"l.*?(l).*?(a).*?(m).*?(a)",x,re.I).start(i) for i in range(5)]

Sample:
in  = Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good.
out = [44, 67, 76, 105, 114]
in[out] = ['l', 'l', 'a', 'M', 'a']

Haskell, 111
import Data.Char
l i(a:as)t@(b:bs)|a==b=i:l(i+1)as bs|True=l(i+1)as t
l _ _ _=[]
r s=l 0(map toUpper s)"LLAMA"

Ungolfed:
import Data.Char

llama :: Int -> String -> String -> [Int]
llama i (a:as) t@(b:bs)
  | a==b      = i : llama (i+1) as bs
  | otherwise = llama (i+1) as t
llama _ _ _ = []

runme :: String -> [Int]
runme s = llama 0 (map toUpper s) "LLAMA"

Example:
*Main> r "Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good."
[44,67,76,105,114]

Matlab, 61 96
Searches the string and replaces everything up to each match with gibberish before searching for next character. Will leave s undefined if an the word does not occur.
t='llama';for q=1:5;s(q)=min(regexpi(z,t(q))),z(1:s(q))=0;end

Note that the charcount could be reduced if case sensitivity is allowed.
Previous versions
 try;t='llama';for q=1:length(t);s(q)=find(lower(z)==t(q),1);z(1:s(q))=ones(1,s(q));end;catch;end

Searches the string and replaces everything up to each match with gibberish before searching for next character. Error handling (try-catch-end) could maybe be dropped, then the program would crash (but s would be undefined as required) if llama not found.
Implementation:
>> z='Pie is good.  I just ate a bunch of pies early this morning.  Actually, it was closer to the afternoon.  Mornings are good.';
>> try;t='llama';for q=1:length(t);s(q)=find(lower(z)==t(q),1);z(1:s(q))=ones(1,s(q));end;catch;end
>> s
s =

    45    68    77   106   115

Without error handling:
t='llama';for q=1:length(t);s(q)=find(lower(z)==t(q),1);z(1:s(q))=ones(1,s(q));end

Like the idea, have reduced charcount a bit.

OpenEuphoria, 147128
I have two examples. First, the shortest:
object t=and_bits(gets(0),#DF),L="LLAMA",i=0,X={}for j=1 to 5 do
i=find(L[j],t,i+1)X&=i
end for
if find(0,X) then X={} end if?X

I can get it down to 126 characters if I use "or" instead of "and" like the C version does up above. However, this also matches the string ''!-! as llama. Uncommon, but still a possible error.
object t=or_bits(gets(0),96),L="llama",i=0,X={}for j=1 to 5 do
i=find(L[j],t,i+1)X&=i
end for
if find(0,X) then X={} end if?X

And then the version using regular expressions:
include std/regex.e
include std/sequence.e
include std/utils.e
object X=regex:find(new("(?i)(l).*?(l).*?(a).*?(m).*?(a)"),gets(0))
? iff(atom(X),{},vslice(X[2..6],2))

Both take input from STDIN and post to STDOUT.
EDIT: Shorter regex example:
include std/regex.e
include std/sequence.e
object X=regex:find(new("(?i)(l).*?(l).*?(a).*?(m).*?(a)"),gets(0))
if atom(X)then?{}else?vslice(X[2..6],2)end if

Is it possible to save a few by building the regex with split/join or explode/implode, or does OpenEuphoria not have short versions of those?

OpenEuphoria can do split/join with strings of characters, but I don't see a way to do it in a shorter manner. I'm not very good with regular expressions; the regex used here was "inspired" (shamelessly stolen) from one of the other examples on this page.

Python (70)
r=[];c=-1
for x in'llama':c=s.lower().find(x,c+1);r+=[c]
r*=1-(-1in r)

We search of each character in 'llama' in turn, starting after the location of the previously-found character. If no character is found, c becomes the default value of -1, in which case the last line turns r into the empty list.
Edit: Found out that str.find(s,...) can be invoked as s.find(...), saving 4 characters.

Powershell - 121 85
I'm still practicing with Powershell, expect this could be improved
$s contains the string, result is in array $a
Original version
$a=@();$w="llama";$n=$c=0;foreach ($i in $s.tochararray()) {if ($i -eq $w[$n]) {$a+=$c;$n+=1} $c+=1};$a*=$a.length -gt 4

Ungolfed
$a=@()
$w="llama"
$n=$c=0
foreach ($i in $s.tochararray()) {
 if ($i -eq $w[$n]) {
  $a+=$c
  $n+=1
 } $c+=1
}
$a*=$a.length -gt 4

New version, with massive thanks to @goric
$a=@();$n=$c=0;[char[]]$s|%{if($_-eq"llama"[$n]){$a+=$c;$n++}$c++};$a*=$a.length-gt4

You can remove a lot of spaces in there to shorten things up to 112: $a=@();$w="llama";$n=$c=0;foreach($i in $s.tochararray()){if($i-eq$w[$n]){$a+=$c;$n+=1}$c+=1};$a*=$a.length-gt4

Also, you can replace foreach($i in $s.tochararray()) with [char[]]$s|%, as long as you change the subsequent $i to a $_. That shaves it down to 93: $a=@();$w="llama";$n=$c=0;[char[]]$s|%{if($_-eq$w[$n]){$a+=$c;$n+=1}$c+=1};$a*=$a.length-gt4

Save 5 more chars by removing the $w variable altogether, since its only used once. Just inline it into the if: if($i-eq"llama"[$n])

..and, of course, replace your +=1s with ++s

Jelly, 16 bytes
ŒlẹⱮ“ṫɠ»Ż>ƇḢ¥@\Ḋ

Try it online!
How it works
ŒlẹⱮ“ṫɠ»Ż>ƇḢ¥@\Ḋ - Main link. Takes a string on the left
Œl               - Lowercase
    “ṫɠ»         - Compressed string: "llama"
   Ɱ             - For each character in "llama":
  ẹ              -   Find the indexes of that character in the input
        Ż        - Prepend 0
            ¥    - Last 2 links as a dyad f(x, y):
         >Ƈ      -   Keep elements of x greater than y
           Ḣ     -   Take the first element
             @\  - Reduce the list by the f(y, x)
               Ḋ - Dequeue

APL, 47
+\↑⊃{a s←⍵⋄~⍺∊s:⍬⍬⋄a,←n←s⍳⍺⋄a(n↓s)}/'amall',⊂⍬⍞

Not the shortest code, but quite warped, in an APL way.
Explanation
'amall',⊂⍬⍞   Make an array of 6 elements: the letters 'amall' and a subarray of 2 elements, themselves subarrays: the empty array and a line of characters read from input.
{...}/... Reduce (right-fold) the 6-element array using the provided function.
a s←⍵     Decompose the right argument into the array of indices and the remaining substring (initially the empty array and the full string.)
~⍺∊s:⍬⍬   If the substring does not contain the next letter ⍺ stop the computation and return the empty array.
a,←n←s⍳⍺  Otherwise, find its position, call it n, and append it to the array of indices.
a(n↓s)    Make and return an array of 2 elements: the extended array of indices and the remaining substring.
+\↑⊃...   Unpack the output of the folding, take the first element (the array of indices) and scan it with addition, to turn relative offsets into absolute ones.
Examples
      +\↑⊃{a s←⍵⋄~⍺∊s:⍬⍬⋄a,←n←s⍳⍺⋄a(n↓s)}/'amall',⊂⍬⍞
All cats meow aloud.
2 3 6 10 15

      +\↑⊃{a s←⍵⋄~⍺∊s:⍬⍬⋄a,←n←s⍳⍺⋄a(n↓s)}/'amall',⊂⍬⍞
Some cats purr instead.

PHP
no PHP answer yet? I think a language heavily string-oriented can beat at least a math-based one
function x($s){$i=$j=0;$r=str_split('llama');$s=strtolower($s);while($i<strlen($s)){if($s[$i]==$r[$j]){$r[$j]=$i;$j++;if($j>4)return$r;}$i++;}return[];}

152 against fortran 154, job done :P
ungolfed
function x($s){
    $i=$j=0;$r=str_split('llama');
    $s=strtolower($s);
    while($i<strlen($s)){
        if ($s[$i]==$r[$j]){
            $r[$j]=$i;
            $j++;
            if($j>4)
                return $r;
        }
        $i++;
    }
    return[];
}

if the caller always passes a lowercase string, it lowers to 137

You need to add <? at the beginning of your code to make it valid. Sorry...

JavaScript, 122 115
function(s,b){z=[];for(i=0;i<5;i++){z.push(b=s.toLowerCase().indexOf("llama"[i],++b))};return z.indexOf(-1)<0?z:[]}

Defines a function that takes a string as its only argument (second arg is a cheap var) and returns either an empty array or a 5-element array.
Drops to 108 if I take the input on a single char variable (s) and leave the output in another (b):
var b=((z="llama".split('').map(function(a){return (b=s.toLowerCase().indexOf(a,++b))})).indexOf(-1)<0?z:[])

Edit: Swapped out map for for loop.

ECMAScript 6 version (81 characters) - b=(z=[].map.call("llama",a=>b=s.toLowerCase().indexOf(a,++b))).indexOf(-1)<0?z:[]

Julia, 76
Another regex example using Julia language.
f(s)=(m=match(r"(?i)(l).*?(l).*?(a).*?(m).*?(a)",s);m==nothing?m:m.offsets)

ARM Thumb-2 machine code, 42 bytes
Machine code (little endian hexdump):
2500 a208 f812 3b01 b15b 5d44 b144 3501
42a3 d003 f084 0420 42a3 d1f6 c120 e7f1
2100 4770 6c6c 6d61 0061

Commented assembly:
        .syntax unified
        .arch armv6t2
        .thumb
        .globl llama
        .thumb_func
        // Input:
        //    r0: null terminated string
        //    r1: output uint32_t array, must be 4 byte aligned
        // Output:
        //    if it matches, the ONE-INDEXED offsets are stored in r1
        //    otherwise, r1 is set to NULL. (Elements are still
        //    modified).
llama:
        // index
        movs    r5, #0
        // lookup table
        adr     r2, .LLAMA
        // loop through "llama"
.Llama:
        // Read byte from llama string, increment
        ldrb    r3, [r2], #1
        // end at null terminator
        cbz     r3, .LlAmA
.LLama:
        // r4 = str[r5]
        ldrb    r4, [r0, r5]
        // if we reach the null terminator, we don't have a match.
        cbz     r4, .LlaMa
        // increment r5 (this is what makes it one indexed)
        adds    r5, #1
        // check for a direct match
        cmp     r3, r4
        beq     .LLAma
        // flip the case by xoring 1<<5
        eor     r4, r4, #0b00100000
        // test the case when flipped
        cmp     r3, r4
        bne     .LLama
.LLAma:
        // *r1++ = index
        stm     r1!, {r5}
        // loop indefinitely (trip condition is the first cbz)
        b       .Llama
.LlaMa:
        // If we don't have a match, set r1 to NULL.
        movs    r1, #0
.LlAmA:
        // Otherwise, return.
        bx      lr
.LLAMA:
        .asciz  "llama"


text:
Old MacDonald function
Create a function in your chosen language that prints out the following:
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a cow, E-I-E-I-O,
With a moo moo here and a moo moo there,
Here a moo, there a moo, everywhere a moo moo,
Old MacDonald had a farm, E-I-E-I-O!

Where cow and moo are strings in the function parameters, and as such, can be changed to pig and oink or sheep and baa, for example.
It should take into account capital letters, hyphens, punctuation, spaces and line breaks.
Aim to type the fewest amount of Unicode characters in your code.

Shouldn't this be [tag:kolmogorov-complexity] though?

You say echoes the following. Do you mean the function should print it out or return it?

To make this fair, I think this should have the exact punctuation, spaces and carriage returns in the question. But what do you think about uppercase / lowercase? I thought a single case might be easier and avoid a load of standard applications of base64 or similar. On balance, the only capitals are at the beginning of the line, the word MacDonald and in the E-I-E-I-O, so it may be more interesting to make that exactly per the question too.

Also, given the use of "sclipting" in similar questions, please clarify if this is per Unicode character, ASCII character, or byte.

Punctuation is essential, as are capitals. The function should print it out.

Is it acceptable to output a oink or should that be made to be an oink?

@ClickRick A pedant may object and the same could be said for examples like some chicks -- perhaps make a "pedants version" which caters for words ending with s and/or beginning with a vowel.

@rybo111 re pedants version - what about plurals that don't end in "s" - e.g. some sheep or some geese?

@DigitalTrauma good point - I guess the pedants version would need some consideration -- perhaps determine both words in the variable, or have a predefined list of animals and their respective sounds!

@rybo111: Were you aware that the great Donald Knuth wrote an academic paper about this kind of thing? It was actually published in a real journal (admittedly in the April edition). More here including a link to the PDF of the paper: http://en.wikipedia.org/wiki/The_Complexity_of_Songs

@Dommer No, I wasn't aware. Interesting!

Javascript ES6 - 204

Aim to type the fewest amount of Unicode characters in your code.

Not the shorter but probably the most obfuscated.
f=(a,b)=>{for(c=[b,a].concat('!,-ADEHIMOWacdefhilmnortvwy \n'.split(o='')),i=62;i;o+=c[e>>10]+c[e/32&31]+c[e&31])e='ⱞᄤ⒇瓤抣瘭㾭癍㚏᫶⦮函࿋Π疽䌐獲樘ྰ㞠戝晐}疽䌐࿈䌐眲Π疽㛏戝癐Π疽伲࿌⒋ფᲉѽ疽䦯䨝抽瘭䦹容㾷碶ᅣᲉᄤྦྷ㜕㞱㗽㾲妴㣗畍⺏'.charCodeAt(--i);alert(o)}

If your browser do not support ES6 :
function f(a,b){for(c=[b,a].concat('!,-ADEHIMOWacdefhilmnortvwy \n'.split(o='')),i=62;i;o+=c[e>>10]+c[e/32&31]+c[e&31])e='ⱞᄤ⒇瓤抣瘭㾭癍㚏᫶⦮函࿋Π疽䌐獲樘ྰ㞠戝晐}疽䌐࿈䌐眲Π疽㛏戝癐Π疽伲࿌⒋ფᲉѽ疽䦯䨝抽瘭䦹容㾷碶ᅣᲉᄤྦྷ㜕㞱㗽㾲妴㣗畍⺏'.charCodeAt(--i);alert(o)}

Copy/Paste that code into your browser console and try f('cow','moo'), f('pig','oink'), f('sheep','baa')
How it works ?
c is an array of 29 letters plus the animal and its sound (let call this our alphabet).
So, all the 31 characters fit in 5 bits (2^5 = 32).
A Unicode character is 16 bits long, so it can encode 3 characters of our alphabet with a padding bit.
The full text with the new lines is 186 characters of our alphabet, it can be encoded with 62 Unicode characters.
For example, Old is encoded like this :
alphabet value         O      l      d
alphabet index         11     20     15
unicode           0  01011  10100  01111  ===> \u2e8f (⺏)

If you have troubles to read some Unicode chars, install Code2000 font

"cow" and "moo" are supposed to be the function parameters. By getting the caller to pass an array, you're saving characters within the function definition at the expense of adding to the character count of the calling code. This smells like a cheat to me. Taking that approach to the extreme you could define function f(a){alert(a)} (23 characters) and say that it needs to be called like f("Old MacDonald had a ...").

I had passed the strings in two separated parameters but after reading the challenge, I saw no reason to not pass the strings in array format, so I edited my answer. This is not cheating, just saving few chars when it's possible. Let @rybo111 decide if this fits the rule or not.

@tobyink I did use the term 'string' (not array) in the rules, so I suppose you are right. I think 'cheating' is a bit harsh, though!

Why does this have so many votes? It's over 200 and not even the shortest javascript solution.

Whell thougth and well explained so have my vote too

The character count is incorrect, it's 205, and the second one is 211.

CJam - 142 / GolfScript - 144
{" had| a |farm|68, |68 8|here|Old MacDonald765|, E-I-E-I-O|10,
And on that 5 he7690,
With3 2 and3 t2,
Here4t24everyw23,
10!"'|/~A,{`/\*}/}:F;

Usage: "cow""moo"F
For GolfScript replace '| with "|" and A with 10
Explanation:
The key part is A,{`/\*}/:
A,{...}/ executes the block for each number from 0 to 9 (A=10)
` converts the number to string
/\* does a string replace: if we have on the stack "bar" "foo 1 baz" "1" then / splits the string resulting in ["foo " " baz"], \ swaps this array with the previous item ("bar") and * joins the array resulting in "foo bar baz"
So the code replaces each number in the main string with a string that's previously on the stack. We have the animal and the sound, then " had", " a ", etc and finally ", E-I-E-I-O" and the main string, "10,...!". To avoid using too many quotes, I put all the strings (except the parameters) in one string, then split it and dumped the resulting array ('|/~)
The main string goes through the following transformations:
10,
And on that 5 he7690,
With3 2 and3 t2,
Here4t24everyw23,
10!

replace "0" with ", E-I-E-I-O":
1, E-I-E-I-O,
And on that 5 he769, E-I-E-I-O,
With3 2 and3 t2,
Here4t24everyw23,
1, E-I-E-I-O!

replace "1" with "Old MacDonald765":
Old MacDonald765, E-I-E-I-O,
And on that 5 he769, E-I-E-I-O,
With3 2 and3 t2,
Here4t24everyw23,
Old MacDonald765, E-I-E-I-O!

replace "2" with "here", then "3" with "68 8" etc.
8 corresponds to the sound, and 9 to the animal.

Can you explain this? I don't even know what CJam is

@Cruncher CJam is a language I made, http://sf.net/p/cjam ; I can explain it once I finish golfing it :)

@Cruncher added explanation now

♬ and on that five he sev'n six nine, ze e e e ro ♬

Can E-I- be a string which is then repeated? :)

@rybo111 maybe, but I ran out of digits

Bash + iconv, 128 Unicode characters
Takes the below pure-bash/ascii function body and reverse-encodes into unicode chars:
m()(c=`iconv -t unicode<<<㵳⁜屡␠ਲ㵨敨敲攊ⰽ⁜ⵅⵉⵅⵉ੏㵯伢摬䴠捡潄慮摬栠摡愠映牡⑭≥攊档␢Ɐ䄊摮漠桴瑡映牡敨栠摡愠␠␱ⱥ圊瑩⑨⁳㈤␠湡⑤⁳㈤琠栤ਬ效敲猤⑴⑨ⱳ攠敶祲⑷⑨⁳㈤ਬ漤™ਠ`
eval "${c:2}")

Defines a shell function m.  Call as:

$ m pony neigh
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a pony, E-I-E-I-O,
With a neigh neigh here and a neigh neigh there,
Here a neigh, there a neigh, everywhere a neigh neigh,
Old MacDonald had a farm, E-I-E-I-O!
$

Pure bash, 171 bytes (ascii-only)
I think its worth noting that the original verse (with "cow" and "moo") is only 203 chars.
m()(s=\ a\ $2
h=here
e=,\ E-I-E-I-O
o="Old MacDonald had a farm$e"
echo "$o,
And on that farm he had a $1$e,
With$s $2 $h and$s $2 t$h,
Here$s, t$h$s, everyw$h$s $2,
$o"!)

Defines the shell function m.  Call as:

$ m sheep baa
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a sheep, E-I-E-I-O,
With a baa baa here and a baa baa there,
Here a baa, there a baa, everywhere a baa baa,
Old MacDonald had a farm, E-I-E-I-O!
$

C++ (403)
Alright, this is a bit of a long shot, but who doesn't like over-defining?
#define O ", E-I-E-I-O"
#define E O<<","
#define I "Old MacDonald had a farm"
#define H(a) "And on that farm he had a "<<a<<E
#define D(s) s<<" "<<s
#define W(s) "With a "<<D(s)<<" here and a "<<D(s)<<" there,"
#define V(s) "Here a "<<s<<", there a "<<s<<", everywhere a "<<D(s)<<","
#define F I<<O<<"!"
#define N endl
void m(string a, string s){cout<<I<<E<<N<<H(a)<<N<<W(s)<<N<<V(s)<<N<<F<<N;}

this.eyes.bleeding = true;

Any defines that could further pack this tighter?

It used to be possible to #define X define and then use #X Y Z. Sadly, those heady IOCCC days are now long past...

What about using + instead of <<?
Or using char* instead of string?
// Only one of these can be used at the same time.

Python, 116 Unicode chars
def f(**a):print u'鱸쿳光䷰癌쿉ы㊲匒ሔ툕謒畲尔㵵䅵忘쮇⼱ⅅ伿⒡넣Ⰴ邩ઑ꩕醪徜妮ꊌ㰺⒳Ⰳ鮕꾟ౙ㎧譒ᕒ끒镈롴쀼怪㪢愐腤닔ꋔ狊兔Ⲹ㾗꽡Ȩ똀䝸å'.encode('u16')[2:].decode('zip')%a

StackOverflow is eating my special characters, though, so here's the file in base64:
77u/ZGVmIGYoKiphKTpwcmludCB1J+mxuOy/s+WFieS3sOeZjOy/idGL44qy5YyS4YiU7YiV6KyS55Wy5bCU47W15IW15b+Y7K6H4ryx4oWF5Ly/4pKh64Sj4rCE6YKp4KqR6qmV6Yaq5b6c5aau6oqM47C64pKz4rCD6a6V6r6f4LGZ446n6K2S4ZWS74yS64GS6ZWI7pKA66G07IC85oCq46qi5oSQ6IWk64uU6ouU54uK5YWU4rK4476X6r2hyKjrmIDknbjDpScuZW5jb2RlKCd1MTYnKVsyOl0uZGVjb2RlKCd6aXAnKSVh

The data is packed using zlib, which efficiently codes repeated strings (zlib is good at compressing text in general). To take advantage of the "Unicode characters" rule, the 121-byte zlib chunk is padded and halved to a 61-character Unicode string by interpreting the bytestring as UTF-16.
Call the function as
f(cow='pig', moo='oink')

Nice, but Where cow and moo are strings in the function parameters, and as such, can be changed to pig and oink or sheep and baa, for example.  Looks like your output is hardcoded to cow/moo.

@DigitalTrauma: My reading comprehension fail! Fixed.

thats better :)  +1

115. No need to count the trailing newline.

@nyuszika7h No, it’s 116. You forgot to count the “UTF-8 BOM” (EF BB BF) at the beginning, which is necessary to let Python 2 accept non-ASCII source. (This isn’t Python 3, which doesn’t have .decode('zip').)

Perl 5 (UTF-8) - 131 characters, 313 bytes
The script below needs to be saved as UTF-8 with no BOM.
use utf8;use Encode;eval encode ucs2,'獵戠晻③㴤∮灯瀻⑥㴢Ⱐ䔭䤭䔭䤭伢㬤漽≏汤⁍慣䑯湡汤慤慲洤攢㬤ⰽ≥牥∻獡礢⑯Ⰺ䅮搠潮⁴桡琠晡牭攠桡搠愠䁟⑥Ⰺ坩瑨③③␬湤③③⁴桥牥Ⰺ䠤Ⱔ戬⁴栤Ⱔ戬癥特睨␬③③Ⰺ⑯™紱';

Usage: f("cow", "moo");.
Perl needs to have been run with the -M5.010 flag to enable Perl 5.10 features. (This is allowed.)
I quite like the symmetry of the character count (131) and byte count (313). It's very yin and yang.
Perl 5 (ASCII) - 181 characters, 181 bytes
sub f{$b=$".pop;$e=", E-I-E-I-O";$o="Old MacDonald had a farm$e";$,="ere a";say"$o,
And on that farm he had a @_$e,
With a$b$b h$,nd a$b$b there,
H$,$b, th$,$b, everywh$,$b$b,
$o!"}

Usage: f("cow", "moo");.
Again, perl needs to have been run with the -M5.010 flag to enable Perl 5.10 features.

Hmm, looks familar http://codegolf.stackexchange.com/a/26633/11259 ;-)

Actually http://codegolf.stackexchange.com/a/26628/12469 was my starting point. I tested a few extra variables that cut down the length further, and then applied the UTF16 trick that several of the other implementations make use of.

CJam (non-ASCII) - 77 chars
"啝裢樃濿䶹讄團챤鋚䖧雿ꆪꆵ䷶텸紎腕Խꍰ搓᩟童䚯⤭刧损⬛豳Ẍ퍾퓱郦퉰怈䡞௳閶蚇⡾쇛蕟猲禼࿆艹蹚㞿䛴麅鞑椢⧨餎쏡첦휽嬴힡ݷ녣㯂鐸㭕"56e3b127b:c~

Usage: "cow""moo"F
The string is my other CJam solution converted from base 127 to base 56000.
A UTF-8 locale might be required.
By the way, now you can try this online at http://cjam.aditsu.net/

Python, 217
You can't really golf this much. I just took out the blatant front-end repetition and...
m,f="Old MacDonald had a farm, E-I-E-I-O",lambda x,y:m+",\nAnd on that farm he had a %s, E-I-E-I-O,\nWith a %shere and a %sthere,\nHere a %s, there a %s, everywhere a %s %s,\n%s!"%((x,)+((y+' ')*2,)*2+(y,)*4+(m,))

Javascript, 241 - JSCrush cheat
Made this with JSCrush...not really a real answer, it'd just be interesting to see if anybody can beat this in a mainstream language. (EDIT: uh)
_='var f=function(c,a){var b=a "+a;return"Anon that he hadcWith  and tHere  t   everyw!"};OlMacDonalhaa a "+, O,\\nhere+"b farm a, d E-I-';for(Y in $=' ')with(_.split($[Y]))_=join(pop());eval(_)

Java - 262 258
void m(String...s){String b=s[1],c=b+" "+b,d="E-I-E-I-O",e="Old MacDonald had a farm, "+d;System.out.print(e+",\n"+"And on that farm he had a "+s[0]+", "+d+",\nWith a "+c+" here and a "+c+" there,\nHere a "+b+", there a "+b+", everywhere a "+c+",\n"+e+"!");}

Further optimization is definitely possible.

You could use printf

Trevin Avery suggested this edit: Java - 243
void String...a){String c=" a "+a[1],d=c+" "+a[1],e=", E-I-E-I-O",f="Old MacDonald had a farm"+e;System.out.print(f+",\nAnd on that farm he had a "+a[0]+e+",\nWith"+d+" here and"+d+" there,\nHere"+c+", there"+c+"', everywhere"+d+",\n"+f+"!");}

Further optimization is definitely possible

Rebol, 206 202
f: func[a b][print reword{$o$e,
And on that farm he had a $a$e,
With a $b $b here and a $b $b there,
Here a $b, there a $b, everywhere a $b $b,
$o$e!}[e", E-I-E-I-O"o"Old MacDonald had a farm"a a b b]]

Usage: f "cow" "moo"

Java, 246
void f(String[] a){String o="Old MacDonald had a farm",e=", E-I-E-I-O",x=" a "+a[1],s=x+" "+a[1];System.out.print(o+e+",\nAnd on that farm he had a "+a[0]+e+",\nWith"+s+" here and"+s+" there,\nHere"+x+", there"+x+", everywhere"+s+",\n"+o+e+"!");}

Usage: f(new String[]{"cow","moo"});

JavaScript: 152 chars / ES6: 149 chars
Here's a JS function called "z" that does the job in 214 chars. (don't execute it!)
function z(a,b){c=' a '+b;d=c+' '+b;e=', E-I-E-I-O';f='Old MacDonald had a farm'+e;return(f+',\nAnd on that farm he had a '+a+e+',\nWith'+d+' here and'+d+' there,\nHere'+c+', there'+c+', everywhere'+d+',\n'+f+'!')}

I "packed" it in unicode chars using a technique created by @subzey and I for 140byt.es).
eval(unescape(escape('').replace(/uD./g,'')))

execute that last snippet, then call z("cow","moo"), and you'll get this string:
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a cow, E-I-E-I-O
With a moo moo here and a moo moo there,
Here a moo, there a moo, everywhere a moo moo,
Old MacDonald had a farm, E-I-E-I-O!"

More info here: http://xem.github.io/golfing/en.html#compress
ES6 version:
eval(unescape(escape('').replace(/uD./g,'')))

I think you didn't copy-paste things correctly, your code seems to have over 250 chars -- oops, maybe not, but my text editor is behaving strangely, I'll investigate.

Oh, most of your characters are from some astral planes (that's probably why they get counted as 2 characters here)... and unallocated too. This is stretching the rules a bit :)

Well, I don't think this is cheating: those symbols are unicode chars, and shouldn't count as 2 chars. Also, Twitter counts each of them as 1 char. If you copy the ES6 version in a tweet, it says it's too long by 9 chars. So, 149 it is :)

C# - 339 Bytes
void x(string c, string d){var a="Old MacDonald had a farm";var b=", E-I-E-I-O";var f=" a ";var g=" there";Debug.WriteLine(a+b+",");Debug.WriteLine("And on that farm he had"+f+c+b+",");Debug.WriteLine("With"+f+d+" "+d+" here and"+f+d+" "+d+g+",");Debug.WriteLine("Here"+f+d+","+g+f+d+", everywhere"+f+d+" "+d+",");Debug.WriteLine(a+b+"!");

Usage: x("cow","moo");

C: 224 bytes
By using the printf precision specifier, we can use the same string as both the printf format string and as two of the parameters.
o(char*x,char*y){char*f="Old MacDonald had a farm, E-I-E-I-O,\nAnd on that farm he had a %s%.13sWith a %s %s here and a %s %s there,\nHere a %s, there a %s, everywhere a %s %s,\n%.35s!\n";printf(f,x,f+24,y,y,y,y,y,y,y,y,f);}

With white space and the string split into lines:
o(char* x, char* y)
{
    char* f=
        "Old MacDonald had a farm, E-I-E-I-O,\n"
        "And on that farm he had a %s%.13s"
        "With a %s %s here and a %s %s there,\n"
        "Here a %s, there a %s, everywhere a %s %s,\n"
        "%.35s!\n";

    printf(f,x,f+24,y,y,y,y,y,y,y,y,f);
}

217 bytes

Delphi XE3 (272 252)
procedure k(a,s:string);const o='Old MacDonald had a farm';e=', E-I-E-I-O';n=','#13#10;begin s:=' '+s;write(o+e+n+'And on that farm he had a '+a+e+n+'With a'+s+s+' here and a'+s+s+' there'+n+'Here a'+s+', there a'+s+' every where a'+s+s+n+o+e+'!');end;

Ungolfed
procedure k(a,s:string);
const
  o='Old MacDonald had a farm';
  e=', E-I-E-I-O';
  n=','#13#10;
begin
  s:=' '+s;
  write(o+e+n+'And on that farm he had a '+a+e+n+'With a'+s+s+' here and a'+s+s+' there'+n+'Here a'+s+', there a'+s+' every where a'+s+s+n+o+e+'!');
end;

Cobra - 203
def f(a,b)
    d=" a [b] "+b
    e=", E-I-E-I-O"
    m="Old MacDonald had a farm[e]"
    print "[m],\nAnd on that farm he had a [a][e],\nWith[d] here and[d] there,\nHere a [b], there a [b], everywhere[d],\n[m]!"

Even for a language with little-to-no multi-lining, and strict indentation rules, Cobra still does pretty well.

Lua 237
function f(a,b)c=b.." "..b;d="Old MacDonald had a farm, E-I-E-I-O"print(d..",\nAnd on that farm he had a "..a..", E-I-E-I-O,\nWith a "..c.." here and a "..c.." there,\nHere a "..b..", there a "..b..", everywhere a "..c..",\n"..d.."!")end

By defining c=b.." "..b, I can save a dozen characters. By defining d as I do, I save 23 characters. I do not see how I can shorten this anymore. This is called via f("<animal>","<sound>").

JavaScript 220
function f(a,b){c=' a '+b;d=c+' '+b;e=', E-I-E-I-O';f='Old MacDonald had a farm'+e;console.log(f+',\nAnd on that farm he had a '+a+e+',\nWith'+d+' here and'+d+' there,\nHere'+c+', there'+c+', everywhere'+d+',\n'+f+'!');}

Called by
f('cow', 'moo');

Java 8(411)

String m(String...m){LinkedHashMap<String,String>n=new LinkedHashMap<>();n.put("/","( * #, -");n.put("#","farm");n.put("-","E-I-E-I-O");n.put("+","here");n.put("*","had a");n.put("(","Old MacDonald");n.put("|"," a )");n.put(")","moo");n.put("moo",m[1]);n.put("cow",m[0]);m[0]="/,\nAnd on that # he * cow, -,\nWith|) + and|) t+,\nHere|, t+|, everyw+|),\n/!";n.forEach((k,v)->m[0]=m[0].replace(k,v));return m[0];}

Abusing of lambda, putted the replaces in a LinkedhashMap to keep em in a defined order then used a foreach lambda to replace key with value in main String. parameters are added as last 2 replacements in the map. that varargs argument is to shave off some bytes in the method header
Ungolfed version:
String m(String... m)
{
    LinkedHashMap<String, String> n = new LinkedHashMap<>();
    n.put("/", "( * #, -");
    n.put("#", "farm");
    n.put("-", "E-I-E-I-O");
    n.put("+", "here");
    n.put("*", "had a");
    n.put("(", "Old MacDonald");
    n.put("|", " a )");
    n.put(")", "moo");
    n.put("moo", m[1]);
    n.put("cow", m[0]);
    m[0] = "/,\nAnd on that # he * cow, -,\nWith|) + and|) t+,\nHere|, t+|, everyw+|),\n/!";
    n.forEach((k, v) -> m[0] = m[0].replace(k, v));
    return m[0];
}

Pure C, 298 bytes, no unicode
In my function I take a single argument, which is actually a bunch of char*'s packed together. Each string is null terminated, and there's an extra null terminator at the end. This allows me to check strlen(a) at the end of each loop, rather than keeping a counter variable.
mcdonald.c:
m(char*a){while(strlen(a)){printf("Old MacDonald had a farm, E-I-E-I-O\nAnd on that farm he had a %s, E-I-E-I-O,\nWith a ",a);a+=strlen(a)+1;printf("%s %s here and a %s %s there,\nHere a %s, there a %s, everywhere a %s %s,\nOld MacDonald had a farm, E-I-E-I-O!\n",a,a,a,a,a,a,a,a);a+=strlen(a)+1;}}

main.c:
int m(char *v);
int main(int argc, char **argv) {
    m("cow\0moo\0programmer\0meh\0\0");
    return 0;
}

Output:
clang main.c mcdonald.c && ./a.out
Old MacDonald had a farm, E-I-E-I-O
And on that farm he had a cow, E-I-E-I-O,
With a moo moo here and a moo moo there,
Here a moo, there a moo, everywhere a moo moo,
Old MacDonald had a farm, E-I-E-I-O!
Old MacDonald had a farm, E-I-E-I-O
And on that farm he had a programmer, E-I-E-I-O,
With a meh meh here and a meh meh there,
Here a meh, there a meh, everywhere a meh meh,
Old MacDonald had a farm, E-I-E-I-O!

254 bytes

PHP - 272 characters, 272 bytes
function m($q,$w){for($e="@&And on that farm he had^<%&With *h# and*th#&H(th(everywh#^> >&@!",$r=1;;$e=$r){$r=str_replace(["@","#","^","%","<",">","&","*","("],["Old MacDonald had^farm%","ere"," a ",", E-I-E-I-O",$q,$w,",\n","^> > ","#^>, "],$e);if($e==$r)break;}echo $e;}

Usage: m("cow", "moo");, m("fox", "Hatee-hatee-hatee-ho");
Parameters with @#%^<>&*( crash the output.

Haskell (282 and still somewhat readable :))
wc -c oldmacdonald.hs
     282 oldmacdonald.hs

The file:
main=mapM putStrLn[s"cow""moo",s"pig""oink",s"sheep""baa"]
s c m=o#",\nAnd on that farm he had"#b c#e#let n=m#" "#m in",\nWith"#b n#" here and"#b n#" there,\nHere"#b m#", there"#b m#", everywhere"#b n#",\n"#o#"!\n"
o="Old MacDonald had a farm"#e
e=", E-I-E-I-O"
b=(" a "#)
(#)=(++)

It's 281, you don't usually count the trailing newline, unless it's a C preprocessor macro or something else that requires newline termination. In most cases, you can just subtract 1 from the byte count returned by wc -c, but I prefer using https://mothereff.in/byte-counter and making sure there's no empty line at the end unless required for the program to work.

ES6, 2 solutions of 179 186 chars without any unicode
f=(a,b)=>alert("325And on that farm he had a025With a11 h4nd a11 th45H41, th41, everywh411532!".replace(/\d/g,x=>[" "+a," "+b,", E-I-E-I-O","Old MacDonald had a farm","ere a",",\n"][x]))

And the second:
f=(a,b)=>alert("3625And on7at6 he ha8025With a11 h4n811745H41,741, everywh4115362!".replace(/\d/g,x=>(` ${a}0 ${b}0, E-I-E-I-O0Old MacDonald had a0ere a0,\n0 farm0 th0d a`).split(0)[x]))

I've added alert call (+7 chars).

I think, it's the shortest solution from non-unicoded ones for now.

JavaScript (E6) 140 chars
Char counter: https://mothereff.in/byte-counter, 140 chars, 425 bytes in UTF-8
eval(unescape(escape('').replace(/uD./g,'')))

Original ASCII code 188 bytes
f=(a,b)=>alert('0125And on 6at13e3ad7 925Wi6 a88347nd a88 645H478, 6478, everywh47885012!'.replace(/\d/g,c=>('Old MacDonald had a0 farm0, E-I-E-I-O0 h0ere0,\n0th0 a0 '+b+0+a).split(0)[c]))

Compressed with http://xem.github.io/obfuscatweet/
Test in FireFox/FireBug console
f('mosquito','zzz')

Output
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a mosquito, E-I-E-I-O,
With a zzz zzz here and a zzz zzz there,
Here a zzz, there a zzz, everywhere a zzz zzz,
Old MacDonald had a farm, E-I-E-I-O!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes